diff --git "a/542.jsonl" "b/542.jsonl" new file mode 100644--- /dev/null +++ "b/542.jsonl" @@ -0,0 +1,639 @@ +{"seq_id":"430530215","text":"class Solution:\r\n def longestCommonPrefix(self, strs):\r\n \"\"\"\r\n :type strs: List[str]\r\n :rtype: str\r\n \"\"\"\r\n if not strs:\r\n return ''\r\n temp = strs[0][0]\r\n for i in range(1,len(strs[0])):\r\n for j in range(1, len(strs)):\r\n if strs[j][0:i] != temp:\r\n if i == 1:\r\n return \"\\\"\\\"\"\r\n return temp[:-1]\r\n temp += strs[0][i]\r\n def _longestCommonPrefix(self, strs):\r\n if not strs:\r\n return ''\r\n prefix = strs[0]\r\n for i in range(1, len(strs)):\r\n s = strs[i]\r\n while not s.startswith(prefix):\r\n prefix = prefix[:-1]\r\n return prefix\r\n \r\n\r\nsol = Solution()\r\nstrs = [\"\"]\r\nresult = sol._longestCommonPrefix(strs)\r\nprint(result)\r\n","sub_path":"LeetCode/14longestCommonPrefix.py","file_name":"14longestCommonPrefix.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"89493618","text":"import asyncio\n\nfrom .base import REDIS_LOCATION\n\nZLIB_CACHES = {\n \"default\": {\n \"BACKEND\": \"django_asyncio_redis.cache.AsyncRedisCache\",\n \"POOLSIZE\": 5,\n \"LOCATION\": REDIS_LOCATION,\n \"LOOP\": asyncio.get_event_loop(),\n \"COMPRESSOR\": \"django_asyncio_redis.compressors.zlib.ZlibCompressor\"\n }\n}\n","sub_path":"tests/settings/zlib.py","file_name":"zlib.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"601700383","text":"zahl = 1337\nversuch = -1\n\nwhile versuch != zahl:\n versuch = int(input(\"Raten bitte...:\"))\n\n if versuch == 0:\n print(\"Abgebrochen\")\n break\nelse: #Mit else kann ein Block in Python ausgeführt werden wenn die Schleife _erfolgreich_ beendet wurde. Bei break wird dieser Block ausgelassen!!\n print(\"Gewonnen\")\n","sub_path":"While-Break-Else/while-break-else-easy.py","file_name":"while-break-else-easy.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"195945276","text":"import random\r\nfrom random import choice\r\n\r\n#Definicja skinow\r\nCaseItems = [\"AK 47 Frontside Misty\",\"AK 47 Urban Hazard\",\"Glock-18 Bunseen Burner\",\"P250 Business class\",\"USP-S Neo-Noir\",\"AWP Dragon Lore\",\"Desert Eagle Shade\", \"Glock-18 Night fight\",\"Galil AR Cerberus\"]\r\n\r\ndef LosujSkrzynke():\r\n randomitem = choice(CaseItems)\r\n print(randomitem)\r\n\r\n\r\n#Pobranie iw alidacja liczby do otwarcia\r\ndef PobierzLiczbeSkrzynek():\r\n global CaseCount\r\n CaseCount = int(input(\"How many chests do you want to open?[1-5]: \"))\r\n while CaseCount <= 0 or CaseCount > 5:\r\n CaseCount = int(input(\"Type in 1 to 5: \"))\r\n return CaseCount\r\n\r\n\r\nwhile True:\r\n try:\r\n PobierzLiczbeSkrzynek()\r\n except ValueError:\r\n print(\"You need to privde valid input, try again\")\r\n PobierzLiczbeSkrzynek()\r\n else:\r\n #correct input\r\n break\r\n\r\nCaseOpened = 0\r\nwhile CaseOpened != CaseCount:\r\n LosujSkrzynke()\r\n CaseOpened += 1","sub_path":"caseSimulator.py","file_name":"caseSimulator.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"522780337","text":"#!/usr/bin/env python3\n\nlanguages = {\n 'Python': 'Guido van Rossum',\n 'Ruby': 'Yukihiro Matsumoto',\n 'PHP': 'Rasmus Lerdorf',\n }\n\ndef main():\n for lang in languages:\n print(f'{lang} was created by {languages[lang]}')\n\nif __name__ == \"__main__\":\n main()","sub_path":"module00/ex05/kata01.py","file_name":"kata01.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"368321434","text":"from radian import main\nimport sys\n\nif __name__ == '__main__':\n if \"--coverage\" in sys.argv:\n import coverage\n cov = coverage.Coverage()\n cov.start()\n\n def cleanup(x):\n cov.stop()\n cov.save()\n\n main.cleanup = cleanup\n\n if \"--cprofile\" in sys.argv:\n import cProfile\n import pstats\n pr = cProfile.Profile()\n pr.enable()\n\n def cleanup(x):\n pr.disable()\n ps = pstats.Stats(pr).sort_stats('cumulative')\n ps.print_stats(10)\n\n main.cleanup = cleanup\n\n main()\n","sub_path":"radian/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"414004534","text":"import wx\nfrom pubsub import pub\n \n# adding in sizers to the mix\n# code for older tutorial can be followed at \n# https://www.blog.pythonlibrary.org/2013/09/05/wxpython-2-9-and-the-newer-pubsub-api-a-simple-tutorial/\nclass OtherFrame(wx.Frame):\n \"\"\"\"\"\"\n \n def __init__(self):\n \"\"\"Constructor\"\"\"\n super().__init__(None, title=\"Secondary Frame\")\n panel = wx.Panel(self)\n \n msg = \"Enter a Message to send to the main frame\"\n instructions = wx.StaticText(panel, label=msg)\n self.msg_txt = wx.TextCtrl(panel, value=\"\")\n close_btn = wx.Button(panel, label=\"Send and Close\")\n close_btn.Bind(wx.EVT_BUTTON, self.on_send_and_slose)\n \n sizer = wx.BoxSizer(wx.VERTICAL)\n flags = wx.ALL|wx.CENTER\n sizer.Add(instructions, 0, flags, 5)\n sizer.Add(self.msg_txt, 0, flags, 5)\n sizer.Add(close_btn, 0, flags, 5)\n panel.SetSizer(sizer)\n \n def on_send_and_slose(self, event):\n \"\"\"\n Send a message and close frame\n \"\"\"\n msg = self.msg_txt.GetValue()\n pub.sendMessage(\"panel_listener\", message=msg) # publish to the topic called \"panel-listener\"\n pub.sendMessage(\"panel_listener\", message=\"test2\",\n arg2=\"2nd argument!\")\n self.Close()\n \n \nclass MyPanel(wx.Panel):\n \"\"\"\"\"\"\n \n def __init__(self, parent):\n \"\"\"Constructor\"\"\"\n super().__init__(parent)\n pub.subscribe(self.my_listener, \"panel_listener\") # the topic to subscribe to\n \n btn = wx.Button(self, label=\"Open Frame\")\n btn.Bind(wx.EVT_BUTTON, self.on_open_frame)\n \n def my_listener(self, message, arg2=None):\n \"\"\"\n Listener function\n \"\"\"\n print(f\"Received the following message: {message}\")\n if arg2:\n print(f\"Received another arguments: {arg2}\")\n \n def on_open_frame(self, event):\n \"\"\"\n Opens secondary frame\n \"\"\"\n frame = OtherFrame()\n frame.Show()\n \n \nclass MyFrame(wx.Frame):\n \"\"\"\"\"\"\n \n def __init__(self):\n \"\"\"Constructor\"\"\"\n wx.Frame.__init__(self, None,\n title=\"New PubSub API Tutorial\")\n panel = MyPanel(self)\n self.Show()\n \n \nif __name__ == \"__main__\":\n app = wx.App(False)","sub_path":"older_tutorials/build-resources/py-pub-sub-module-use/2013_py_pub_sub_2_9.py","file_name":"2013_py_pub_sub_2_9.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"264547301","text":"\"\"\"\nModule: comp110_lab03\n\nPractice code for working with sounds in Python.\n\"\"\"\nimport sound\n\n\nlove_sound = sound.load_sound(\"love.wav\")\nlove_sound.play()\nsound.wait_until_played() # waits until love_sound is done playing\n\n# change the volume of the love sound\nfor i in range(len(love_sound)):\n sample = love_sound.get_sample(i)\n new_left_val = sample.get_left() * 2\n new_right_val = sample.get_right() * 2\n sample.set_left(new_left_val)\n sample.set_right(new_right_val)\n\nlove_sound.play()\nsound.wait_until_played() # waits until love_sound is done playing\n","sub_path":"comp110_lab03.py","file_name":"comp110_lab03.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"250711117","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 12 16:22:26 2020\n\n@author: encry973r\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\n# import dataset\ndataset = pd.read_csv('Churn_Modelling.csv')\n# matrix of features and dependent variables\nX = dataset.iloc[:, 3:13].values\ny = dataset.iloc[:, 13].values\n\n# encode categorical data\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\nfrom sklearn.compose import ColumnTransformer\n\n# encode gender column (because it contains )\nle = LabelEncoder()\nX[:, 2] = le.fit_transform(X[:, 2])\n\n\"\"\"encode gender column\n# ct = ColumnTransformer(transformers=[('one_hot_encoder', OneHotEncoder(categories='auto'), [2])], remainder='passthrough')\nfit to X\nX = ct.fit_transform(X)\ndrop one encoded column to avoid the dummie variable trap\nX = X[:, 1:]\n\"\"\"\n\n# encode country column\nct = ColumnTransformer(transformers=[('one_hot_encoder', OneHotEncoder(categories='auto'), [1])], remainder='passthrough')\n# fit to X\nX = ct.fit_transform(X)\n# drop one encoded column to avoid the dummie variable trap\nX = X[:, 1:]\n# convert X to floating point array\nX = np.array(X, dtype=np.float)\n\n# split dataset into train and test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\n# feature scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n\n# import keras\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n# initialize model\nclassifier = Sequential()\n# adding the input layer and the first hidden layer\nclassifier.add(Dense(units = 6, kernel_initializer='uniform', activation='relu', input_dim=11))\n# adding the second hidden layer\nclassifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu'))\n# adding the output layer\n# use activation = 'softmax' when dealing with an output of more than 2 categories\nclassifier.add(Dense(units=1, kernel_initializer='uniform', activation='sigmoid'))\n# compile the ANN\n# when dealing with an output of more than 2 categories, use loss = 'categorical_crossentropy'\nclassifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n# fitting the ANN to the training set\nclassifier.fit(X_train, y_train, batch_size=10, epochs=100)\n\n\n# predict y for our test set\ny_pred = classifier.predict(X_test)\ny_pred = (y_pred > 0.5)\n\n# making the confusion matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\ncorrect_values = cm[0,0] + cm[1,1]\nwrong_values = cm[0,1] + cm[1,0]\naccuracy = np.round((correct_values/(correct_values + wrong_values))*100, 2)\n\nprint(\"Correct values : {0}\\nWrong values : {1}\\nAccuracy : {2}%\"\n .format(correct_values, wrong_values, accuracy))\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":"7DeepLearning/ANN/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"298449966","text":"##\n# Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...\n##\n##\n# Theory: the n-th element is the sum of the (n-th - 1) + (n-th - 2) element.\n# Or in plain english: any element of the sequence is the sum of the previous two.\n##\n\ndef fibonacci(count):\n a, b = -1, 1\n while count > 0:\n c = a + b\n yield c # saves a lot of memory since the caller is called once\n\n a, b = b, c\n count -= 1\n\n\nseq = [i for i in fibonacci(67)]\nprint(seq)\n\n\n# Just for the sake of completion here's the standard application with recursion:\ndef recursive_fibonacci(n):\n if n == 0 or n == 1:\n return 1\n else:\n return recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2)\n\n\n\n","sub_path":"generators/fibonacci_sequence.py","file_name":"fibonacci_sequence.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"310916448","text":"from .forms import RegisterForm\nfrom django.views.generic.edit import FormView\n\n# Create your views here.\nclass RegisterView(FormView):\n template_name='subscribe.html'\n form_class = RegisterForm\n success_url = '/thanks/'\n\n def form_valid(self, form):\n form.register_email()\n return super(RegisterView, self).form_valid(form)\n\n","sub_path":"subscribe/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"230366318","text":"# Schwab's aliasing ratio\n\nimport numpy as np\nimport scipy\nfrom scipy import constants\nimport math\nimport pylab as P\nimport time\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.fftpack import fft, ifft\nfrom Schwab_grid_func import Schwab_grid\nfrom rk4_test import rk4\n\ndef c_x(u,y):\n u1 = -3. + 6.*u\n ALPHA = 1\n IM = 6\n ETA = 2*u1/IM\n y = Schwab_grid(ALPHA, IM, ETA) *np.cos(2*np.pi*u1*x)\n return y\n\nIM = 6\nALPHA = 1\nnx = 2000\nxx = np.linspace(-6+1E-14,6-1E-14,nx)\nA_up = np.zeros(nx)\nA_down = np.zeros(nx)\nAlia = np.zeros(nx)\nAlia2 = np.zeros(nx)\nstep = 600\na = 0\nb = 1\nya = 0\n\nfor i in range(0,nx):\n x = xx[i]\n #x = xx[i] % 2 - 1 # ETA mod 2 -1\n u, y = rk4(c_x, a, ya, b, step)\n A_up[i] = 6*y[step]\n\nfor i in range(0,nx):\n #x = xx[i]\n x = xx[i] % 2 - 1 # ETA mod 2 -1\n u, y = rk4(c_x, a, ya, b, step)\n A_down[i] = 6*y[step]\n\nfor i in range(0,nx):\n Alia[i] = np.abs(A_up[i]/A_down[i])\n\nplt.subplot(211)\nplt.plot(np.log10(Alia))\n\nxx = np.linspace(-1+1E-14,1-1E-14,nx)\nfor i in range(0,nx):\n ETA = xx[i]\n ETA_0 = ETA % 2 - 1 # ETA mod 2 -1\n temp_up = Schwab_grid(ALPHA, IM, ETA)/((1 - ETA **2)**ALPHA)\n temp_down = Schwab_grid(ALPHA, IM, ETA_0)/((1 - ETA_0 **2)**ALPHA)\n Alia2[i] = np.abs(temp_up/temp_down)\n\nplt.subplot(212)\nplt.plot(np.log10(Alia2))\nplt.show()\n","sub_path":"Schwab_aliasing_ratio.py","file_name":"Schwab_aliasing_ratio.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"375097065","text":"\"\"\"Support for binary sensors to display Proxmox VE data.\"\"\"\nimport homeassistant.components.proxmox as proxmox\nfrom homeassistant.components.binary_sensor import BinarySensorDevice\nfrom homeassistant.const import ATTR_ATTRIBUTION\n\nDEVICE_CLASS = 'connectivity'\nATTRIBUTION = 'Data provided by Proxmox'\n\n\nasync def async_setup_platform(\n hass, config, async_add_entities, discovery_info=None):\n \"\"\"Set up Proxmox VE binary sensor.\"\"\"\n nodes = hass.data[proxmox.DATA_PROXMOX_NODES]\n sensors = []\n attributes = {\n 'status': 'status',\n 'vcpu_count': 'cpus',\n 'mem_used': 'mem',\n 'max_memory': 'maxmem',\n 'disk_used': 'disk',\n 'max_disk': 'maxdisk'\n }\n\n for node_name in nodes.keys():\n item = nodes[node_name]\n if 'type' not in item or item['type'] != 'node':\n sensor = PXMXBinarySensor(hass, node_name, item, attributes)\n sensors.append(sensor)\n\n async_add_entities(sensors)\n\n\nclass PXMXBinarySensor(BinarySensorDevice):\n \"\"\"Define a binary sensor for Proxmox VE VM/Container state.\"\"\"\n\n def __init__(self, hass, node_name, item, attributes):\n \"\"\"Initialize Proxmox VE binary sensor.\"\"\"\n self._hass = hass\n self._node_name = node_name\n self._is_available = False\n self._state = None\n self._attributes = attributes\n self._vm_id = item['vmid']\n self._vm_name = item['name']\n self._item = item\n self._unique_id = proxmox.DOMAIN + 'st' + item['vmid']\n\n @property\n def unique_id(self) -> str:\n \"\"\"Return a unique ID.\"\"\"\n return self._unique_id\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return '{} ({})'.format('Status', self._node_name)\n\n @property\n def is_on(self):\n \"\"\"Return true if sensor is on.\"\"\"\n return self._state\n\n @property\n def available(self):\n \"\"\"Return True if sensor is available.\"\"\"\n return self._is_available\n\n @property\n def device_class(self) -> str:\n \"\"\"Return the class of this device.\"\"\"\n return DEVICE_CLASS\n\n @property\n def state_attributes(self):\n \"\"\"Return state attributes of the vm.\"\"\"\n attributes = {}\n for key in self._attributes.keys():\n attributes[key] = self._item[self._attributes[key]]\n return attributes\n\n @property\n def device_state_attributes(self):\n \"\"\"Return device attributes of the vm.\"\"\"\n return {\n 'vmid': self._vm_id,\n 'name': self._vm_name,\n ATTR_ATTRIBUTION: ATTRIBUTION\n }\n\n def update(self):\n \"\"\"Update the sensor.\"\"\"\n nodes = self._hass.data[proxmox.DATA_PROXMOX_NODES]\n node = nodes[self._node_name]\n self._item = node\n if not node:\n self._state = None\n self._is_available = False\n else:\n self._state = node['status'] == 'running'\n self._is_available = True\n","sub_path":"homeassistant/components/proxmox/binary_sensor.py","file_name":"binary_sensor.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"41699507","text":"#!/usr/bin/env python3\n'''Copyright [2017] '''\n\n\ndef main():\n text = input()\n names = text.split(',')\n\n for i, _ in enumerate(names):\n names[i] = names[i][1:-1]\n\n names = sorted(names)\n\n score_sum = 0\n for i, name in enumerate(names):\n for _, cha in enumerate(name):\n score_sum += (ord(cha) - ord('A') + 1) * (i + 1)\n\n print(score_sum)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"project_euler/02/022.py","file_name":"022.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"265361881","text":"\n\n# Tratamiento de datos\n# ==============================================================================\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport seaborn as sns\nimport os\n\n# Gráficos\n# ==============================================================================\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager\nfrom matplotlib import style\nstyle.use('ggplot') or plt.style.use('ggplot')\n\n# Preprocesado y modelado\n# ==============================================================================\nfrom sklearn import preprocessing # procesamiento de datos\nfrom pandas_profiling import ProfileReport\nfrom sklearn.decomposition import PCA\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import scale\nfrom sklearn.svm import SVR\n\n# Configuración warnings\n# ==============================================================================\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#%% importamos archivos de excel y csv y los convertimos en df\n\n\nos.chdir('/Users/milleralexanderquirogacampos/OneDrive - Universidad Sergio Arboleda/4_TAMDML/Clase6/')\ncwd=os.getcwd() #Asigna la variable cwd el directorio de trabajo\n\ndatos = pd.read_csv('Position_Salaries.csv')\n\ndatos.describe()\n\nprint(datos.head(5))\nprint(datos.tail(5))\n\nprint(datos.columns)\n\n\n#Suport Vector Regresion\n\n#%%\n\nX = datos.iloc[:,1:-1].values\ny = datos.iloc[:,-1].values\n\nX\ny\n\n#Cambiar las dimensiones de y de una dimensión a 2 dimensiones\ny = y.reshape(len(y),1)\n\ny\n\n#Estandarizamos las variables\nsc_X = StandardScaler()\nsc_y = StandardScaler()\n\nX = sc_X.fit_transform(X)\ny = sc_X.fit_transform(y)\n\nX\ny\n\n\nregressor = SVR(kernel='rbf')\nregressor.fit(X,y)\n\n#Si hay errores\nregressor.fit(X,y.ravel())\n\n#finalizamos todo.., ahora hacemos la predicción\n\n\n#supongamos que hay un argumento de 6,5 millones\nregressor.predict([[6.5]])\n#realizamos la transformación inversa. - \nsc_y.inverse_transform(regressor.predict(sc_X.transform([[6.5]])))\n\n#Grafica de Dispersión\nplt.scatter(sc_X.inverse_transform(X), sc_y.inverse_transform(y), color = 'red')\nplt.plot(sc_X.inverse_transform(X), sc_y.inverse_transform(regressor.predict(X)), color = 'blue')\nplt.title('uju')\nplt.xlabel('Position Level')\nplt.ylabel('Salary')\nplt.grid()\nplt.show()\n\n#%% - Regresión polinomial\n\nX_p = datos.iloc[:,1:-1].values\ny_p = datos.iloc[:,-1].values\n\nX_p\ny_p\n\n#Cambiar las dimensiones de y de una dimensión a 2 dimensiones\ny_p = y_p.reshape(len(y_p),1)\n\ny_p\n\n#Graficar los datos x_p y y_p\nplt.scatter(X_p, y_p)\nplt.grid()\nplt.show()\n\nfrom sklearn.model_selection import train_test_split\n\n#separo los datos de train en entrenamiento y prueba para probar los algoritmos\nX_train_p, X_test_p, y_train_p, y_test_p = train_test_split(X_p, y_p, test_size = 0.2)\n\n#Se agregan las características polinomiales de\nfrom sklearn.preprocessing import PolynomialFeatures\n\n#Se define el grado del polinomio, se puede empezar desde 2 y luego subir hasta ver el ajuste\n#polig_reg = PolynomialFeatures(degree = 2)\npolig_reg = PolynomialFeatures(degree = 2)\n\n\n#se transforma las características existentes en características de mayor grado\nX_train_poli = polig_reg.fit_transform(X_train_p)\nX_test_poli = polig_reg.fit_transform(X_test_p)\n\nfrom sklearn import datasets, linear_model\n#Defino el algoritmo a utilizar\npr = linear_model.LinearRegression()\n\n#Entrenamos el modelo\npr.fit(X_train_poli, y_train_p)\n\n#realizo una predicción\nY_pred_pr = pr.predict(X_test_poli)\n\n#Graficamos los datos junto con modelo\nplt.scatter(X_test_p, y_test_p)\nplt.plot(X_test_p, Y_pred_pr, color = 'red', linewidth=3)\nplt.grid()\nplt.show()\n\n\n#Calculamos los coeficientes del polinomio\nprint()\nprint('Datos del Modelo REGRESIÓN POLINOMIAL')\nprint()\n\nprint('Valor de la pendiente o del cofeiciente a :')\nprint(pr.coef_)\n\nprint('Valor de la intesección o del cofeiciente b :')\nprint(pr.intercept_)\n\n#Calculamos la precisión del algoritmo - r^2\n\nprint('Precision del modelo')\nprint(pr.score(X_train_poli, y_train_p)*100)\n\n\n#Se obtiene una precisión del 93.74%, esto indica que este modelo se ajusta para el \n\n\n\n\n","sub_path":"Jhon Gutierrez/Mineria de datos - semestre 4/Taller 7/Sup_Vect_Reg.py","file_name":"Sup_Vect_Reg.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"328082682","text":"#-*- coding: utf-8 -*-\nimport numpy as np\nimport json\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import IncrementalPCA\nimport seaborn as sns\n# 支持中文\n\nimport matplotlib as mpl\n# mpl.rcParams['font.sans-serif'] = ['STHeiti\\ Medium']\n# mpl.rcParams['font.serif'] = ['STHeiti\\ Medium']\n# mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串\n\n\nprovince = []\n# province=['河北','山西','内蒙古','辽宁','吉林','黑龙江','江苏','浙江','安徽','福建','江西','山东','河南','湖北','湖南','广东','广西','海南','四川','贵州','云南','西藏','陕西','甘肃','青海','宁夏','新疆']\n\n\n\ndef scatter(x, colors):\n palette = np.array(sns.color_palette(\"hls\", 40))\n \n f = plt.figure(figsize=(8, 8))\n ax = plt.subplot(aspect='equal')\n sc = ax.scatter(x[:,0], x[:,1], lw=0, s=40,\n c=palette[colors.astype(np.int)])\n # sc = ax.scatter(x[:,0], x[:,1], lw=0, s=40,\n # c=colors)\n plt.xlim(-25, 25)\n plt.ylim(-25, 25)\n ax.axis('off')\n ax.axis('tight')\n\n\n\nfp = open(\"all_city_ans_str\", \"r\")\nsource_lines = \"\"\ntry:\n source_lines = fp.read()\nfinally:\n fp.close()\ntrain_date = json.loads(source_lines)\n\n\nfp = open(\"province_list.log\", \"r\")\nsource_lines = \"\"\ntry:\n source_lines = fp.read()\nfinally:\n fp.close()\ncity_name = json.loads(source_lines)\n\n\n\n# train_date = []\n# load_data()\n# print (train_date)\n\n# X = np.array([[-1, -1,2], [-2, -1,3], [-3, -2,4], [1, 1,5], [2, 1,6], [3, 2,7]])\n\nX = np.array(train_date)\n# ipca = IncrementalPCA(n_components=1, batch_size=300)\n# kmeans = KMeans(n_clusters=5, random_state=0).fit_predict(X)\nkmeans_model = KMeans(n_clusters=20, max_iter=3000, random_state=9).fit(X)\nlabels = kmeans_model.labels_\n\n\n\n # 数组输出\nzu = {}\ntmp_count = 0\nfor i in labels:\n if str(i) not in zu:\n zu[str(i)] = []\n if city_name[tmp_count] in province:\n tmp_count +=1\n continue\n zu[str(i)].append(city_name[tmp_count])\n tmp_count +=1\n\n\n\n# show_str = json.dumps( zu )\n# print (show_str)\nfor i in range(0,20):\n i = str(i)\n print (i+\"\\n\",end=' ')\n for j in zu[i]:\n print (\"\\t\"+j+\"\\t\",end=' ')\n print (\"\\n\",end=' ')\n\n\n\n\n\n# digits_proj = TSNE().fit_transform(X) #将X降到2维\n# scatter(digits_proj, labels)\n# tmp_count = 0\n# for a,b in digits_proj:\n# plt.text(a,b+0.1,city_name[tmp_count]+\"_\"+str(labels[tmp_count]),ha = 'center',va = 'bottom',fontsize=7)\n# tmp_count+=1\n# plt.show()\n\n\n","sub_path":"province/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"548116851","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/wmpy_util/file_util.py\n# Compiled at: 2020-01-14 23:28:27\n# Size of source mod 2**32: 13397 bytes\n\"\"\"\n@Author : WeiWang Zhang\n@Time : 2019-09-19 14:33\n@File : file_util.py\n@Desc : 文件操作工具类\n\"\"\"\nimport os, sys, random, shutil\nfrom wmpy_util.time_util import timer\nimport time, re\nfrom wmpy_util import sys_util as su\n\nclass FilePrinter:\n __stdout_write__ = sys.stdout.write\n\n def __init__(self, file_path, mode='w', console=False, **kwargs):\n \"\"\"\n 将print形式输出的文字输出到文件中\n -------使用方式-------\n with(FilePrinter(file_path, \"w\")):\n print(\"Hello World\")\n ---------------------\n :param file_path:\n :param mode:\n :param console: 是否同时输出文件和console\n \"\"\"\n file_path = os.path.abspath(file_path)\n self.file_path = file_path\n check_dir((os.path.dirname(file_path)), create=True)\n self.mode = mode\n self.fopen = None\n self.console = console\n\n def __enter__(self):\n sys.stdout.write = self.file_write\n self.fopen = open((self.file_path), mode=(self.mode), encoding='utf-8')\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n sys.stdout.write = FilePrinter.__stdout_write__\n self.fopen.flush()\n self.fopen.close()\n\n def file_write(self, *args, **kwargs):\n arg_list = list(args)\n for index, arg in enumerate(arg_list):\n if not isinstance(arg, str):\n arg_list[index] = str(arg)\n\n message = ' '.join(arg_list)\n self.fopen.write(message)\n if self.console:\n (FilePrinter.__stdout_write__)(*args, **kwargs)\n\n\ndef get_temp_path(relative_folder=None):\n \"\"\"\n 获取一个临时文件目录\n :param relative_folder: 临时路径下的,相对路径\n :return:\n \"\"\"\n platform = sys.platform\n if platform == 'darwin':\n temp_path = os.path.join(os.path.expanduser('~'), 'temp')\n else:\n if platform.startswith('win'):\n raise NotImplementedError('windows 临时路径待定')\n else:\n if platform == 'linux':\n temp_path = os.path.join(os.path.expanduser('~'), 'temp')\n else:\n raise ValueError('未知系统平台:%s' % platform)\n check_dir(temp_path, create=True)\n if relative_folder is not None:\n temp_path = os.path.join(temp_path, relative_folder)\n check_dir(temp_path, create=True)\n print('Get tmp path:%s' % os.path.abspath(temp_path))\n return temp_path\n\n\ndef get_file_name(file_path):\n \"\"\"\n 返回不带路径及拓展名的文件名\n :param file_path:\n :return:\n \"\"\"\n file_name = os.path.split(file_path)[1]\n file_name = os.path.splitext(file_name)[0]\n return file_name\n\n\ndef read_file(file_path):\n \"\"\"\n 读取文件\n :param file_path:\n :return:\n \"\"\"\n fopen = open(file_path, 'r')\n result = ''\n for eachline in fopen:\n result += eachline\n\n return result\n\n\ndef read_file_lines(file_path):\n \"\"\"\n 按行读取文件\n :param file_path:\n :return:\n \"\"\"\n fopen = open(file_path, 'r', encoding='UTF-8')\n for eachline in fopen:\n yield eachline\n\n fopen.close()\n\n\ndef write_to_file(file_path, data, encoding='utf-8', mode='w'):\n \"\"\"\n 往文件里写入信息\n :param filename:\n :param data:\n :return:\n \"\"\"\n path = os.path.dirname(file_path)\n if not os.path.exists(path):\n os.mkdir(path)\n fopen = open(file_path, mode=mode, encoding=encoding)\n fopen.write(data)\n fopen.flush()\n fopen.close()\n\n\ndef write_array_to_file(file_path, array_data, split='\\n', encoding='utf-8'):\n \"\"\"\n 往文件里写入信息\n :param filename:\n :param array_data:\n :return:\n \"\"\"\n path = os.path.dirname(file_path)\n if not os.path.exists(path):\n os.mkdir(path)\n fopen = open(file_path, 'w', encoding=encoding)\n for text in array_data:\n fopen.write(text + split)\n\n fopen.flush()\n fopen.close()\n\n\ndef get_img_from_url(url, path, file_name):\n \"\"\"\n 从url上下载图片\n :param url:\n :param path:\n :param file_name:\n :return:\n \"\"\"\n pass\n\n\ndef filter_image(files):\n \"\"\"\n 图片文件过滤器\n :param files:\n :return:\n \"\"\"\n if not files:\n return\n for file in files:\n if is_image_file(file):\n yield file\n\n\ndef get_files(paths, filter_func=filter_image):\n \"\"\"\n 将目录下的所有文件返回为一个可迭代对象\n :param paths: 可以是一个路径列表,或是单条路径\n :param filter_func: 过滤函数接,接收一个文件名的list,返回另一个list或\n :return:\n \"\"\"\n if isinstance(paths, str):\n paths = [\n paths]\n root_set = set()\n for path in paths:\n for root, dirs, files in os.walk(path):\n if root in root_set:\n continue\n else:\n root_set.add(root)\n if callable(filter_func):\n if files is not None:\n files = filter_func(files)\n for file in files:\n yield os.path.join(root, file)\n\n\ndef is_image_file(file_name):\n if file_name is None:\n return False\n else:\n ext = file_name.split('.')[(-1)]\n if ext in IMG_FILE_EX:\n return True\n return False\n\n\ndef check_file(file_path):\n if os.path.isfile(file_path):\n return True\n else:\n print('file not found path=%s' % str(file_path))\n return False\n\n\ndef check_dir(dir, create=False):\n if dir is None:\n return False\n else:\n if os.path.exists(dir):\n return True\n if create:\n os.mkdir(dir)\n return os.path.exists(dir)\n\n\ndef clear_path_file(path):\n \"\"\"\n 删除该目录下的所有文件\n :param path:\n :return:\n \"\"\"\n if not os.path.isdir(path):\n return\n count = 0\n files = os.listdir(path)\n for file in files:\n file_path = os.path.join(path, file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n count += 1\n\n print('Delete %d files under: %s' % (count, path))\n\n\ndef clear_path(path):\n \"\"\"\n 删除该目录下的所有文件及路径\n :param path:\n :return:\n \"\"\"\n del_file_num, del_dir_num = __clear_path_iter(path, 0, 0)\n print('Delete %d files, %d dirs under: %s' % (del_file_num, del_dir_num, path))\n\n\ndef __clear_path_iter(path, del_file_num, del_dir_num):\n \"\"\"\n 清除目录的递归函数\n :param path: 待清除的目标路径\n :param del_file_num: 已经清除的文件数量\n :param del_dir_num: 已经清除的路径数量\n :return:\n \"\"\"\n if not os.path.isdir(path):\n return (del_file_num, del_dir_num)\n else:\n files = os.listdir(path)\n files.sort(reverse=True)\n for file in files:\n file_path = os.path.join(path, file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n del_file_num += 1\n else:\n if os.path.isdir(file_path):\n del_file_num, del_dir_num = __clear_path_iter(file_path, del_file_num, del_dir_num)\n try:\n os.removedirs(file_path)\n except FileNotFoundError as error:\n pass\n\n del_dir_num += 1\n\n return (\n del_file_num, del_dir_num)\n\n\ndef part_copy(from_path, to_path, ratio=1, sample_ext=('jpg', 'png', 'jpeg')):\n \"\"\"\n 按概率复制部分文件到指定路径,\n 应用场景:线上数据集过大,想在本机做简单测试,奈何无法完成copy数据集合,智能先用脚本随机挑选出十分之一的数据\n 然后搬移到线下做测试。\n :param from_path:\n :param to_path:\n :param ratio:\n :param sample_ext: 进行采样的文件拓展名,不在此列表里的文件则全部保留\n :return:\n \"\"\"\n sample_ext = [ext.lower() for ext in sample_ext]\n random.seed = time.time()\n ratio = float(ratio)\n from_abs = os.path.abspath(from_path)\n to_abs = os.path.abspath(to_path)\n check_dir(to_path, True)\n count = 0\n if not os.path.isdir(to_abs):\n raise ValueError('path: %s not a illegal' % to_abs)\n for root, dirs, files in os.walk(from_path):\n for directory in dirs:\n to_dir = replace_head_path(os.path.join(root, directory), from_abs, to_abs)\n check_dir(to_dir, create=True)\n\n for file in files:\n extend = os.path.splitext(file)[1]\n if extend.lower() in sample_ext:\n rand = random.random()\n else:\n rand = -1\n if rand < ratio:\n from_file = os.path.abspath(os.path.join(root, file))\n to_file = replace_head_path(from_file, from_abs, to_abs)\n shutil.copy(from_file, to_file)\n if (count + 1) % 100 == 0:\n print('Copy %d files' % count)\n count += 1\n\n\n@timer(combine=True, batch=100)\ndef replace_head_path(path, old, new):\n \"\"\"\n 将地址的前缀替换\n FIXME 考虑之后替换成更高效的算法\n :param path:\n :param old:\n :param new:\n :return:\n \"\"\"\n path = os.path.abspath(path)\n return path.replace(old, new)\n\n\ndef copy_file(file_src, to_file):\n to_path = os.path.split(to_file)[0]\n if not os.path.exists(to_path):\n os.makedirs(to_path)\n shutil.copy(file_src, to_file)\n\n\ndef compare_dir_based_on_name(dir1, dir2):\n \"\"\"\n 基于名称比较两个路径下的文件\n :param dir1:\n :param dir2:\n :return:\n \"\"\"\n dir_files1 = os.listdir(dir1)\n dir_files2 = os.listdir(dir2)\n if not len(dir_files1) == len(dir_files2):\n return False\n else:\n dir_files1.sort(key=(lambda x: str(x)))\n dir_files2.sort(key=(lambda x: str(x)))\n return dir_files1 == dir_files2\n\n\nIMG_FILE_EX = [\n 'jpeg', 'jpg', 'png', 'bmp', 'jif']\n\ndef turn_py2_to_py3(dirname):\n for root, dirs, files in os.walk(dirname):\n for file in files:\n if not file.endswith('.py'):\n pass\n else:\n file_path = os.path.join(root, file)\n with open(file_path, 'r') as (fp):\n contents, flag = _scan_file(fp)\n new_file_path = file_path\n if flag:\n print('Change file {}'.format(new_file_path))\n write_array_to_file(new_file_path, contents)\n\n\ndef _scan_file(fp):\n content_list = list()\n change = False\n while True:\n line = fp.readline()\n if not line:\n break\n line, tmp = _print_transform(line)\n change |= tmp\n line, tmp = _xrange_transform(line)\n change |= tmp\n content_list.append(line.rstrip())\n\n return (\n content_list, change)\n\n\ndef _print_transform(line):\n change = False\n if line.strip().startswith('print'):\n index = line.find('print')\n rest = line[index + 5:]\n if not rest.strip().startswith('(') or not rest.strip().endswith(')'):\n line = line[:index + 5] + '(' + line[index + 5:].strip() + ')' + '\\n'\n change = True\n return (\n line, change)\n\n\nxrange_re = '(? 0)\n\n\n@timer\ndef count_line(file):\n count = 0\n for line in read_file_lines(file):\n count += 1\n\n return count\n\n\n@timer\ndef count_line_faster(file_path):\n if not os.path.isfile(file_path):\n raise FileNotFoundError(file_path)\n cmd = 'wc -l {:s}'.format(os.path.abspath(file_path))\n line = su.excute(cmd)\n number = line.strip().split(' ')[0]\n return int(number)\n\n\n@timer\ndef split_file_to(source_file, start_line, end_line, target_file):\n \"\"\"\n 将文件中间的若干行分到另一个文件\n :param source_file:\n :param start_line: include\n :param end_line: include\n :param target_file:\n :return:\n \"\"\"\n assert os.path.isfile(source_file)\n source_file = os.path.abspath(source_file)\n target_file = os.path.abspath(target_file)\n lines = end_line - start_line + 1\n cmd = 'head -n {:d} {:s}|tail -n {:d} >> {:s}'.format(end_line, source_file, lines, target_file)\n print(cmd)\n ret = su.excute(cmd)\n return ret\n\n\nif __name__ == '__main__':\n import sys\n path = os.path.abspath('.')\n argv = sys.argv\n if len(argv) > 1:\n func = argv[1]\n args = argv[2:]\n eval_value = '%s(*args)' % func\n print('%s going to execute' % eval_value)\n print('Args = %s' % args)\n eval('%s(*args)' % func)\n else:\n turn_py2_to_py3('./test')","sub_path":"pycfiles/bloodstone_core-0.0.5-py3.6/file_util.cpython-36.py","file_name":"file_util.cpython-36.py","file_ext":"py","file_size_in_byte":13086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"420804318","text":"from json import dumps\n\nfrom common.json import loadb\nfrom common.test_utils import PinpointTestCase\n\nclass TestUserFeaturesView(PinpointTestCase):\n \"\"\"\n Tests relating to the relationship view between a user and its features.\n \"\"\"\n\n def test_getting_user_features(self):\n \"\"\"\n Test that using a valid user ID to get a user's created features returns a\n valid list of features as a response.\n \"\"\"\n\n response = self.client.get('/users/{}/features/'.format(self.USER_ID))\n response_body = loadb(response.content)\n\n self.assertEqual(response.status_code, 200)\n self.assert_feature_list_correctness(response_body)\n\n for feature in response_body['data']:\n relationships = feature['relationships']\n self.assertEqual(relationships['location']['data']['id'], self.LOCATION_ID)\n self.assertEqual(relationships['created-by']['data']['id'], self.USER_ID)\n\n def test_getting_missing_user_features(self):\n \"\"\"\n Test that using an invalid user ID to get a non-existent user returns a 404\n status code.\n \"\"\"\n\n response = self.client.get('/users/{}/features/'.format('invalid'))\n response_body = loadb(response.content)\n\n self.assertEqual(response.status_code, 404)\n","sub_path":"apps/users/tests/integration/test_user_features_view.py","file_name":"test_user_features_view.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"458010924","text":"def test_large_delete_related(self):\n TEST_SIZE = 2000\n s = S.objects.create(r=R.objects.create())\n for i in range(TEST_SIZE):\n T.objects.create(s=s)\n batch_size = max(connection.ops.bulk_batch_size(['pk'], range(TEST_SIZE)), 1)\n expected_num_queries = ((ceil((TEST_SIZE // batch_size)) + ceil((TEST_SIZE // GET_ITERATOR_CHUNK_SIZE))) + 2)\n self.assertNumQueries(expected_num_queries, s.delete)\n self.assertFalse(S.objects.exists())\n self.assertFalse(T.objects.exists())","sub_path":"Data Set/bug-fixing-5/3fb1ad9505fa28ec9c89039fbba40f6ebea8bf8e--bug.py","file_name":"3fb1ad9505fa28ec9c89039fbba40f6ebea8bf8e--bug.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"446327405","text":"import json\n\n\ndef lambda_handler(event, context):\n food_times = {\n \"/breakfast\": {\"time\": \"9 AM\", \"menu\": [\"poha\", \"chai\"]},\n \"/brunch\": {\"time\": \"12 PM\", \"menu\": [\"fancy stuff\"]},\n \"/lunch\": {\"time\": \"1:30 PM\", \"menu\": [\"rajma\", \"chawal\"]},\n \"/supper\": {\"time\": \"5:30 PM\", \"menu\": [\"pakoday\", \"chai\"]},\n \"/dinner\": {\"time\": \"8 PM\", \"menu\": [\"besan chilla\", \"chutney\"]},\n }\n\n result = food_times.get(event[\"path\"], \"not_found\")\n\n status_code = 200\n if result == \"not_found\":\n status_code = 404\n\n response = {\"body\": json.dumps({event[\"path\"]: result}), \"statusCode\": str(status_code)}\n print(json.dumps(response, indent=2, default=str))\n return response\n\n\nif __name__ == \"__main__\":\n output = lambda_handler(None, None)\n print(output[\"body\"])\n","sub_path":"app_code/lambda.py","file_name":"lambda.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"89385211","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 26 20:47:28 2020\r\n\r\n@author: 6794c\r\n\"\"\"\r\nimport pickle\r\nimport numpy as np\r\n\r\n# OUTER_TURRET='-', 'BOT_LANE-', 'BOT_LANE-MID_LANE',\r\n# 'BOT_LANE-MID_LANE-TOP_LANE', 'BOT_LANE-TOP_LANE', 'MID_LANE-',\r\n# 'MID_LANE-TOP_LANE', 'TOP_LANE-'\r\n# INNER_TURRET='-', 'BOT_LANE-', 'BOT_LANE-MID_LANE',\r\n# 'BOT_LANE-MID_LANE-TOP_LANE', 'BOT_LANE-TOP_LANE', 'MID_LANE-',\r\n# 'MID_LANE-TOP_LANE', 'TOP_LANE-'\r\n# BASE_TURRET='-', 'BOT_LANE-', 'BOT_LANE-MID_LANE',\r\n# 'BOT_LANE-MID_LANE-TOP_LANE', 'BOT_LANE-TOP_LANE', 'MID_LANE-',\r\n# 'MID_LANE-TOP_LANE', 'TOP_LANE-'\r\n# UNDEFINED(INHIB)_TURRET='-', 'BOT_LANE-', 'BOT_LANE-MID_LANE',\r\n# 'BOT_LANE-MID_LANE-TOP_LANE', 'BOT_LANE-TOP_LANE', 'MID_LANE-',\r\n# 'MID_LANE-TOP_LANE', 'TOP_LANE-'\r\n# NEXUS_TURRET = '-', '-MID_LANE-', '-MID_LANE-MID_LANE-'\r\n\r\n\r\n\r\nclass ObjectAnalysis:\r\n def __init__(self, first_object_model=None, object_kills_model=None, object_killsAnd_first_model=None):\r\n # ObjectAnalysis.py in kugg-web/menu/\r\n self.model_dic_path = \"kugg/static/analysis_models/\"\r\n self.first_object_model=None\r\n self.object_kills_model=None\r\n self.object_killsAnd_first_model=None\r\n \r\n \r\n self.object_analysismodel=None\r\n self.data_encoder=None\r\n self.update_model(\"first_object_model\")\r\n self.update_model(\"object_kills_model\")\r\n self.update_model(\"object_killsAnd_first_model\")\r\n #self.update_model(\"tmp_modelupdate\")\r\n self.update_model(\"object_modelupdate\")\r\n #self.update_mdoel('data_encoder')\r\n \r\n # parameter = pickle file\r\n def update_model(self, object_model):\r\n if object_model == \"first_object_model\":\r\n model_path = self.model_dic_path+\"dt_model1.pkl\"\r\n with open(model_path, 'rb') as file:\r\n self.first_object_model = pickle.load(file)\r\n return 1\r\n \r\n elif object_model == \"object_kills_model\":\r\n model_path = self.model_dic_path+\"dt_model2.pkl\"\r\n with open(model_path, 'rb') as file:\r\n self.object_kills_model = pickle.load(file)\r\n return 2\r\n \r\n elif object_model == \"object_killsAnd_first_model\":\r\n model_path = self.model_dic_path+\"dt_model3.pkl\"\r\n with open(model_path, 'rb') as file:\r\n self.object_killsAnd_first_model = pickle.load(file)\r\n return 3\r\n\r\n elif object_model == \"object_modelupdate\":\r\n model_path = self.model_dic_path+'second_object_dtmodel.pickle'\r\n with open(model_path, 'rb') as file:\r\n self.object_analysismodel = pickle.load(file)\r\n return 4\r\n \r\n elif object_model == 'data_encoder':\r\n model_path = self.model_dic_path+'categorical_data_encoder.pickle'\r\n with open(model_path, 'rb') as file:\r\n self.data_encoder = pickle.load(file)\r\n return 5\r\n \r\n else:\r\n print(\"wrong input\")\r\n return -1\r\n \r\n # def tmp_model_predict(self, teamId, baronKills, riftHeraldKills, OUTER_TURRET,\r\n # INNER_TURRET, BASE_TURRET, UNDEFINED_TURRET, NEXUS_TURRET,\r\n # AIR_DRAGON, WATER_DRAGON, EARTH_DRAGON, FIRE_DRAGON, ELDER_DRAGON):\r\n \r\n # predict_array = self.tmp_modelupdate.predict_proba(\r\n # np.array([teamId, baronKills, riftHeraldKills, OUTER_TURRET, INNER_TURRET,\r\n # BASE_TURRET, UNDEFINED_TURRET, NEXUS_TURRET,\r\n # AIR_DRAGON, WATER_DRAGON, EARTH_DRAGON, FIRE_DRAGON, ELDER_DRAGON]).reshape(1, -1))\r\n \r\n # return predict_array[0][1]\r\n\r\n def oneteam_model_predict(self, teamId, baronKills, riftHeraldKills, OUTER_TURRET,\r\n INNER_TURRET, BASE_TURRET, UNDEFINED_TURRET, NEXUS_TURRET,\r\n AIR_DRAGON, WATER_DRAGON, EARTH_DRAGON, FIRE_DRAGON, ELDER_DRAGON):\r\n \r\n predict_array = self.object_analysismodel.predict_proba(\r\n np.array([teamId, baronKills, riftHeraldKills, OUTER_TURRET, INNER_TURRET,\r\n BASE_TURRET, UNDEFINED_TURRET, NEXUS_TURRET,\r\n AIR_DRAGON, WATER_DRAGON, EARTH_DRAGON, FIRE_DRAGON, ELDER_DRAGON]).reshape(1, -1))\r\n \r\n return predict_array[0][1]\r\n \r\n def twoteam_model_predict(self, BteamId, BbaronKills, BriftHeraldKills, BOUTER_TURRET,\r\n BINNER_TURRET, BBASE_TURRET, BUNDEFINED_TURRET, BNEXUS_TURRET,\r\n BAIR_DRAGON, BWATER_DRAGON, BEARTH_DRAGON, BFIRE_DRAGON, BELDER_DRAGON,\r\n RteamId, RbaronKills, RriftHeraldKills, ROUTER_TURRET,\r\n RINNER_TURRET, RBASE_TURRET, RUNDEFINED_TURRET, RNEXUS_TURRET,\r\n RAIR_DRAGON, RWATER_DRAGON, REARTH_DRAGON, RFIRE_DRAGON, RELDER_DRAGON):\r\n \r\n Bpredict_array = self.object_analysismodel.predict_proba(\r\n np.array([BteamId, BbaronKills, BriftHeraldKills, BOUTER_TURRET, BINNER_TURRET,\r\n BBASE_TURRET, BUNDEFINED_TURRET, BNEXUS_TURRET, BAIR_DRAGON,\r\n BWATER_DRAGON, BEARTH_DRAGON, BFIRE_DRAGON, BELDER_DRAGON]).reshape(1,-1))\r\n Rpredict_array = self.object_analysismodel.predict_proba(\r\n np.array([RteamId, RbaronKills, RriftHeraldKills, ROUTER_TURRET, RINNER_TURRET,\r\n RBASE_TURRET, RUNDEFINED_TURRET, RNEXUS_TURRET, RAIR_DRAGON,\r\n RWATER_DRAGON, REARTH_DRAGON, RFIRE_DRAGON, RELDER_DRAGON]).reshape(1, -1))\r\n \r\n total_prob = Bpredict_array[0][1]+Rpredict_array[0][1]\r\n \r\n # return blue team win probability, red team win probability\r\n return Bpredict_array[0][1]/total_prob, Rpredict_array[0][1]/total_prob\r\n \r\n def first_object_predict(self, fdragon, fharry, fblood, ftower,\r\n fbaron, finhib):\r\n predict_array = self.first_object_model.predict_proba(\r\n np.array([fblood, finhib, ftower, fharry, fdragon, fbaron]).reshape(1, -1))\r\n \r\n # ex. 0.641095145921092....\r\n return predict_array[0][1]\r\n \r\n def object_kills_predict(self, dragonkills, baronkills, inhibkills,\r\n harrykills, towerkills):\r\n predict_array = self.object_kills_model.predict_proba(\r\n np.array([harrykills, inhibkills, towerkills, baronkills,\r\n dragonkills]).reshape(1, -1))\r\n \r\n # ex. 0.124412512451231....\r\n return predict_array[0][1]\r\n \r\n def object_killsAnd_first_predict(self, fdragon, fharry, fblood, ftower, fbaron, \r\n finhib, dragonkills, baronkills, inhibkills,\r\n harrykills, towerkills):\r\n predict_array = self.object_killsAnd_first_model.predict_proba(\r\n np.array([harrykills, fharry, inhibkills, fblood, towerkills, dragonkills, baronkills,\r\n finhib, fdragon, fbaron, ftower]).reshape(1, -1))\r\n \r\n return predict_array[0][1]","sub_path":"KUGG_Django/kugg/object_analysis_module.py","file_name":"object_analysis_module.py","file_ext":"py","file_size_in_byte":7282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"24037261","text":"import json\nimport os\nimport sqlite3\nfrom pathlib import Path\n\nimport numpy as np\nimport requests\nfrom flask import (\n Flask,\n g,\n jsonify,\n redirect,\n render_template,\n request,\n session,\n url_for,\n)\nfrom flask_dropzone import Dropzone\nfrom orthanc_rest_client import Orthanc\n\nimport orthanc.wrist as wrist\nfrom infer.convert import convert\nfrom infer.image import retrieve, save\nfrom infer.results import list\nfrom infer.db import load, store, load_by_series_uid\n\nDATABASE = \"wrist.db\"\n\napp = Flask(__name__, instance_relative_config=True)\napp.config.from_object(\"infer.default_config\")\napp.config.from_pyfile(\"config.cfg\")\nversion = app.config[\"VERSION\"] = \"0.0.1\"\n\napp.secret_key = b'_5#y2L\"F4Q8z\\n\\xec]/897'\napp.config.update(\n UPLOADED_PATH=\"./uploads\",\n # Flask-Dropzone config:\n DROPZONE_ALLOWED_FILE_TYPE=\"image\",\n DROPZONE_MAX_FILE_SIZE=3,\n DROPZONE_MAX_FILES=1,\n DROPZONE_REDIRECT_VIEW=\"example_view\",\n)\n\ndropzone = Dropzone(app)\n\n\northanc = Orthanc(\"http://localhost:8042\")\n\n\ndef get_db():\n db = getattr(g, \"_database\", None)\n if db is None:\n db = g._database = sqlite3.connect(DATABASE)\n return db\n\n\ndef init_db():\n with app.app_context():\n db = get_db()\n with app.open_resource(\"schema/schema.sql\", mode=\"r\") as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n\ninit_db()\n\n\n@app.teardown_appcontext\ndef close_connection(exception):\n db = getattr(g, \"_database\", None)\n if db is not None:\n db.close()\n\n\n@app.route(\"/\")\ndef MainDicomTags():\n r = wrist.find_wrist_studies(orthanc)\n return render_template(\"orthanc.html\", results=r)\n\n\n@app.route(\"/study\")\ndef s():\n study_id = request.args.get(\"id\", \"\")\n if not study_id:\n return 400, \"no study id given\"\n\n study, series = wrist.find_wrist_study(orthanc, study_id)\n accession_number = study[\"MainDicomTags\"][\"AccessionNumber\"]\n rows = load(get_db(), accession_number)\n for i in series:\n if i[\"MainDicomTags\"][\"Modality\"] == \"CR\":\n result = load_by_series_uid(\n get_db(), i[\"MainDicomTags\"][\"SeriesInstanceUID\"]\n )\n if not result:\n i[\"ml_fracture\"] = _run_inference(i)\n store(get_db(), study, i, i[\"ml_fracture\"])\n else:\n i[\"ml_fracture\"] = {\n \"hardplaster\": result[0][\"ml_fracture_hardplaster\"],\n \"view\": result[0][\"ml_fracture_view\"],\n \"fracture_probability\": result[0][\"ml_fracture_probability\"],\n }\n return render_template(\"study.html\", study=study, series=series)\n\n\ndef _run_inference(i):\n img_array = retrieve(i.get(\"Instances\")[0])\n data = {\"image\": img_array.tolist(), \"bla\": \"blub\"}\n r = requests.post(\"http://localhost:9556/inference\", json=data)\n return r.json()\n","sub_path":"infer/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"142053312","text":"import pytest\n\nfrom blockkit import MarkdownText, PlainText\nfrom blockkit.components import Component\nfrom blockkit.fields import StringField, TextField, ArrayField\n\n\ndef test_component_detects_all_fields():\n class NotField:\n pass\n\n class FakeComponent(Component):\n title = StringField()\n text = StringField()\n not_field = NotField()\n\n component = FakeComponent()\n assert list(component._fields.keys()) == [\"title\", \"text\"]\n\n\ndef test_component_with_exeeding_args_raises_exception():\n class FakeComponent(Component):\n title = StringField()\n\n with pytest.raises(IndexError):\n FakeComponent(\"test\", \"test\", \"test\")\n\n\ndef test_component_builds_fields(values):\n class ParentFakeComponent(Component):\n title = StringField()\n text = TextField()\n\n class FakeComponent(ParentFakeComponent):\n elements = ArrayField(PlainText)\n users = ArrayField(str)\n\n users = [\"U123456\", \"U654321\"]\n component = FakeComponent(\n values.title,\n MarkdownText(values.text),\n [PlainText(values.text) for _ in range(2)],\n users,\n )\n\n assert component.build() == {\n \"title\": values.title,\n \"text\": {\"type\": \"mrkdwn\", \"text\": values.text},\n \"elements\": [\n {\"type\": \"plain_text\", \"text\": values.text},\n {\"type\": \"plain_text\", \"text\": values.text},\n ],\n \"users\": users,\n }\n","sub_path":"tests/test_components.py","file_name":"test_components.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"462317688","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 18 13:41:18 2021\n\n@author: 20172458\n\"\"\"\n\nimport or_gym\nimport numpy as np\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.losses import MeanSquaredError\nfrom tensorflow.keras.initializers import RandomNormal\n\nfrom collections import deque\n\n# Load environment\nenv = or_gym.make('Knapsack-v2')\nenv.mask = False\nnp.random.seed(2021)\n\nprint(\"Action Space: {}\".format(env.action_space))\nprint(\"State space: {}\".format(env.observation_space))\n\n#___ PARAMETERS ___#\nTRAIN_EPSISODES = 10_000\nTEST_EPSISODES = 100\nLEARNING_RATE = 0.4 \nDISCOUNT_RATE = 0.9 \nMIN_REPLAY_SIZE = 250\nBATCH_SIZE = 100 # Number of items to be sampled\nFACTOR = 2 # How much one wants to punish or prize high rewards\nHIGH_PER = 10 # The high and low percentage of rewards in the replay memory\nMAX_EPSILON = 1 # You can't explore more than 100% of the time\nMIN_EPSILON = 0.01 # At a minimum, we'll always explore 1% of the time\nDECAY = 0.0005 # How fast the epsilon decays\n#_________________#\n\ndef agent(item_count = env.N):\n \"\"\" \n Requires the values of all the available items\n \"\"\"\n init = RandomNormal(mean=0.0, stddev=0.05, seed=10)\n model = Sequential()\n model.add(Dense(item_count * 3, activation=\"relu\", input_shape=(item_count,), kernel_initializer = init))\n model.add(Dense(item_count * 2, activation=\"relu\", kernel_initializer = init))\n model.add(Dense(item_count, activation=\"relu\", kernel_initializer = init))\n model.add(Dense(item_count, kernel_initializer = init))\n model.compile(Adam(1e-3), MeanSquaredError(), metrics=[\"accuracy\"])\n \n return model\n\ndef train(env, replay_memory, model, target_model, done):\n \"\"\"\n Train model with Belman equation\n \"\"\"\n len_replay = len(replay_memory)\n if len_replay < MIN_REPLAY_SIZE:\n return\n\n rewards = [transition[2] for transition in replay_memory] # Extract rewards from replay memory\n rewards.sort() # Sort the rewards list \n nr_items = int(len_replay / HIGH_PER) # Number of items in the 'HIGH_PER' range\n high_list = [ x * (((i * FACTOR) + nr_items) / nr_items) for x, i in zip(rewards[-nr_items:], range(nr_items))] # Apply factor to high rewards \n low_list = [ x * (i / nr_items) for x, i in zip(rewards[:nr_items], range(nr_items))] # Apply factor to low rewards\n rewards = low_list + rewards[nr_items:-nr_items] + high_list # Overwrite with the adjusted rewards list\n mini_batch_ind = np.random.choice(list(range(len(rewards))), BATCH_SIZE, p = [x/sum(rewards) for x in rewards]) # Sample the indices of observations\n # where the observations with high rewards are more likely sampled.\n mini_batch = [replay_memory[ind] for ind in mini_batch_ind] # Retrieve the observations with the given indices \n current_states = np.array([transition[0] for transition in mini_batch]) # Extract the observations from the mini_batch\n current_qs_list = model.predict(current_states) \n new_current_states = np.array([transition[3] for transition in mini_batch]) # Extract the new observation from the mini_batch\n future_qs_list = target_model.predict(new_current_states)\n\n X = []\n Y = []\n for index, (observation, action, reward, new_observation, done) in enumerate(mini_batch):\n if not done:\n max_future_q = reward + DISCOUNT_RATE * np.max(future_qs_list[index]) # Future Q value\n else:\n max_future_q = reward\n\n current_qs = current_qs_list[index]\n current_qs[action] = (1 - LEARNING_RATE) * current_qs[action] + LEARNING_RATE * max_future_q # Belman equation\n\n X.append(observation)\n Y.append(current_qs)\n \n model.fit(np.array(X), np.array(Y), batch_size=BATCH_SIZE, verbose=0, shuffle=True) # Update neural network\n\n\ndef avail_item_values():\n \"\"\"\n Returns the available item values\n \"\"\"\n avail_item_values = []\n for item in range(env.N):\n if env.item_weights[item] + env.current_weight < env.max_weight:\n if env.item_limits[item] > 0:\n avail_item_values.append(env.item_values[item])\n else:\n avail_item_values.append(0)\n else:\n avail_item_values.append(0)\n \n return np.array(avail_item_values)\n\ndef main():\n \n epsilon = 1 # Epsilon-greedy algorithm in initialized at 1 meaning every step is random at the start\n # 1. Initialize the Target and Main models\n # Main Model (updated every 4 steps)\n model = agent()\n # Target Model (updated every 100 steps)\n target_model = agent()\n # Set the same weights as the Main Model for Target Model\n target_model.set_weights(model.get_weights())\n # Initialize Replay Memory\n replay_memory = deque(maxlen=800)\n\n steps_to_update_target_model = 0\n all_rewards = []\n \n for episode in range(TRAIN_EPSISODES):\n total_training_rewards = 0\n observation = env.reset()\n done = False\n reward_list = []; item_list = []\n while not done:\n steps_to_update_target_model += 1\n random_number = np.random.rand()\n # 2. Explore using the Epsilon Greedy Exploration Strategy\n observation = avail_item_values()\n if random_number <= epsilon: # Explore\n action = env.action_space.sample() \n else: # Exploit\n predicted = model.predict(observation.reshape(1, env.N))\n action = np.argmax(predicted)\n \n new_observation, reward, done, info = env.step(action)\n new_observation = avail_item_values()\n replay_memory.append([observation, action, reward, new_observation, done])\n\n # 3. Update the Main Network using the Bellman Equation\n if steps_to_update_target_model % 4 == 0 or done:\n train(env, replay_memory, model, target_model, done)\n\n observation = new_observation\n total_training_rewards += reward\n reward_list.append(reward); item_list.append(action)\n\n if done:\n print(u'_________ n = {} _________'\n u'\\nTotal training rewards: {}\\n'\n u'Reward list = {}\\n'\n u'item list = {}\\n'.format(episode,total_training_rewards,reward_list, item_list))\n\n if steps_to_update_target_model >= 100:\n print('Copying main network weights to the target network weights')\n target_model.set_weights(model.get_weights())\n steps_to_update_target_model = 0\n break\n \n all_rewards.append(reward)\n epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * np.exp(-DECAY * episode)\n print(\"Epsilon:\", epsilon, \"\\n\")\n env.close()\n\nif __name__ == '__main__':\n main()","sub_path":"Assignment_2/Main/MAIN - Mike.py","file_name":"MAIN - Mike.py","file_ext":"py","file_size_in_byte":6906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"632049088","text":"import json\nimport logging\nimport random\nimport socket\nfrom threading import Thread\nimport threading\nimport time\n\nfrom magi.util import helpers\n\n\nPORT=38814\nBUFF=1024\nFALSE=0\nTXTIMEOUT=1\n\nlog = logging.getLogger(__name__)\n\nclass ClientCommService:\n \n def __init__(self, clientId):\n self.active = False\n self.clientId = clientId\n self.connected = False\n self.sock = None\n \n def initCommClient(self, address, replyHandler):\n functionName = self.initCommClient.__name__\n helpers.entrylog(log, functionName, level=logging.INFO)\n \n self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.sock.settimeout(TXTIMEOUT)\n \n retries = 0 \n while not self.connected:\n log.info(\"Trying to connect to server, attempt #%d...\" % (retries+1))\n try:\n self.sock.connect((address, PORT))\n self.connected = True\n log.info(\"Connected to server\")\n except socket.error as e:\n retries += 1\n log.info(\"Socket timed out, exception: %s\" % repr(e))\n time.sleep(0.1 + (random.random()*0.3))\n\n data = json.dumps({'src': self.clientId})\n self.sock.send(data)\n \n self.active = True\n thread = Thread(name=\"ClientHandler for \" + self.clientId, target=self.ClientHandler, args=(replyHandler,))\n thread.start()\n \n helpers.exitlog(log, functionName, level=logging.INFO)\n return thread\n \n def ClientHandler(self, replyHandler):\n \n t = threading.currentThread()\n log.info(\"Running %s\" % t.name)\n \n while self.active:\n #blocks on recv, but may timeout\n try:\n rxdata = self.sock.recv(BUFF)\n log.debug(\"Data Received: %s\" %(repr(rxdata)))\n except socket.timeout:\n continue\n\n try:\n jdata = json.loads(rxdata.strip())\n except:\n log.info(\"ClientHandler could not parse JSON string: %s\" % repr(rxdata))\n continue\n \n log.debug('Client RX jdata: %s' %(repr(jdata)))\n replyHandler(jdata)\n\n #cleanup\n self.sock.close()\n log.info(\"Leaving %s\" % threading.currentThread().name)\n \n def sendData(self, data):\n data['src'] = self.clientId\n data = json.dumps(data)\n log.debug('Sending data %s' %(data))\n self.sock.send(data)\n \n def stop(self):\n self.active = False\n","sub_path":"dmm/generator/commClient.py","file_name":"commClient.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"524266756","text":"\n\n\"\"\"\nExercise 8: Rename key city to location in the following 8_dictionary\nsampleDict = {\n \"name\": \"Kelly\",\n \"age\":25,\n \"salary\": 8000,\n \"city\": \"New york\"\n}\n\nExpected output:\n\n{\n \"name\": \"Kelly\",\n \"age\":25,\n \"salary\": 8000,\n \"location\": \"New york\"\n}\n\n\"\"\"\n\n\ndef rename_key(dic: dict, old_key, new_key):\n if old_key in dic:\n dic.update({new_key: dic[old_key]})\n dic.pop(old_key)\n return dic\n\n\ndef rename_key2(dic: dict, old_key, new_key):\n if old_key in dic:\n dic[new_key] = dic.pop(old_key)\n\n\nsampleDict = {\n \"name\": \"Kelly\",\n \"age\": 25,\n \"salary\": 8000,\n \"city\": \"New york\"\n}\n\nprint(rename_key(dic=sampleDict, old_key=\"city\", new_key=\"location\"))\nprint(rename_key(dic=sampleDict, old_key=\"test\", new_key=\"TEST\"))\nprint(rename_key(dic=sampleDict, old_key=\"salary\", new_key=\"money\"))","sub_path":"pynative/8_dictionary/ex_8.py","file_name":"ex_8.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"503224129","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nif __name__=='__main__':\r\n X = np.array([1.5,2.3,2.4,0.2,2.8,2.3,4,3])\r\n y = np.array([1.6,2.6,3,0.8,0.6,2.1,1.6,2.2])\r\n label = np.array([1,1,1,1,2,2,2,2])\r\n \r\n center1 = np.array([np.mean(X[label==1]),np.mean(y[label==1])])\r\n center2 = np.array([np.mean(X[label==2]),np.mean(y[label==2])])\r\n\r\n a = -1/(center2[1]-center1[1])/(center2[0]-center1[0])\r\n b = a*(-(center2[0]+center1[0])/2)+(center2[1]+center1[1])/2\r\n\r\n classes = np.sign(-a*X+y-b)\r\n classes[classes==-1] = 2\r\n J = 4*sum(classes==label)\r\n \r\n print('a: ',a)\r\n print('b: ',b)\r\n print('J: ',J)\r\n print('classes: ',classes)\r\n \r\n plt.figure(1)\r\n plt.plot(X[label==1],y[label==1],'o',color='r')\r\n plt.plot(X[label==2],y[label==2],'o',color='b')\r\n plt.plot(np.arange(0,3,0.1),a*np.arange(0,3,0.1)+b,'-',color='g')\r\n plt.xlabel('X')\r\n plt.ylabel('Y')\r\n \r\n\r\n\r\n","sub_path":"center_of_gravity.py","file_name":"center_of_gravity.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"58048554","text":"def user_input():\n global radius\n global start_node\n global end_node\n inp = input(\"What txt file do you want to read: Germany, Hungary or SampleCoordinates - Possible inputs: g, h and s\")\n if inp == \"g\" or inp == \"G\":\n radius = 0.0025\n start_node = 1573\n end_node = 10584\n return \"GermanyCities.txt\"\n elif inp == \"h\" or inp == \"H\":\n radius = 0.005\n start_node = 311\n end_node = 702\n return \"HungaryCities.txt\"\n elif inp == \"s\" or inp == \"S\":\n radius = 0.08\n start_node = 0\n end_node = 5\n return \"SampleCoordinates.txt\"","sub_path":"Lectures/TestLib/user_input.py","file_name":"user_input.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"608973752","text":"#coding: utf-8\ndef adicion(uno = 0, dos = 0, tres = 0, cuatro = 0, cinco = 0):\n\tsuma = uno + dos + tres + cuatro + cinco\n\tprint(\"La suma es: \" + str(suma))\ndef producto(uno, dos, tres, cuatro, cinco):\n\tprint(\"El producto es: \" + str(uno*dos*tres*cuatro*cinco))\n\nprint(\"Necesito cinco numeros distintos de cero para sumarlos y multiplicarlos, y asi darte sus resultados\")\nnumUno = input()\nnumDos = input()\nnumTres = input()\nnumCuatro = input()\nnumCinco = input()\nadicion(numUno, numDos, numTres, numCuatro, numCinco)\nproducto(numUno, numDos, numTres, numCuatro, numCinco)","sub_path":"Python/SumaYMultiplicacion.py","file_name":"SumaYMultiplicacion.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"309740899","text":"from __future__ import division\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom RandomGenerator import get_expected_value, get_dispersion, estimate_correlation\nimport matplotlib.pyplot as plt\nimport Tkinter\n\n\nclass PlotDrawer:\n mainwin = None\n canvas = None\n n_arr = [100, 1000]\n bar_chart = ()\n\n def __init__(self, mainwin):\n self.mainwin = mainwin\n self.canvas = FigureCanvasTkAgg(plt.figure(), master=mainwin)\n self.canvas.show()\n self.canvas.get_tk_widget().grid(row=0, column=0, sticky=Tkinter.NSEW)\n toolbar = NavigationToolbar2TkAgg(self.canvas, mainwin)\n toolbar.grid(row=1, column=0)\n toolbar.update()\n\n def draw(self, get_bar_chart, *args):\n plot_rows = len(args)\n plot_cols = len(self.n_arr)\n plot_index = 1\n plt.clf()\n for random_generator in args:\n for n in self.n_arr:\n subplt = plt.subplot(plot_rows, plot_cols, plot_index)\n plot_index += 1\n values = [random_generator.next() for i in range(n)]\n left,heights, width = get_bar_chart(values)\n subplt.bar(left, heights, width=width)\n expected_value = get_expected_value(values)\n plt.title(\"n={}, M={:.3f}, D={:.3f}, R={:.3f}\".format(n, expected_value,\n get_dispersion(values, expected_value),\n estimate_correlation(values, 2)))\n plt.axis([0, 1, 0, 1])\n plt.xlabel('X')\n plt.ylabel('Density')\n self.canvas.draw()\n","sub_path":"8term/MM/lab1/PlotDrawer.py","file_name":"PlotDrawer.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"202256150","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 24 13:31:31 2020\n\nhttps://learn.datacamp.com/courses/data-manipulation-with-pandas\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nfrom IPython.display import display, HTML\npd.set_option(\"display.max_columns\", 8)\n\npath_avoplotto = 'data/pandas_datamanipulation/avoplotto.pkl'\npath_homeless = 'data/pandas_datamanipulation/homeless_data.pkl'\npath_walmart = 'data/pandas_datamanipulation/walmart_sales.pkl'\n\nhomelessness = pickle.load(open(path_homeless, 'rb')) # Pickle returns a DF\nsales = pickle.load(open(path_walmart, 'rb'))\navocados = pickle.load(open(path_avoplotto, 'rb'))\n\n\n''' EDA '''\n# print(homelessness) # The entire DF\n# display(homelessness) # BETTER OUTPUT for IPython\n# print(homelessness.head())\n# print(homelessness.info())\n# print(homelessness.describe()) # STATISTICS: count (non-missing values), mean, max\n\n# 4 Attrbitutes\n# print(homelessness.shape)\n# print(homelessness.values) # All VALUES in each row\n# print(homelessness.columns)\n# print(homelessness.index)\n\n\n''' SORT '''\n# print(homelessness.sort_values(['family_members', 'state_pop'], ascending=True))\n# Soting on multiple values ONLY MATTERs if 2 values in the first column are the same\n# print(homelessness.sort_values('family_members', inplace=True)) # -> IF inplace\n# is True, NOTHING is returned\n# print(homelessness.head())\n\n# Check sort on multiple columns\n# df = pd.DataFrame({1:1, 2:2}, index=[1]) # If values are NOT LIST, index MUST be passed\ndf = pd.DataFrame({'a':[1,1,1], 'b':[10,10,30], 'c':[100,200,300]})\n# print(df)\n# print(df.sort_values(['a', 'b', 'c'], ascending=[True, False, False])) \n\n\n''' SUBSET:\nFor column, only write name of column, meaning DF['col']. \nFor row, write boolean condition with DF name, meaning DF[DF['col'] > 100]. '''\n# 1) COLUMN =========\n# print(homelessness['individuals']) # SQUARE brackets\n# print(homelessness[['state', 'individuals']]) # Subset MULTIPLE columns\n# 2) ROW =========\n# print(homelessness[homelessness['individuals'] > 9000])# Subset ROWS\n# print(homelessness[homelessness['state'].str.lower() == 'florida'])\n# 2.1) Multiple row conditions\n# print(homelessness[(homelessness['region']=='Mountain') & # Parenthesis MANDATORY\n# (homelessness['individuals']>5000)])\n# 2.2) Subset row by CATEGORICAL VARIABLE: Checking if value in a column matches a set of values\n# print(homelessness[homelessness['state'].isin(['California', 'Florida'])])\n# Below does not properly work for double columns\n# print(homelessness[homelessness['state'].isin(['California', 'Florida'])])\n# 3) BOTH row and column =========\n# print(homelessness.loc[homelessness['state'].str.lower() == 'florida', \n # ['region', 'state']]) # BOTH row and column\n\n\n''' Create New Column '''\n# homelessness['state-region'] = homelessness['state'].values + ' in ' + homelessness['region']\n# del homelessness['individuals']\n# del homelessness['family_members']\n# display(homelessness.head())\nx = homelessness[homelessness['individuals'] > 10000].sort_values('family_members', ascending=True).loc[:, ['state-region', 'individuals', 'state_pop']]\n# print(x)\n\n\n''' Summary Statistics (no group, all rows) '''\n# 1) Basic/Individual Column\n# print(homelessness['individuals'].mean())\n# print(homelessness['individuals'].median())\n# print(homelessness['individuals'].mode()) # NOT SURE what happens\n# print(homelessness['individuals'].min()) # Can also do this on DATE column\n# print(homelessness['individuals'].var())\n# print(homelessness['individuals'].std())\n# print(homelessness['individuals'].sum())\n# print(homelessness['individuals'].quantile(0.6)) # need PARAMETER\n# print(homelessness[['individuals', 'state_pop']].mean()) # MULTIPLE columns\n\n# 2) Cumulative\n# print(homelessness['individuals'].cumsum()) # First, First+Second, First+Second+Third ...\n# print(homelessness['individuals'].cumprod())\n# print(homelessness['individuals'].cummax(axis=0))\n# print(homelessness[['individuals', 'state_pop']].cummax(axis=0)) # Each cell is populated with the maximum value seen so far.\n\n# 3) Aggregate\n# print(homelessness['individuals'].agg(np.mean)) # ONLY MEAN does not work, because mean is not a function but a method\n# print(homelessness[['individuals', 'state_pop']].agg(np.mean)) # multiple COLUMNS\n# print(homelessness['individuals'].agg([np.mean, np.median])) # multiple FUNCTIONS\n# print(homelessness[['individuals', 'state_pop']].agg([np.mean, np.median])) # Output is 2D\n\n# print(sales['weekly_sales'].mean(), sales['weekly_sales'].median()) # Relation between median and mean can tell us something. \n# E.g. if median is much lower than mean, this means there are a handful of very high sales that is dragging mean forward\n# print(sales['date'].max(), sales['date'].min()) # The date range\n\n\n''' Counting '''\n# print(sales)\n# print(sales.drop_duplicates(subset=\"type\")) # TEMPORARY change\n# print(sales.drop_duplicates(subset=\"store\")[['store', 'type', 'department']])\n\n# Only drops DUPLICATE DEPARTMENTS-STORE pairs, then prints bottom 30 in sorted fashion\n# print(sales.drop_duplicates(subset=['store', 'department']).tail(30).sort_values(['store','department'], ascending=[True, True])[['store', 'type', 'department']]) \n\n# How many different departments in all stores?\nunique_dept = sales.drop_duplicates(subset=['store', 'department'])\n# print(unique_dept['department'].value_counts(sort=True, normalize=True)) # value_counts() does NOT WORK on df, only on column\n# Notice the parameters above: SORT, not sorted\n# print(unique_dept['department'].value_counts().reset_index().sort_values('index')) # If we want to sort based on index\n''' reset_index() stores the previous index into a new column called 'index' '''\n\n\n# Q. Count the number of stores of each store type.\n# Count the proportion of stores of each store type.\n# Count the number of different department numbers, sorting the counts in descending order.\n# Count the proportion of different department numbers, sorting the proportions in descending order.\nstores = sales.drop_duplicates(subset=['store', 'type']) # No duplicate stores\ndepartments = sales.drop_duplicates(subset=['store', 'department']) # No duplicate dept in a store\nstore_count = stores['store'].value_counts(sort=True) # How many stores\nstore_prop = stores['store'].value_counts(normalize=True)\ndept_count = departments['department'].value_counts(normalize=True)\ndept_prop = departments['department'].value_counts(normalize=True, sort=True) # How many depts across stores\n\n\n\n''' Grouped Summary Statistics '''\n# Only considers a subset of rows in a column\n# print(homelessness[homelessness['region']=='Mountain']['individuals'].mean())\n# print(sales[sales['department']==10]['weekly_sales'].mean())\n# Can check if one store has better weekly sales than others\n# print(sales[sales['store']==20]['weekly_sales'].mean())\n\n# Q. Calculate the total weekly sales over the whole dataset.\n# Subset for type \"A\" stores, and calculate their total weekly sales.\n# Do the same for type \"B\" and type \"C\" stores.\n# Combine the A/B/C results into a list, and divide by overall sales to get the proportion of sales by type.\nsales_a = sales[sales['type']=='A']['weekly_sales'].sum()\nsales_b = sales[sales['type']=='B']['weekly_sales'].sum()\nsales_c = sales[sales['type']=='C']['weekly_sales'].sum()\n# print([sales_a, sales_b, sales_c]/sales['weekly_sales'].sum())\n\n\n# The same can be easily achieved without specifying each store number using GROUPBY\n# print(sales.groupby('store')['weekly_sales']) # Only returns a groupby object, need to specify statistical method\n# print(sales.groupby('store')['weekly_sales'].mean())\n# print(sales.groupby('store')['is_holiday'].mean()) # provides a number for int, float, and BOOLEAN!!\n# print(sales.groupby('store').mean()) # Provides group stats summary for all columns if column not specified\n# print(sales.groupby('store').agg([min, max, sum, np.mean, np.median, stats.mode]))\n# Cannot specify a column in the end, may specify it right after groupby\n# sales.groupby('store).mean()['date'] -> INVALID SYNTAX\n# print(sales.groupby(['store', 'department']).agg([min]).tail(20)) # groupny on multiple columns\n\n# Q. Group sales by \"type\", take the sum of \"weekly_sales\", and store as sales_by_type.\n# Calculate the proportion of sales at each store type by dividing by the sum of sales_by_type. Assign to sales_propn_by_type.\nsales_by_type = sales.groupby('type')['weekly_sales'].sum()\nsales_prop_by_type = sales_by_type/sum(sales_by_type)\n# print(sum(sales_by_type))\n\n\n''' Pivot Tables - df with sorted index '''\n# print(sales.groupby('type')['store'].mean())\n# print(sales.pivot_table(index='type', values='store')) # Same as above, default is mean()\n# print(sales.pivot_table(index=['type','is_holiday'], values='store', aggfunc=np.sum))\n# Different look but same result as two indexes below\n# print(sales.pivot_table(index='type', columns='department', values='store')) # columns contain the secondary index\n# print(sales.pivot_table(index='type', values='is_holiday', columns='store', aggfunc=np.min)) # lots of NaN values\n# Fills NaN with ZERO\n# print(sales.pivot_table(index='type', values='is_holiday', columns='store', fill_value=0, aggfunc=np.min))\n# print(sales.pivot_table(index='type', values='weekly_sales', margins=True, columns='is_holiday', aggfunc=[np.sum, np.mean])) # Last row & column have summary\n\n# Pivot Table Slicing\nsales_pivot = sales.pivot_table(index='type', values='weekly_sales', columns='store')\n# print(sales_pivot)\n# print(sales_pivot.loc['A':'B', 1:3])\n\n# Access only YEAR FROM DATE\n# sales['year'] = sales['date'].dt.year\n# print(sales)\n\n# Summary with Axis on Pivot Table - makes sense because EVERY COLUMNS HAS SAME DATA TYPE\n# print(sales_pivot.mean(axis=0)) # Taking each COLUMN at a time\n# print(sales_pivot.mean(axis=1)) # Taking each ROW at a time\n# print(sales_pivot.mean(axis='index')) # Same as AXIS=0\n# print(sales_pivot.mean(axis='columns')) # Same as AXIS=1\n\n\n''' Index - makes subsetting code cleaner - index may not be unique - left-aligned'''\n# print(sales.set_index('is_holiday')) # does NOT CHANGE the original df\n# print(sales.set_index('is_holiday').reset_index())\n# print(sales.set_index('is_holiday').reset_index(drop=True)) # GETS RID OF prev index column\n\n# Code EASIER after SETTIGN INDEX\n# print(sales[sales['unemployment'].isin([8.106, 8.3])])\nx = sales.set_index('unemployment')\n# print(x.loc[[8.106, 8.3], :])\n\n# Duplicate indexes\n# print(sales.set_index('department').loc[1])\n\n# Multi-level index - second index is nested inside the first one\nmulti_index_sales = sales.set_index(['type', 'department'])\n# print(multi_index_sales)\n# print(multi_index_sales.loc[['A'], :])\n# print(multi_index_sales.loc[[\"A\"]])\n# The command below needs pairing items each from one level of index\n# print(multi_index_sales.loc[[('A',98), ('B',9)]])\n# Sort will start from outer to inner, ascending\n# print(multi_index_sales.sort_index())\n# print(multi_index_sales.sort_index(level=['department','type'], ascending=[False,True]))\n\n''' Problems with indexes:\n 1) Index values are just data\n 2) Violated \"tidy data\" principle of data getting its own column\n'''\nmulti_index_sales2 = sales.set_index(['type', 'store'])\n# print(multi_index_sales)\nmulti_index_sales2 = multi_index_sales2.sort_index()\n# If index not sorted, SLICING WON'T WORK\n# print(multi_index_sales2.loc['A':'B']) # Final value INCLUDED\n# print(multi_index_sales2.loc[[('B',43), ('B',45)]]) # Tuples do not have colon inside\n# print(multi_index_sales2.loc[('B',43) : ('B',45)]) # using COLON needs single square brackets\n# print(multi_index_sales2.loc[:, 'department':'weekly_sales']) # COLUMN SLICING\n\n# Date slicing\n# print(sales[(sales[\"date\"] >= \"2010\") & (sales[\"date\"] < \"2012\")]) # Adjusts for month/day\nmulti_index_sales3 = sales.set_index('date').sort_index()\n# print(multi_index_sales3)\n# print(multi_index_sales3.loc['2010-02-05':'2010-02-06'])\n# print(multi_index_sales3.loc['2010':'2010']) # PARTIAL dates slicing\n\n''' iloc - final value not included - row & column both needed '''\n# print(sales.iloc[1:3, 2:3])\n\n\n''' Visualization '''\n# sales['type'].hist() # sales['store'].hist() or sales['date'].hist()\n# sales['date'].hist()\n\n# x = sales.groupby('type')['weekly_sales'].mean() # AGG func in MANDATORY\n# print(x)\n# x.plot(kind='bar', title='The groupby argument is on X axis vertically')\n# sales.plot(x='type', y='unemployment', kind='bar') -> DOES NOT WORK\n\n# sales.plot(x='date', y='weekly_sales', kind='line', rot=45) # rot -> rotate xlabel\n\n# sales.plot(x='weekly_sales', y='store', kind='scatter')\n\n# sales[sales['type']=='A']['weekly_sales'].hist(alpha=0.7)\n# sales[sales['type']=='B']['weekly_sales'].hist(alpha=0.7) # Only when 2 has index and column same, then they will show together\n# plt.legend(['type A', 'type B'])\nplt.show()\n\n\n''' Missing Values '''\n# Introduce missing values to avocados dataframe\ndef introduce_missing_values(df, pct):\n for col in df:\n ori_rat = df[col].isna().mean()\n if ori_rat >= pct: continue\n add_miss_rat = (pct - ori_rat) / (1 - ori_rat)\n vals_to_nan = df[col].dropna().sample(frac=add_miss_rat).index\n df.loc[vals_to_nan, col] = np.NaN\nintroduce_missing_values(avocados, 0.2)\n# print(avocados.isna().sum()) # How many missing values for each column\n# print(avocados.isna().any()) # Is there any missing value at all in a column?\n# avocados.isna().sum().plot(kind='bar')\n# print(avocados.shape)\n# avocados = avocados.dropna()\n# print(avocados.shape)\n\n# avocados.fillna(0) # Only fills numerical columns\n# print(avocados.head(10))","sub_path":"pandas_datamanipulation.py","file_name":"pandas_datamanipulation.py","file_ext":"py","file_size_in_byte":13679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"601221224","text":"import csv\nf=open('subwayfee.csv')\ndata = csv.reader(f)\n\nnext(data)\n\nmx=[0]*4\nmx_station=['']*4\nlabel=['유임승차','유임하차','무임승차','무임하차']\n\nfor row in data:\n for i in range(4,8):\n row[i]=int(row[i])\n if row[i] >mx[i-4]:\n mx[i-4]=row[i]\n mx_station[i-4] = row[3]+' '+row[1]\nfor i in range(4): \n print(label[i]+' : '+mx_station[i],mx[i])","sub_path":"지하철_유임승하차인원.py","file_name":"지하철_유임승하차인원.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"359678759","text":"# %%\nfrom sklearn.base import TransformerMixin, BaseEstimator\nfrom sklearn.model_selection import train_test_split\nfrom timeit import default_timer as timer\nimport pandas as pd\nimport numpy as np\nfrom umap import UMAP\nfrom ivis import Ivis\nfrom evaluation import Doc2VecModel\nfrom tqdm import tqdm\nfrom pyod.models.ocsvm import OCSVM\nfrom pyod.models.hbos import HBOS\nfrom pyod.models.pca import PCA\nfrom itertools import permutations\nfrom utils import next_path, product_dict, get_scores, reject_outliers, sample_data, remove_short_texts\n\n\n\ntqdm.pandas(desc=\"progess: \")\n\n\nclass IQROutlier:\n def __init__(self, contamination=0.1):\n self.contamination = contamination\n\n def fit(self, X, y=None):\n pcnt = self.contamination / 2\n qlow, self.median, qhigh = np.quantile(X, [pcnt, 0.50, 1-pcnt])\n self.iqr = qhigh - qlow\n return self\n\n def transform(self, X, thresh_factor=1.0):\n iqr = self.iqr*thresh_factor\n preds = ((np.abs(X - self.median)) >= iqr/2)\n return [-1 if x else 1 for x in preds]\n\n\ndef get_outlier_data(oe_path, n_oe, seed):\n df_oe = pd.read_pickle(oe_path)\n df_oe = df_oe.iloc[np.random.RandomState(\n seed=seed).permutation(len(df_oe))].head(n_oe)\n df_oe[\"label\"], df_oe[\"outlier_label\"], df_oe[\"scorable\"] = 0, -1, 0\n return df_oe\n\n\ndef label_data(df, seed, labeled_data, outlier_classes):\n df = df[[\"text\", \"target\", \"vecs\"]]\n df[\"scorable\"] = 1\n # get all 20 news data\n df = df.where(df.target != -1).dropna()\n # set everything except one class to inlier\n\n df[\"outlier_label\"] = -1\n df.loc[~df.target.isin(outlier_classes), \"outlier_label\"] = 1\n # create labels for UMAP and ivis that\n # are 0 and 1 (derived from the just created outlier labels)\n df[\"label\"] = (df[\"outlier_label\"]+1)/2\n # stratified sample and set unlabeled data based on labeled_data variable\n\n if labeled_data < 1.0:\n df_unlabeled = df[['target']].groupby('target', group_keys=False).apply(\n lambda x: x.sample(frac=1-labeled_data, random_state=seed))\n \n df.loc[df_unlabeled.index, \"label\"] = -1\n return df\n\n\ndef prepare_data(df, outliers, inliers, seed, fixed_cont,\n labeled_data, n_oe, oe_path, doc2vec_model, **kwargs):\n print(\"Only use classes that are in inliers or outliers\")\n df = df.where(df.target.isin(\n outliers+inliers)).dropna()\n # label data as inliers and outliers (for scoring) and whether\n # they have labels or not (semi-supervised)\n df = label_data(df, seed, labeled_data, outliers)\n\n if fixed_cont:\n df = sample_data(df, 1.0, fixed_cont, seed)\n print(\"Data after adjusting for fixed contamination:\\n\")\n print(df.groupby(['label', 'outlier_label']).size(\n ).reset_index().rename(columns={0: 'count'}), \"\\n\")\n\n if n_oe:\n df_oe = get_outlier_data(oe_path, n_oe, seed=42)\n df_oe[\"vecs\"] = doc2vec_model.vectorize(df_oe[\"text\"])\n df = df.append(df_oe)\n\n if -1 in df.label.unique() and df.label.value_counts()[-1] != df.shape[0]:\n if df[(df.label == 0) & (df.outlier_label == -1)].shape[0] == 0:\n print(\"Adding missing sample for labeled outlier\")\n df.loc[((df.label == -1) & (df.outlier_label == -1)\n ).idxmax(), 'label'] = 0\n\n print(\"Training data:\\n\", df.groupby(['label', 'outlier_label']).size(\n ).reset_index().rename(columns={0: 'count'}), \"\\n\\n\")\n\n return df\n\n\ndef umap_reduce(docvecs, label, umap_model, use_nn, use_umap, **kwargs):\n if not use_umap:\n return np.array(docvecs), None\n\n if not umap_model:\n print(f\"Train UMAP...\")\n umap_n_components = min(256, len(docvecs)-2) if use_nn else 1\n umap_model = UMAP(metric=\"cosine\", set_op_mix_ratio=1.0,\n n_components=umap_n_components, random_state=42,\n verbose=False)\n umap_model = umap_model.fit(docvecs, y=label)\n dim_reduced_vecs = umap_model.transform(docvecs)\n if not use_nn:\n dim_reduced_vecs = dim_reduced_vecs.astype(float)\n return dim_reduced_vecs, umap_model\n\n\ndef ivis_reduce(docvecs, label, ivis_model, use_nn, **kwargs):\n if use_nn:\n if not ivis_model:\n print(f\"Train ivis...\")\n ivis_model = Ivis(embedding_dims=1, k=15, model=\"maaten\",\n n_epochs_without_progress=15, verbose=0,\n batch_size=128)\n if -1 in label.unique() and label.value_counts()[-1] == label.shape[0]:\n print(\"No labeled data found.\")\n ivis_model = ivis_model.fit(docvecs)\n else:\n ivis_model = ivis_model.fit(\n docvecs, Y=label.to_numpy())\n\n dim_reduced_vecs = ivis_model.transform(docvecs)\n decision_scores = dim_reduced_vecs.astype(float)\n return decision_scores, ivis_model\n else:\n return docvecs, None\n\n\ndef score_out_preds(docvecs, iqr_model, contamination, **kwargs):\n if not iqr_model:\n iqrout = IQROutlier(contamination=contamination)\n iqrout = iqrout.fit(docvecs)\n preds = iqrout.transform(docvecs)\n return preds, iqrout\n\n\ndef main():\n standard_split = [\n ([0, 1, 2, 11], [3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15])]\n pairwise_split = list(permutations([[x] for x in range(0, 16)], 2))\n # %%\n param_combinations = product_dict(**dict(\n seed=[42, 43, 44],\n test_size=[0.2],\n labeled_data=[0.1, 0.3, 0.5, 0.8, 1.0],\n fixed_cont=[0.05, 0.1],\n n_oe=[0],\n use_nn=[True],\n pair=standard_split\n ))\n # how many samples per class are used for all tests\n n_class = 3000\n\n # split the outlier, inlier tuple pairs and print all parameters for run\n for d in param_combinations:\n d[\"inliers\"], d[\"outliers\"] = d[\"pair\"]\n d.pop('pair', None)\n\n #data_path = \"/home/philipp/projects/dad4td/data/processed/20_news_imdb_vec.pkl\"\n data_path = \"/home/philipp/projects/dad4td/data/raw/QS-OCR-Large/rvl_cdip.pkl\"\n oe_path = \"/home/philipp/projects/dad4td/data/processed/oe_data.pkl\"\n res_path = next_path(\n \"/home/philipp/projects/dad4td/reports/semisupervised/semisup_rvl_pw_%04d.tsv\")\n\n doc2vec_model = Doc2VecModel(\"apnews\", \"apnews\", 1.0,\n 100, 1,\n \"/home/philipp/projects/dad4td/models/apnews_dbow/doc2vec.bin\")\n\n # load data and get the doc2vec vectors for all of the data used\n df_full = pd.read_pickle(data_path)\n\n # sample only a portion of the data\n df_full = df_full.groupby('target', group_keys=False).apply(\n lambda df: df.sample(n=n_class, random_state=42))\n\n # %%\n df_full[\"vecs\"] = doc2vec_model.vectorize(df_full[\"text\"])\n df_full[\"vecs\"] = df_full[\"vecs\"].apply(tuple)\n\n # %%\n result_df = pd.DataFrame()\n for i, params in enumerate(param_combinations):\n print(\n f\"\\n\\n---------------------\\n\\nRun {i+1} out of {len(param_combinations)}\\n\\n{params}\")\n\n df, df_test = prepare_data(df_full, **params)\n\n # UMAP Train\n docvecs, umap_model = umap_reduce(\n df[\"vecs\"].to_list(), df[\"label\"], None, **params)\n\n # Ivis\n docvecs, ivis_model = ivis_reduce(\n docvecs, df[\"label\"], None, **params)\n\n # remove OE data, so it's not scored as well\n df[\"decision_scores\"] = docvecs\n df = df.where(df.scorable == 1).dropna()\n\n # find outliers in 1D scores\n preds, iqr_model = score_out_preds(df[\"decision_scores\"], None,\n contamination=df.outlier_label.value_counts(normalize=True)[-1])\n\n # score the predictions for outliers\n scores = get_scores(dict(), df[\"outlier_label\"], preds)\n\n # %%\n # write the scores to df and save\n scores.update(params)\n scores[\"data\"] = \"train\"\n result_df = result_df.append(scores, ignore_index=True)\n result_df.to_csv(res_path, sep=\"\\t\")\n print(f\"\\nTraining scores:\\n{pd.DataFrame([scores], index=[0])}\")\n # %%\n # test UMAP and ivis\n docvecs_test, _ = umap_reduce(\n df_test[\"vecs\"].to_list(), None, umap_model, **params)\n\n docvecs_test, _ = ivis_reduce(docvecs_test, None, ivis_model, **params)\n\n # remove OE data, so it's not scored as well\n df_test[\"decision_scores\"] = docvecs_test\n df_test = df_test.where(df_test.scorable == 1).dropna()\n\n # find outliers in 1D scores\n preds = iqr_model.transform(\n df_test[\"decision_scores\"], thresh_factor=1)\n\n # score the predictions for outliers\n scores = get_scores(dict(), df_test[\"outlier_label\"], preds)\n\n # write the scores to df and save\n scores.update(params)\n scores[\"data\"] = \"test\"\n result_df = result_df.append(scores, ignore_index=True)\n result_df.to_csv(res_path, sep=\"\\t\")\n print(f\"\\nTest scores:\\n{pd.DataFrame([scores], index=[0])}\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/semisupervised.py","file_name":"semisupervised.py","file_ext":"py","file_size_in_byte":9108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"645368251","text":"menu = 0\nwhile (menu != 3):\n print(\"\"\"\n MINI MENU\n 1. Opcion 1\n 2. Opcion 2\n 3. salir\n \"\"\")\n menu = input(\"Ingrese una opción: \")\n\n if menu.isdigit():\n if int(menu) == 1: \n print(\"opcion 1\")\n elif int(menu) == 2: \n print(\"opción 2\")\n elif int(menu) == 3:\n quit()\n else:\n print(\"Ingrese una opcion valida\")","sub_path":"python/[244]Com 2/Proyecto/while02.py","file_name":"while02.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"331728913","text":"# -*- coding: utf-8 -*-\n\n# Copyright (C) 2018 by eHealth Africa : http://www.eHealthAfrica.org\n#\n# See the NOTICE file distributed with this work for additional information\n# regarding copyright ownership.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom rest_framework import serializers\nfrom rest_framework.reverse import reverse\nfrom drf_dynamic_fields import DynamicFieldsMixin\n\nfrom . import constants, models, utils, validators\n\nimport urllib\n\n\nM_OPTIONS = constants.MergeOptions\n\nMERGE_CHOICES = (\n (M_OPTIONS.overwrite.value, 'Overwrite (Do not merge)'),\n (M_OPTIONS.lww.value, 'Last Write Wins (Target to Source)'),\n (M_OPTIONS.fww.value, 'First Write Wins (Source to Target)')\n)\n\n\nclass FilteredHyperlinkedRelatedField(serializers.HyperlinkedRelatedField):\n '''\n This custom field does essentially the same thing as\n serializers.HyperlinkedRelatedField. The only difference is that the url of\n a foreign key relationship will be:\n\n {\n ...\n 'entities_url': '/entities?projectschema='\n ...\n }\n\n Instead of:\n\n {\n ...\n 'entities': [\n '/entities/',\n '/entities/',\n ]\n ...\n }\n\n '''\n\n def get_url(self, obj, view_name, request, format):\n lookup_field_value = obj.instance.pk\n result = '{}?{}'.format(\n reverse(view_name, kwargs={}, request=request, format=format),\n urllib.parse.urlencode({self.lookup_field: lookup_field_value})\n )\n return result\n\n\nclass ProjectSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n read_only=True,\n view_name='project-detail',\n )\n mappingset_url = FilteredHyperlinkedRelatedField(\n lookup_field='project',\n read_only=True,\n source='mappingsets',\n view_name='mappingset-list',\n )\n projectschemas_url = FilteredHyperlinkedRelatedField(\n lookup_field='project',\n read_only=True,\n source='projectschemas',\n view_name='projectschema-list',\n )\n\n class Meta:\n model = models.Project\n fields = '__all__'\n\n\nclass MappingSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n read_only=True,\n view_name='mapping-detail',\n )\n mappingset_url = serializers.HyperlinkedRelatedField(\n read_only=True,\n source='mappingset',\n view_name='mappingset-detail',\n )\n\n projectschemas_url = FilteredHyperlinkedRelatedField(\n lookup_field='mapping',\n read_only=True,\n source='projectschemas',\n view_name='projectschema-list',\n )\n\n def validate_definition(self, value):\n validators.validate_mapping_definition(value)\n return value\n\n class Meta:\n model = models.Mapping\n fields = '__all__'\n\n\nclass MappingSetSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n read_only=True,\n view_name='mappingset-detail',\n )\n project_url = serializers.HyperlinkedRelatedField(\n read_only=True,\n source='project',\n view_name='project-detail',\n )\n mappings_url = FilteredHyperlinkedRelatedField(\n lookup_field='mappingset',\n read_only=True,\n source='mappings',\n view_name='mapping-list',\n )\n submissions_url = FilteredHyperlinkedRelatedField(\n lookup_field='mappingset',\n read_only=True,\n source='submissions',\n view_name='submission-list',\n )\n\n class Meta:\n model = models.MappingSet\n fields = '__all__'\n\n\nclass AttachmentSerializerNested(DynamicFieldsMixin, serializers.ModelSerializer):\n name = serializers.CharField(read_only=True)\n url = serializers.CharField(read_only=True, source='attachment_file_url')\n\n class Meta:\n model = models.Attachment\n fields = ('name', 'url')\n\n\nclass SubmissionSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='submission-detail',\n read_only=True\n )\n project_url = serializers.HyperlinkedRelatedField(\n view_name='project-detail',\n source='project',\n read_only=True,\n )\n mappingset_url = serializers.HyperlinkedRelatedField(\n view_name='mappingset-detail',\n source='mappingset',\n read_only=True,\n )\n entities_url = FilteredHyperlinkedRelatedField(\n lookup_field='submission',\n view_name='entity-list',\n read_only=True,\n source='entities',\n )\n attachments_url = FilteredHyperlinkedRelatedField(\n lookup_field='submission',\n view_name='attachment-list',\n read_only=True,\n source='attachments',\n )\n\n # this will return all linked attachment files\n # (name, relative url) in one request call\n attachments = AttachmentSerializerNested(many=True, read_only=True)\n\n def create(self, validated_data):\n try:\n submission = models.Submission(**validated_data)\n submission.save()\n\n utils.run_entity_extraction(submission)\n return submission\n except Exception as e:\n raise serializers.ValidationError({\n 'description': 'Submission validation failed >> ' + str(e)\n })\n\n class Meta:\n model = models.Submission\n fields = '__all__'\n\n\nclass AttachmentSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n name = serializers.CharField(allow_null=True, default=None)\n submission_revision = serializers.CharField(allow_null=True, default=None)\n\n url = serializers.HyperlinkedIdentityField('attachment-detail', read_only=True)\n attachment_file_url = serializers.CharField(read_only=True)\n submission_url = serializers.HyperlinkedRelatedField(\n 'submission-detail',\n source='submission',\n read_only=True\n )\n\n class Meta:\n model = models.Attachment\n fields = '__all__'\n\n\nclass SchemaSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='schema-detail',\n read_only=True,\n )\n projectschemas_url = FilteredHyperlinkedRelatedField(\n lookup_field='schema',\n read_only=True,\n source='projectschemas',\n view_name='projectschema-list',\n )\n\n def validate_definition(self, value):\n validators.validate_avro_schema(value)\n validators.validate_id_field(value)\n return value\n\n class Meta:\n model = models.Schema\n fields = '__all__'\n\n\nclass ProjectSchemaSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n read_only=True,\n view_name='projectschema-detail',\n )\n project_url = serializers.HyperlinkedRelatedField(\n view_name='project-detail',\n source='project',\n read_only=True,\n )\n schema_url = serializers.HyperlinkedRelatedField(\n view_name='schema-detail',\n source='schema',\n read_only=True,\n )\n entities_url = FilteredHyperlinkedRelatedField(\n lookup_field='projectschema',\n read_only=True,\n source='entities',\n view_name='entity-list',\n )\n mappings_url = FilteredHyperlinkedRelatedField(\n lookup_field='projectschema',\n read_only=True,\n source='mappings',\n view_name='mapping-list',\n )\n\n class Meta:\n model = models.ProjectSchema\n fields = '__all__'\n\n\nclass EntitySerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='entity-detail',\n read_only=True\n )\n projectschema_url = serializers.HyperlinkedRelatedField(\n read_only=True,\n source='projectschema',\n view_name='projectschema-detail',\n )\n submission_url = serializers.HyperlinkedRelatedField(\n read_only=True,\n source='submission',\n view_name='submission-detail',\n )\n merge = serializers.ChoiceField(MERGE_CHOICES, default=M_OPTIONS.overwrite.value)\n resolved = serializers.JSONField(default={})\n\n # this will return all linked attachment files\n # (name, relative url) in one request call\n attachments = AttachmentSerializerNested(\n many=True,\n read_only=True,\n source='submission.attachments',\n )\n\n def create(self, validated_data):\n try:\n utils.validate_payload(validated_data['projectschema'].schema.definition, validated_data['payload'])\n except Exception as schemaError:\n raise serializers.ValidationError(schemaError)\n try:\n entity = models.Entity(\n payload=validated_data.pop('payload'),\n status=validated_data.pop('status'),\n projectschema=validated_data.pop('projectschema'),\n )\n if 'submission' in validated_data:\n entity.submission = validated_data.pop('submission')\n if 'id' in validated_data:\n entity.id = validated_data.pop('id')\n entity.payload['_id'] = str(entity.id)\n entity.save()\n return entity\n except Exception as e:\n raise serializers.ValidationError({\n 'description': 'Submission validation failed >> ' + str(e)\n })\n\n def update(self, instance, validated_data):\n try:\n if 'submission' in validated_data and validated_data['submission'] is not None:\n instance.submission = validated_data.pop('submission')\n if 'status' in validated_data:\n instance.status = validated_data.pop('status')\n if 'projectschema' in validated_data and validated_data['projectschema'] is not None:\n instance.projectschema = validated_data.pop('projectschema')\n elif instance.projectschema is not None:\n pass # We can use the existing projectschema.\n # This is helpful in situations where a user only has the ID and payload\n # and wants to make an update to an existing entity.\n else:\n raise serializers.ValidationError({\n 'description': 'Project schema must be specified'\n })\n if 'payload' in validated_data:\n target_payload = validated_data.pop('payload')\n else:\n target_payload = {}\n merge_value = None\n if 'merge' in self.context['request'].query_params:\n merge_value = self.context['request'].query_params['merge']\n elif 'merge' in validated_data:\n merge_value = validated_data.pop('merge')\n if (merge_value == M_OPTIONS.fww.value\n or merge_value == M_OPTIONS.lww.value):\n instance.payload = utils.merge_objects(instance.payload, target_payload, merge_value)\n else:\n instance.payload = target_payload\n try:\n utils.validate_payload(instance.projectschema.schema.definition, instance.payload)\n except Exception as schemaError:\n raise serializers.ValidationError(schemaError)\n instance.save()\n return instance\n except Exception as e:\n raise serializers.ValidationError({\n 'description': 'Submission validation failed >> ' + str(e)\n })\n\n class Meta:\n model = models.Entity\n fields = '__all__'\n\n\nclass EntityLDSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='entity-detail',\n read_only=True\n )\n projectschema_url = serializers.HyperlinkedRelatedField(\n read_only=True,\n source='projectschema',\n view_name='projectschema-detail',\n )\n merge = serializers.ChoiceField(MERGE_CHOICES, default=M_OPTIONS.overwrite.value)\n\n class Meta:\n model = models.Entity\n fields = '__all__'\n\n\nclass ProjectStatsSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n first_submission = serializers.DateTimeField()\n last_submission = serializers.DateTimeField()\n submissions_count = serializers.IntegerField()\n entities_count = serializers.IntegerField()\n\n class Meta:\n model = models.Project\n fields = (\n 'id', 'name', 'created',\n 'first_submission', 'last_submission',\n 'submissions_count', 'entities_count',\n )\n\n\nclass MappingSetStatsSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n first_submission = serializers.DateTimeField()\n last_submission = serializers.DateTimeField()\n submissions_count = serializers.IntegerField()\n entities_count = serializers.IntegerField()\n\n class Meta:\n model = models.MappingSet\n fields = (\n 'id', 'name', 'created',\n 'first_submission', 'last_submission',\n 'submissions_count', 'entities_count',\n )\n\n\nclass MappingValidationSerializer(serializers.Serializer):\n submission_payload = serializers.JSONField()\n mapping_definition = serializers.JSONField()\n schemas = serializers.JSONField()\n\n def validate_schemas(self, value):\n if not isinstance(value, dict):\n raise serializers.ValidationError(\n 'Value {value} is not an Object'.format(value=value)\n )\n for schema in value.values():\n validators.validate_avro_schema(schema)\n validators.validate_id_field(schema)\n return value\n","sub_path":"aether-kernel/aether/kernel/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":14330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"556709163","text":"class Solution:\n def longestConsecutive(self,nums):\n longest_streak = 0\n memo = set(nums)\n for num in nums:\n if num-1 not in memo:\n current_num = num\n streak = 1\n\n while current_num + 1 in memo:\n current_num += 1\n streak += 1\n longest_streak = max(longest_streak,streak)\n\n return longest_streak\nif __name__ == \"__main__\":\n nums = [100,4,200,1,3,2]\n # nums = [1,2,0,1]\n # nums = [1,3,5,2,4]\n # nums = [0,3,7,2,5,8,4,6,0,1]\n s = Solution()\n print(s.longestConsecutive(nums))\n","sub_path":"128.Longest_Consecutive_Sequence.py","file_name":"128.Longest_Consecutive_Sequence.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"200402298","text":"import os\nimport requests\nfrom bs4 import BeautifulSoup\nfrom decimal import Decimal\nfrom decimal import InvalidOperation\nfrom ..utils.time import (\n local_string_to_utc_string,\n format_standard,\n parse_bomgovau_raw_footer_string_to_utc_datetime,\n parse_bomgovau_merge_date_as_dt_and_hour_as_string,\n parse_bom_gov,\n hours_since_utc_datetime,\n decaminutes_since_utc_datetime,\n utc_string_to_utc_datetime,\n)\nfrom ..utils.browser_profiles import Browser\nfrom ..exceptions import HttpError, BadResponse, UnexpectedFormat, OutOfRange\n\nDECIMAL_PLACES = int(os.getenv(\"DECIMAL_PLACES\", 2))\nSERVICE_NAME = \"Bom.gov.au\"\n\n\ndef fetch(location_object):\n url = location_object[\"bom.gov.au\"]\n browser_profile = Browser()\n headers = browser_profile.headers\n r = requests.get(url, headers=headers)\n if r.ok:\n return r.text\n else:\n raise HttpError({\"service\": SERVICE_NAME, \"response\": r.status_code})\n\n\ndef parse_string_temperature(raw_string):\n \"\"\"Util function to parse the temperature strings found on the BOM website\n\n Input:\n \"–\"\n \"16\"\n\n Ouput:\n Decimal(0)\n Decimal(16)\n \"\"\"\n if raw_string == \"–\":\n return None\n try:\n return Decimal(raw_string)\n except InvalidOperation:\n raise UnexpectedFormat(\n {\n \"service\": SERVICE_NAME,\n \"message\": f\"Could not parse as decimal the temperature {raw_string}\",\n }\n )\n\n\ndef soup_to_forecast_object(soup, timezone):\n \"\"\"Takes a soup object and returns an object listing all forecasts\n found in the page\n\n Output:\n {\n \"issue_time\": \"2020-04-11T11:00:00Z\",\n \"forecasts\": \n [\n {\n \"time_utc\": \"2020-04-11T11:00:00Z\",\n \"temperature_celcius\": 12\n },\n {\n \"time_utc\": \"2020-04-11T12:00:00Z\",\n \"temperature_celcius\": 13\n }\n ]\n }\n \"\"\"\n forecast = {}\n\n # Retrieving the forecast issue time\n footer = soup.find(\"div\", attrs={\"id\": \"footer\"})\n if not footer:\n raise BadResponse({\"service\": SERVICE_NAME, \"message\": \"div id=footer\"})\n timestamp_text = footer.find(\"p\", attrs={\"id\": \"timestamp\"}).text.strip()\n if not timestamp_text:\n raise BadResponse({\"service\": SERVICE_NAME, \"message\": \"p id=timestamp\"})\n str_padding = \"This page was created at \" # String to be removed\n if not str_padding in timestamp_text:\n raise UnexpectedFormat(\n {\n \"service\": SERVICE_NAME,\n \"message\": \"Did not find 'This page was created at'\",\n }\n )\n timestamp_text = timestamp_text.replace(str_padding, \"\")\n issue_time = format_standard(\n parse_bomgovau_raw_footer_string_to_utc_datetime(timestamp_text)\n )\n forecast[\"issue_time\"] = issue_time\n\n # Retrieving the individual forecasts\n forecast[\"forecasts\"] = []\n days = soup.find_all(\"div\", attrs={\"class\": \"forecast-day collapsible\"})\n if not days:\n BadResponse(\n {\"service\": SERVICE_NAME, \"message\": \"div class='forecast-day collapsible'\"}\n )\n for day in days:\n try:\n date_string = day[\"id\"]\n except KeyError:\n raise BadResponse({\"service\": SERVICE_NAME, \"message\": \"day id=''\"})\n date = parse_bom_gov(date_string, timezone)\n search_string = \"temperature\"\n tables = day.find_all(\"table\")\n if not tables:\n raise BadResponse({\"service\": SERVICE_NAME, \"message\": \"table\"})\n for table in tables:\n if search_string in table[\"summary\"].lower():\n temperatures_table = table\n break\n else:\n # Exhausted list without finding search string\n raise BadReponse(\n {\n \"service\": SERVICE_NAME,\n \"message\": f\"Did not find a table with '{search_string}' in\",\n }\n )\n\n # Listing the local times\n #\n #\n\n ### Skipping the first one:\n ### At\n times_raw = table.find(\"thead\").find_all(\"th\")[1:]\n if not times_raw:\n raise BadResponse({\"service\": SERVICE_NAME, \"message\": \"thead > th\"})\n times_raw = [elt.text.strip() for elt in times_raw]\n\n ### Composing a full date string\n ### Prepend with the date\n time_utc_strings = []\n for t in times_raw:\n time = format_standard(\n parse_bomgovau_merge_date_as_dt_and_hour_as_string(\n date_dt=date, hour_string=t, target_timezone=timezone\n )\n )\n time_utc_strings.append(time)\n\n # Listing the temperatures\n #\n #\n temperatures_raw = temperatures_table.find(\"tbody\")\n if not temperatures_raw:\n raise BadResponse({\"service\": SERVICE_NAME, \"message\": \"tbody\"})\n search_string = \"Air temperature (°C)\"\n tr_list = temperatures_raw.find_all(\"tr\")\n if not tr_list:\n raise BadResponse({\"service\": SERVICE_NAME, \"message\": \"tbody > tr\"})\n for tmp_block in tr_list:\n if search_string in tmp_block.text:\n temperature_values = tmp_block.find_all(\"td\")\n if not temperature_values:\n raise BadResponse(\n {\"service\": SERVICE_NAME, \"message\": \"tbody > tr > td\"}\n )\n temperature_values = [\n parse_string_temperature(elt.text.strip())\n for elt in temperature_values\n ]\n break\n else:\n # Exhausted list without finding search string\n raise UnexpectedFormat(\n {\n \"service\": SERVICE_NAME,\n \"message\": f\"Did not find a table with '{search_string}' in\",\n }\n )\n\n # Ensuring as many hours as temperatures\n if len(time_utc_strings) != len(temperature_values):\n raise BadReponse(\n {\n \"service\": SERVICE_NAME,\n \"message\": f\"Date: {date}. Found {len(time_utc_strings)} hours, but {len(temperature_values)} hours\",\n }\n )\n\n # Saving the temperature forecasts\n for time, temperature in zip(time_utc_strings, temperature_values):\n if temperature:\n # Otherwise, the cell is empty because this time has passed\n forecast[\"forecasts\"].append(\n {\"time_utc\": time, \"temperature_celcius\": temperature}\n )\n return forecast\n\n\ndef retrieve(location_object, target_local_time):\n \"\"\"Retrieves the forecast for the desired time from the API\n\n Input:\n location_object\n {\n \"coordinates\": (-33.86, 151.21),\n \"accuweather_key\": 12481,\n \"timezone\": \"Australia/Sydney\",\n \"bom.gov.au\": \"http://www.bom.gov.au/places/nsw/sydney/forecast/detailed/\"\n }\n target_local_time\n '2020-04-11T09:00'\n\n Output:\n {\n \"ok\": True,\n \"time_utc\": \"\",\n \"temperature_celcius\": \"\"\n }\n \"\"\"\n target_time_utc = local_string_to_utc_string(\n time_local=target_local_time,\n timezone=location_object[\"timezone\"],\n format_func=format_standard,\n )\n\n html = fetch(location_object)\n soup = BeautifulSoup(html, \"lxml\")\n\n # Composing a forecast object\n forecast_object = soup_to_forecast_object(soup, location_object[\"timezone\"])\n\n # Retrieving the issue time, forecast age\n # Debug\n issue_time = forecast_object[\"issue_time\"]\n forecast_age_hours = hours_since_utc_datetime(\n utc_string_to_utc_datetime(issue_time)\n )\n forecast_age_decaminutes = decaminutes_since_utc_datetime(\n utc_string_to_utc_datetime(issue_time)\n )\n\n # Retrieving the forecasted temperature\n forecasts = forecast_object[\"forecasts\"]\n for forecast in forecasts:\n if forecast[\"time_utc\"] == target_time_utc:\n temperature = round(\n Decimal(forecast[\"temperature_celcius\"]), DECIMAL_PLACES\n )\n\n return {\n \"ok\": True,\n \"time_utc\": target_time_utc,\n \"temperature_celcius\": temperature,\n \"forecast_age_hours\": None, # The issue time appears incorrect\n \"forecast_age_decaminutes\": None,\n \"forecast_issue_time\": None, # The issue time appears incorrect\n }\n else:\n # Exhausted list of forecasts\n raise OutOfRange(\n {\n \"service\": SERVICE_NAME,\n \"message\": f\"Could not find a forecast for {target_time_utc}. Latest is {forecast['time_utc']}.\",\n }\n )\n\n\ndef retrieve_document(location_object):\n \"\"\"Calls the API to fetch the document once only\n May perform additional transformation depending on the service\n \"\"\"\n html = fetch(location_object)\n soup = BeautifulSoup(html, \"lxml\")\n\n # Composing a forecast object\n forecast_object = soup_to_forecast_object(soup, location_object[\"timezone\"])\n\n return forecast_object\n\n\ndef find_in_document(location_object, target_local_time, document):\n \"\"\"Finds the forecast for the desired time from the supplied API response\n\n Input:\n location_object\n {\n \"coordinates\": (-33.86, 151.21),\n \"accuweather_key\": 12481,\n \"timezone\": \"Australia/Sydney\",\n \"bom.gov.au\": \"http://www.bom.gov.au/places/nsw/sydney/forecast/detailed/\"\n }\n target_local_time\n '2020-04-11T09:00'\n\n Output:\n {\n \"ok\": True,\n \"time_utc\": \"\",\n \"temperature_celcius\": \"\"\n }\n \"\"\"\n target_time_utc = local_string_to_utc_string(\n time_local=target_local_time,\n timezone=location_object[\"timezone\"],\n format_func=format_standard,\n )\n\n # Retrieving a forecast object\n forecast_object = document\n\n # Retrieving the issue time, forecast age\n # Debug\n issue_time = forecast_object[\"issue_time\"]\n forecast_age_hours = hours_since_utc_datetime(\n utc_string_to_utc_datetime(issue_time)\n )\n forecast_age_decaminutes = decaminutes_since_utc_datetime(\n utc_string_to_utc_datetime(issue_time)\n )\n\n # Retrieving the forecasted temperature\n forecasts = forecast_object[\"forecasts\"]\n for forecast in forecasts:\n if forecast[\"time_utc\"] == target_time_utc:\n temperature = round(\n Decimal(forecast[\"temperature_celcius\"]), DECIMAL_PLACES\n )\n\n return {\n \"ok\": True,\n \"time_utc\": target_time_utc,\n \"temperature_celcius\": temperature,\n \"forecast_age_hours\": None, # The issue time appears incorrect\n \"forecast_age_decaminutes\": None,\n \"forecast_issue_time\": None, # The issue time appears incorrect\n }\n else:\n # Exhausted list of forecasts\n raise OutOfRange(\n {\n \"service\": SERVICE_NAME,\n \"message\": f\"Could not find a forecast for {target_time_utc}. Latest is {forecast['time_utc']}.\",\n }\n )\n","sub_path":"pyweather/pyweather/api/bom.py","file_name":"bom.py","file_ext":"py","file_size_in_byte":11580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"114653666","text":"\"\"\" Deploy and install a package to a target\n\n\"\"\"\n\nimport os\nimport sys\nimport zipfile\n\nfrom qisys import ui\n\nimport qisys.command\nimport qisys.parsers\n\ndef configure_parser(parser):\n qisys.parsers.default_parser(parser)\n qisys.parsers.deploy_parser(parser)\n parser.add_argument(\"pkg_path\")\n\ndef do(args):\n urls = qisys.parsers.get_deploy_urls(args)\n pkg_path = args.pkg_path\n if pkg_path.endswith(\".mpkg\"):\n pkg_paths = extract_meta_package(pkg_path)\n else:\n pkg_paths = [pkg_path]\n for url in urls:\n deploy(pkg_paths, url)\n\ndef deploy(pkg_paths, url):\n for i, pkg_path in enumerate(pkg_paths):\n ui.info_count(i, len(pkg_paths),\n ui.green, \"Deploying\",\n ui.reset, ui.blue, pkg_path,\n ui.reset, ui.green, \"to\",\n ui.reset, ui.blue, url.as_string)\n scp_cmd = [\"scp\",\n pkg_path,\n \"%s@%s:\" % (url.user, url.host)]\n qisys.command.call(scp_cmd)\n\n try:\n _install_package(url, pkg_path)\n except Exception as e:\n ui.error(\"Unable to install package on target\")\n ui.error(\"Error was: \", e)\n\ndef _install_package(url, pkg_path):\n import qi\n session = qi.Session()\n session.connect(\"tcp://%s:9559\" % (url.host))\n package_manager = session.service(\"PackageManager\")\n ret = package_manager.install(\n \"/home/%s/%s\" % (url.user, os.path.basename(pkg_path)))\n ui.info(\"PackageManager returned: \", ret)\n\ndef extract_meta_package(mpkg_path):\n res = list()\n with zipfile.ZipFile(mpkg_path) as archive:\n members = archive.infolist()\n for (i, member) in enumerate(members):\n if member.filename.endswith(\"-symbols.zip\"):\n continue\n archive.extract(member)\n res.append(member.filename)\n return res\n","sub_path":"python/qipkg/actions/deploy_package.py","file_name":"deploy_package.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"472895000","text":"#encoding: utf-8\nimport json\nimport time\nfrom operator import itemgetter\n\nfrom spider2 import get_response\nfrom mkexcel2 import simple_excel\nfrom filetool2 import emptydir\nfrom mail2 import send_email\n\nclass XueQiu:\n def __init__(self):\n self.url = 'http://xueqiu.com/stock/quote_order.json'\n self.headers = {\n 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4',\n 'Accept-Encoding': 'deflate, sdch',\n 'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',\n 'Host' : 'xueqiu.com',\n 'Cookie' : 'xq_a_token=ef3d00f3891d9974ecc1180ee6b20edf51d00d44; xqat=ef3d00f3891d9974ecc1180ee6b20edf51d00d44; xq_r_token=89dbe5bfb062a42ce04f6bf475eac835f783186c; xq_is_login=1; xq_token_expire=Tue%20May%2019%202015%2009%3A28%3A22%20GMT%2B0800%20(CST); bid=96a0af5d0fe7ea4f2443e9f25ae2025a_i8ux6d03; snbim_minify=true; __utma=1.982576837.1429838325.1430118616.1430122413.4; __utmb=1.5.10.1430122413; __utmc=1; __utmz=1.1429838325.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); Hm_lvt_1db88642e346389874251b5a1eded6e3=1429843458,1429852111,1430097686,1430110994; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1430122648'\n }\n\n self.stock_type = 'cyb'\n\n self.start_page = 1\n self.end_page = 1\n\n self.size = 90 #每页显示\n\n self.pause_time = 5 #停5秒\n\n self.data = [['代码', '名称', '当前价', '52周最高价', '降幅']]\n\n self.template = '/home/hong/github/cookie/python/template/stock_xueqiu.xls'\n self.filename = '/home/hong/github/cookie/python/output/stock_xueqiu.xls'\n\n def crawl_page(self):\n for page in xrange(self.start_page, self.end_page+1):\n params = {\n 'page': page,\n 'size': self.size,\n 'order': 'desc',\n 'exchange': 'CN',\n 'stockType': self.stock_type,\n 'column': 'symbol,name,current,chg,percent,last_close,open,high,low,volume,amount,market_capital,pe_ttm,high52w,low52w,hasexist',\n 'orderBy': 'percent',\n }\n\n response = json.loads(get_response(self.url, headers = self.headers, params = params).read().decode('utf-8'))\n\n for row in response['data']:\n drop = round((row[-3] - row[2])/row[-3], 4)\n\n if drop >= 0.15:\n self.data.append([row[0], row[1], row[2], row[-3], '{}%'.format(100 * drop)])\n\n self.data = list(set(tuple(i) for i in self.data)) #remove duplicates\n\n self.data.sort(key=itemgetter(4), reverse=True) #sort by drop\n\n time.sleep(self.pause_time)\n\n def produce(self):\n type_list = [\n ('cyb', 5), #创业板\n ('sha', 11), #沪A\n ('sza', 16), #深A\n ('zxb', 7) #中小板\n ]\n\n for (stock_type, end_page) in type_list:\n self.stock_type = stock_type\n self.end_page = end_page\n self.crawl_page()\n\n def make_file(self):\n emptydir('/home/hong/github/cookie/python/output')\n\n simple_excel(self.data, self.template, self.filename)\n\n def send_email(self):\n send_from = 'reporting@pinstore.cn'\n send_to = ['181366927@qq.com', 'hongjiongteng@pinstore.cn']\n subject = '从52周最高值降幅超过15%的股票(来自雪球)'\n text = ''\n files = [self.filename]\n server = 'mail.pinstore.cn'\n auth = {'user': send_from, 'password': '1fa4ed'}\n\n send_email(send_from, send_to, subject, text, files, server, auth)\n","sub_path":"python/lib/stock_xueqiu.py","file_name":"stock_xueqiu.py","file_ext":"py","file_size_in_byte":3816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"650839493","text":"# type: ignore\n\nimport os\nimport types\n\nfrom setuptools import setup, find_packages\nfrom importlib.machinery import SourceFileLoader\n\nBASE_PATH = os.path.abspath(os.path.dirname(__file__))\n\n\ndef get_version():\n version_filepath = os.path.join(BASE_PATH, \"cmaes\", \"version.py\")\n module_name = \"version\"\n target_module = types.ModuleType(module_name)\n loader = SourceFileLoader(module_name, version_filepath)\n loader.exec_module(target_module)\n\n return getattr(target_module, \"__version__\")\n\n\nsetup(\n name=\"cmaes\",\n version=get_version(),\n author=\"Masashi Shibata\",\n author_email=\"shibata_masashi@cyberagent.co.jp\",\n url=\"https://github.com/CyberAgent/cmaes\",\n description=\"Lightweight Covariance Matrix Adaptation Evolution Strategy (CMA-ES) \"\n \"implementation for Python 3.\",\n long_description=open(os.path.join(BASE_PATH, \"README.md\")).read(),\n long_description_content_type=\"text/markdown\",\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Intended Audience :: Science/Research\",\n ],\n packages=find_packages(exclude=[\"test*\", \"benchmark*\", \"examples\"]),\n install_requires=[\"numpy\"],\n extras_require={\n \"benchmark\": [\"kurobako\", \"cma\", \"optuna\"],\n \"visualization\": [\"matplotlib\", \"scipy\"],\n \"lint\": [\"mypy\", \"flake8\", \"black\", \"optuna\"],\n \"test\": [\"optuna\"],\n \"release\": [\"wheel\", \"twine\"],\n },\n tests_require=[],\n keywords=\"cma-es evolution-strategy optuna\",\n license=\"MIT License\",\n include_package_data=True,\n test_suite=\"tests\",\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"316987088","text":"# \n#\n# Imports\nimport json\n# import pdb # debug\nfrom functools import partial #functional style\n\ndef is_valid_input(inp):\n jval = '{ \"val\": ' + '[' + inp + ']' + ' }'\n try:\n json.loads(jval)\n return True\n except:\n return False\n\n\ndef add_record(record,db):\n db.append(record)\n\n\n# make query\ndef select(db,selector):\n rds = filter(selector,db)\n return list(rds)\n\ndef comp_2(key,dict1,dict2):\n if dict1[key]==dict2[key]:\n return True\n else:\n return False\n\ndef compare_records(dict1,dict2):\n keys=dict1.keys()\n ans=[]\n for item in keys:\n ans.append(comp_2(item,dict1,dict2))\n return all(ans)\n\n# make selector\n# Create the query to select\n# Should be like '\"key\": value'\ndef where(clauses=\"\"):\n clauses = '{'+clauses+'}'\n if is_valid_input(clauses):\n cls_map = json.loads(clauses)\n else: \n cls_map = json.loads(\"{}\")\n return partial(compare_records,cls_map)\n\n","sub_path":"src/MyDB.py","file_name":"MyDB.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"437550498","text":"\n# Las listas son un conjunto de objetos\n# Pueden cambiar de tamaño y pueden cambiar los tipos de datos que tienen\n\n# ─────────────────────────────────────────────────────────────────────────────\n\nlista = [1,2,3,4,5]\n\n# También se puede usar:\n\nlista_nueva = list([1,2,3,4])\n\n# Si queremos agregar un elemento\n\nlista = lista + [6,7]\n\n# También se puede usar:\n\nlista += [8,9]\n\n# También se puede usar:\n\nlista.append(10)\nlista.append(\"Alex\")\n\n# Podemos agregar una lista dentro de otra\n\nlista.append([-1,-2,-3])\n\n# .append() solo acepta un elemento\n\n# .extend() para agregar más de un elemento\n\nlista.extend([-4,-5])\n\n# .remove() para quitar un elemento\n\nlista.remove(2)\n\n# ─────────────────────────────────────────────────────────────────────────────\n\n# Para repetir la lista\n\nlista * 3\n\n# ─────────────────────────────────────────────────────────────────────────────\n\n# .split() separa una cadena de texto usando de separador el espacio\n\n\"Hola buenas noches\".split()\n# ['Hola','buenas','noches']\n\n# También se puede usar como separador cualquier elemento que queramos\n\ncomida_favorita = \"Pupusas, Pollo, Carne\"\ncomida_favorita.split(\",\")\n# ['Pupusas','Pollo','Carne']\n\n\n# .join() une los elementos de un array en una cadena\n\n\",\".join(comida_favorita)\n# ['Pupusas, Pollo, Carne']\n","sub_path":"Python/Introduccion/listas.py","file_name":"listas.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"33373615","text":"import re\nimport sys\nfrom collections import defaultdict\n\n\ndef normalized_scores(scores, small_is_better=False):\n zero = 0.000001\n if small_is_better:\n min_score = min(scores.values())\n return {u: float(min_score) / max(zero, v) for u, v in scores.items()}\n else:\n max_score = max(scores.values())\n max_score = max_score if max_score != 0 else zero\n return {u: float(v) / max_score for u, v in scores.items()}\n\n\ndef frequency_score(urls):\n scores = defaultdict(int)\n for url, positions in urls:\n scores[url] += len(positions)\n return normalized_scores(scores)\n\n\ndef unique_word_score(urls):\n scores = defaultdict(int)\n for url, positions in urls:\n scores[url] += 1\n return normalized_scores(scores)\n\n\ndef location_score(urls):\n scores = defaultdict(lambda: sys.maxsize)\n for url, positions in urls:\n scores[url] = min(scores[url], positions[0])\n return normalized_scores(scores, small_is_better=True)\n\n\ndef get_scored_urls(urls):\n total_scores = defaultdict(float)\n weights = [\n (1.0, frequency_score(urls)),\n (1.0, unique_word_score(urls)),\n (0.25, location_score(urls)),\n ]\n for weight, scores in weights:\n for url in scores:\n total_scores[url] += weight * scores[url]\n total_scores = {k: round(v, 1) for k, v in total_scores.items()}\n return list(total_scores.items())\n\n\nclass Searcher(object):\n def __init__(self, index, query):\n self.index = index\n self.words = re.findall(r'[\\w-]+', query)\n\n def get_matched_urls(self):\n all_urls = []\n for word in self.words:\n word_dict = self.index.get(word, dict())\n for url in word_dict:\n all_urls.append((url, word_dict[url]))\n return all_urls\n\n def search(self, with_scores=False):\n urls = self.get_matched_urls()\n if not urls:\n return urls\n scored_urls = get_scored_urls(urls)\n scored_urls.sort(key=lambda x: x[1], reverse=True)\n if with_scores:\n return scored_urls\n return [url for url, _ in scored_urls]\n","sub_path":"searching.py","file_name":"searching.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"587653292","text":"# -*- coding: utf-8 -*-\n\nimport os\n\nfrom application.lib import LoginRequest\n\n\ndef keepalive_job(app):\n url = app.config.get('KEEPALIVE')\n\n if url is not None:\n with app.app_context():\n app.logger.info('**[KeepAlive-Jobs]** Access %s' % url)\n webhook = LoginRequest()\n webhook.curl(url)\n","sub_path":"working/application/jobs/keepalive.py","file_name":"keepalive.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"634300415","text":"from __future__ import print_function, division\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport time\n\nfrom nilmtk import DataSet, TimeFrame, MeterGroup, HDFDataStore\nfrom nilmtk.disaggregate import FHMM\n\nimport pandas as pd\n\n# Bring packages onto the path\nimport sys, os\nsys.path.append(os.path.abspath('../bayesian_optimization/'))\n\nfrom utils import metrics\n\n\ndef fhmm(dataset_path, train_building, train_start, train_end, val_building, val_start, val_end, test_building, test_start, test_end, meter_key, sample_period):\n\n # Start tracking time\n start = time.time()\n\n # Prepare dataset and options\n # print(\"========== OPEN DATASETS ============\")\n dataset_path = dataset_path\n train = DataSet(dataset_path)\n train.set_window(start=train_start, end=train_end)\n val = DataSet(dataset_path)\n val.set_window(start=val_start, end=val_end)\n test = DataSet(dataset_path)\n test.set_window(start=test_start, end=test_end)\n train_building = train_building\n test_building = test_building\n meter_key = meter_key\n\n sample_period = sample_period\n\n\n train_elec = train.buildings[train_building].elec\n val_elec = val.buildings[val_building].elec\n test_elec = test.buildings[test_building].elec\n\n appliances = [meter_key]\n selected_meters = [train_elec[app] for app in appliances]\n selected_meters.append(train_elec.mains())\n selected = MeterGroup(selected_meters)\n\n fhmm = FHMM()\n\n # print(\"========== TRAIN ============\")\n fhmm.train(selected, sample_period=sample_period)\n\n # print(\"========== DISAGGREGATE ============\")\n # Validation\n val_disag_filename = 'disag-out-val.h5'\n output = HDFDataStore(val_disag_filename, 'w')\n fhmm.disaggregate(val_elec.mains(), output_datastore=output)\n output.close()\n # Test\n test_disag_filename = 'disag-out-test.h5'\n output = HDFDataStore(test_disag_filename, 'w')\n fhmm.disaggregate(test_elec.mains(), output_datastore=output)\n output.close()\n\n # print(\"========== RESULTS ============\")\n # Validation\n result_val = DataSet(val_disag_filename)\n res_elec_val = result_val.buildings[val_building].elec\n rpaf_val = metrics.recall_precision_accuracy_f1(res_elec_val[meter_key], val_elec[meter_key])\n\n val_metrics_results_dict = {\n 'recall_score': rpaf_val[0],\n 'precision_score': rpaf_val[1],\n 'accuracy_score': rpaf_val[2],\n 'f1_score': rpaf_val[3],\n 'mean_absolute_error': metrics.mean_absolute_error(res_elec_val[meter_key], val_elec[meter_key]),\n 'mean_squared_error': metrics.mean_square_error(res_elec_val[meter_key], val_elec[meter_key]),\n 'relative_error_in_total_energy': metrics.relative_error_total_energy(res_elec_val[meter_key], val_elec[meter_key]),\n 'nad': metrics.nad(res_elec_val[meter_key], val_elec[meter_key]),\n 'disaggregation_accuracy': metrics.disaggregation_accuracy(res_elec_val[meter_key], val_elec[meter_key])\n }\n # Test\n result = DataSet(test_disag_filename)\n res_elec = result.buildings[test_building].elec\n rpaf = metrics.recall_precision_accuracy_f1(res_elec[meter_key], test_elec[meter_key])\n\n test_metrics_results_dict = {\n 'recall_score': rpaf[0],\n 'precision_score': rpaf[1],\n 'accuracy_score': rpaf[2],\n 'f1_score': rpaf[3],\n 'mean_absolute_error': metrics.mean_absolute_error(res_elec[meter_key], test_elec[meter_key]),\n 'mean_squared_error': metrics.mean_square_error(res_elec[meter_key], test_elec[meter_key]),\n 'relative_error_in_total_energy': metrics.relative_error_total_energy(res_elec[meter_key], test_elec[meter_key]),\n 'nad': metrics.nad(res_elec[meter_key], test_elec[meter_key]),\n 'disaggregation_accuracy': metrics.disaggregation_accuracy(res_elec[meter_key], test_elec[meter_key])\n }\n\n # end tracking time\n end = time.time()\n\n time_taken = end-start # in seconds\n\n # model_result_data = {\n # 'algorithm_name': 'FHMM',\n # 'datapath': dataset_path,\n # 'train_building': train_building,\n # 'train_start': str(train_start.date()) if train_start != None else None ,\n # 'train_end': str(train_end.date()) if train_end != None else None ,\n # 'test_building': test_building,\n # 'test_start': str(test_start.date()) if test_start != None else None ,\n # 'test_end': str(test_end.date()) if test_end != None else None ,\n # 'appliance': meter_key,\n # 'sampling_rate': sample_period,\n #\n # 'algorithm_info': {\n # 'options': {\n # 'epochs': None\n # },\n # 'hyperparameters': {\n # 'sequence_length': None,\n # 'min_sample_split': None,\n # 'num_layers': None\n # },\n # 'profile': {\n # 'parameters': None\n # }\n # },\n #\n # 'metrics': metrics_results_dict,\n #\n # 'time_taken': format(time_taken, '.2f'),\n # }\n\n model_result_data = {\n 'val_metrics': val_metrics_results_dict,\n 'test_metrics': test_metrics_results_dict,\n 'time_taken': format(time_taken, '.2f'),\n 'epochs': None,\n }\n\n # Close digag_filename\n result.store.close()\n result_val.store.close()\n\n # Close Dataset files\n train.store.close()\n val.store.close()\n test.store.close()\n\n return model_result_data\n","sub_path":"bayesian_optimization/algorithms/fhmm.py","file_name":"fhmm.py","file_ext":"py","file_size_in_byte":5432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"208876136","text":"import os\nimport re\n\nimport pandas as pd\nimport numpy as np\n\nwork_dir = os.getcwd()\n\ncolumns = ['X2', 'X3', 'X15', 'X23', 'X32']\ndf_train = pre_process_data(work_dir, is_train=True, transform=False).loc[:, columns]\ndf_test = pre_process_data(work_dir, is_train=False, transform=False).loc[:, columns]\n\nto_dates = ['X15', 'X23']\n#df = df_test.copy()\ndf = df_test[df_test.X23 == 'Dec-68'].copy()\n\n\ndef year_trans(x):\n if bool(re.search(\"[A-Za-z]-\\d+\", x)):\n year = int(re.sub('\\D+', '', re.search(\"[A-Za-z]?-(\\\\d+)\", x).group()))\n if year < 16:\n res = pd.to_datetime(x, format='%b-%y')\n else:\n res = pd.to_datetime(x, format='%b-%y') - pd.DateOffset(years=100)\n return res\n elif bool(re.search(\"\\d+-[A-Za-z]\", x)):\n res = pd.to_datetime(x, dayfirst=True, format=\"%d-%b\") + pd.DateOffset(years=114)\n return res\n\nfor c in to_dates:\n if c in ['X15']:\n df.loc[:, c] = df.loc[:, c].apply(lambda x: pd.to_datetime(x, format='%y-%b'))\n elif c in ['X23']:\n df.loc[:, c] = df.loc[:, c].apply(lambda x: year_trans(x))\n\ndf.loc[:, 'X33'] = [int(i.days) for i in (df.X15 - df.X23)]","sub_path":"tmp.py","file_name":"tmp.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"235435993","text":"from lampost.context.resource import m_requires\r\n\r\nm_requires('cls_registry', __name__)\r\n\r\n\r\nclass TemplateException(Exception):\r\n pass\r\n\r\n\r\nclass Template(object):\r\n dbo_fields = (\"dbo_rev\", \"instance_class\", \"world_max\")\r\n class_map = {}\r\n template_fields = []\r\n instance_count = 0\r\n instance_class = None\r\n world_max = 1000000\r\n dbo_rev = 0\r\n\r\n def __init__(self, dbo_id):\r\n self.dbo_id = unicode(dbo_id)\r\n\r\n def config_instance(self, instance):\r\n pass\r\n\r\n def get_class(self):\r\n clazz = self.class_map.get(self.instance_class)\r\n if clazz:\r\n return clazz\r\n split_path = self.instance_class.split(\".\")\r\n module_name = \".\".join(split_path[:-1])\r\n class_name = split_path[-1]\r\n module = __import__(module_name, globals(), locals(), [class_name])\r\n clazz = getattr(module, class_name)\r\n self.class_map[self.instance_class] = clazz\r\n return clazz\r\n\r\n def create_instance(self):\r\n if self.instance_count >= self.world_max:\r\n raise TemplateException\r\n instance = self.get_class()(self.dbo_id)\r\n for field in self.template_fields:\r\n setattr(instance, field, getattr(self, field, None))\r\n instance.on_loaded()\r\n instance.template = self\r\n self.instance_count += 1\r\n self.config_instance(instance)\r\n return instance\r\n\r\n def delete_instance(self, instance):\r\n self.instance_count -= 1\r\n\r\n","sub_path":"lampost/gameops/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"289893108","text":"import os\n\ndef initialize_flask_server_debugger_if_needed():\n if os.environ.get(\"DEBUGGER\", \"True\") == \"True\":\n import multiprocessing\n\n if multiprocessing.current_process().pid > 1:\n import debugpy\n\n DEBUG_PORT = int(os.environ.get(\"DEBUG_PORT\", \"10001\"))\n\n debugpy.listen((\"0.0.0.0\", DEBUG_PORT))\n print(\"⏳ VS Code debugger can now be attached, press F5 in VS Code ⏳\", flush=True)\n debugpy.wait_for_client()\n print(\"🎉 VS Code debugger attached, enjoy debugging 🎉\", flush=True)","sub_path":"app/debugger.py","file_name":"debugger.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"9607870","text":"import io\nimport logging\nfrom PIL import Image\nimport time\n\n\ndef make_thumbnail(img_buf, target_size):\n with io.BytesIO(img_buf) as fp:\n with Image.open(fp) as img:\n logging.info('beginning image resizing')\n\n start = time.perf_counter()\n wpercent = (target_size / float(img.size[0]))\n hsize = int((float(img.size[1]) * float(wpercent)))\n img = img.resize((target_size, hsize), Image.LANCZOS)\n\n with io.BytesIO() as fp_ret:\n img.save(fp_ret, 'JPEG')\n fp_ret.seek(0)\n end = time.perf_counter()\n logging.info(f'created thumbnail in {end-start} seconds')\n return fp_ret.read()\n","sub_path":"image_processing/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"365053861","text":"#! /usr/bin/python3.3\n\"\"\"\n Project Euler #20\n Author: Robert McLaughlin\n \n Consult LICENSE file for license.\n\"\"\"\n\nimport math\n\ndef main():\n \"\"\"\n Returns the solution to the problem\n \"\"\"\n return sum(map(lambda x: int(x), str(math.factorial(100))))\n\nif __name__ == '__main__':\n import time\n start = time.time()\n \n print(\"Solution: {0:,d}\".format(main()))\n \n diff = time.time() - start\n if diff < 1:\n print(\"Took {0:.4f} milliseconds\".format(diff*1000))\n elif diff < 60:\n print(\"Took {0:.4f} seconds\".format(diff))\n elif diff < 360:\n print(\"Took {0:.4f} minutes\".format(diff/60))\n else:\n print(\"Took {0:.4f} hours\".format(diff/60/60))\n","sub_path":"20/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"632774322","text":"import tensorflow as tf\nfrom tensorflow.core.framework import graph_pb2\n\n# read frozen graph and display nodes\ngraph = tf.GraphDef()\ngraph.ParseFromString(open('rounded_graph.pb','rb').read())\n\ndef display_nodes(nodes):\n for i, node in enumerate(nodes):\n print('%d %s %s' % (i, node.name, node.op))\n # [print(u'└─── %d ─ %s' % (i, n.encode(\"utf-8\"))) for i, n in enumerate(node.input)]\n \ndisplay_nodes(graph.node)\n\n# # Connect 'MatMul_1' with 'Relu_2'\ngraph.node[419].input[0] = 'Pad' # 44 -> MatMul_1\n# # Remove dropout nodes\nnodes = graph.node[:416] + graph.node[417:] # 33 -> MatMul_1 \n# del nodes[1] # 1 -> keep_prob\n\n# Save graph\noutput_graph = graph_pb2.GraphDef()\noutput_graph.node.extend(nodes)\nwith tf.gfile.GFile('./rounded_graph_without_dropout.pb', 'w') as f:\n f.write(output_graph.SerializeToString())","sub_path":"tf_pi/remove.py","file_name":"remove.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"226808222","text":"import requests\nimport re\nimport json\nimport hashlib\nimport datetime\nfrom pyaria2 import PyAria2\n\nBILIBILI_APP_KEY = '84956560bc028eb7'\nBILIBILI_APP_SECRET = '94aba54af9065f71de72f5508f1cd42e'\n\nRE_VIDEOINFO = re.compile(r'window.__INITIAL_STATE__=(.*);\\(function\\(\\){var s;')\n\ndef getPostInfo(avid):\n html = requests.get('https://www.bilibili.com/video/av%s' % avid).text\n match = RE_VIDEOINFO.search(html)\n if match:\n result = json.loads(match.group(1))\n if 'code' not in result['error'].keys():\n return result\n\ndef getVideoSegmentedLinks(cid):\n params = 'appkey=%s&cid=%s&otype=json&qn=80&quality=80' % (BILIBILI_APP_KEY, cid)\n sign = hashlib.md5((params + BILIBILI_APP_SECRET).encode('utf-8')).hexdigest()\n playurl = 'https://interface.bilibili.com/v2/playurl?%s&sign=%s' % (params, sign)\n\n hds = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',\n 'Referer': 'https://www.bilibili.com/',\n 'Origin': 'https://www.bilibili.com'\n }\n result = requests.get(playurl, headers=hds).json()\n links = []\n if result['result'] == 'suee':\n for durl in result['durl']:\n current_links = []\n current_links.append(durl['url'])\n for l in durl['backup_url']:\n current_links.append(l)\n links.append(current_links)\n return links\n\ndef durationToTime(duration):\n (min, sec) = divmod(duration, 60)\n (hrs, min) = divmod(min, 60)\n return datetime.time(hour=hrs, minute=min, second=sec)\n\ndef escapeFileName(fileName):\n return re.sub(r'[\\/:*?\"<>|]', ' ', fileName)\n\ndef getAria2cClientInstance():\n return PyAria2(host='localhost', port=6800) # configure here","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"174717792","text":"class Node(object):\n def __init__(self, val, next, random):\n self.val = val\n self.next = next\n self.random = random\n\n\n# clone nodes first, then clone the connections between them\n# note: many random pointers may point to None, not only the last node\n\nclass Solution(object):\n def copyRandomList(self, head):\n \"\"\"\n :type head: Node\n :rtype: Node\n \"\"\"\n if not head:\n return None\n \n # copy every node, don't set the randome pointer yet\n # the copied node is inserted right after the original node\n p1 = head\n while p1:\n p2 = p1.next\n new_node = Node(p1.val, p2, None)\n p1.next = new_node\n p1 = p2\n \n # set the random pointer\n p1 = head\n while p1:\n if p1.random: # p1.random might be None !!!\n p1.next.random = p1.random.next\n p1 = p1.next.next\n \n # separate original list and the newly copied list\n dummy = Node(0, None, None)\n cur = dummy\n p1 = head\n while p1:\n p2 = p1.next\n p3 = p2.next\n cur.next = p2\n cur = cur.next\n p1.next = p3\n p1 = p3\n if cur:\n cur.next = None\n \n return dummy.next\n\n\n\n\"\"\"\nA linked list is given such that each node contains an additional random pointer \nwhich could point to any node in the list or null.\n\nReturn a deep copy of the list.\n\n \n\nExample 1:\n\n\n\nInput:\n{\"$id\":\"1\",\"next\":{\"$id\":\"2\",\"next\":null,\"random\":{\"$ref\":\"2\"},\"val\":2},\"random\":{\"$ref\":\"2\"},\"val\":1}\n\nExplanation:\nNode 1's value is 1, both of its next and random pointer points to Node 2.\nNode 2's value is 2, its next pointer points to null and its random pointer points to itself.\n \n\nNote:\n\nYou must return the copy of the given head as a reference to the cloned list.\n\"\"\"\n","sub_path":"Templates/0138. Copy List with Random Pointer.py","file_name":"0138. Copy List with Random Pointer.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"117856936","text":"\"\"\"\nMondrian Pictures in Python\n\"\"\"\n\n# Import Modules\nfrom graphics import *\nfrom random import *\n\n# Height & Width\npic_width = 600\npic_height = 600\n\nwin = GraphWin(title = \"Cooper's Coffee\", width = pic_width, height = pic_height)\nwin.setCoords(0,0,pic_width-1, pic_height-1)\nwin.setBackground(\"gray\")\n\n# Rectangles (all possible)\ngrid1 = Rectangle(Point(0,0), Point(200,200)) \ngrid2 = Rectangle(Point(200,200), Point(400,400)) \ngrid3 = Rectangle(Point(400,400), Point(600,600))\ngrid4 = Rectangle(Point(0,200), Point(200,400))\ngrid5 = Rectangle(Point(0,400), Point(200,600))\ngrid6 = Rectangle(Point(200,400), Point(400,600))\ngrid7 = Rectangle(Point(200,0), Point(400,200))\ngrid8 = Rectangle(Point(400,0), Point(600,200))\ngrid9 = Rectangle(Point(400,200), Point(600,400))\n\n#List of grid spaces\nposition_list = [grid1, grid2, grid3, grid4, grid5, grid6, grid7, grid8, grid9]\n\n# Rectangle creation\nrect1 = choice(position_list)\nrect1.setFill(color_rgb(randint(0, 255), randint(0, 255), randint(0, 255)))\nrect1.setWidth(8)\nrect1.draw(win)\n\nrect2 = choice(position_list)\nrect2.setFill(color_rgb(randint(0, 255), randint(0, 255), randint(0, 255)))\nrect2.setWidth(8)\nrect2.draw(win)\n\nrect3 = choice(position_list)\nrect3.setFill(color_rgb(randint(0, 255), randint(0, 255), randint(0, 255)))\nrect3.setWidth(8)\nrect3.draw(win)\n\nwin.getMouse()\nwin.close()\n\n","sub_path":"mondrian_pics.py","file_name":"mondrian_pics.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"344875827","text":"from django.conf import settings\nfrom django.test import TestCase\nfrom django.core.urlresolvers import reverse\nfrom livesettings import config_value, config_get\nfrom cc.conf import coresettings\nfrom cc.shop import postage_required\nfrom cc.shop.payments.sagepay.payment import ProtxPayment\nfrom cc.shop.payments.paypal.payment import PayPal\nfrom cc.shop.models.orders import *\nfrom cc.shop.models.products import *\nfrom cc.shop.models.basket import *\nfrom cc.shop.models.postage import *\nfrom cc.shop.models.customer import * \nfrom cc.shop.forms.postage import *\nfrom original_tests import BaseBasketTest\n#\n\n\nclass BillingAddressTestCases(BaseBasketTest):\n fixtures = ['shop.json']\n \n def setUp(self):\n self.address_data_billing = {\n 'address1' : '1 Test House', \n 'region' : 'Test Region', \n 'postcode' : 'T35 T3R', \n 'country' : '1',\n 'billing-address1' : '1 Test House Billing', \n 'billing-locality' : 'Test Locality Billing', \n 'billing-region' : 'Test Region', \n 'billing-postcode' : 'BIL LNG', \n 'billing-country' : '1'\n \n }\n self.address_data_no_billing = {\n 'address1' : '1 Test House', \n 'region' : 'Test Region', \n 'postcode' : 'T35 T3R', \n 'country' : '1',\n 'billing_is_delivery' : 'on'\n }\n \n \n def test_order_has_billing_address(self):\n # product in basket\n p1, p2, p3 = self.products()\n request = self.client.post(reverse('shop_basket_update'), {'product_ctype_pk' : self.ct_pk(p1), 'product_pk' : p1.pk, 'quantity': 1})\n # enter personal details\n request = self.client.post(reverse('shop_checkout_customer'), {'name' : 'Mr Test', 'email' : 'jamie+mrtest@designcc.co.uk', 'phone' : '123123'}, follow=True)\n self.failUnlessEqual(('http://testserver%s' % reverse('shop_checkout_address')), request.redirect_chain[0][0])\n # send address and seperate billing address\n request = self.client.post(reverse('shop_checkout_address'), self.address_data_billing, follow=True)\n self.failUnlessEqual(('http://testserver%s' % reverse('shop_checkout_postage')), request.redirect_chain[0][0])\n # choose the postage method\n request = self.client.post(reverse('shop_checkout_postage'), {'postage' : 1}, follow=True)\n self.failUnlessEqual(('http://testserver%s' % reverse('shop_checkout_confirm')), request.redirect_chain[0][0])\n #\n # get the current amount of orders\n orders = Order.objects.new()\n self.failUnlessEqual(orders.count(), 3)\n #\n # now submit the form and we should get re-directed to the orders page\n request = self.client.post(reverse('shop_payments_dummy'), follow=True)\n self.failUnlessEqual(('http://testserver%s' % reverse('shop_order_success', args=[request.context['order'].ref])), request.redirect_chain[0][0])\n #\n # we should now have one more order\n orders = Order.objects.new()\n self.failUnlessEqual(orders.count(), 4)\n # order should have a billing address matching the one we sent\n order = Order.objects.get(pk=4)\n self.assertEqual(order.billing_address1, self.address_data_billing['billing-address1'] )\n self.assertEqual(order.billing_locality, self.address_data_billing['billing-locality'] )\n self.assertEqual(order.billing_region, self.address_data_billing['billing-region'] )\n self.assertEqual(order.billing_postcode, self.address_data_billing['billing-postcode'] )\n self.assertEqual(order.billing_country, 'United Kingdom' )\n \n \n \n ","sub_path":"cc/shop/tests/billing_address_tests.py","file_name":"billing_address_tests.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"14284824","text":"\"\"\"\nName: QuadMeshClass.py\nAuthor: Sid Bishnu\nDetails: This script defines the quadrilateral mesh class for two-dimensional spectral element methods.\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FuncFormatter\nimport os\nimport sys\nfrom IPython.utils import io\nwith io.capture_output() as captured:\n import HashTableClass as HT\n import GeometryBasics2DClass as GB2D\n import CornerNode2DClass as CN2D\n import QuadElementClass as QE\n import EdgeClass as EC\n\n\nclass QuadMeshParameters:\n \n def __init__(myQuadMeshParameters):\n myQuadMeshParameters.NONE = 10**5\n myQuadMeshParameters.INTERIOR = 10**6\n myQuadMeshParameters.DIRICHLET_SOUTH = 10**7\n myQuadMeshParameters.DIRICHLET_EAST = 10**8\n myQuadMeshParameters.DIRICHLET_NORTH = 10**9\n myQuadMeshParameters.DIRICHLET_WEST = 10**10\n\n\nclass QuadMesh:\n \n def __init__(myQuadMesh,lX,lY,nElementsX,nElementsY,myDGNodalStorage2D,ProblemType,ProblemType_EquatorialWave=False,\n PrintEdgeProperties=False):\n myQuadMesh.myQuadMeshParameters = QuadMeshParameters()\n myQuadMesh.lX = lX\n myQuadMesh.lY = lY\n myQuadMesh.nElementsX = nElementsX\n myQuadMesh.nElementsY = nElementsY\n nElements = nElementsX*nElementsY\n myQuadMesh.nElements = nElements\n myQuadMesh.dx = lX/float(nElementsX)\n myQuadMesh.dy = lY/float(nElementsY)\n myQuadMesh.myQuadElements = np.empty(nElements,dtype=QE.QuadElement) \n nNodes = (nElementsX + 1)*(nElementsY + 1)\n myQuadMesh.nNodes = nNodes\n myQuadMesh.myCornerNodes = np.empty(nNodes,dtype=CN2D.CornerNode)\n nEdgesByFormula = nElements + nNodes - 1 # This is true for a structured mesh with no holes as in our case.\n myQuadMesh.myEdges = np.empty(nEdgesByFormula,dtype=EC.Edge)\n nXi = myDGNodalStorage2D.nXi\n nEta = myDGNodalStorage2D.nEta\n myQuadMesh.SideMap = np.array([0,nXi,nEta,0],dtype=int)\n # The sidemap of a side is nothing but the coordinate of every point on that side which remains constant.\n myQuadMesh.CornerMap = np.zeros((2,4),dtype=int)\n myQuadMesh.CornerMap[0,:] = np.array([0,nXi,nXi,0],dtype=int)\n myQuadMesh.CornerMap[1,:] = np.array([0,0,nEta,nEta],dtype=int)\n # The CornerMaps are nothing but the coordinates of each corner viz. {(0,0), (nXi,0), (nXi,nEta) and (0,nEta)}.\n myQuadMesh.EdgeMap = np.zeros((2,4),dtype=int)\n myQuadMesh.EdgeMap[0,:] = np.array([1,2,4,1],dtype=int)\n myQuadMesh.EdgeMap[1,:] = np.array([2,3,3,4],dtype=int)\n # The EdgeMap is just the set of local NodeIDs connected by each edge viz. {(1,2), (2,3), (4,3) and (1,4)} \n # where the ordering of the local NodeIDs are along the positive xi and eta directions.\n # Construct the corner nodes with their x and y coordinates. \n myQuadMesh.BuildCornerNodes(ProblemType,ProblemType_EquatorialWave)\n # Construct the elements with elementID, the global NodeIDs of the four corner nodes, boundary curves, and \n # geometry.\n myQuadMesh.BuildQuadElements(myDGNodalStorage2D)\n myQuadMesh.GetNodeConnectivityAndConstructEdges(PrintEdgeProperties)\n\n def BuildCornerNodes(myQuadMesh,ProblemType,ProblemType_EquatorialWave=False):\n lX = myQuadMesh.lX\n lY = myQuadMesh.lY\n nElementsX = myQuadMesh.nElementsX\n nElementsY = myQuadMesh.nElementsY\n dx = myQuadMesh.dx\n dy = myQuadMesh.dy\n for iNodeY in range(0,nElementsY+1):\n for iNodeX in range(0,nElementsX+1):\n GlobalNodeID = iNodeY*(nElementsX+1) + iNodeX + 1\n if ProblemType == 'Plane_Gaussian_Wave':\n xCoordinate = float(iNodeX)*dx - 0.5*lX\n else:\n xCoordinate = float(iNodeX)*dx\n if ProblemType == 'Plane_Gaussian_Wave' or ProblemType_EquatorialWave:\n yCoordinate = float(iNodeY)*dy - 0.5*lY\n else:\n yCoordinate = float(iNodeY)*dy\n myQuadMesh.myCornerNodes[GlobalNodeID-1] = CN2D.CornerNode(xCoordinate,yCoordinate)\n \n def BuildQuadElements(myQuadMesh,myDGNodalStorage2D):\n nElementsX = myQuadMesh.nElementsX\n nElementsY = myQuadMesh.nElementsY\n xCoordinate = np.zeros(4)\n yCoordinate = np.zeros(4)\n nParametricNodes = 2\n ParametricNodes = np.array([-1.0,1.0])\n BoundaryCurve11 = np.zeros(2)\n BoundaryCurve12 = np.zeros(2)\n BoundaryCurve21 = np.zeros(2)\n BoundaryCurve22 = np.zeros(2)\n BoundaryCurve31 = np.zeros(2)\n BoundaryCurve32 = np.zeros(2)\n BoundaryCurve41 = np.zeros(2)\n BoundaryCurve42 = np.zeros(2)\n BoundaryCurve = np.empty(4,dtype=GB2D.CurveInterpolant2D)\n for iElementY in range(0,nElementsY):\n ElementIDY = iElementY + 1\n for iElementX in range(0,nElementsX):\n ElementIDX = iElementX + 1\n ElementID = (ElementIDY - 1)*nElementsX + ElementIDX\n NodeIDs = np.zeros(4,dtype=int)\n NodeIDs[0] = (ElementIDY - 1)*(nElementsX + 1) + ElementIDX\n NodeIDs[1] = (ElementIDY - 1)*(nElementsX + 1) + ElementIDX + 1\n NodeIDs[2] = ElementIDY*(nElementsX + 1) + ElementIDX + 1\n NodeIDs[3] = ElementIDY*(nElementsX + 1) + ElementIDX \n xCoordinate[0] = myQuadMesh.myCornerNodes[NodeIDs[0]-1].x\n yCoordinate[0] = myQuadMesh.myCornerNodes[NodeIDs[0]-1].y \n xCoordinate[1] = myQuadMesh.myCornerNodes[NodeIDs[1]-1].x\n yCoordinate[1] = myQuadMesh.myCornerNodes[NodeIDs[1]-1].y\n xCoordinate[2] = myQuadMesh.myCornerNodes[NodeIDs[2]-1].x\n yCoordinate[2] = myQuadMesh.myCornerNodes[NodeIDs[2]-1].y\n xCoordinate[3] = myQuadMesh.myCornerNodes[NodeIDs[3]-1].x\n yCoordinate[3] = myQuadMesh.myCornerNodes[NodeIDs[3]-1].y\n for iParametricNode in range(0,nParametricNodes):\n BoundaryCurve11[iParametricNode] = (\n xCoordinate[0] + 0.5*(xCoordinate[1] - xCoordinate[0])*(ParametricNodes[iParametricNode] + 1.0))\n BoundaryCurve12[iParametricNode] = (\n yCoordinate[0] + 0.5*(yCoordinate[1] - yCoordinate[0])*(ParametricNodes[iParametricNode] + 1.0))\n BoundaryCurve21[iParametricNode] = (\n xCoordinate[1] + 0.5*(xCoordinate[2] - xCoordinate[1])*(ParametricNodes[iParametricNode] + 1.0))\n BoundaryCurve22[iParametricNode] = (\n yCoordinate[1] + 0.5*(yCoordinate[2] - yCoordinate[1])*(ParametricNodes[iParametricNode] + 1.0))\n BoundaryCurve31[iParametricNode] = (\n xCoordinate[3] + 0.5*(xCoordinate[2] - xCoordinate[3])*(ParametricNodes[iParametricNode] + 1.0))\n BoundaryCurve32[iParametricNode] = (\n yCoordinate[3] + 0.5*(yCoordinate[2] - yCoordinate[3])*(ParametricNodes[iParametricNode] + 1.0))\n BoundaryCurve41[iParametricNode] = (\n xCoordinate[0] + 0.5*(xCoordinate[3] - xCoordinate[0])*(ParametricNodes[iParametricNode] + 1.0))\n BoundaryCurve42[iParametricNode] = (\n yCoordinate[0] + 0.5*(yCoordinate[3] - yCoordinate[0])*(ParametricNodes[iParametricNode] + 1.0))\n BoundaryCurve[0] = GB2D.CurveInterpolant2D(ParametricNodes,BoundaryCurve11,BoundaryCurve12)\n BoundaryCurve[1] = GB2D.CurveInterpolant2D(ParametricNodes,BoundaryCurve21,BoundaryCurve22)\n BoundaryCurve[2] = GB2D.CurveInterpolant2D(ParametricNodes,BoundaryCurve31,BoundaryCurve32)\n BoundaryCurve[3] = GB2D.CurveInterpolant2D(ParametricNodes,BoundaryCurve41,BoundaryCurve42)\n myQuadMesh.myQuadElements[ElementID-1] = QE.QuadElement(NodeIDs,ElementIDX,ElementIDY,ElementID,\n BoundaryCurve,myDGNodalStorage2D)\n \n def GetNodeToElement(myQuadMesh):\n nElements = myQuadMesh.nElements\n for iElement in range(0,nElements): # Loop over the elements in the mesh.\n ElementID = iElement + 1\n for iNode in range(0,4): # Loop over the nodes.\n # Add element to the corner node connectivity list.\n NodeID = iNode + 1\n GlobalNodeID = myQuadMesh.myQuadElements[iElement].NodeIDs[iNode]\n myQuadMesh.myCornerNodes[GlobalNodeID-1].NodeToElement.AddToList(ElementID,NodeID)\n # The key is the local node ID, the data is the element ID.\n\n def ConstructMeshEdges(myQuadMesh,PrintEdgeProperties):\n \"\"\"\n This function takes in the mesh of quadrilaterals which has not filled in the edge information and finds all of \n the unique edges in the mesh. The space for the edges is reallocated with the correct number of edges.\n \"\"\"\n nNodes = myQuadMesh.nNodes\n nElements = myQuadMesh.nElements\n nEdges = 0\n # First just count the number of edges.\n EdgeTable = HT.HashTable(nNodes)\n for iElement in range(0,nElements): # Loop over the elements in the mesh.\n for iSide in range(0,4): # Loop over the sides of each element.\n l1 = myQuadMesh.EdgeMap[0,iSide] # Starting local node for this edge.\n l2 = myQuadMesh.EdgeMap[1,iSide] # Ending local node for this edge.\n startID = myQuadMesh.myQuadElements[iElement].NodeIDs[l1-1]\n endID = myQuadMesh.myQuadElements[iElement].NodeIDs[l2-1]\n key1 = np.min([startID,endID])\n key2 = np.max([startID,endID])\n if not(EdgeTable.ContainsKeys(key1,key2)): # This is a new edge. Add the edge to the list.\n nEdges += 1\n EdgeTable.AddDataForKeys(nEdges,key1,key2) \n EdgeTable.DestructHashTable() # Trash the EdgeTable.\n EdgeTable = HT.HashTable(nNodes) # And rebuild it.\n NONE = myQuadMesh.myQuadMeshParameters.NONE\n # Reallocate space for the mesh edges.\n myQuadMesh.myEdges = np.empty(nEdges,dtype=EC.Edge)\n for iEdge in range(0,nEdges):\n myQuadMesh.myEdges[iEdge] = EC.Edge()\n nEdges = 0 # Restart the edge counting.\n for iElement in range(0,nElements): # Loop over the elements in the mesh.\n for iSide in range(0,4): # Loop over the sides of each element.\n l1 = myQuadMesh.EdgeMap[0,iSide] # Starting local node for this edge.\n l2 = myQuadMesh.EdgeMap[1,iSide] # Ending local node for this edge.\n startID = myQuadMesh.myQuadElements[iElement].NodeIDs[l1-1] \n endID = myQuadMesh.myQuadElements[iElement].NodeIDs[l2-1]\n key1 = np.min([startID,endID])\n key2 = np.max([startID,endID])\n if EdgeTable.ContainsKeys(key1,key2): # This edge already exists. Get the EdgeID.\n EdgeID = EdgeTable.GetDataForKeys(key1,key2)\n iEdge = EdgeID - 1\n # Find the primary element and the starting node for this element's edge. This is compared with the\n # secondary element's starting node to infer the relative orientation of the two elements.\n e1 = myQuadMesh.myEdges[iEdge].ElementIDs[0]\n s1 = myQuadMesh.myEdges[iEdge].ElementSides[0]\n l1 = myQuadMesh.EdgeMap[0,s1-1]\n n1 = myQuadMesh.myQuadElements[e1-1].NodeIDs[l1-1]\n # Set the secondary element information.\n myQuadMesh.myEdges[iEdge].ElementIDs[1] = iElement + 1\n if startID == n1: # The elements are oriented the same direction.\n myQuadMesh.myEdges[iEdge].ElementSides[1] = iSide + 1\n else:\n # The elements are oriented in the opposite direction. For these edges, we mark the side ID as \n # negative. A post-process step will mark:\n # myQuadMesh.myEdges[iEdge].start = nXi - 1, myQuadMesh.myEdges[iEdge].increment = -1.\n myQuadMesh.myEdges[iEdge].ElementSides[1] = -(iSide + 1) \n else: \n nEdges += 1\n EdgeID = nEdges\n iEdge = EdgeID - 1\n NodeIDs = np.zeros(2,dtype=int)\n NodeIDs[0] = startID\n NodeIDs[1] = endID\n myQuadMesh.myEdges[iEdge].OverwriteEdgeProperties(\n EdgeID,NodeIDs,np.array([iElement+1,NONE],dtype=int),np.array([iSide+1,NONE],dtype=int))\n EdgeTable.AddDataForKeys(EdgeID,key1,key2)\n for iElement in range(0,nElements): # Loop over the elements in the mesh.\n for iSide in range(0,4): # Loop over the sides of each element.\n l1 = myQuadMesh.EdgeMap[0,iSide] # Starting local node for this edge.\n l2 = myQuadMesh.EdgeMap[1,iSide] # Ending local node for this edge.\n startID = myQuadMesh.myQuadElements[iElement].NodeIDs[l1-1]\n endID = myQuadMesh.myQuadElements[iElement].NodeIDs[l2-1]\n key1 = np.min([startID,endID])\n key2 = np.max([startID,endID])\n myQuadMesh.nEdges = nEdges\n EdgeTable.DestructHashTable()\n if PrintEdgeProperties:\n print('Checking correct assignment of element IDs and element sides to the edges ' \n + 'before specifying boundary edges!')\n print('iEdge EdgeID NodeIDs ElementIDs ElementSides')\n for iEdge in range(0,myQuadMesh.nEdges):\n print('%2d %2d [%2d %2d] [%6d %6d] [%6d %6d]' \n %(iEdge,myQuadMesh.myEdges[iEdge].EdgeID,myQuadMesh.myEdges[iEdge].NodeIDs[0],\n myQuadMesh.myEdges[iEdge].NodeIDs[1],myQuadMesh.myEdges[iEdge].ElementIDs[0],\n myQuadMesh.myEdges[iEdge].ElementIDs[1],myQuadMesh.myEdges[iEdge].ElementSides[0],\n myQuadMesh.myEdges[iEdge].ElementSides[1]))\n\n def GenerateMeshEdges(myQuadMesh,PrintEdgeProperties):\n nNodes = myQuadMesh.nNodes\n nElements = myQuadMesh.nElements\n nEdges = nElements + nNodes - 1 # This is true for a structured mesh with no holes, as in our case.\n myQuadMesh.nEdges = nEdges\n NONE = myQuadMesh.myQuadMeshParameters.NONE\n E = np.ones((nNodes,nNodes),dtype=int)*NONE\n EdgeID = 0\n for iEdge in range(0,nEdges):\n myQuadMesh.myEdges[iEdge] = EC.Edge()\n myQuadMesh.myEdges[iEdge].ElementIDs = np.array([NONE,NONE],dtype=int)\n myQuadMesh.myEdges[iEdge].ElementSides = np.array([NONE,NONE],dtype=int)\n for iElement in range(0,nElements):\n for iSide in range(0,4):\n LocalNodeIDs = myQuadMesh.EdgeMap[:,iSide]\n NodeIDs = np.array([myQuadMesh.myQuadElements[iElement].NodeIDs[LocalNodeIDs[0]-1],\n myQuadMesh.myQuadElements[iElement].NodeIDs[LocalNodeIDs[1]-1]],dtype=int)\n key1 = np.min(NodeIDs)\n key2 = np.max(NodeIDs)\n if E[key1-1,key2-1] == NONE:\n EdgeID += 1\n iEdge = EdgeID - 1\n myQuadMesh.myEdges[iEdge].EdgeID = EdgeID\n myQuadMesh.myEdges[iEdge].NodeIDs = np.array([key1,key2],dtype=int)\n myQuadMesh.myEdges[iEdge].ElementIDs[0] = iElement + 1\n myQuadMesh.myEdges[iEdge].ElementSides[0] = iSide + 1\n E[key1-1,key2-1] = EdgeID\n else:\n EID = E[key1-1,key2-1]\n iEdge = EID - 1\n myQuadMesh.myEdges[iEdge].ElementIDs[1] = iElement + 1\n myQuadMesh.myEdges[iEdge].ElementSides[1] = iSide + 1\n if PrintEdgeProperties:\n print('Checking correct assignment of element IDs and element sides to the edges ' \n + 'before specifying boundary edges!')\n print('iEdge EdgeID NodeIDs ElementIDs ElementSides')\n for iEdge in range(0,myQuadMesh.nEdges):\n print('%2d %2d [%2d %2d] [%6d %6d] [%6d %6d]' \n %(iEdge,myQuadMesh.myEdges[iEdge].EdgeID,myQuadMesh.myEdges[iEdge].NodeIDs[0],\n myQuadMesh.myEdges[iEdge].NodeIDs[1],myQuadMesh.myEdges[iEdge].ElementIDs[0],\n myQuadMesh.myEdges[iEdge].ElementIDs[1],myQuadMesh.myEdges[iEdge].ElementSides[0],\n myQuadMesh.myEdges[iEdge].ElementSides[1]))\n \n def GetNodeConnectivityAndConstructEdges(myQuadMesh,PrintEdgeProperties):\n nXi = myQuadMesh.myQuadElements[0].myMappedGeometry2D.nXi\n myQuadMesh.GetNodeToElement()\n DefaultOption = True\n if DefaultOption:\n myQuadMesh.ConstructMeshEdges(PrintEdgeProperties)\n else: \n myQuadMesh.GenerateMeshEdges(PrintEdgeProperties)\n NONE = myQuadMesh.myQuadMeshParameters.NONE\n INTERIOR = myQuadMesh.myQuadMeshParameters.INTERIOR\n DIRICHLET_WEST = myQuadMesh.myQuadMeshParameters.DIRICHLET_WEST\n DIRICHLET_EAST = myQuadMesh.myQuadMeshParameters.DIRICHLET_EAST\n DIRICHLET_SOUTH = myQuadMesh.myQuadMeshParameters.DIRICHLET_SOUTH\n DIRICHLET_NORTH = myQuadMesh.myQuadMeshParameters.DIRICHLET_NORTH\n for iEdge in range(0,myQuadMesh.nEdges): # Loop over the edges.\n myQuadMesh.myEdges[iEdge].EdgeType = INTERIOR\n # Specify the types of boundary conditions.\n for iEdge in range(0,myQuadMesh.nEdges): # Loop over the edges.\n ElementSide1 = myQuadMesh.myEdges[iEdge].ElementSides[0]\n ElementID2 = myQuadMesh.myEdges[iEdge].ElementIDs[1]\n ElementSide2 = myQuadMesh.myEdges[iEdge].ElementSides[1]\n # Specify the boundary conditions.\n if ElementID2 == NONE: # This edge is a physical boundary.\n NodeID1 = myQuadMesh.myEdges[iEdge].NodeIDs[0]\n NodeID2 = myQuadMesh.myEdges[iEdge].NodeIDs[1]\n iNode1 = NodeID1 - 1\n iNode2 = NodeID2 - 1\n if ElementSide1 == 1:\n myQuadMesh.myEdges[iEdge].ElementIDs[1] = DIRICHLET_SOUTH\n myQuadMesh.myEdges[iEdge].ElementSides[1] = DIRICHLET_SOUTH\n myQuadMesh.myEdges[iEdge].EdgeType = DIRICHLET_SOUTH\n myQuadMesh.myCornerNodes[iNode1].NodeType = DIRICHLET_SOUTH\n myQuadMesh.myCornerNodes[iNode2].NodeType = DIRICHLET_SOUTH\n elif ElementSide1 == 2:\n myQuadMesh.myEdges[iEdge].ElementIDs[1] = DIRICHLET_EAST\n myQuadMesh.myEdges[iEdge].ElementSides[1] = DIRICHLET_EAST\n myQuadMesh.myEdges[iEdge].EdgeType = DIRICHLET_EAST\n myQuadMesh.myCornerNodes[iNode1].NodeType = DIRICHLET_EAST\n myQuadMesh.myCornerNodes[iNode2].NodeType = DIRICHLET_EAST\n elif ElementSide1 == 3:\n myQuadMesh.myEdges[iEdge].ElementIDs[1] = DIRICHLET_NORTH\n myQuadMesh.myEdges[iEdge].ElementSides[1] = DIRICHLET_NORTH\n myQuadMesh.myEdges[iEdge].EdgeType = DIRICHLET_NORTH\n myQuadMesh.myCornerNodes[iNode1].NodeType = DIRICHLET_NORTH\n myQuadMesh.myCornerNodes[iNode2].NodeType = DIRICHLET_NORTH\n elif ElementSide1 == 4:\n myQuadMesh.myEdges[iEdge].ElementIDs[1] = DIRICHLET_WEST\n myQuadMesh.myEdges[iEdge].ElementSides[1] = DIRICHLET_WEST\n myQuadMesh.myEdges[iEdge].EdgeType = DIRICHLET_WEST\n myQuadMesh.myCornerNodes[iNode1].NodeType = DIRICHLET_WEST\n myQuadMesh.myCornerNodes[iNode2].NodeType = DIRICHLET_WEST\n myQuadMesh.myEdges[iEdge].start = 1\n myQuadMesh.myEdges[iEdge].increment = 1 \n else: # We need to exchange information.\n if ElementSide2 > 0:\n myQuadMesh.myEdges[iEdge].start = 1\n myQuadMesh.myEdges[iEdge].increment = 1\n else: \n myQuadMesh.myEdges[iEdge].start = nXi - 1\n myQuadMesh.myEdges[iEdge].increment = -1\n for iEdge in range(0,myQuadMesh.nEdges): # Loop over the edges.\n if myQuadMesh.myEdges[iEdge].ElementIDs[1] == NONE:\n print('Not all boundary elements have been labelled yet! Stopping!')\n sys.exit()\n \n def WriteQuadMesh(myQuadMesh,OutputDirectory,filename):\n cwd = os.getcwd()\n path = cwd + '/' + OutputDirectory + '/'\n if not os.path.exists(path):\n os.mkdir(path) # os.makedir(path)\n os.chdir(path)\n filename = filename + '.tec'\n outputfile = open(filename,'w')\n outputfile.write('VARIABLES = \"X\", \"Y\", \"Jacobian\"\\n')\n for iElement in range(0,myQuadMesh.nElements):\n nXi = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.nXi\n nEta = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.nEta\n ZoneID = myQuadMesh.myQuadElements[iElement].ElementID\n ZoneIDString = 'Element' + '%7.7d' %ZoneID\n outputfile.write('ZONE T=\"%s\", I=%d, J=%d, F=POINT\\n' %(ZoneIDString,nXi+1,nEta+1))\n for iY in range(0,nEta+1):\n for iX in range(0,nXi+1):\n outputfile.write('%.15g %.15g %.15g\\n' \n %(myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.x[iX,iY],\n myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.y[iX,iY],\n myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.Jacobian[iX,iY]))\n outputfile.close()\n os.chdir(cwd)\n \n def PlotQuadMesh(myQuadMesh,OutputDirectory,linewidth,linestyle,color,marker,markersize,labels,labelfontsizes,\n labelpads,tickfontsizes,title,titlefontsize,SaveAsPDF,FileName,Show,fig_size=[9.5,9.5],\n UseDefaultMethodToSpecifyTickFontSize=True,titlepad=1.035):\n cwd = os.getcwd()\n path = cwd + '/' + OutputDirectory + '/'\n if not os.path.exists(path):\n os.mkdir(path) # os.makedir(path)\n os.chdir(path)\n fig = plt.figure(figsize=(fig_size[0],fig_size[1])) # Create a figure object\n ax = fig.add_subplot(111) # Create an axes object in the figure\n nElementsX = myQuadMesh.nElementsX\n nElementsY = myQuadMesh.nElementsY\n for iNodeY in range(0,nElementsY+1):\n for iNodeX in range(0,nElementsX+1):\n GlobalNodeID = iNodeY*(nElementsX+1) + iNodeX + 1\n iGlobalNode = GlobalNodeID - 1\n x1 = myQuadMesh.myCornerNodes[iGlobalNode].x\n y1 = myQuadMesh.myCornerNodes[iGlobalNode].y\n GlobalNodeIDOnRight = GlobalNodeID + 1\n iGlobalNodeOnRight = GlobalNodeIDOnRight - 1\n GlobalNodeIDOnTop = GlobalNodeID + nElementsX + 1\n iGlobalNodeOnTop = GlobalNodeIDOnTop - 1\n if GlobalNodeIDOnRight <= (nElementsX+1)*(nElementsY+1):\n x2 = myQuadMesh.myCornerNodes[iGlobalNodeOnRight].x\n y2 = myQuadMesh.myCornerNodes[iGlobalNodeOnRight].y\n if x2 > x1 and y2 == y1:\n x = np.array([x1,x2])\n y = np.array([y1,y2])\n plt.plot(x,y,linewidth=linewidth,linestyle=linestyle,color=color,marker=None)\n if GlobalNodeIDOnTop <= (nElementsX+1)*(nElementsY+1):\n x2 = myQuadMesh.myCornerNodes[iGlobalNodeOnTop].x\n y2 = myQuadMesh.myCornerNodes[iGlobalNodeOnTop].y\n if x2 == x1 and y2 > y1:\n x = np.array([x1,x2])\n y = np.array([y1,y2])\n plt.plot(x,y,linewidth=linewidth,linestyle=linestyle,color=color,marker=None)\n for iElement in range(0,myQuadMesh.nElements):\n nXi = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.nXi\n nEta = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.nEta\n for iY in range(0,nEta+1):\n for iX in range(0,nXi+1):\n x1 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.x[iX,iY]\n y1 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.y[iX,iY]\n plt.plot([x1],[y1],color=color,marker=marker,markersize=markersize)\n if iX < nXi:\n x2 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.x[iX+1,iY]\n y2 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.y[iX+1,iY]\n x = np.array([x1,x2])\n y = np.array([y1,y2])\n plt.plot(x,y,linewidth=0.5*linewidth,linestyle=linestyle,color=color,marker=None)\n if iY < nEta:\n x2 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.x[iX,iY+1]\n y2 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.y[iX,iY+1]\n x = np.array([x1,x2])\n y = np.array([y1,y2])\n plt.plot(x,y,linewidth=0.5*linewidth,linestyle=linestyle,color=color,marker=None)\n plt.xlabel(labels[0],fontsize=labelfontsizes[0],labelpad=labelpads[0])\n plt.ylabel(labels[1],fontsize=labelfontsizes[1],labelpad=labelpads[1])\n if UseDefaultMethodToSpecifyTickFontSize:\n plt.xticks(fontsize=tickfontsizes[0])\n plt.yticks(fontsize=tickfontsizes[1])\n else:\n ax.tick_params(axis='x',labelsize=tickfontsizes[0])\n ax.tick_params(axis='y',labelsize=tickfontsizes[1])\n plt.gca().get_xaxis().set_major_formatter(FuncFormatter(lambda x, p: format(int(x/1000.0), '')))\n plt.gca().get_yaxis().set_major_formatter(FuncFormatter(lambda y, p: format(int(y/1000.0), '')))\n ax.set_title(title,fontsize=titlefontsize,fontweight='bold',y=titlepad)\n if SaveAsPDF:\n plt.savefig(FileName+'.pdf',format='pdf',bbox_inches='tight')\n if Show:\n plt.show()\n plt.close()\n os.chdir(cwd)\n\n \ndef PlotQuadMeshes(myCoarseQuadMesh,myFineQuadMesh,OutputDirectory,linewidths,linestyles,colors,markers,markersizes,\n labels,labelfontsizes,labelpads,tickfontsizes,title,titlefontsize,SaveAsPDF,FileName,Show,\n fig_size=[9.5,9.5],UseDefaultMethodToSpecifyTickFontSize=True,titlepad=1.035):\n cwd = os.getcwd()\n path = cwd + '/' + OutputDirectory + '/'\n if not os.path.exists(path):\n os.mkdir(path) # os.makedir(path)\n os.chdir(path)\n fig = plt.figure(figsize=(fig_size[0],fig_size[1])) # Create a figure object\n ax = fig.add_subplot(111) # Create an axes object in the figure\n myQuadMeshes = [myCoarseQuadMesh,myFineQuadMesh]\n for iQuadMesh in range(0,2):\n myQuadMesh = myQuadMeshes[iQuadMesh]\n nElementsX = myQuadMesh.nElementsX\n nElementsY = myQuadMesh.nElementsY\n linewidth = linewidths[iQuadMesh]\n linestyle = linestyles[iQuadMesh]\n color = colors[iQuadMesh]\n marker = markers[iQuadMesh]\n markersize = markersizes[iQuadMesh]\n for iNodeY in range(0,nElementsY+1):\n for iNodeX in range(0,nElementsX+1):\n GlobalNodeID = iNodeY*(nElementsX+1) + iNodeX + 1\n iGlobalNode = GlobalNodeID - 1\n x1 = myQuadMesh.myCornerNodes[iGlobalNode].x\n y1 = myQuadMesh.myCornerNodes[iGlobalNode].y\n GlobalNodeIDOnRight = GlobalNodeID + 1\n iGlobalNodeOnRight = GlobalNodeIDOnRight - 1\n GlobalNodeIDOnTop = GlobalNodeID + nElementsX + 1\n iGlobalNodeOnTop = GlobalNodeIDOnTop - 1\n if GlobalNodeIDOnRight <= (nElementsX+1)*(nElementsY+1):\n x2 = myQuadMesh.myCornerNodes[iGlobalNodeOnRight].x\n y2 = myQuadMesh.myCornerNodes[iGlobalNodeOnRight].y\n if x2 > x1 and y2 == y1:\n x = np.array([x1,x2])\n y = np.array([y1,y2])\n plt.plot(x,y,linewidth=linewidth,linestyle=linestyle,color=color,marker=None)\n if GlobalNodeIDOnTop <= (nElementsX+1)*(nElementsY+1):\n x2 = myQuadMesh.myCornerNodes[iGlobalNodeOnTop].x\n y2 = myQuadMesh.myCornerNodes[iGlobalNodeOnTop].y\n if x2 == x1 and y2 > y1:\n x = np.array([x1,x2])\n y = np.array([y1,y2])\n plt.plot(x,y,linewidth=linewidth,linestyle=linestyle,color=color,marker=None)\n for iElement in range(0,myQuadMesh.nElements):\n nXi = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.nXi\n nEta = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.nEta\n for iY in range(0,nEta+1):\n for iX in range(0,nXi+1):\n x1 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.x[iX,iY]\n y1 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.y[iX,iY]\n plt.plot([x1],[y1],color=color,marker=marker,markersize=markersize)\n if iX < nXi:\n x2 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.x[iX+1,iY]\n y2 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.y[iX+1,iY]\n x = np.array([x1,x2])\n y = np.array([y1,y2])\n plt.plot(x,y,linewidth=0.5*linewidth,linestyle=linestyle,color=color,marker=None)\n if iY < nEta:\n x2 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.x[iX,iY+1]\n y2 = myQuadMesh.myQuadElements[iElement].myMappedGeometry2D.y[iX,iY+1]\n x = np.array([x1,x2])\n y = np.array([y1,y2])\n plt.plot(x,y,linewidth=0.5*linewidth,linestyle=linestyle,color=color,marker=None)\n plt.xlabel(labels[0],fontsize=labelfontsizes[0],labelpad=labelpads[0])\n plt.ylabel(labels[1],fontsize=labelfontsizes[1],labelpad=labelpads[1])\n if UseDefaultMethodToSpecifyTickFontSize:\n plt.xticks(fontsize=tickfontsizes[0])\n plt.yticks(fontsize=tickfontsizes[1])\n else:\n ax.tick_params(axis='x',labelsize=tickfontsizes[0])\n ax.tick_params(axis='y',labelsize=tickfontsizes[1])\n plt.gca().get_xaxis().set_major_formatter(FuncFormatter(lambda x, p: format(int(x/1000.0), '')))\n plt.gca().get_yaxis().set_major_formatter(FuncFormatter(lambda y, p: format(int(y/1000.0), '')))\n ax.set_title(title,fontsize=titlefontsize,fontweight='bold',y=titlepad)\n if SaveAsPDF:\n plt.savefig(FileName+'.pdf',format='pdf',bbox_inches='tight')\n if Show:\n plt.show()\n plt.close()\n os.chdir(cwd)","sub_path":"src/DGSEM_Rotating_Shallow_Water/QuadMeshClass.py","file_name":"QuadMeshClass.py","file_ext":"py","file_size_in_byte":31593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"150640983","text":"# -*- coding: utf-8 -*-\n\"\"\"\nProduces fake instrument data for testing.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport functools\nimport numpy as np\n\nimport pandas as pds\n\nimport pysat\nfrom pysat.instruments.methods import testing as mm_test\n\n# pysat required parameters\nplatform = 'pysat'\nname = 'testing'\n\n# dictionary of data 'tags' and corresponding description\n# tags are used to choose the behaviour of dummy1\ntags = {'': 'Regular testing data set',\n 'ascend': 'Ascending Integers from 0 testing data set',\n 'descend': 'Descending Integers from 0 testing data set',\n 'plus10': 'Ascending Integers from 10 testing data set',\n 'fives': 'All 5s testing data set',\n 'mlt_offset': 'dummy1 is offset by five from regular testing set'}\n\n# dictionary of satellite IDs, list of corresponding tags\n# a numeric string can be used in sat_id to change the number of points per day\nsat_ids = {'': ['', 'ascend', 'descend', 'plus10', 'fives', 'mlt_offset']}\n_test_dates = {'': {'': pysat.datetime(2009, 1, 1)}}\n\n\ndef init(self):\n \"\"\"Initializes the Instrument object with instrument specific values.\n\n Runs once upon instantiation.\n\n Shifts time index of files by 5-minutes if mangle_file_dates\n set to True at pysat.Instrument instantiation.\n\n Creates a file list for a given range if the file_date_range\n keyword is set at instantiation.\n\n Parameters\n ----------\n inst : pysat.Instrument\n This object\n file_date_range : pds.date_range\n Optional keyword argument that specifies the range of dates for which\n test files will be created\n mangle_file_dates : bool\n If True, the loaded file list time index is shifted by 5-minutes.\n\n \"\"\"\n\n self.new_thing = True\n\n # work on file index if keyword present\n if self.kwargs['file_date_range'] is not None:\n # set list files routine to desired date range\n # attach to the instrument object\n fdr = self.kwargs['file_date_range']\n self._list_rtn = functools.partial(list_files, file_date_range=fdr)\n self.files.refresh()\n\n # mess with file dates if kwarg option present\n if self.kwargs['mangle_file_dates']:\n self.files.files.index = \\\n self.files.files.index + pds.DateOffset(minutes=5)\n\n\ndef default(self):\n \"\"\"Default customization function.\n\n This routine is automatically applied to the Instrument object\n on every load by the pysat nanokernel (first in queue).\n\n Parameters\n ----------\n self : pysat.Instrument\n This object\n\n \"\"\"\n\n pass\n\n\ndef load(fnames, tag=None, sat_id=None, sim_multi_file_right=False,\n sim_multi_file_left=False, root_date=None, file_date_range=None,\n malformed_index=False, mangle_file_dates=False):\n \"\"\" Loads the test files\n\n Parameters\n ----------\n fnames : list\n List of filenames\n tag : str or NoneType\n Instrument tag (accepts '')\n sat_id : str or NoneType\n Instrument satellite ID (accepts '' or a number (i.e., '10'), which\n specifies the number of data points to include in the test instrument)\n sim_multi_file_right : boolean\n Adjusts date range to be 12 hours in the future or twelve hours beyond\n root_date (default=False)\n sim_multi_file_left : boolean\n Adjusts date range to be 12 hours in the past or twelve hours before\n root_date (default=False)\n root_date : NoneType\n Optional central date, uses _test_dates if not specified.\n (default=None)\n file_date_range : pds.date_range or NoneType\n Range of dates for files or None, if this optional arguement is not\n used. Shift actually performed by the init function.\n (default=None)\n malformed_index : boolean\n If True, time index will be non-unique and non-monotonic.\n mangle_file_dates : bool\n If True, the loaded file list time index is shifted by 5-minutes.\n This shift is actually performed by the init function.\n\n Returns\n -------\n data : (pds.DataFrame)\n Testing data\n meta : (pysat.Meta)\n Metadataxs\n\n \"\"\"\n\n # create an artifical satellite data set\n iperiod = mm_test.define_period()\n drange = mm_test.define_range()\n uts, index, date = mm_test.generate_times(fnames, sat_id, freq='1S')\n\n # Specify the date tag locally and determine the desired date range\n pds_offset = pds.DateOffset(hours=12)\n if sim_multi_file_right:\n root_date = root_date or _test_dates[''][''] + pds_offset\n elif sim_multi_file_left:\n root_date = root_date or _test_dates[''][''] - pds_offset\n else:\n root_date = root_date or _test_dates['']['']\n\n data = pysat.DataFrame(uts, columns=['uts'])\n\n # need to create simple orbits here. Have start of first orbit default\n # to 1 Jan 2009, 00:00 UT. 14.84 orbits per day\n time_delta = date - root_date\n data['mlt'] = mm_test.generate_fake_data(time_delta.total_seconds(),\n uts, period=iperiod['lt'],\n data_range=drange['lt'])\n\n # do slt, 20 second offset from mlt\n data['slt'] = mm_test.generate_fake_data(time_delta.total_seconds()+20,\n uts, period=iperiod['lt'],\n data_range=drange['lt'])\n\n # create a fake longitude, resets every 6240 seconds\n # sat moves at 360/5820 deg/s, Earth rotates at 360/86400, takes extra time\n # to go around full longitude\n data['longitude'] = mm_test.generate_fake_data(time_delta.total_seconds(),\n uts, period=iperiod['lon'],\n data_range=drange['lon'])\n\n # create latitude area for testing polar orbits\n angle = mm_test.generate_fake_data(time_delta.total_seconds(),\n uts, period=iperiod['angle'],\n data_range=drange['angle'])\n data['latitude'] = 90.0 * np.cos(angle)\n\n # fake orbit number\n fake_delta = date - (_test_dates[''][''] - pds.DateOffset(years=1))\n data['orbit_num'] = mm_test.generate_fake_data(fake_delta.total_seconds(),\n uts, period=iperiod['lt'],\n cyclic=False)\n\n # create some fake data to support testing of averaging routines\n mlt_int = data['mlt'].astype(int)\n long_int = (data['longitude'] / 15.0).astype(int)\n if tag == 'ascend':\n data['dummy1'] = [i for i in range(len(data['mlt']))]\n elif tag == 'descend':\n data['dummy1'] = [-i for i in range(len(data['mlt']))]\n elif tag == 'plus10':\n data['dummy1'] = [i + 10 for i in range(len(data['mlt']))]\n elif tag == 'fives':\n data['dummy1'] = [5 for i in range(len(data['mlt']))]\n elif tag == 'mlt_offset':\n data['dummy1'] = mlt_int + 5\n else:\n data['dummy1'] = mlt_int\n data['dummy2'] = long_int\n data['dummy3'] = mlt_int + long_int * 1000.0\n data['dummy4'] = uts\n data['string_dummy'] = ['test'] * len(data)\n data['unicode_dummy'] = [u'test'] * len(data)\n data['int8_dummy'] = np.ones(len(data), dtype=np.int8)\n data['int16_dummy'] = np.ones(len(data), dtype=np.int16)\n data['int32_dummy'] = np.ones(len(data), dtype=np.int32)\n data['int64_dummy'] = np.ones(len(data), dtype=np.int64)\n\n if malformed_index:\n index = index.tolist()\n # nonmonotonic\n index[0:3], index[3:6] = index[3:6], index[0:3]\n # non unique\n index[6:9] = [index[6]]*3\n\n data.index = index\n data.index.name = 'Epoch'\n return data, meta.copy()\n\n\nlist_files = functools.partial(mm_test.list_files, test_dates=_test_dates)\ndownload = functools.partial(mm_test.download)\n\n\nmeta = pysat.Meta()\nmeta['uts'] = {'units': 's',\n 'long_name': 'Universal Time',\n 'custom': False}\nmeta['Epoch'] = {'units': 'Milliseconds since 1970-1-1',\n 'Bin_Location': 0.5,\n 'notes': 'UTC time at middle of geophysical measurement.',\n 'desc': 'UTC seconds', }\nmeta['mlt'] = {'units': 'hours',\n 'long_name': 'Magnetic Local Time',\n 'label': 'MLT',\n 'axis': 'MLT',\n 'desc': 'Magnetic Local Time',\n 'value_min': 0.0,\n 'value_max': 24.0,\n 'notes': ('Magnetic Local Time is the solar local time of the '\n 'field line at the location where the field crosses '\n 'the magnetic equator. In this case we just simulate '\n '0-24 with a consistent orbital period and an offste '\n 'with SLT.'),\n 'fill': np.nan,\n 'scale': 'linear'}\nmeta['slt'] = {'units': 'hours',\n 'long_name': 'Solar Local Time',\n 'label': 'SLT',\n 'axis': 'SLT',\n 'desc': 'Solar Local Time',\n 'value_min': 0.0,\n 'value_max': 24.0,\n 'notes': ('Solar Local Time is the local time (zenith angle of '\n 'sun) of the given location. Overhead noon, +/- 90 '\n 'is 6, 18 SLT .'),\n 'fill': np.nan,\n 'scale': 'linear'}\nmeta['orbit_num'] = {'units': '',\n 'long_name': 'Orbit Number',\n 'label': 'Orbit Number',\n 'axis': 'Orbit Number',\n 'desc': 'Orbit Number',\n 'value_min': 0.0,\n 'value_max': 25000.0,\n 'notes': ('Number of orbits since the start of the '\n 'mission. For this simulation we use the '\n 'number of 5820 second periods since the '\n 'start, 2008-01-01.'),\n 'fill': np.nan,\n 'scale': 'linear'}\n\nmeta['longitude'] = {'units': 'degrees', 'long_name': 'Longitude'}\nmeta['latitude'] = {'units': 'degrees', 'long_name': 'Latitude'}\nmeta['dummy1'] = {'units': '', 'long_name': 'dummy1'}\nmeta['dummy2'] = {'units': '', 'long_name': 'dummy2'}\nmeta['dummy3'] = {'units': '', 'long_name': 'dummy3'}\nmeta['dummy4'] = {'units': '', 'long_name': 'dummy4'}\nmeta['string_dummy'] = {'units': '', 'long_name': 'string_dummy'}\nmeta['unicode_dummy'] = {'units': '', 'long_name': 'unicode_dummy'}\nmeta['int8_dummy'] = {'units': '', 'long_name': 'int8_dummy'}\nmeta['int16_dummy'] = {'units': '', 'long_name': 'int16_dummy'}\nmeta['int32_dummy'] = {'units': '', 'long_name': 'int32_dummy'}\nmeta['int64_dummy'] = {'units': '', 'long_name': 'int64_dummy'}\n","sub_path":"pysat/instruments/pysat_testing.py","file_name":"pysat_testing.py","file_ext":"py","file_size_in_byte":10842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"460262345","text":"import cv2\r\nimport time\r\nfrom threading import Thread\r\n\r\n\r\ndef async_threaded(f):\r\n def wrapper(*args, **kwargs):\r\n thr = Thread(target=f, args=args, kwargs=kwargs)\r\n thr.start()\r\n\r\n return wrapper\r\n\r\nclass VideoWorker():\r\n\r\n on_img = None\r\n on_vid = None\r\n on_end = None\r\n interval = 0.1\r\n started = False\r\n screenshot = False\r\n bottle_result = None\r\n\r\n def __init__(self, camera_number: int = 0):\r\n self.webcam = cv2.VideoCapture(camera_number)\r\n return\r\n\r\n @async_threaded\r\n def start(self):\r\n print('Webcam start')\r\n self.started = True\r\n # default : 848x480 on MacBook\r\n\r\n while True:\r\n if self.webcam.isOpened():\r\n rc, frame = self.webcam.read()\r\n if not rc:\r\n print('Camera image capture failed')\r\n continue\r\n\r\n if self.on_vid is not None:\r\n self.on_vid(frame)\r\n\r\n if self.screenshot and self.on_img is not None:\r\n self.bottle_result = self.on_img(frame)\r\n self.screenshot = False\r\n\r\n time.sleep(self.interval)\r\n else:\r\n print('No available camera')\r\n break\r\n\r\n self.end()\r\n\r\n def end(self):\r\n print('End webcam')\r\n\r\n if self.webcam is not None:\r\n self.webcam.release()\r\n cv2.destroyAllWindows()\r\n\r\n if self.on_end is not None:\r\n self.on_end()\r\n\r\nvid_worker = VideoWorker()\r\n","sub_path":"programming_practice_l/camera_library.py","file_name":"camera_library.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"429489659","text":"import pandas as pd\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nfrom sklearn.linear_model import ElasticNet, Ridge, Lasso\nfrom dataloader import AmazonDataset\n\nclass Evaluater():\n \n \n def __init__(self, data_dir):\n #self.user_num = user_num\n self.dataset = AmazonDataset(data_dir=data_dir) \n \n \n def topn_precision(self, ranking_mat):\n user_idx = [self.dataset.entity_list.index(u) for u in self.dataset.user_list]\n not_count = 0\n precision_sum = 0\n for i in range(len(user_idx)):\n if len(self.dataset.user_items_test_dict[user_idx[i]]) == 0:\n not_count += 1\n continue\n\n precision = self.__topn_precision(ranking_mat[i], user_idx[i])\n precision_sum += precision\n \n return precision_sum / (len(self.dataset.user_list) - not_count)\n\n\n def __topn_precision(self, sorted_idx, target_user_id, n=10):\n\n #if len(self.user_items_dict[target_user_id]) == 0:\n \n topn_idx = sorted_idx[:n] \n #print(topn_idx)\n #print(user_items_test_dict[target_user_id])\n hit = len(set(topn_idx) & set(self.dataset.user_items_test_dict[target_user_id]))\n \n #precision = hit / len(self.user_items_dict[target_user_id])\n precision = hit / n\n # precision_sum += precision\n \n return precision\n\n\n def topn_map(self, ranking_mat):\n user_idx = [self.dataset.entity_list.index(u) for u in self.dataset.user_list]\n not_count = 0\n map_sum = 0\n\n for i in range(len(user_idx)):\n if len(self.dataset.user_items_test_dict[user_idx[i]]) == 0:\n not_count += 1\n continue\n\n sorted_idx = ranking_mat[i]\n precision_sum = 0\n for j in self.dataset.user_items_test_dict[user_idx[i]]:\n n = list(sorted_idx).index(j) + 1\n precision = self.__topn_precision(sorted_idx, user_idx[i], n)\n precision_sum += precision\n \n map_sum += precision_sum / len(self.dataset.user_items_test_dict[user_idx[i]])\n\n return map_sum / (len(self.dataset.user_list) - not_count)\n \n \n def topn_recall(n=10):\n return 0","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"564376984","text":"\ndef escape(text):\n r = text\n r = text.strip()\n r = r.replace(\"\\t\",\" \")\n r = r.replace(\"\\r\",\" \")\n r = r.replace(\"\\n\",\" \")\n r = r.strip(\"\")\n return r\n\ndef unescape(text):\n r = text\n r = r.replace(\"\\\\t\",\"\\t\")\n r = r.replace(\"\\\\r\",\"\\r\")\n r = r.replace(\"\\\\n\",\"\\n\")\n return r\n\ndef serialize_node(node, parents=[]):\n result = []\n attr = []\n level = []\n\n for k in sorted(node.attrib.keys()):\n v = node.attrib[k]\n vv = v.strip()\n r = \"%s=\\\"%s\\\"\" % (k.strip() ,v.strip())\n attr.append(r)\n\n my_name = node.tag\n if type(my_name) != type(\"\"):\n my_name = \"!\"+ str(my_name).split(\" \")[-1].strip(\"><\").lower()\n me_included = parents + [my_name]\n name = \"/\".join(me_included)\n text = node.text or \"\"\n\n depth = len(name.split(\"/\"))\n row = \"%s\\t%s\\t%s\\t%s\" % (name, escape(text), escape(node.tail or \"\"), \" \".join(attr))\n result.append(row)\n for i in node:\n result.extend(serialize_node(i, me_included))\n return result\n\ndef attach_node(a, b):\n d = b['level'] - a['level']\n if d == 1:\n a['children'].append(b)\n else:\n attach_node(a['children'][-1], b)\n\ndef str_node(a, pretty=False):\n result = \"\"\n if len(a['attrs']) > 0:\n result += u\"<%(name)s %(attrs)s>%(content)s\" % a\n else:\n result += \"<%(name)s>%(content)s\" % a\n for i in a['children']:\n result += str_node(i, pretty)\n if len(a['children']) > 0 or a['content']:\n result += \"\" % a\n result += \"%(tail)s\" % a\n return result","sub_path":"xflat/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"648254491","text":"# Create your views here.\nfrom django.http import HttpResponse\nfrom django.http import Http404\nfrom django.contrib.auth.models import User\nfrom players.models import Player, Team\nfrom events.models import Event\nfrom django.contrib.auth import authenticate, login\nfrom models import UserProfile\nfrom django.db import IntegrityError\nfrom django.core.context_processors import csrf\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.contrib.csrf.middleware import csrf_exempt\nimport base64\nfrom django.utils import simplejson\nfrom django_c2dm.models import AndroidDevice\n\ndef is_auth(request):\n #if (request.user is not AnonymouseUser):\n # return request.user\n\n user = None\n if 'HTTP_AUTHORIZATION' in request.META:\n auth = request.META['HTTP_AUTHORIZATION'].split()\n if len(auth) == 2:\n #only basic auth right now\n if auth[0].lower() == \"basic\":\n uname, passwd = base64.b64decode(auth[1]).split(':')\n user = authenticate(username=uname, password=passwd)\n if user is not None:\n if user.is_active:\n login(request,user)\n request.user = user\n return user\n\ndef auth_required_response():\n response = HttpResponse()\n response.status_code = 401\n realm = ''\n response['WWW-Authenticate'] = 'Basic realm=\"%s\"' % realm\n return response\n\ndef create_user(request):\n username = request.POST['username']\n password = request.POST['password']\n response = {}\n try:\n newUser = User.objects.create_user(username, username, password)\n response['response'] = \"Account successfully created\"\n response['status_code'] = 200\n except IntegrityError:\n response['response'] = \"Account creation failed\"\n response['status_code'] = 0\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n\ndef authenticate_user(request):\n user = is_auth(request)\n response = {}\n if user is not None:\n if user.is_active:\n response['status_code'] = 200\n response['response'] = \"Successful authentication\"\n else:\n response['status_code'] = 0 #TOOD: Figure out what this should be\n response['response'] = \"Your account has been disabled\"\n return HttpResponse(simplejson.dumps(response),mimetype=\"application/json\")\n else:\n return auth_required_response()\n\ndef remove_user(request):\n user = is_auth(request)\n response = {}\n if user is not None:\n if user.is_active:\n user.delete()\n response['status_code'] = 200\n response[\"response\"] = \"Successful account removal\"\n else:\n response['status_code'] = 0\n response[\"response\"] = \"Your account has been disabled\"\n else:\n return auth_required_response()\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n \ndef add_favorite_player(request):\n user = is_auth(request)\n response = {}\n if user is None:\n return auth_required_response()\n pid = request.GET['id']\n try:\n player = Player.objects.get(pk=pid)\n except Player.DoesNotExist:\n response['status_code'] = 404\n response[\"response\"] = \"Player id does not exist!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n profile = user.get_profile()\n profile.favorite_players.add(player)\n profile.save()\n response['status_code'] = 200\n response[\"response\"] = \"Add favorite player successful!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n \ndef add_favorite_team(request):\n user = is_auth(request)\n response = {}\n if user is None:\n return auth_required_response()\n tid = request.GET['id']\n try:\n team = Team.objects.get(pk=tid)\n except Team.DoesNotExist:\n response['status_code'] = 404\n response[\"response\"] = \"Team id does not exist!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n profile = user.get_profile()\n profile.favorite_teams.add(team)\n profile.save()\n response['status_code'] = 200\n response[\"response\"] = \"Add favorite team successful!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n \ndef add_favorite_event(request):\n user = is_auth(request)\n response = {}\n if user is None:\n return auth_required_response()\n eid = request.GET['id']\n try:\n event = Event.objects.get(pk=eid)\n except Event.DoesNotExist:\n response['status_code'] = 404\n response[\"response\"] = \"Event id does not exist!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n profile = user.get_profile()\n profile.favorite_events.add(event)\n profile.save()\n response['status_code'] = 200\n response[\"response\"] = \"Add favorite event successful!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n \ndef remove_favorite_player(request):\n user = is_auth(request)\n response = {}\n if user is None:\n return auth_required_response()\n pid = request.GET['id']\n try:\n player = Player.objects.get(pk=pid)\n except Player.DoesNotExist:\n response['status_code'] = 404\n response[\"response\"] = \"Player id does not exist!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n profile = user.get_profile()\n try:\n fav_player = profile.favorite_players.get(pk=player.pk)\n except Player.DoesNotExist:\n response['status_code'] = 404\n response[\"response\"] = \"Player not in favorites!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n profile.favorite_players.remove(player)\n profile.save()\n response['status_code'] = 200\n response[\"response\"] = \"Remove favorite player successful!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n \ndef remove_favorite_team(request):\n user = is_auth(request)\n response = {}\n if user is None:\n return auth_required_response()\n tid = request.GET['id']\n try:\n team = Team.objects.get(pk=tid)\n except Team.DoesNotExist:\n response['status_code'] = 404\n response[\"response\"] = \"Team id does not exist!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n profile = user.get_profile()\n try:\n fav_team = profile.favorite_teams.get(pk=team.pk)\n except Team.DoesNotExist:\n response['status_code'] = 404\n response[\"response\"] = \"Team not in favorites!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n profile.favorite_teams.remove(team)\n profile.save()\n response['status_code'] = 200\n response[\"response\"] = \"Remove favorite team successful!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n\ndef remove_favorite_event(request):\n user = is_auth(request)\n response = {}\n if user is None:\n return auth_required_response()\n eid = request.GET['id']\n try:\n event = Event.objects.get(pk=eid)\n except Event.DoesNotExist:\n response['status_code'] = 404\n response[\"response\"] = \"Event id does not exist!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n profile = user.get_profile()\n try:\n fav_event = profile.favorite_events.get(pk=event.pk)\n except Event.DoesNotExist:\n response['status_code'] = 404\n response[\"response\"] = \"Event not in favorites!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n profile.favorite_events.remove(event)\n profile.save()\n response['status_code'] = 200\n response[\"response\"] = \"Remove favorite event successful!\"\n return HttpResponse(simplejson.dumps(response), mimetype=\"application/json\")\n\ndef get_favorites(request):\n user = is_auth(request)\n response = {}\n if user is None:\n return auth_required_response()\n profile = user.get_profile()\n response['status_code'] = 200\n response['response'] = [profile.favorites_to_dict()]\n return HttpResponse(simplejson.dumps(response), mimetype='application/json')\n\ndef set_device(request):\n user = is_auth(request)\n if user is None:\n return auth_required_response()\n response = {}\n type = request.GET['type']\n device_id = request.GET['did']\n registration_id = request.GET['rid']\n device = user.get_profile().device\n if device is None:\n user.get_profile().device = AndroidDevice.objects.create(device_id=device_id, registration_id=registration_id, collapse_key=\"\")\n user.get_profile().save()\n else:\n device.device_id = device_id\n device.registration_id = registration_id\n device.save()\n response['status_code'] = 200\n response['response'] = \"Device set successful\"\n return HttpResponse(simplejson.dumps(response), mimetype='application/json')\n \ncreate_user = csrf_exempt(create_user)\nauthenticate_user = csrf_exempt(authenticate_user)\nremove_user = csrf_exempt(remove_user)\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"464840729","text":"H, W = map(int, input().split())\nA = [input() for _ in range(H)]\n\ndef isOK():\n for h in range(H):\n for w in range(W):\n if A[h][w] == '.':\n continue\n if all([A[h + dh][w + dw] == '.' for dh, dw in [(0, 1), (0, -1), (1, 0), (-1, 0)] if (0 <= h + dh < H and 0 <= w + dw < W)]):\n return False\n return True\n\nprint('Yes' if isOK() else 'No')\n","sub_path":"AtCoder/abc/096c_2.py","file_name":"096c_2.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"198491969","text":"\"\"\"\nUnit tests for the Deis api app.\n\nRun the tests with \"./manage.py test api\"\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport json\nimport mock\nimport requests\n\nfrom django.test import TransactionTestCase\nfrom django.test.utils import override_settings\n\nfrom api.models import Config\n\n\ndef mock_import_repository_task(*args, **kwargs):\n resp = requests.Response()\n resp.status_code = 200\n resp._content_consumed = True\n return resp\n\n\n@override_settings(CELERY_ALWAYS_EAGER=True)\nclass ConfigTest(TransactionTestCase):\n\n \"\"\"Tests setting and updating config values\"\"\"\n\n fixtures = ['tests.json']\n\n def setUp(self):\n self.assertTrue(\n self.client.login(username='autotest', password='password'))\n body = {'id': 'autotest', 'domain': 'autotest.local', 'type': 'mock',\n 'hosts': 'host1,host2', 'auth': 'base64string', 'options': {}}\n response = self.client.post('/api/clusters', json.dumps(body),\n content_type='application/json')\n self.assertEqual(response.status_code, 201)\n\n @mock.patch('requests.post', mock_import_repository_task)\n def test_config(self):\n \"\"\"\n Test that config is auto-created for a new app and that\n config can be updated using a PATCH\n \"\"\"\n url = '/api/apps'\n body = {'cluster': 'autotest'}\n response = self.client.post(url, json.dumps(body), content_type='application/json')\n self.assertEqual(response.status_code, 201)\n app_id = response.data['id']\n # check to see that an initial/empty config was created\n url = \"/api/apps/{app_id}/config\".format(**locals())\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertIn('values', response.data)\n self.assertEqual(response.data['values'], json.dumps({}))\n config1 = response.data\n # set an initial config value\n body = {'values': json.dumps({'NEW_URL1': 'http://localhost:8080/'})}\n response = self.client.post(url, json.dumps(body), content_type='application/json')\n self.assertEqual(response.status_code, 201)\n self.assertIn('x-deis-release', response._headers)\n config2 = response.data\n self.assertNotEqual(config1['uuid'], config2['uuid'])\n self.assertIn('NEW_URL1', json.loads(response.data['values']))\n # read the config\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n config3 = response.data\n self.assertEqual(config2, config3)\n self.assertIn('NEW_URL1', json.loads(response.data['values']))\n # set an additional config value\n body = {'values': json.dumps({'NEW_URL2': 'http://localhost:8080/'})}\n response = self.client.post(url, json.dumps(body), content_type='application/json')\n self.assertEqual(response.status_code, 201)\n config3 = response.data\n self.assertNotEqual(config2['uuid'], config3['uuid'])\n self.assertIn('NEW_URL1', json.loads(response.data['values']))\n self.assertIn('NEW_URL2', json.loads(response.data['values']))\n # read the config again\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n config4 = response.data\n self.assertEqual(config3, config4)\n self.assertIn('NEW_URL1', json.loads(response.data['values']))\n self.assertIn('NEW_URL2', json.loads(response.data['values']))\n # unset a config value\n body = {'values': json.dumps({'NEW_URL2': None})}\n response = self.client.post(url, json.dumps(body), content_type='application/json')\n self.assertEqual(response.status_code, 201)\n config5 = response.data\n self.assertNotEqual(config4['uuid'], config5['uuid'])\n self.assertNotIn('NEW_URL2', json.dumps(response.data['values']))\n # unset all config values\n body = {'values': json.dumps({'NEW_URL1': None})}\n response = self.client.post(url, json.dumps(body), content_type='application/json')\n self.assertEqual(response.status_code, 201)\n self.assertNotIn('NEW_URL1', json.dumps(response.data['values']))\n # disallow put/patch/delete\n self.assertEqual(self.client.put(url).status_code, 405)\n self.assertEqual(self.client.patch(url).status_code, 405)\n self.assertEqual(self.client.delete(url).status_code, 405)\n return config5\n\n @mock.patch('requests.post', mock_import_repository_task)\n def test_config_set_same_key(self):\n \"\"\"\n Test that config sets on the same key function properly\n \"\"\"\n url = '/api/apps'\n body = {'cluster': 'autotest'}\n response = self.client.post(url, json.dumps(body), content_type='application/json')\n self.assertEqual(response.status_code, 201)\n app_id = response.data['id']\n url = \"/api/apps/{app_id}/config\".format(**locals())\n # set an initial config value\n body = {'values': json.dumps({'PORT': '5000'})}\n response = self.client.post(url, json.dumps(body), content_type='application/json')\n self.assertEqual(response.status_code, 201)\n self.assertIn('PORT', json.loads(response.data['values']))\n # reset same config value\n body = {'values': json.dumps({'PORT': '5001'})}\n response = self.client.post(url, json.dumps(body), content_type='application/json')\n self.assertEqual(response.status_code, 201)\n self.assertIn('PORT', json.loads(response.data['values']))\n self.assertEqual(json.loads(response.data['values'])['PORT'], '5001')\n\n @mock.patch('requests.post', mock_import_repository_task)\n def test_config_str(self):\n \"\"\"Test the text representation of a node.\"\"\"\n config5 = self.test_config()\n config = Config.objects.get(uuid=config5['uuid'])\n self.assertEqual(str(config), \"{}-{}\".format(config5['app'], config5['uuid'][:7]))\n","sub_path":"controller/api/tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":5989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"289246852","text":"import matplotlib.pyplot as plt\nfrom models import DispNetS, PoseExpNet\nimport torch\nfrom torch.autograd import Variable\nimport time\nimport numpy as np\nimport os\nimport cv2\nimport glob\ndevice_name= \"cuda\" if torch.cuda.is_available() else \"cpu\"\ndevice = torch.device(device_name)\n\n\nclass time_lapse:\n\tdef __init__(self):\n\t\tself.start=time.time()\n\t\tself.count=0\n\tdef now(self):\n\t\tself.count += 1\n\t\tprint(\"[%d]time elasped = %f\"% (self.count,time.time()-self.start))\n\ntl=time_lapse()\ntl.now()\n\n\ndef init_disp_net(pretrained):\n\tweights = torch.load(pretrained, map_location=device_name)\n\tdisp_net = DispNetS().to(device)\n\tdisp_net.load_state_dict(weights['state_dict'])\n\tdisp_net.eval()\n\treturn disp_net\n\ndef dis_predict(disp_net, img):\n\t#an_input0 = cv2.imread(img, cv2.IMREAD_COLOR)\n\tan_input0 = cv2.imread(img, cv2.IMREAD_UNCHANGED)\n\t# convert RGB <-> BGR\n\tan_input0 = an_input0[:,:,::-1]\n\t\n\th, w, c = an_input0.shape\n\tprint(h, w, c)\n\tww=300\n\thh=int(h*ww/w+0.5)\n\tan_input0=cv2.resize(an_input0, (ww,hh))\n\t#an_input0 = transform.resize(an_input0, (hh, ww))\n\tan_input = np.transpose(an_input0, (2,0,1))\n\tan_input = torch.from_numpy(an_input)\n\tan_input = an_input.unsqueeze(0)\n\n\t#print(an_input)\n\tan_input = ( (an_input.float()/255-0.5)/0.5)\n\tan_input = an_input.to(device)\n\ttl.now()\n\tpred_disp = disp_net(an_input).cpu().detach().numpy()[0,0]\n\tpred_disp = (pred_disp * 2 +0.5)*255*100\n\treturn an_input0, pred_disp/pred_disp.max()\n\ndef main():\n\tpretrained = \"pretrained/dispnet_model_best.pth.tar\"\n\tinputs_dir = \"samples\"\n\tdisp_net = init_disp_net(pretrained)\n\timgs=[ f for f in glob.glob(os.path.join(inputs_dir,\"*\")) if os.path.isfile(f) ]\n\tprint(imgs)\n\tan_inputs, outputs=[], []\n\tfor img in imgs:\n\t\tan_input0, pred_disp=dis_predict(disp_net, img)\n\t\tan_inputs.append(an_input0)\n\t\toutputs.append(pred_disp)\n\t\t\n\ttl.now()\n\tnrows = len(an_inputs)\n\tfig, axes = plt.subplots(nrows,2)\n\tfor i in range(nrows):\n\t\taxes[i][1].imshow(an_inputs[i])\n\t\taxes[i][0].imshow(outputs[i])\n\tplt.show()\n\n\nif __name__==\"__main__\":\n\tmain()\n","sub_path":"jtest.py","file_name":"jtest.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"599663107","text":"class Solution(object):\n def minSubArrayLen(self, s, nums):\n \"\"\"\n :type s: int\n :type nums: List[int]\n :rtype: int\n \"\"\"\n i, j, result, sum = 0, 0, sys.maxint, 0\n while i < len(nums):\n sum += nums[i]\n i += 1\n while sum >= s:\n result = min(result, i-j)\n sum -= nums[j]\n j += 1\n \n return result if result != sys.maxint else 0\n","sub_path":"python_solutions/209-minimum-size-subarray-sum.py","file_name":"209-minimum-size-subarray-sum.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"642161549","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, JsonResponse\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth import authenticate, logout\nfrom django.contrib.auth import login as auth_login #cambio nombre por problema con vista login, no puede llamarse igual que el metodo\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\t\nfrom .decorators import unauthenticated_user, admin_only\nfrom .models import *\nfrom .forms import *\n\n# Create your views here.\n\n# Acceso\ndef register(request):\n\tif request.user.is_authenticated:\n\t\treturn redirect(\"/\")\n\telse:\n\t\tform=CreateUserForm()\n\t\tif request.method == \"POST\":\n\t\t\tform=CreateUserForm(request.POST)\n\t\t\tif form.is_valid():\n\t\t\t\tuser=form.save()\n\t\t\t\tusername=form.cleaned_data.get(\"username\")\n\t\t\t\temail=form.cleaned_data.get(\"email\")\n\n\t\t\t\tgroup=Group.objects.get(name=\"vendedor\")\n\t\t\t\tuser.groups.add(group)\n\t\t\t\tUsuario.objects.create(\n\t\t\t\t\tuser=user,\n\t\t\t\t\tnombre=username,\n\t\t\t\t\temail=email\n\t\t\t\t\t)\n\n\t\t\t\tmessages.success(request, \"Registro exitoso para \"+ username)\n\t\t\t\treturn redirect (\"/login\")\n\t\treturn render(request, \"register.html\", {\"form\":form})\n\n\n@unauthenticated_user\ndef login(request):\n\tif request.method==\"POST\":\n\t\tusername=request.POST.get(\"username\")\n\t\tpassword=request.POST.get(\"password\")\n\n\t\tuser=authenticate(request, username=username, password=password)\n\n\t\tif user is not None:\n\t\t\tauth_login(request, user)\n\t\t\treturn redirect(\"/\")\n\t\telse:\n\t\t\tmessages.info(request, \"Datos erroneos\")\n\treturn render(request, \"login.html\")\n\n\n@login_required(login_url='/login')\ndef config(request):\n\tusuario=request.user.usuario\n\tform=UsuarioForm(instance=usuario)\n\n\tif request.method==\"POST\":\n\t\tform=UsuarioForm(request.POST, request.FILES, instance=usuario)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\treturn render(request, \"configurar.html\", {\"form\":form})\n\n\n@login_required(login_url='/login')\ndef logouts(request):\n\tlogout(request)\n\treturn redirect(\"/login\")\n\n\n# Sistema\n@login_required(login_url='/login')\n@admin_only\ndef index(request):\n\tif \"fecha_inicio\" in request.GET and \"fecha_termino\" in request.GET:\n\n\t\tf_inicio=request.GET[\"fecha_inicio\"]\n\t\tf_fin=request.GET[\"fecha_termino\"]\n\n\t\tif f_inicio>f_fin:\n\t\t\tmessages.info(request, \"Las fechas ingresadas son incorrectas\")\n\n\t\tventas=Venta.objects.filter(fecha__range=(f_inicio, f_fin))\n\t\tcostos=venta=ingresos=0\n\n\t\tfor v in ventas:\n\t\t costos += v.fruta.precio_compra * v.cantidad\n\t\t venta += v.precio_total\n\n\t\tingresos=venta - costos\n\t\treturn render(request, \"dashboard.html\", {\"ventas\":ventas, \"costos\":costos, \"venta\":venta, \"ingresos\":ingresos})\n\telse:\n\t\tventas=Venta.objects.all()\n\t\tcostos=venta=ingresos=0\n\t\tfor v in ventas:\n\t\t costos += v.fruta.precio_compra * v.cantidad\n\t\t venta += v.precio_total\n\t\tingresos=venta - costos\n\t\treturn render(request, \"dashboard.html\", {\"ventas\":ventas, \"costos\":costos, \"venta\":venta, \"ingresos\":ingresos})\n\n\n@login_required(login_url='/login')\ndef frutas(request):\n\tfrutas=Fruta.objects.all()\n\treturn render(request, \"frutas.html\", {\"models\": frutas})\n\n\n@login_required(login_url='/login')\ndef ventas(request):\n\tventas=Venta.objects.all().order_by('-fecha')\n\treturn render(request, \"ventas.html\", {\"models\": ventas})\n\n\n@login_required(login_url='/login')\n@admin_only\ndef stocks(request):\n\tstocks=Abastece.objects.all().order_by('-fecha')\n\treturn render(request, \"stock.html\", {\"models\": stocks})\n\n\n# CRUDS\n# frutas\n@login_required(login_url='/login')\n@admin_only\ndef createfruta(request):\n\tif request.method == \"POST\":\n\t\tmodel=FrutaForm(request.POST)\n\t\tif model.is_valid():\n\t\t\ttry:\n\t\t\t\tmodel.save()\n\t\t\t\treturn redirect (\"/frutas\")\n\t\t\texcept Exception as e:\n\t\t\t\tpass\n\telse:\n\t\tmodel=FrutaForm()\n\t\treturn render(request, \"form_fruta.html\", {\"formulario\":model})\n\n\n\n@login_required(login_url='/login')\n@admin_only\ndef viewfruta(request, id):\n\tmodel=Fruta.objects.get(id=id)\n\treturn render(request, \"temp_fruta.html\", {\"model\":model})\n\n\n\n@login_required(login_url='/login')\n@admin_only\ndef updatefruta(request, id):\n\tmodelo=Fruta.objects.get(id=id)\n\tmodel=FrutaForm(instance=modelo)\n\n\tif request.method == \"POST\":\n\t\tmodel=FrutaForm(request.POST, instance=modelo)\n\t\tif model.is_valid():\n\t\t\ttry:\n\t\t\t\tmodel.save()\n\t\t\t\treturn redirect (\"/frutas\")\n\t\t\texcept Exception as e:\n\t\t\t\tpass\n\telse:\n\t\treturn render(request, \"form_fruta.html\", {\"formulario\":model})\n\n\n\n@login_required(login_url='/login')\n@admin_only\ndef deletefruta(request, id):\n\tif Venta.objects.filter(fruta=id).exists():\n\t\tmessages.info(request, \"No se puede eliminar esta fruta porque tiene ventas asociadas\")\n\telse:\n\t\tmodel=Fruta.objects.get(id=id)\n\t\tmodel.delete()\n\treturn redirect (\"/frutas\")\n\n\n\n# Venta\n@login_required(login_url='/login')\ndef createventa(request):\n\tif request.method == \"POST\":\n\t\tmodel=VentaForm(request.POST)\n\t\tif model.is_valid():\n\t\t\ttry:\n\t\t\t\tmodel.save()\n\t\t\t\t# La venta disminuye el stock\n\t\t\t\tid_fruta=request.POST.get('fruta')\n\t\t\t\tcantidad=request.POST.get('cantidad')\n\t\t\t\tfruta=Fruta.objects.get(id=id_fruta)\n\t\t\t\tfruta.cantidad=fruta.cantidad - int(cantidad)\n\t\t\t\tfruta.save()\n\t\t\t\treturn redirect (\"/ventas\")\n\t\t\texcept Exception as e:\n\t\t\t\tpass\n\telse:\n\t\tmodel=VentaForm()\n\t\treturn render(request, \"form_venta.html\", {\"formulario\":model})\n\n\n\n@login_required(login_url='/login')\ndef viewventa(request, id):\n\tmodel=Venta.objects.get(id=id)\n\treturn render(request, \"temp_venta.html\", {\"model\":model})\n\n\n\n@login_required(login_url='/login')\ndef updateventa(request, id):\n\tmodelo=Venta.objects.get(id=id)\n\tcant_antes=modelo.cantidad\n\tstock_antes=modelo.fruta.cantidad\n\tif request.method == \"POST\":\n\t\tmodel=VentaForm(request.POST, instance=modelo)\n\t\tif model.is_valid():\n\t\t\ttry:\n\t\t\t\tcant_actual=model.cleaned_data['cantidad']\n\t\t\t\tmov_stock=cant_antes - cant_actual\n\t\t\t\tid_fruta=request.POST.get('fruta')\n\t\t\t\tfruta=Fruta.objects.get(id=id_fruta)\n\t\t\t\tfruta.cantidad=fruta.cantidad + int(mov_stock)\n\t\t\t\tfruta.save()\n\t\t\t\tmodel.save()\n\t\t\t\treturn redirect (\"/ventas\")\n\t\t\texcept Exception as e:\n\t\t\t\tpass\n\telse:\n\t\tmodel=VentaForm(instance=modelo)\n\t\treturn render(request, \"form_venta.html\", {\"formulario\":model})\n\n\n@login_required(login_url='/login')\ndef deleteventa(request, id):\n\tmodel=Venta.objects.get(id=id)\n\tid_fruta=model.fruta.id\n\tcantidad=model.cantidad\n\tif model.delete():\n\t\tfruta=Fruta.objects.get(id=id_fruta)\n\t\tfruta.cantidad=fruta.cantidad + int(cantidad)\n\t\tfruta.save()\n\treturn redirect (\"/ventas\")\n\n\n# Stock\n@login_required(login_url='/login')\n@admin_only\ndef createstock(request):\n\tif request.method == \"POST\":\n\t\tmodel=AbasteceForm(request.POST)\n\t\tif model.is_valid():\n\t\t\ttry:\n\t\t\t\tif model.save():\n\t\t\t\t\tid_fruta=request.POST.get('fruta')\n\t\t\t\t\tcantidad=request.POST.get('cantidad')\n\t\t\t\t\tfruta=Fruta.objects.get(id=id_fruta)\n\t\t\t\t\tfruta.cantidad=fruta.cantidad + int(cantidad)\n\t\t\t\t\tfruta.save()\n\t\t\t\t\treturn redirect (\"/stocks\")\n\t\t\texcept Exception as e:\n\t\t\t\tpass\n\telse:\n\t\tmodel=AbasteceForm()\n\t\treturn render(request, \"form_stock.html\", {\"formulario\":model})\n\n\n\n@login_required(login_url='/login')\n@admin_only\ndef deletestock(request, id):\n\tmodel=Abastece.objects.get(id=id)\n\tid_fruta=model.fruta.id\n\tcantidad=model.cantidad\n\t# si se borra hay que quitar elementos de stock\n\tif model.delete():\n\t\tfruta=Fruta.objects.get(id=id_fruta)\n\t\tfruta.cantidad=fruta.cantidad - int(cantidad)\n\t\tfruta.save()\n\treturn redirect (\"/stocks\")\n\n\n# Ajax\ndef obtener_precio(request):\n id = request.GET.get('id', None)\n fruta=Fruta.objects.get(id=id)\n valor=fruta.precio_venta\n data = {\n 'valor_vta': valor\n }\n return JsonResponse(data)","sub_path":"ventas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"621243098","text":"import scrapy\nimport random\nfrom scrapy_proxycrawl import ProxyCrawlRequest\nimport requests\nfrom .shops_categories import shops, categories_urls\n\n\nclass AmazonSpider(scrapy.Spider):\n name = 'yandexspider'\n shop = random.choice(list(shops.keys()))\n shop_id = shops[shop]['id']\n category = random.choice(shops[shop]['categories'])\n url = categories_urls[category]\n\n def clean_price_to_int(self, str_to_number):\n numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']\n price = str_to_number\n for i in price:\n if i not in numbers:\n price = price.replace(i, '')\n return price\n\n def start_requests(self):\n yield ProxyCrawlRequest(url=self.url.format(self.shop_id),\n device='desktop',\n country='DE',\n callback=self.parse)\n\n def parse(self, response):\n deal_links = response.xpath('.//h3[@class=\"n-snippet-cell2__title\"]/a/@href').getall()\n random_link = random.choice(deal_links)\n absolute_url = response.urljoin(random_link)\n yield ProxyCrawlRequest(url=absolute_url,\n device='desktop',\n country='DE',\n callback=self.parse_detail,\n )\n\n def parse_detail(self, response):\n data = {}\n data['name'] = response.css('div.n-title__text h1::text').get()\n data['price'] = self.clean_price_to_int(response.css('div.n-product-price-cpa2__price span::text').get())\n data['oldprice'] = self.clean_price_to_int(response.css('div.n-product-default-offer__old-price-cpa2 span::text').get())\n data['description'] = response.css('ul.n-product-spec-list').get()\n data['image'] = 'https:' + response.css('div.n-gallery__item img::attr(src)').get()\n data['brand'] = response.css('span.n-product-summary__brand-text-all-products-brandname::text').get()\n data['shop'] = self.shop\n data['category'] = self.category\n url_to_shop = response.css('div.n-offer-action__main a::attr(href)').get()\n request_to_shop = requests.get('https:' + url_to_shop).url\n data['link_to_shop'] = request_to_shop[0:request_to_shop.find('?')]\n yield data\n\n\nclass CountriesSpider(scrapy.Spider):\n name = 'countries'\n allowed_domains = ['www.worldometers.info/']\n start_urls = ['https://www.worldometers.info/world-population/population-by-country/']\n\n def parse(self, response):\n title = response.xpath('//h1/text()').get()\n countries = response.xpath('//td/a/text()').getall()\n\n yield {\n 'title': title,\n 'countries': countries,\n }","sub_path":"deals/management/yanspider/spiders/deal_spider.py","file_name":"deal_spider.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"199624715","text":"import telebot \r\nimport configure\r\nimport sqlite3\r\nfrom sqlite3 import Error\r\nfrom telebot import types\r\n\r\nbot = telebot.TeleBot(configure.config['token'])\r\n\r\n\t\r\n\t#работа со стартом \r\n\t\r\n@bot.message_handler(commands=['start'])\r\ndef start(message):\r\n\r\n\tsend_mess = f\"Привет {message.from_user.first_name}, классный ник!\\nА теперь давай найдем тебе классную одежду\"\r\n\t\t\r\n\tmarkup = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n\titem_catalog = types.KeyboardButton('📂 Каталог')\r\n\titem_basket = types.KeyboardButton('🛒 Корзина')\r\n\titem_orders = types.KeyboardButton('📦 Заказы')\r\n\titem_news = types.KeyboardButton('📡 Новости')\r\n\titem_settings = types.KeyboardButton('⚙️ Настройки')\r\n\titem_help = types.KeyboardButton('❓ Помощь')\r\n\t\r\n\tmarkup.row(item_catalog, item_basket)\r\n\tmarkup.row(item_orders, item_news)\r\n\tmarkup.row(item_settings, item_help)\r\n\tbot.send_message(message.chat.id, send_mess, parse_mode='html', reply_markup = markup)\r\n\r\n\r\n@bot.message_handler(commands=['admin'])\r\ndef admin(message):\r\n\r\n\tif message.text == '123456778':\r\n\t\tkeyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n\t\titem_newproduct = types.KeyboardButton('Добавить товар')\r\n\t\titem_deleteproduct = types.KeyboardButton('Удалить товар')\r\n\t\tkeyboard.add(item_newproduct, item_deleteproduct)\r\n\t\tbot.send_message(message.chat.id, \"Введите пароль:\", reply_markup = keyboard)\r\n\telse: \r\n\t\tbot.send_message(message.chat.id, 'Неверный пароль')\r\n\t\r\n\t#работа с текстом (этаж 1)\r\n\t\r\n@bot.message_handler(content_types = ['text'])\r\ndef get_button(message):\r\n\r\n\r\n\tif message.text == '📂 Каталог':\r\n\t\tmarkup_reply1 = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n\t\titem_catalog1 = types.KeyboardButton('👕 Верхняя одежда 👚')\r\n\t\titem_catalog2 = types.KeyboardButton('👖 Штаны/Юбки/Шорты 🩳')\r\n \r\n\t\tmarkup_reply1.row(item_catalog1)\r\n\t\tmarkup_reply1.row(item_catalog2)\r\n\t\tbot.send_message(message.chat.id, 'Выберите раздел:', reply_markup = markup_reply1)\r\n\r\n\telif message.text == '🛒 Корзина':\r\n\t\tbot.send_message(message.chat.id, 'К сожалению, пока что корзины нет 😢')\r\n\r\n\telif message.text == '📦 Заказы':\r\n\t\tbot.send_message(message.chat.id, 'К сожалению, пока что заказов нет 😢')\r\n\r\n\telif message.text == '📡 Новости':\r\n\t\tbot.send_message(message.chat.id, 'К сожалению, пока что новостей нет 😢')\r\n\r\n\telif message.text == '⚙️ Настройки':\r\n\t\tbot.send_message(message.chat.id, 'К сожалению, пока что настроек нет 😢')\r\n\r\n\telif message.text == '❓ Помощь':\r\n\t\tbot.send_message(message.chat.id, 'К сожалению, пока что помощи ��ет 😢')\r\n\r\n\telif message.text == 'Купить':\r\n\t\tbot.send_message(message.chat.id, 'Ваш заказ принят\\nМожете забрать когда будет удобно 😌')\r\n\r\n\t#этаж 2 \r\n\r\n\telif message.text == '👕 Верхняя одежда 👚':\t\r\n\t\tmarkup_inline = types.InlineKeyboardMarkup()\r\n\t\tmarkup_inline.add(*[types.InlineKeyboardButton(text=name, callback_data=name)\r\n\t\t\t\tfor name in ['Куртки', 'Кофты', 'Свитера']])\r\n\t\tbot.send_message(message.chat.id, 'Выберите товар:', reply_markup = markup_inline)\r\n\r\n\telif message.text == \"👖 Штаны/Юбки/Шорты 🩳\":\r\n\t\tmarkup_inline1 = types.InlineKeyboardMarkup()\r\n\t\tmarkup_inline1.add(*[types.InlineKeyboardButton(text=name, callback_data=name)\r\n\t\t\t\tfor name in ['Штаны', 'Юбки', 'Шорты']])\r\n\t\tbot.send_message(message.chat.id, 'Выберите товар:', reply_markup = markup_inline1)\r\n\r\n\telse: \r\n\t\tbot.send_message(message.chat.id, 'Сейчас не понял 😒')\r\n\r\n\t#работа с инлайновой клавиатурой (этаж 3) \r\n\t\t \r\n@bot.callback_query_handler(func = lambda call: True)\t\r\ndef back_menu(call):\r\n\t\r\n\tcid = call.message.chat.id\r\n\r\n\tsqlite_connection = sqlite3.connect('database.db')\r\n\tcursor = sqlite_connection.cursor()\r\n\r\n\t\t\t\t\r\n\tif call.data == 'Куртки':\r\n\t\tmarkup_reply3 = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n\t\titem_menu = types.KeyboardButton('🤷‍♀️ Главное меню')\r\n\t\titem_buy = types.KeyboardButton('Купить')\r\n\r\n\t\tmarkup_reply3.add(item_menu, item_buy)\r\n\t\tsqlite_insert_blob_query = \"SELECT photo, description, price from bd where id = 1\"\r\n\t\tcursor.execute(sqlite_insert_blob_query)\r\n\t\tbot.send_photo(cid, photo=open(\"product/jacket_kappa.jpg\", 'rb'))\r\n\t\tbot.send_message(cid, str(cursor.fetchone()[1]) + '\\nЦена: 1750 грн.', reply_markup = markup_reply3)\r\n\r\n\telif call.data == 'Кофты':\r\n\t\tmarkup_reply4 = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n\t\titem_menu = types.KeyboardButton('🤷‍♀️ Главное меню')\r\n\t\titem_buy = types.KeyboardButton('Купить')\r\n\r\n\t\tmarkup_reply4.add(item_menu, item_buy)\r\n\t\tsqlite_insert_blob_query2 = \"SELECT photo, description, price from bd where id = 2\"\r\n\t\tcursor.execute(sqlite_insert_blob_query2)\r\n\t\tbot.send_photo(cid, photo=open(\"product/blose_tnf.jpg\", 'rb'))\r\n\t\tbot.send_message(cid, str(cursor.fetchone()[1]) + '\\nЦена: 1175 грн.', reply_markup = markup_reply4)\r\n\r\n\telif call.data == 'Свитера':\r\n\t\tmarkup_reply5 = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n\t\titem_menu = types.KeyboardButton('🤷‍♀️ Главное меню')\r\n\t\titem_buy = types.KeyboardButton('Купить')\r\n\r\n\t\tmarkup_reply5.add(item_menu, item_buy)\r\n\t\tsqlite_insert_blob_query3 = \"SELECT photo, description, price from bd where id = 3\"\r\n\t\tcursor.execute(sqlite_insert_blob_query3)\r\n\t\tbot.send_photo(cid, photo=open(\"product/sweater_ripndip.jpg\", 'rb'))\r\n\t\tbot.send_message(cid, str(cursor.fetchone()[1]) + '\\nЦена: 1050 грн.', reply_markup = markup_reply5)\r\n\t\t\r\n\r\n\telif call.data == 'Штаны':\r\n\t\tmarkup_reply6 = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n\t\titem_menu = types.KeyboardButton('🤷‍♀️ Главное меню')\r\n\t\titem_buy = types.KeyboardButton('Купить')\r\n\r\n\t\tmarkup_reply6.add(item_menu, item_buy)\r\n\t\tsqlite_insert_blob_query4 = \"SELECT photo, description, price from bd where id = 4\"\r\n\t\tcursor.execute(sqlite_insert_blob_query4)\r\n\t\tbot.send_photo(cid, photo=open(\"product/trousers_nasa.jpg\", 'rb'))\r\n\t\tbot.send_message(cid, str(cursor.fetchone()[1]) + '\\nЦена: 1200 грн.', reply_markup = markup_reply6)\r\n\t\r\n\r\n\telif call.data == 'Юбки':\r\n\t\tmarkup_reply7 = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n\t\titem_menu = types.KeyboardButton('🤷‍♀️ Главное меню')\r\n\t\titem_buy = types.KeyboardButton('Купить')\r\n\r\n\t\tmarkup_reply7.add(item_menu, item_buy)\r\n\t\tsqlite_insert_blob_query5 = \"SELECT photo, description, price from bd where id = 5\"\r\n\t\tcursor.execute(sqlite_insert_blob_query5)\r\n\t\tbot.send_photo(cid, photo=open(\"product/skirt_nike.jpg\", 'rb'))\r\n\t\tbot.send_message(cid, str(cursor.fetchone()[1]) + '\\nЦена: 850 грн.', reply_markup = markup_reply7)\r\n\t\t\r\n\r\n\telif call.data == 'Шорты':\r\n\t\tmarkup_reply8 = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n\t\titem_menu = types.KeyboardButton('🤷‍♀️ Главное меню')\r\n\t\titem_buy = types.KeyboardButton('Купить')\r\n\r\n\t\tmarkup_reply8.add(item_menu, item_buy)\r\n\t\tsqlite_insert_blob_query6 = \"SELECT photo, description, price from bd where id = 6\"\r\n\t\tcursor.execute(sqlite_insert_blob_query6)\r\n\t\tbot.send_photo(cid, photo=open(\"product/shorts_ripndip.jpg\", 'rb'))\r\n\t\tbot.send_message(cid, str(cursor.fetchone()[1]) + '\\nЦена: 1000 грн.', reply_markup = markup_reply8)\r\n\r\nbot.polling(none_stop=True)","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"555276710","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$',views.login,name='login'),\n url(r'logme/',views.logme,name='logme'),\n url(r'logout/',views.logout,name='logout'),\n ]\n\n","sub_path":"authsApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"254126762","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.urls import reverse\nfrom embed_video.fields import EmbedVideoField\n\nclass Blop(models.Model):\n creator = models.ForeignKey(User, on_delete =models.CASCADE)\n title = models.CharField (max_length=50)\n video = EmbedVideoField(max_length=200, null=True, blank=True) \n image = models.URLField(max_length=200, null=True, blank=True)\n article = models.TextField(max_length=10000, blank=True)\n likes = models.PositiveIntegerField(default=0)\n created_at = models.DateTimeField(auto_now_add=True)\n def get_absolute_url(self):\n return reverse('main_app:home')\n def __str__(self):\n if len(self.article) < 150:\n return self.article[:150]\n return self.article[:150] + \"...\"\n class Meta():\n ordering = ['-likes']\n\nclass Blopper(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n liked_blops = models.ManyToManyField(Blop)\n @receiver(post_save, sender=User)\n def create_user_profile(sender, instance, created, **kwargs):\n if created:\n Blopper.objects.create(user=instance)\n @receiver(post_save, sender=User)\n def save_user_profile(sender, instance, **kwargs):\n instance.blopper.save()\n\nclass Comment(models.Model):\n creator = models.ForeignKey(User, on_delete=models.CASCADE)\n content = models.TextField(max_length= 300)\n blop = models.ForeignKey(Blop, on_delete=models.CASCADE)\n created_at = models.DateTimeField(auto_now_add=True)\n class Meta():\n ordering = ['-created_at']\n def __str__(self):\n return f'{self.content}'","sub_path":"main_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"26640115","text":"# http://connor-johnson.com/2014/02/25/spatial-point-processes/\n\nimport scipy\nfrom scipy.stats import poisson\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom collections import defaultdict\n\ntotal_no_of_cells=25\ntotal_no_of_users=1000\nmax_number_of_users=1100\ninitial_no_of_users=total_no_of_users\ntotal_no_of_epochs=100 \nlambda_user_join = 1\nduration_of_epoch=5 # in hours\nduration_of_t=15\t\t # in Minutes \nrekeying_time = 1\non_off_state_matrix=np.zeros((total_no_of_users,int((total_no_of_epochs*duration_of_epoch*60)/duration_of_t)),dtype=int)\nnewly_joined_users=0\nusers=defaultdict(dict)\ncells=defaultdict(list) \nreassignment_time=1\nreassignment_time_array=[1,1.2,1.5,1.83,1.9,2.01,2.3,2.5,2.8,2.97,3.5]\ntotal_reassignment_delay=0\ntotal_rekeying_delay=0\nleader_db_query_delay=0\nactive_cells=[]\ninactive_cells=[]\ntotal_delay=0\n#p = 0.5\t\t\t\t # user active probability\nq = 0.1\t\t\t\t # user inactive probability \nquery_delay = [1.96, 3.26, 3.53, 4.85, 5.74, 7, 7.68, 8.28, 10.17, 10.73, 12.34, 12.48, 12.67, 13.21, 13.94, 14.36, 14.87, 16.46, 16.72, 17.06, 18.93, 19.49, 20.93, 21.51, 21.94]\nno_of_users_array=[]\nno_of_reassignments_array=[]\nno_of_epochs_array=[]\nreassignment_delay_array=[]\ntotal_no_of_distruptions_array=[]\ntotal_reassign_c=0\np_array=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]\nq_array=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]\nNd_array=[]\n\nfor p in p_array:\n\ttotal_no_of_distruptions=0\n\tdef calculateDistance(x1,y1,x2,y2): \n\t\t dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) \n\t\t return dist \n\n\tdef PoissonPP( rt, Dx, Dy=None ):\n\t\tif Dy == None:\n\t\t\tDy = Dx\n\t\t\tN = scipy.stats.poisson( rt ).rvs()\n\t\t\tt=total_no_of_cells-N\n\t\t\t#print(\"No of cells :\",N)\n\t\t\tx = scipy.stats.uniform.rvs(0,Dx,((N,1)))\n\t\t\ty = scipy.stats.uniform.rvs(0,Dy,((N,1)))\n\t\t\tx1 = scipy.stats.uniform.rvs(0,Dx,((t,1)))\n\t\t\ty1 = scipy.stats.uniform.rvs(0,Dy,((t,1)))\n\t\t\tP = np.hstack((x,y))\n\t\t\tNP = np.hstack((x1,y1))\n\t\treturn P,NP\n\t\t\n\tdef NewUsersLocations( nUCount, Dx, Dy=None ):\n\t\tif Dy == None:\n\t\t\tDy = Dx\n\t\t\tN = nUCount\n\t\t\tx = scipy.stats.uniform.rvs(0,Dx,((N,1)))\n\t\t\ty = scipy.stats.uniform.rvs(0,Dy,((N,1)))\n\t\t\tP = np.hstack((x,y))\n\t\treturn P\n\t\t\n\tdef uniformDisk( x, y, r ):\n\t\tr = scipy.stats.uniform( 0, r**2.0 ).rvs()\n\t\ttheta = scipy.stats.uniform( 0, 2*np.pi ).rvs()\n\t\txt = np.sqrt( r ) * np.cos( theta )\n\t\tyt = np.sqrt( r ) * np.sin( theta )\n\t\treturn x+xt, y+yt\n\t\t\n\tdef MaternPP( kappa, r, mu, Dx ):\n\t\tparents, nonParents = PoissonPP( kappa, Dx )\n\t\tM = parents.shape[0]\n\t\tMP = list()\n\t\tk=0\n\t\twhile k=total_no_of_users+1:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tx, y = uniformDisk( parents[i,0], parents[i,1], r )\n\t\t\t\t\tusers[k]['location']=(x,y)\n\t\t\t\t\tusers[k]['cell']=i+1\n\t\t\t\t\tcells[i+1].append(k)\n\t\t\t\t\tif i not in active_cells:\n\t\t\t\t\t\tactive_cells.append(i)\n\t\t\t\t\tMP.append( [ x, y ] )\n\t\t\t\tif k>=total_no_of_users:\n\t\t\t\t\tbreak\n\t\tMP = np.array( MP )\n\t\tprint(\"Total number of user : \",k)\n\t\treturn MP,parents,nonParents\n\t\t\n\tP,active_parents,inactive_parents=MaternPP(10,2,70,total_no_of_cells)\n\tparents=np.vstack((active_parents,inactive_parents))\n\t# print(active_parents.shape)\n\t# print(inactive_parents.shape)\n\n\tfor i in range(total_no_of_epochs):\n\t\tno_of_epochs_array.append(i)\n\t\tno_of_users_array.append(total_no_of_users)\n\t\tleader_db_query_delay+=query_delay[len(active_cells)-1]\n\t\ta=np.zeros((newly_joined_users,int((total_no_of_epochs*duration_of_epoch*60)/duration_of_t)),dtype=int)\n\t\tnew_on_off_state_matrix=np.vstack((on_off_state_matrix,a)) \t\n\t\treassignment_delay_for_the_epoch=0\n\t\tfor usr in range(total_no_of_users):\n\t\t\tsum=0\n\t\t\tcolumn=int(((i*duration_of_epoch*60)/duration_of_t))\n\t\t\twhile sum < (duration_of_epoch*60)/duration_of_t:\n\t\t\t\tr_active=np.random.random()\n\t\t\t\tr_inactive=np.random.random()\n\t\t\t\tif r_active>r_inactive:\n\t\t\t\t\tif r_active0 and total_no_of_users+newly_joined_users active_parents.shape[0]-1:\n\t\t\t\t\t\tcells[index].append(total_no_of_users)\n\t\t\t\t\t\tactive_cells.append(active_parents.shape[0])\n\t\t\t\t\t\tactive_parents=np.vstack((active_parents,min_parent))\n\t\t\t\t\t\tP=np.vstack((P,u))\n\t\t\t\t\telse:\n\t\t\t\t\t\tP=np.vstack((P,u))\n\t\t\t\ttotal_rekeying_delay+=rekeying_time\n\t\t#print(active_cells)\t\t\t\n\t# print(inactive_parents.shape)\n\ttotal_delay=total_reassignment_delay+leader_db_query_delay+total_rekeying_delay\n\tprint(\"Average processing time for leader : \",total_delay/total_no_of_epochs)\n\tprint(\"Average time spent on rekeying per user : \",total_rekeying_delay/total_no_of_epochs)\n\n\tprint(\" Percentage of processing time over the duration of the simulation : \", (total_delay/(total_no_of_epochs*duration_of_epoch*60*60))*100)\n\tprint(\" Percentage of reassignment time for the user : \", (total_reassignment_delay/(total_no_of_epochs*duration_of_epoch*60*60))*100)\n\tNd_array.append(total_no_of_distruptions/total_no_of_epochs)\n\tprint(\"Total reassignment delay : \",total_reassignment_delay)\n\tprint(\"Total rekeying delay : \",total_rekeying_delay)\n\tprint(\"Average number of distruptions : \",total_no_of_distruptions/total_no_of_epochs)\n\tprint(\"Total leader database query delay : \",leader_db_query_delay)\n\n\n\n# No of epochs to no of distruptions Graph\n# P=P.T\nplt.plot(Nd_array, p_array, '-',color='r')\nplt.axis([0, 10, 0, 1])\nplt.xlabel('Number of distruptions')\nplt.ylabel('Probability P')\n#No of users to no of epochs Graph\n#P=P.T\n# plt.plot(no_of_epochs_array, no_of_users_array, '-',color='r')\n# plt.axis([0, 1000, 0, 1100])\n# plt.xlabel('Number of epochs')\n# plt.ylabel('Number of users')\n#No of users to no of reassignments Graph\n#P=P.T\n# plt.plot(no_of_epochs_array, reassignment_delay_array, '-',color='r')\n# plt.axis([0, 1000, 0, 30000])\n# plt.xlabel('Number of epochs')\n# plt.ylabel('Reassignement delay')\n#No of users to no of reassignments Graph\n# P=P.T\n# plt.plot(no_of_users_array, no_of_reassignments_array, '-',color='r')\n# plt.axis([0, 1100, 0, 30])\n# plt.xlabel('Number of users')\n# plt.ylabel('Number of reassignments')\n# Users Graph\n# P=P.T\n# plt.plot(P[0], P[1], 'o',color='g')\n# plt.axis([0, 30, 0, 30])\n# print(total_reassign_c)\n# print(total_no_of_users)\n# for i in cells:\n\t# print(i,cells[i])\n# for i in list(users.keys())[:10]:\n\t# print(users[i])\nplt.show()\n\n\n","sub_path":"Python_Point_Process/PP.py","file_name":"PP.py","file_ext":"py","file_size_in_byte":8943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"69317872","text":"import wget\nimport spotipy\nimport spotipy.util as util\nimport time\nimport os\nimport config\n\nscope = config.scope\nusername = config.username\nclient_id = config.client_id\nclient_secret = config.client_secret\nredirect_uri = config.redirect_uri\n\ndef tokenGen():\n token = util.prompt_for_user_token(username, scope, client_id=client_id, client_secret=client_secret,\n redirect_uri=redirect_uri)\n sp = spotipy.Spotify(auth=token)\n return sp\n\ndef run_mac():\n sp = tokenGen()\n sp.trace = True\n while True:\n user = sp.currently_playing()\n temp = user\n try:\n time.sleep(1)\n user = sp.currently_playing()\n if temp[\"item\"][\"album\"][\"id\"] == user[\"item\"][\"album\"][\"id\"]:\n continue\n else:\n old_filename = temp['item']['album']['images'][0]['url'].split(\"/\")[-1]\n old_absolute_filename = os.path.join(\n os.path.abspath(os.getcwd()), old_filename)\n os.system(f\"rm {old_absolute_filename}\")\n link = user['item']['album']['images'][0]['url']\n local_filename = wget.download(link)\n full_local_filename = os.path.abspath(local_filename)\n os.system(\n f\"osascript -e 'tell application \\\"Finder\\\" to set desktop picture to POSIX file \\\"{full_local_filename}\\\"'\")\n time.sleep(1)\n except spotipy.client.SpotifyException:\n sp = tokenGen()\n continue\n\ndef run_linux():\n sp = tokenGen()\n sp.trace = True\n while True:\n user = sp.currently_playing()\n temp = user\n try:\n time.sleep(2)\n user = sp.currently_playing()\n if temp[\"item\"][\"album\"][\"id\"] == user[\"item\"][\"album\"][\"id\"]:\n continue\n else:\n link = user['item']['album']['images'][0]['url']\n os.system(\"gsettings set org.gnome.desktop.background picture-uri \" + link)\n time.sleep(2)\n except spotipy.client.SpotifyException:\n sp = tokenGen()\n continue\n\ndef run_windows():\n print(\"Windows is not currently supported\")\n\ndef main():\n platform = os.sys.platform\n if platform == \"darwin\":\n run_mac()\n elif platform in (\"linux1\", \"linux2\"):\n run_linux()\n elif platform == \"win32\":\n run_windows()\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"AlbumArtWallpaper.py","file_name":"AlbumArtWallpaper.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"511540073","text":"import math\r\n\r\ndef find_prime(M, N, limit):\r\n prime_board = [False] * (limit+1)\r\n prime_board[0] = True\r\n prime_board[1] = True\r\n result = []\r\n\r\n for i in range(2, int(math.sqrt(limit))+1):\r\n if prime_board[i] is False:\r\n for j in range(i*2, limit+1, i):\r\n prime_board[j] = True\r\n\r\n for i in range(M, N+1):\r\n if prime_board[i] is False:\r\n result.append(i)\r\n\r\n return result\r\n\r\n\r\ndef main():\r\n input_line = input()\r\n len_input = len(input_line)\r\n space_index = 0\r\n for i in range(0, len_input):\r\n if input_line[i] == \" \":\r\n space_index = i\r\n break\r\n M = int(input_line[0:space_index])\r\n N = int(input_line[space_index+1:len_input])\r\n\r\n # M and N <= 1,000,000 Integer.\r\n if (M < 0 or N < 0) or (M > N):\r\n return\r\n\r\n limit = 1000000\r\n result = find_prime(M, N, limit)\r\n\r\n for each in result:\r\n print(each)\r\n\r\n\r\nmain()\r\n","sub_path":"BAEJOON/1929_소수구하기.py","file_name":"1929_소수구하기.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"300101176","text":"\r\nimport operator\r\nimport os, feather\r\nimport ta\r\n\r\nimport pandas_datareader as pdr\r\nimport pandas as pd\r\n\r\nfrom multiprocessing.pool import ThreadPool\r\n\r\nfrom datetime import date, timedelta\r\n\r\n## TA Filter Conditions\r\nBBandsPeriod = 20\r\nBBandsStdDev = 2\r\n\r\nRSIUpper = 75\r\nRSILower = 25\r\n\r\nRSIPeriod = 14\r\n\r\n## Assume args[0] always refer to ticker\r\ndef tryExcept(f):\r\n def wrapper(*args, **kwargs):\r\n try: \r\n return f(*args, **kwargs) \r\n except Exception as e:\r\n print(f'{args[0]} EXCEPTION: {e}')\r\n return None\r\n return wrapper\r\n\r\ndef getDate(inter=0):\r\n return date.today() - timedelta(days=1+inter)\r\n\r\ndef getNASDAQTickers():\r\n data = pdr.nasdaq_trader.get_nasdaq_symbols()\r\n return data[data['Nasdaq Traded']].index.values\r\n\r\ndef writeToDB(data, file, resetIndex=True):\r\n if not os.path.exists(\"db\"):\r\n os.makedirs('db')\r\n print(f\"Writing to db/{file}.file\")\r\n feather.write_dataframe(data.reset_index() if resetIndex else data, f'db/{file}.file') \r\n\r\ndef filterDF(data, dt, oper=operator.ge):\r\n return data[[oper(i.date(), dt) for i in pd.to_datetime(data.index)]]\r\n\r\ndef findDateIndex(data, idx, oper=operator.add):\r\n return oper(pd.to_datetime(data.index.values[idx]).date(), timedelta(days=1)) \r\n\r\n## Only extract data that doesn't exist so avoid repetitive extraction\r\n@tryExcept\r\ndef extractYahooData(tick, startDate, endDate):\r\n \r\n ## If exists, take only dates that one needs\r\n if os.path.exists(f'db/{tick}.file'):\r\n \r\n df = pd.read_feather(f'db/{tick}.file').set_index('Date')\r\n df = filterDF(df, startDate)\r\n\r\n ## Get original length to determine if it has been appended with new data \r\n origLen = len(df) \r\n\r\n ## If len is zero, instantly go to reading the entire database and rewriting it\r\n if 0 == origLen:\r\n df = pdr.data.get_data_yahoo(tick, startDate, endDate)\r\n writeToDB(df, tick)\r\n return df\r\n\r\n ## Get first and last date\r\n firstdt = findDateIndex(df, 0, operator.sub) \r\n lastdt = findDateIndex(df, -1) \r\n\r\n ## Account for missing earlier dates (Try-except to avoid date-violation if for e.g. data doesnt exist)\r\n if firstdt >= startDate:\r\n try: \r\n add_df = pdr.data.get_data_yahoo(tick, startDate, firstdt)\r\n add_df = filterDF(add_df, firstdt, operator.le) \r\n df = df.combine_first(add_df) \r\n except:\r\n pass\r\n\r\n ## Account for missing latest dates \r\n if lastdt <= endDate:\r\n try: \r\n add_df = pdr.data.get_data_yahoo(tick, lastdt, endDate)\r\n add_df = filterDF(add_df, lastdt, operator.ge) \r\n df = add_df.combine_first(df) \r\n except:\r\n pass\r\n \r\n ## Only write to feather.file if length changes\r\n if origLen != len(df):\r\n writeToDB(df, tick) \r\n\r\n else: \r\n df = pdr.data.get_data_yahoo(tick, startDate, endDate)\r\n writeToDB(df, tick) \r\n\r\n return df\r\n\r\ndef getErrorTicks():\r\n file = 'db/error.file'\r\n return pd.read_feather(file) if os.path.exists(file) else pd.DataFrame({'ErrorTicks': []})\r\n\r\n## Parallel download of ticker symbols - Default 8 processes\r\ndef populateDB(procs=8):\r\n \r\n print(\"Initiating population of DB for last 250 days\")\r\n \r\n ticks = getNASDAQTickers()\r\n \r\n errorTicks = set(getErrorTicks()['ErrorTicks'])\r\n \r\n origLen = len(errorTicks)\r\n\r\n pool = ThreadPool(processes=procs)\r\n\r\n async_result = []\r\n tickProcs = []\r\n\r\n startDate, endDate = getDate(250), getDate()\r\n for i in ticks:\r\n if i not in errorTicks:\r\n async_result.append(pool.apply_async(extractYahooData, (i,startDate,endDate)))\r\n tickProcs.append(i)\r\n\r\n for k,v in enumerate(async_result):\r\n v.wait()\r\n if v.get() is None:\r\n errorTicks.add(tickProcs[k])\r\n\r\n ## Updating error.file\r\n if origLen != len(errorTicks):\r\n df = pd.DataFrame({'ErrorTicks': list(errorTicks)})\r\n writeToDB(df, 'error', False)\r\n\r\n print(\"Completion of population of DB\")\r\n\r\n## Check for Bollinger Bands and RSI Violations\r\ndef checkTAFilter(tick, startDate, endDate):\r\n \r\n df = extractYahooData(tick, startDate, endDate)\r\n\r\n if df is None:\r\n return None\r\n\r\n indicator_rsi = ta.momentum.RSIIndicator(close=df['Adj Close'], n=RSIPeriod, fillna=False)\r\n df['RSI'] = indicator_rsi.rsi()\r\n \r\n indicator_bb = ta.volatility.BollingerBands(close=df['Adj Close'], n=BBandsPeriod, ndev=BBandsStdDev)\r\n df['bb_High'] = indicator_bb.bollinger_hband_indicator() \r\n df['bb_Low'] = indicator_bb.bollinger_lband_indicator()\r\n \r\n ## Get last row of dataframe\r\n row = df.iloc[-1]\r\n\r\n ## Use limits to determine if it should be appended to overbought/oversold variable\r\n if (row['RSI'] >= RSIUpper) and bool(row['bb_High']):\r\n return tick \r\n\r\n if (row['RSI'] <= RSILower) and bool(row['bb_Low']):\r\n return tick \r\n \r\n return None\r\n\r\n## Multi-processing wrapper for checkTAFilter \r\ndef getFilteredTicks(procs=8):\r\n \r\n print(\"Identifying Overbought/Oversold Tick Symbols\")\r\n\r\n ticks = set(getNASDAQTickers())\r\n errorTicks = set(getErrorTicks()['ErrorTicks'])\r\n ticks -= errorTicks\r\n\r\n pool = ThreadPool(processes=procs)\r\n\r\n ## Storage of results/tickSymbols\r\n async_result = []\r\n filteredTicks = []\r\n\r\n startDate, endDate = getDate(250), getDate()\r\n for i in ticks:\r\n async_result.append(pool.apply_async(checkTAFilter, (i,startDate,endDate)))\r\n\r\n for k,v in enumerate(async_result):\r\n v.wait()\r\n res = v.get()\r\n if res is not None:\r\n filteredTicks.append(res)\r\n\r\n print(\"Completion of Identification\")\r\n\r\n return filteredTicks\r\n\r\ndef getAndStoreFilteredTicks(file='filteredTicks'):\r\n filteredTicks = pd.DataFrame({'Potential Ticks': getFilteredTicks()})\r\n writeToDB(filteredTicks, file, False)\r\n\r\ndef readFilteredTicks(file='filteredTicks'):\r\n file = f'db/{file}.file'\r\n return pd.read_feather(file) if os.path.exists(file) else pd.DataFrame({'Potential Ticks': []}) ","sub_path":"utils/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":6305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"156538009","text":"import clearmem_my_functions as mf\nimport os\nimport numpy as np\nimport nibabel as nib\nimport pandas as pd\n\n'''\nconda activate conda_fmri\nxcluster='local'\nxstep='ph1_create_nodes'\nxnodes='glasser'\nxsubj='001'\n'''\n'''\nimport imp\nimp.reload(mf)\nfrom clearmem_my_functions import *\n'''\n\n'''\n#------ run all subjects\nimport clearmem_operation_rsa as cp\ncp.clearmem_rsa('blanca','ph1_create_nodes','glasser', '001')\ncp.clearmem_rsa('local','ph1_create_nodes','glasser', '001')\nimport imp\nimp.reload(cp)\nfrom clearmem_operation_rsa import *\n'''\n\n\ndef clearmem_rsa(xcluster, xstep, xnodes, xsubj):\n # steps: True False\n steps = {'ph1_create_nodes': False, 'ph2_grp_results': False, 'ph3_kmean': False, xstep: True}\n\n ###########################################\n # arguments\n ###########################################\n xargs = {'cluster': xcluster,\n 'subject_id': 'sub-%s' % xsubj,\n 'nodes': xnodes,\n 'node_mask': 'mask',\n 'resolution': 1,\n 'n_vox_cluster': 5}\n\n if xargs['nodes'] == 'glasser':\n xargs['n_nodes'] = 180\n\n ###########################################\n # logging\n ###########################################\n def logs(txt, xlog=False):\n print(txt)\n if xlog:\n # print >> xlog, txt\n print(txt, file=xlog)\n\n ###########################################\n # SET UP\n ###########################################\n dirs = mf.setup_directory(xargs)\n\n if steps['ph1_create_nodes']:\n xlog_dir = dirs['node_log']\n else:\n xlog_dir = dirs['operation_rsa_log']\n\n if os.path.isdir(xlog_dir) == False:\n os.mkdir(xlog_dir)\n\n ######### subjects\n f = open(os.path.join(dirs['params'], \"subjectlist.txt\"), \"r\")\n subject_lists = f.read().split('\\n')\n f.close()\n subject_lists = list(filter(None, subject_lists))\n print('* Number of subjects: %s' % str(len(subject_lists)))\n\n xargs['subject_lists'] = subject_lists\n xargs['n_subjs'] = len(subject_lists)\n\n ######### Open log file\n xlog_fname = os.path.join(xlog_dir,\n 'logs_%s_n%d.txt' % (xstep, xargs['n_subjs']))\n\n xlog = open(xlog_fname, 'a')\n logs(xargs, xlog)\n\n ###########################################\n # ph1_create_nodes: mask/load nii\n ###########################################\n if steps['ph1_create_nodes']:\n\n logs('#########################', xlog)\n logs('# PH1: preparation', xlog)\n logs('#########################', xlog)\n\n xparcel_prep = False\n xmni_node_prep = False\n xnode_mni2sub = True\n\n ######### pacels in MNI 1mm to subject func space\n # ------ redefine parcel id in MNI 1mm\n if xparcel_prep:\n mf.redefine_parcel(xargs, dirs, xlog, logs)\n \n if xmni_node_prep:\n mf.creat_parcel(xargs, dirs, xlog, logs)\n\n if xnode_mni2sub:\n mf.mni2sub_node(xargs, dirs, xlog, logs)\n\n ###########################################\n # ph2_grp_results: visualization\n ###########################################\n if steps['ph2_grp_results']:\n\n logs('################################', xlog)\n logs('# PH2: grp results visualization', xlog)\n logs('################################', xlog)\n\n import csv\n\n hemi_name = ['LH', 'RH']\n model_name = ['attention', 'inhibition', 'attention2']\n w_name = ['pat', 'pat-w']\n xd_name = ['p', 'n'] # positive, negative\n\n xparcel_file = os.path.join(dirs['parcels'],\n 'ori_Parcels_MNI_%d.nii' % xargs['resolution'])\n xparcel = nib.load(xparcel_file)\n xparcel_mx = xparcel.get_fdata()\n\n xmap = {}\n\n for xhemi in hemi_name:\n for xm in model_name:\n for xw in w_name:\n logs('(+) creating Nii for %s/ %s/ %s' % (xhemi, xm, xw))\n # ------ read map\n xmap_cvs = os.path.join(dirs['operation_rsa_grp_map'],\n 'fit_bmap_fdr_%s_%s_%s.csv' % (xhemi, xm, xw))\n\n xmean_p = []\n xmean_n = []\n xse_p = []\n xse_n = []\n xp_p = []\n xp_n = []\n xmean = []\n xse = []\n xp = []\n\n with open(xmap_cvs) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n print(f'Column names are {\", \".join(row)}')\n line_count += 1\n else:\n line_count += 1\n xmean.append(float(row[0]))\n xse.append(float(row[1]))\n xp.append(float(row[2]))\n\n if float(row[0]) < 0:\n xmean_n.append(abs(float(row[0])))\n xse_n.append(abs(float(row[1])))\n xp_n.append(abs(float(row[2])))\n else:\n xmean_p.append(float(row[0]))\n xse_p.append(float(row[1]))\n xp_p.append(float(row[2]))\n\n print(f'Processed {line_count} lines.')\n\n xmap['mean_%s_%s_%s_p' % (xhemi, xm, xw)] = xmean_p\n xmap['mean_%s_%s_%s_n' % (xhemi, xm, xw)] = xmean_n\n xmap['se_%s_%s_%s_p' % (xhemi, xm, xw)] = xse_p\n xmap['se_%s_%s_%s_n' % (xhemi, xm, xw)] = xse_n\n xmap['pvalue_%s_%s_%s_p' % (xhemi, xm, xw)] = xp_p\n xmap['pvalue_%s_%s_%s_n' % (xhemi, xm, xw)] = xp_n\n\n xmap['mean_%s_%s_%s' % (xhemi, xm, xw)] = xmean\n xmap['se_%s_%s_%s' % (xhemi, xm, xw)] = xse\n xmap['pvalue_%s_%s_%s' % (xhemi, xm, xw)] = xp\n\n for xd in xd_name:\n # ------ write on tmeplate\n xbmap = np.zeros(xparcel.shape)\n xpmap = np.zeros(xparcel.shape)\n\n n_nodes = len(xmap['mean_%s_%s_%s_%s' % (xhemi, xm, xw, xd)])\n if n_nodes > 0:\n for xnode in range(n_nodes):\n xnode_file = os.path.join(dirs['node_mni'],\n 'node_%s_%0.3d_1mm_%s_bin.nii.gz' % (\n xargs['nodes'], xnode + 1, xhemi))\n it_node = nib.load(xnode_file)\n it_node_mx = it_node.get_fdata()\n\n xbmap[np.where(it_node_mx == 1)] = xmap['mean_%s_%s_%s_%s' % (xhemi, xm, xw, xd)][xnode]\n xpmap[np.where(it_node_mx == 1)] = xmap['pvalue_%s_%s_%s_%s' % (xhemi, xm, xw, xd)][\n xnode]\n\n # ------ beta map\n xbmap_img = nib.Nifti1Image(xbmap, affine=xparcel.affine)\n xbmap_img.set_data_dtype(xparcel_mx.dtype)\n\n xbimg_name = os.path.join(dirs['operation_rsa_grp_map'],\n 'bmap_fdr_%s_%s_%s_%s' % (xhemi, xm, xw, xd))\n nib.save(xbmap_img, '%s.nii.gz' % xbimg_name)\n\n # ------ pvalue map\n xpmap_img = nib.Nifti1Image(xpmap, affine=xparcel.affine)\n xpmap_img.set_data_dtype(xparcel_mx.dtype)\n\n xpimg_name = os.path.join(dirs['operation_rsa_grp_map'],\n 'pmap_fdr_%s_%s_%s_%s' % (xhemi, xm, xw, xd))\n nib.save(xpmap_img, '%s.nii.gz' % xpimg_name)\n\n # ------ write on tmeplate\n xbmap = np.zeros(xparcel.shape)\n xpmap = np.zeros(xparcel.shape)\n\n n_nodes = len(xmap['mean_%s_%s_%s' % (xhemi, xm, xw)])\n if n_nodes > 0:\n for xnode in range(n_nodes):\n xnode_file = os.path.join(dirs['node_mni'],\n 'node_%s_%0.3d_1mm_%s_bin.nii.gz' % (\n xargs['nodes'], xnode + 1, xhemi))\n it_node = nib.load(xnode_file)\n it_node_mx = it_node.get_fdata()\n\n xbmap[np.where(it_node_mx == 1)] = xmap['mean_%s_%s_%s' % (xhemi, xm, xw)][xnode]\n xpmap[np.where(it_node_mx == 1)] = xmap['pvalue_%s_%s_%s' % (xhemi, xm, xw)][xnode]\n\n # ------ beta map\n xbmap_img = nib.Nifti1Image(xbmap, affine=xparcel.affine)\n xbmap_img.set_data_dtype(xparcel_mx.dtype)\n\n xbimg_name = os.path.join(dirs['operation_rsa_grp_map'],\n 'bmap_fdr_%s_%s_%s' % (xhemi, xm, xw))\n nib.save(xbmap_img, '%s.nii.gz' % xbimg_name)\n\n # ------ pvalue map\n xpmap_img = nib.Nifti1Image(xpmap, affine=xparcel.affine)\n xpmap_img.set_data_dtype(xparcel_mx.dtype)\n xpimg_name = os.path.join(dirs['operation_rsa_grp_map'],\n 'pmap_fdr_%s_%s_%s' % (xhemi, xm, xw))\n nib.save(xpmap_img, '%s.nii.gz' % xpimg_name)\n\n ## combine RH/LH\n for xm in model_name:\n for xw in w_name:\n for xbp in ['bmap', 'pmap']:\n xbimg_name_l = os.path.join(dirs['operation_rsa_grp_map'],\n '%s_fdr_LH_%s_%s' % (xbp, xm, xw))\n xbimg_name_r = os.path.join(dirs['operation_rsa_grp_map'],\n '%s_fdr_RH_%s_%s' % (xbp, xm, xw))\n\n xbimg_name = os.path.join(dirs['operation_rsa_grp_map'],\n '%s_fdr_%s_%s' % (xbp, xm, xw))\n\n os.system('fslmaths %s -add %s %s' % (xbimg_name_l, xbimg_name_r, xbimg_name))\n\n for xd in xd_name:\n xbimg_name_l = os.path.join(dirs['operation_rsa_grp_map'],\n '%s_fdr_LH_%s_%s_%s' % (xbp, xm, xw, xd))\n xbimg_name_r = os.path.join(dirs['operation_rsa_grp_map'],\n '%s_fdr_RH_%s_%s_%s' % (xbp, xm, xw, xd))\n\n xbimg_name = os.path.join(dirs['operation_rsa_grp_map'],\n '%s_fdr_%s_%s_%s' % (xbp, xm, xw, xd))\n\n os.system('fslmaths %s -add %s %s' % (xbimg_name_l, xbimg_name_r, xbimg_name))\n\n ###########################################\n # ph3_kmean\n ###########################################\n if steps['ph3_kmean']:\n\n logs('################################', xlog)\n logs('# PH2: ph3_kmean', xlog)\n logs('################################', xlog)\n \n # parcel files\n xparcel_mx = {}\n for xhemi in ['LH','RH']:\n xparcel_file = os.path.join(dirs['parcels'], 'Parcels_MNI_1_%s.nii.gz' % xhemi)\n xparcel = nib.load(xparcel_file)\n xparcel_mx[xhemi] = xparcel.get_fdata()\n \n # mapping the idx\n alg_name = ['sqeuclidean','correlation']\n col_name = ['k_2', 'k_3', 'k_4', 'k_5']\n xkmean_id = {}\n for xa in alg_name:\n xcsv = os.path.join(dirs['operation_rsa_grp_kmean'], 'kmean_idx_%s.csv' % xa)\n xkmean_id[xa] = pd.read_csv(xcsv, index_col=None, header=0)\n \n n_nodes, n_clusters = xkmean_id[xa].shape\n xid_map = np.zeros(xparcel.shape)\n\n for xcl in range(0, n_clusters):\n for xnode in range(0, n_nodes):\n\n if xnode < 180:\n it_node = xnode + 1\n xhemi = 'LH'\n else:\n it_node = xnode + 1 - 180\n xhemi = 'RH'\n\n xid_map[np.where(xparcel_mx[xhemi] == it_node)] = xkmean_id[xa].values[xnode, xcl]\n xmap_img = nib.Nifti1Image(xid_map, affine=xparcel.affine)\n xmap_img.set_data_dtype(xparcel_mx[xhemi].dtype)\n\n xout_nii = os.path.join(dirs['operation_rsa_grp_kmean'], \n 'kmean_idx_map_%s_cluster_%s' % (xa, col_name[xcl]))\n nib.save(xmap_img, '%s.nii.gz' % xout_nii)\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":"analysis/clearmem_operation_rsa.py","file_name":"clearmem_operation_rsa.py","file_ext":"py","file_size_in_byte":13228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"273748221","text":"from tkinter import *\nfrom tkinter import ttk\n\n\n\ndef multi_choise_screen(self, root, selectedVerse, allDecoyWordsDict):\n\n # create welcome frame\n game_frame = Frame(root)\n game_frame.grid(row=0, column=0, sticky=N+S+W+E)\n game_frame.grid_rowconfigure(1, weight=1)\n game_frame.grid_columnconfigure(0, weight=1)\n game_frame.isgridded = True\n\n # create all of the main containers\n top_frame = Frame(game_frame, width=450, height=50, pady=3)\n center_frame = Frame(game_frame, width=50, height=40, padx=3, pady=3)\n btm_frame1 = Frame(game_frame, width=450, height=45, pady=3)\n btm_frame2 = Frame(game_frame, width=450, height=60, pady=3)\n btm_frame3 = Frame(game_frame, width=450, height=60, pady=3)\n\n\n\n # layout all of the main containers\n top_frame.grid(row=0, sticky=\"ew\")\n center_frame.grid(row=1, sticky=\"nsew\")\n btm_frame1.grid(row=3, sticky=\"ew\")\n btm_frame2.grid(row=4, sticky=\"ew\")\n btm_frame3.grid(row=5, sticky=\"ew\")\n\n top_frame.grid_columnconfigure(2, weight=1)\n center_frame.grid_columnconfigure(2, weight=1)\n\n btm_frame1.grid_columnconfigure(1, weight=1)\n btm_frame1.grid_columnconfigure(2, weight=1)\n btm_frame1.grid_columnconfigure(3, weight=1)\n\n btm_frame2.grid_columnconfigure(1, weight=1)\n btm_frame2.grid_columnconfigure(2, weight=1)\n btm_frame2.grid_columnconfigure(3, weight=1)\n\n btm_frame3.grid_columnconfigure(1, weight=1)\n btm_frame3.grid_columnconfigure(2, weight=1)\n btm_frame3.grid_columnconfigure(3, weight=1)\n\n\n\n ## creating various labels and gui items\n\n instuctLabel = Label(top_frame, text=\"Fill in the blanks!\")\n instuctLabel.grid(row=0, column=2)\n\n verseLabel = Message(center_frame, text=selectedVerse[\"verseQuest\"])\n verseLabel.config(font=(\"helvetica\", 20), aspect=300)\n verseLabel.grid(row=1, column=2, sticky=N+S+W+E)\n\n sep = ttk.Separator(center_frame)\n sep.grid(row=2, column=2, sticky=W+E, pady=20)\n\n\n\n\n # creating answer buttons\n\n row1Var = StringVar()\n row2Var = StringVar()\n row3Var = StringVar()\n\n row1Var.set(\"None\")\n row2Var.set(\"None\")\n row3Var.set(\"None\")\n\n row1AnsBtn1 = Radiobutton(btm_frame1, indicatoron=0, variable=row1Var, width=12, height=2)\n row1AnsBtn1.grid(row=0, column=1)\n row1AnsBtn2 = Radiobutton(btm_frame1, indicatoron=0, variable=row1Var, width=12, height=2)\n row1AnsBtn2.grid(row=0, column=2)\n row1AnsBtn3 = Radiobutton(btm_frame1, indicatoron=0, variable=row1Var, width=12, height=2)\n row1AnsBtn3.grid(row=0, column=3)\n row1Label1 = Label(btm_frame1, text=\"Answer 1: \")\n row1Label1.grid(row=0, column=0, padx=10)\n\n row2AnsBtn1 = Radiobutton(btm_frame1, indicatoron=0, variable=row2Var, width=12, height=2)\n row2AnsBtn1.grid(row=1, column=1)\n row2AnsBtn2 = Radiobutton(btm_frame1, indicatoron=0, variable=row2Var, width=12, height=2)\n row2AnsBtn2.grid(row=1, column=2)\n row2AnsBtn3 = Radiobutton(btm_frame1, indicatoron=0, variable=row2Var, width=12, height=2)\n row2AnsBtn3.grid(row=1, column=3)\n row1Label2 = Label(btm_frame1, text=\"Answer 2: \")\n row1Label2.grid(row=1, column=0, padx=10)\n\n row3AnsBtn1 = Radiobutton(btm_frame1, indicatoron=0, variable=row3Var, width=12, height=2)\n row3AnsBtn1.grid(row=2, column=1)\n row3AnsBtn2 = Radiobutton(btm_frame1, indicatoron=0, variable=row3Var, width=12, height=2)\n row3AnsBtn2.grid(row=2, column=2)\n row3AnsBtn3 = Radiobutton(btm_frame1, indicatoron=0, variable=row3Var, width=12, height=2)\n row3AnsBtn3.grid(row=2, column=3)\n row1Label3 = Label(btm_frame1, text=\"Answer 3: \")\n row1Label3.grid(row=2, column=0, padx=10)\n\n\n butRow1 = [row1AnsBtn1, row1AnsBtn2, row1AnsBtn3]\n butRow2 = [row2AnsBtn1, row2AnsBtn2, row2AnsBtn3]\n butRow3 = [row3AnsBtn1, row3AnsBtn2, row3AnsBtn3]\n\n buttonsDict = {\"decoy1\":butRow1, \"decoy2\":butRow2, \"decoy3\":butRow3}\n\n for key in allDecoyWordsDict.keys():\n words = allDecoyWordsDict[key]\n buttons = buttonsDict[key]\n for word, button in zip(words, buttons):\n button.configure(text=word, value=word)\n\n\n userAnswers = {\"answer1\":row1Var, \"answer2\":row2Var, \"answer3\":row3Var}\n okBtn = Button(btm_frame2, text=\"Check Answer\", width=25, height=4,\n command=lambda: self.verseCheckAnswer(userAnswers, selectedVerse))\n okBtn.grid(row=0, column=2, pady=20)\n\n exitBtn = Button(btm_frame3, text=\"Quit\", width=25, height=4,\n command=lambda: self.screenSwitcher(\"home\"))\n exitBtn.grid(row=0, column=2, pady=20)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"guis/game_screen.py","file_name":"game_screen.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"13697629","text":"from dscribe.descriptors import MBTR\nfrom dscribe.core import System\nimport matplotlib.pyplot as mpl\nimport ase.data\n\n# Define the system under study: NaCl in a conventional cell.\nNaCl_conv = System(\n cell=[\n [5.6402, 0.0, 0.0],\n [0.0, 5.6402, 0.0],\n [0.0, 0.0, 5.6402]\n ],\n scaled_positions=[\n [0.0, 0.5, 0.0],\n [0.0, 0.5, 0.5],\n [0.0, 0.0, 0.5],\n [0.0, 0.0, 0.0],\n [0.5, 0.5, 0.5],\n [0.5, 0.5, 0.0],\n [0.5, 0.0, 0.0],\n [0.5, 0.0, 0.5]\n ],\n symbols=[\"Na\", \"Cl\", \"Na\", \"Cl\", \"Na\", \"Cl\", \"Na\", \"Cl\"],\n)\n\n# Setup the MBTR desciptor for the system\ndecay_factor = 0.5\nmbtr = MBTR(\n atomic_numbers=[11, 17],\n k=[1, 2, 3],\n periodic=True,\n grid={\n \"k1\": {\n \"min\": 10,\n \"max\": 18,\n \"sigma\": 0.1,\n \"n\": 200,\n },\n \"k2\": {\n \"min\": 0,\n \"max\": 0.7,\n \"sigma\": 0.01,\n \"n\": 200,\n },\n \"k3\": {\n \"min\": -1.0,\n \"max\": 1.0,\n \"sigma\": 0.05,\n \"n\": 200,\n }\n },\n weighting={\n \"k2\": {\n \"function\": \"exponential\",\n \"scale\": decay_factor,\n \"cutoff\": 1e-3\n },\n \"k3\": {\n \"function\": \"exponential\",\n \"scale\": decay_factor,\n \"cutoff\": 1e-3\n },\n },\n flatten=True\n)\n\n# Lets first create a flattened output vector that is directly suitable for\n# machine learning applications. When the \"flatten\" parameter is set to True,\n# the create function will return a flattened sparse COO-matrix.\ndesc = mbtr.create(NaCl_conv)\n\n# The corresponding dense numpy array can be create like this:\ndesc_dense = desc.toarray()\n\n# Optionally we can preserve the tensorial nature of the data by specifying\n# \"Flatten\" as False. In this case the output will be a list of\n# multidimensional numpy arrays for each k-term. This form is easier to\n# visualize as done in the following.\nmbtr.flatten = False\ndesc = mbtr.create(NaCl_conv)\n\n# Create variable contains the mapping between an index in the output and the\n# corresponding atomic number\nn_elements = len(set(NaCl_conv.get_atomic_numbers()))\nimap = mbtr.index_to_atomic_number\nsmap = {}\nfor index, number in imap.items():\n smap[index] = ase.data.chemical_symbols[number]\n\n# Plot K1\nx1 = mbtr._axis_k1\nfor i in range(n_elements):\n mpl.plot(x1, desc[\"k1\"][i, :], label=\"{}\".format(smap[i]))\nmpl.ylabel(\"$\\phi$ (arbitrary units)\", size=20)\nmpl.xlabel(\"Atomic number\", size=20)\nmpl.title(\"The element count in NaCl crystal.\", size=20)\nmpl.legend()\nmpl.show()\n\n# Plot K2. Only the combinations i-j where j >= 1 are included in the output.\n# The combination where i > i would contain the same information due to\n# distance symmetry with respect to changing the indices.\nx2 = mbtr._axis_k2\nfor i in range(n_elements):\n for j in range(n_elements):\n if j >= i:\n mpl.plot(x2, desc[\"k2\"][i, j, :], label=\"{}-{}\".format(smap[i], smap[j]))\nmpl.ylabel(\"$\\phi$ (arbitrary units)\", size=20)\nmpl.xlabel(\"Inverse distance (1/angstrom)\", size=20)\nmpl.title(\"The exponentially weighted inverse distance distribution in NaCl crystal.\", size=20)\nmpl.legend()\nmpl.show()\n\n# Plot K3. Only the combinations i-j-k where k >= i are included in the output.\n# The combination where i > k would contain the same information due to angle\n# symmetry with respect to permuting i and k.\nx3 = mbtr._axis_k3\nfor i in range(n_elements):\n for j in range(n_elements):\n for k in range(n_elements):\n if k >= i:\n mpl.plot(x3, desc[\"k3\"][i, j, k, :], label=\"{}-{}-{}\".format(smap[i], smap[j], smap[k]))\nmpl.ylabel(\"$\\phi$ (arbitrary units)\", size=20)\nmpl.xlabel(\"cos(angle)\", size=20)\nmpl.title(\"The exponentially weighted angle distribution in NaCl crystal.\", size=20)\nmpl.legend()\nmpl.show()\n","sub_path":"examples/mbtr.py","file_name":"mbtr.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"530939444","text":"def somarMatrizes22(A,B):\n\treturn [ [ A[0][0] + B[0][0] , A[0][1] + B[0][1] ] , [ A[1][0] + B[1][0] , A[1][1] + B[1][1] ] ]\ndef multiplicarMatrizes22(A,B):\n\ta = A[0][0]*B[0][0] + A[0][1]*B[1][0]\n\tb = A[0][0]*B[0][1] + A[0][1]*B[1][1]\n\tc = A[1][0]*B[0][0] + A[1][1]*B[1][0]\n\td = A[1][0]*B[0][1] + A[1][1]*B[1][1]\n\treturn [ [a,b] , [c,d] ]\n\t\n# -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nqtd = int(input())\n\nfor _ in range(qtd):\n\tx,y,z,w = input().split()\n\tx,y,z,w = int(x), int(y), int(z), int(w)\n\t\n\tmatriz \t\t\t= [ [x,y], [z,w] ]\n\t#print('Matriz:',matriz)\t\t\t\t\t\t\t# DEBUG\n\tdeterminante \t= x * w - y * z\n\t#print('Determinante:',determinante)\t\t\t\t# DEBUG\n\tif determinante != 0:\n\t\t\n\t\tmatrizInv \t\t= [\t[w / determinante, y * (-1) / determinante], [z * (-1) / determinante, x / determinante] ]\n\t\t#print('Matriz Invertida:', matrizInv)\n\t\tsoma \t\t\t= somarMatrizes22(matriz,matrizInv)\n\t\t#print('Soma:',soma)\t\t\t\t\t\t\t# DEBUG\n\t\tx,y,z,w\t\t\t= soma[0][0],soma[0][1], soma[1][0], soma[1][1]\n\t\t\n\t\tdeterminante \t= x * w - y * z\n\t\t#print('Determinante:',determinante)\t\t\t# DEBUG\n\t\tif determinante != 0:\n\t\t\tsomaInv\t\t\t= [\t[w / determinante, y * (-1) / determinante], [z * (-1) / determinante, x / determinante] ]\n\t\t\t#print('Soma Invertida:', somaInv)\t\t\t# DEBUG\n\t\t\tresultado \t\t= multiplicarMatrizes22(matriz,somaInv)\n\t\t\t#print('Resultado:',resultado)\t\t\t\t# DEBUG\n\t\t\t\n\t\t\tvalores = []\n\t\t\tfor linha in resultado:\n\t\t\t\tfor valor in linha:\n\t\t\t\t\tvalores.append(valor)\n\t\t\t\n\t\t\tmaior \t\t= valores[1]\n\t\t\tquadrante \t= 1\n\t\t\tquadrantes = [2, 1, 3, 4,]\n\t\t\tfor posicao, valor in enumerate(valores):\n\t\t\t\tif valor > maior:\n\t\t\t\t\tquadrante = quadrantes[posicao]\n\t\t\t\t\tmaior = valor\n\t\t\t#print(valores, maior, quadrante)\t\t\t# DEBUG\n\t\t\tprint(quadrante)\n\t\t\t\n\t\telse:\n\t\t\tprint('!')\n\telse:\n\t\tprint('!')\n\t\t\n\t","sub_path":"Curso/Solução Seletiva 2017/G/SoluçãoProblemaG.py","file_name":"SoluçãoProblemaG.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"411622897","text":"from django import forms\r\nfrom django.forms import ModelForm\r\nfrom . import models\r\n\r\nclass PatientProfile(ModelForm):\r\n class Meta:\r\n model = models.App_User\r\n fields = ['first_name', 'last_name', 'address', 'city', 'pincode', 'country', 'aboutme','user']\r\n\r\n\r\nclass ReportUploadForm(ModelForm):\r\n\r\n class Meta:\r\n model = models.Report\r\n fields = ('__all__')\r\n\r\n def __init__(self, *args, **kwargs):\r\n super(ReportUploadForm, self).__init__(*args, **kwargs)\r\n self.fields['doctor'].widget = forms.HiddenInput()\r\n\r\n ","sub_path":"user_acc/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"132967553","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', nodes: 'List[TreeNode]') -> 'TreeNode':\n if root is None: return None\n def helper(node, node1, node2):\n if node is None or node1 is None or node2 is None: return None \n if node == node1 or node == node2: return node\n left = helper(node.left, node1, node2)\n right = helper(node.right, node1, node2)\n \n if left and right: return node\n if left: return left\n if right: return right\n \n while nodes:\n if len(nodes) == 1: return nodes[0]\n node1 = nodes.pop()\n node2 = nodes.pop()\n if node1 == root or node2 == root: return root\n node = helper(root, node1, node2)\n if node is not None:\n nodes.append(node)\n return None\n ","sub_path":"1676. Lowest Common Ancestor of a Binary Tree IV.py","file_name":"1676. Lowest Common Ancestor of a Binary Tree IV.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"557961366","text":"#!/usr/bin/python3\n# coding: utf-8\n\n\nimport numpy as np\nfrom gradient_2d import numerical_gradient\n\n\ndef gradient_descent(f, init_x, lr=0.01, step_num=100):\n x = init_x\n\n for i in range(step_num):\n grad = numerical_gradient(f, x)\n x -= lr * grad\n\n return x\n\n\ndef main():\n def function_2(x):\n return x[0] ** 2 + x[1] ** 2\n\n init_x = np.array([3.0, 4.0])\n print(gradient_descent(function_2, init_x=init_x, lr=0.1, step_num=100))\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"ch04/gradient_method.py","file_name":"gradient_method.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"172070151","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n'No externally useful functions here. Read the `run.py` docblock instead.'\nimport subprocess\n\nfrom typing import Any, Callable\n\nfrom fs_image.fs_utils import Path\n\nSHADOWED_PATHS_ROOT = Path('__fs_image__/shadowed')\n\n# This determines which binaries we shadow. Our runtimes are expected to\n# ensure that this is the PATH for the user command in the container.\n#\n# For now, the non-booted case implicitly uses the `systemd-nspawn` default\n# `PATH`, so if that changes our test will fail. That test failure in time\n# will be an opportunity to decide whether to set our own, or follow.\nDEFAULT_SEARCH_PATHS = (Path(p) for p in (\n '/usr/local/sbin',\n '/usr/local/bin',\n '/usr/sbin',\n '/usr/bin',\n '/sbin',\n '/bin',\n))\nDEFAULT_PATH_ENV = b':'.join(DEFAULT_SEARCH_PATHS)\n\n_PopenCtxMgr = Any # Quacks like `popen_{non_,}booted_nspawn`\n# The intention of this wrapper API is to allow users of `run_*_nspawn` to\n# wrap the underlying `popen_*_nspawn` implementation uniformly, without\n# having to distinguish between the booted and non-booted cases.\n_PopenWrapper = Callable[[_PopenCtxMgr], _PopenCtxMgr]\n\n\ndef _nspawn_version():\n '''\n We now care about the version of nspawn we are running. The output of\n systemd-nspawn --version looks like:\n\n ```\n systemd 242 (v242-2.fb1)\n +PAM +AUDIT +SELINUX +IMA ...\n ```\n So we can get the major version as the second token of the first line.\n We hope that the output of systemd-nspawn --version is stable enough\n to keep parsing it like this.\n '''\n return int(subprocess.check_output([\n 'systemd-nspawn', '--version']).split()[1])\n","sub_path":"fs_image/nspawn_in_subvol/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"63663199","text":"\nimport datetime\n\nfrom flask import Blueprint, render_template, request, redirect, url_for, session, config\n\nfrom src.models.users.user import User\nfrom src.models.updater.updater import Updater\nimport src.models.updater.decorators as updater_decorators\nimport src.models.globalconstants as Constants\n\n__author__ = 'mptmg'\n\n\nupdater_blueprint = Blueprint('updater', __name__)\n\n\n@updater_blueprint.route('/')\n@updater_decorators.requires_login\n@updater_decorators.requires_admin\ndef index():\n updates = Updater.all_sorted(vsort='update')\n now = datetime.datetime.utcnow()\n return render_template('updater/updater_index.jinja2', updates=updates, now=now)\n\n\n@updater_blueprint.route('/new', methods=['GET', 'POST'])\n@updater_decorators.requires_login\ndef create_update():\n user = User.find_by_email_object(session['email'])\n if request.method == 'POST':\n user_id = user['_id']\n fname = user['fname']\n lname = user['lname']\n handle = user['handle']\n callsign = user ['callsign']\n update = datetime.datetime.utcnow()\n Updater.delete_by_id(user_id)\n Updater(user_id, fname, lname, handle, callsign, update).save_to_mongo()\n return redirect(url_for('hangar.index'))\n\n else:\n return redirect(url_for('hangar.index'))\n\n\n@updater_blueprint.route('/delete/')\n@updater_decorators.requires_login\ndef delete_update(user_id):\n Updater.delete_by_id(user_id)\n return redirect(url_for('.index'))\n\n\n@updater_blueprint.route('/admin_update/')\n@updater_decorators.requires_login\ndef admin_update(user_id):\n if session['email'] in Constants.ADMINS:\n user=User.find_by_id_object(user_id)\n Updater.delete_by_id(user_id)\n user_id = user_id\n fname = user['fname']\n lname = user['lname']\n handle = user['handle']\n callsign = user ['callsign']\n update = datetime.datetime.utcnow()\n Updater(user_id, fname, lname, handle, callsign, update).save_to_mongo()\n return redirect(url_for('updater.index'))\n\n else:\n return redirect(url_for('updater.index'))\n","sub_path":"src/models/updater/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"431046514","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 30 15:11:07 2020\n\n@author: sauli\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 10 16:35:55 2019\n\nSTFT CNN constants\n\n@author: MWS\n\"\"\"\n\n#%% INITIALIZATION\nfrom ssfunctions import *\nfrom CNN_DOA_MAP_WANDB_CLEAN_FUNCTIONS import *\nfrom CNN_3D_FIELD_FUNCTIONS import *\n# %%\ncurr_file = os.path.splitext(__file__)[0]\npath = os.path.dirname(__file__)\n\nplt.close('all')\n# sys.exit(\"Stopped for manual execution\") \n\n# %% CONSTANTS\n\nMAKE_TESTSPEECH_SPOS = False\nMAKE_NEW_DATASET = False\nMAKE_NEW_DATASET_SPEECHTEST = False\nCREATE_STFTS = False\nCREATE_FIELDS = False\n\nshuffle = False\n\nhyperparameter_defaults = dict(\n fs = 16000, \n lengthx = 5.40,\n lengthy = 5.86,\n height = 2.84,\n th_side = 0.4,\n mpos_center = [3,2,2],\n duration = 0.1, # duration of simulation in seconds\n NUM_SIGNALS = 1, # per one doa simulation\n NUM_SIGNALS_TO_CONCATENATE = 3,\n absorbtion = 0.8,\n order = 7,\n window = 'hann', \n nperseg = 512, \n noverlap = 256, \n nfft = 512,\n detrend = False, \n return_onesided = True, \n boundary = 'zeros', \n padded = True,\n axis = -1,\n num_samples = 100000,\n conv1_units = 128,\n conv2_units = 64,\n conv3_units = 32,\n conv1_kernel = (2,1),\n conv2_kernel = (2,1),\n conv3_kernel = (2,1),\n conv1_activ = 'elu',\n conv2_activ = 'elu',\n conv3_activ = 'elu',\n conv_dropout = 0.125,\n dense1_units = 512,\n dense2_units = 512,\n dense3_units = 16,\n dense1_activ = 'elu',\n dense2_activ = 'elu',\n dense3_activ = 'elu',\n dense_dropout = 0.125,\n lr = 0.001,\n loss = 'binary_crossentropy',\n optimizer_str = 'adam',\n batch_size = 512,\n epochs=100,#epochs = 5,\n resolution = 0.25,\n sigma = 0.25,\n doa_res_x = 10,\n doa_res_y = 10,\n sigma_x = 10,\n sigma_y = 10\n )\n\nwandb.init(project=\"cnn_doa_map\",config=hyperparameter_defaults,dir=\"wandb\")\nconfig = wandb.config\n\nprint(config)\n\nfs = config.fs\nFs = fs\n\n# %%% Room parameters\n\nlengthx = config.lengthx\nlengthy = config.lengthy\nheight = config.height\n\nlimits = np.array([[0,0,0],[lengthx,lengthy,height]])\n\n# %%% Microphone array parameters\n\n# actual antennae-based thetrahedral microphone array\nth_side = config.th_side\n\nth = create_tetrahedron(th_side)\n# plot_scatter_3d(th[:,0],th[:,1],th[:,2])\n\nmpos_center = config.mpos_center # fixed microphone array position\nmpos0 = th\nmpos = mpos0 + mpos_center # shift microphone array to a position within a room\n\nNUM_MIC = mpos0.shape[0]\nmic_array_center = np.mean(mpos0,axis=0)\nmic_arr_center = mic_array_center\n\nmposlimits = np.copy(limits)\n\n# %%% Signal parameters\n\nsposlimits = np.copy(limits)\n#sposlimits[:,2] = np.array([mic_array_center[2], mic_array_center[2]])\n\nduration = config.duration # duration of simulation in seconds\nNUM_SIGNALS = config.NUM_SIGNALS # per one doa simulation\nNUM_SIGNALS_TO_CONCATENATE = config.NUM_SIGNALS_TO_CONCATENATE\nabsorbtion = config.absorbtion\norder = config.order\n\n# %%% Training sample generation parameters\n\nsample_gen_args = {'limits':limits,\n 'sposlimits':sposlimits,\n 'mposlimits':mposlimits,\n 'NUM_SIGNALS_TO_CONCATENATE':NUM_SIGNALS_TO_CONCATENATE,\n 'mpos0':mpos0,\n 'mpos':mpos,\n 'duration':duration,\n 'absorbtion':absorbtion,\n 'order':order,\n 'doa_res_x':config.doa_res_x,\n 'doa_res_y':config.doa_res_y,\n 'sigma_x':config.sigma_x,\n 'sigma_y':config.sigma_y}\n\nstft_args = {'fs':Fs, \n 'window':config.window, \n 'nperseg':config.nperseg, \n 'noverlap':config.noverlap, \n 'nfft':config.nfft,\n 'detrend':config.detrend, \n 'return_onesided':config.return_onesided, \n 'boundary':config.boundary, \n 'padded':config.padded,\n 'axis':config.axis}\n\n\nDATA_DIR = \"E:\\DISSERTATION\\PY\\LIBRISpeech\\dev-clean\\LibriSpeech\\dev-clean\"\nhdf5_dir = \"D:\\CNN3DFIELD_DATASETS\"\nhdf5_filename = \"{}_src_{}_resolution_{}_sigma_{}_dataset.hdf5\".format(config.NUM_SIGNALS_TO_CONCATENATE,\n os.path.split(curr_file)[-1],\n config.resolution,\n config.sigma)\nhdf5_path = os.path.join(hdf5_dir,hdf5_filename)\nmodel_name = curr_file+\"_model.h5\"\n\n# %%\nimport xarray as xr\n#%%\n# if we would like to create a new set of SPOS, uncomment\nif MAKE_TESTSPEECH_SPOS:\n SPOS = []\n for i in range(100):\n SPOS.append(get_random_n_spos(sposlimits,2))\n SPOS = np.array(SPOS)\n spos_ds = xr.DataArray(SPOS, dims=[\"sample\", \"source\", \"xyz\"])\n spos_ds.to_netcdf('CONSISTENT_2SRC_SPOS_100_TESTSPEECH.nc')\n\n\n#%% Create speech dataset\n# from speech dataset dir select n_spos files\nCREATE_DRY_SPEECH_DATASET = False\nif CREATE_DRY_SPEECH_DATASET:\n DATA_DIR = \"E:\\DISSERTATION\\PY\\LIBRISpeech\\dev-clean\\LibriSpeech\\dev-clean\"\n \n n_files = 1000\n n_seconds = 5\n \n filenames = []\n for path, subdirs, files in os.walk(DATA_DIR):\n for name in files:\n if name.endswith('.flac'):\n filenames.append(os.path.join(path, name))\n print(os.path.join(path, name))\n \n \n SECONDS = []\n for rf in tqdm(filenames):\n with open(rf, 'rb') as f:\n rfdata, rfsr = sf.read(f)\n \n seconds = rfdata.shape[0]/rfsr\n SECONDS.append(seconds)\n SECONDS = np.array(SECONDS)\n \n sns.distplot(SECONDS,kde=False)\n # cut n_seconds from each of the files\n # if file is shorter, select next file\n # duration is n_seconds; noise signal was 0.1 second. \n # the distribution of the duration of the files is:\n '''\n , \n ,,, \n ,,, \n ,*, \n ,.,. (,, \n ,,,,, \n ,,,,, \n (*#* (,,,,,,,. \n ,,,,,,,,,(, \n ,,,,,,,,,,* \n ,,#, / ,,,,,,,,,,,* \n . ,,,,,,,,,,,,# \n ,,,,,,,,,,,,,,,. \n (. . ,,,,,,,,,,,,,,,, \n *,,,,,,,,,,,,,,,,, \n ,,,,,,,,,,,,,,,,,,,#, \n , , / ,,,,,,,,,,,,,,,,,,,,,..( \n ,,,,,,,,,,,,,,,,,,,,,,,,,,,/,, \n . ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, . \n . @ # \n 0 5 10 15 20 30 35 %& \n '''\n #%%\n # so we might select files over 5 seconds.\n FILES = []\n n_speech_files = 100\n i = 0\n while len(FILES) n_seconds):\n FILES.append(rf)\n \n i+=1\n \n #%%\n # take 5 seconds from each file and write all files to dataset dir, dry speech subdir\n speech_dry_files_subdir = 'speech_dry_audio_100_files_5_seconds'\n SECONDS = []\n file_counter = 0\n for file in tqdm(FILES):\n with open(file, 'rb') as f:\n rfdata, rfsr = sf.read(f)\n \n seconds = rfdata.shape[0]/rfsr\n \n speech_filepath = os.path.join(hdf5_dir,speech_dry_files_subdir,str(file_counter)+'.wav')\n sf.write(speech_filepath,rfdata[0:int(n_seconds*rfsr)],rfsr)\n \n file_counter += 1\n \n SECONDS.append(seconds)\n SECONDS = np.array(SECONDS)\n \n plt.figure()\n sns.distplot(SECONDS,kde=False)\n\n\n#%% CREATE NOISE SIGNALS, save to wav\n\nnoise_dry_files_subdir = 'noise_dry_audio_100_files_5_seconds'\n\nn_files = 100\nfor i in tqdm(range(n_files)):\n n_seconds = 5\n\n sig = np.random.random(n_seconds*config.fs) ### GENERATE THE FUCKING NOISE SIGNAL HERE ###\n sig = np.array(sig, dtype=float) # Convert signal (of list type) to float array\n \n noise_filepath = os.path.join(hdf5_dir,noise_dry_files_subdir,str(i)+'.wav')\n sf.write(noise_filepath,sig,config.fs)\n\n#%% CREATE SPEECH STFTS\n\n# only needs to be recreated if stft params or speech files change\n\n# open 5 second files created in last step and load to RAM\n\ndef create_stft_ds_from_files(input_dir=None,\n SPOS_TEST=None,\n limits=None,\n mpos=None,\n absorbtion=None,\n order=None,\n Fs=None,\n stft_args=None,\n ds_stft_filename=None,\n ds_spos_filename=None,\n train=False):\n SIGNALS = []\n for file in os.listdir(input_dir):\n print(file)\n if file.endswith('.wav'):\n rfdata, rfsr = sf.read(os.path.join(input_dir,file))\n SIGNALS.append(rfdata)\n SIGNALS = np.array(SIGNALS)\n\n num_sigfiles = SIGNALS.shape[0]\n\n if train:\n signal = np.array([SIGNALS[np.random.randint(num_sigfiles)][0:int(fs*duration)],\n SIGNALS[np.random.randint(num_sigfiles)][0:int(fs*duration)],\n SIGNALS[np.random.randint(num_sigfiles)][0:int(fs*duration)]])\n else:\n signal = np.array([SIGNALS[n],SIGNALS[len(SPOS_TEST)-1-n]])\n\n\n STFTS = []\n for n in tqdm(range(int(len(SPOS_TEST)/8))):\n x = generate_STFT_signal_sample_spos_mpos(signal=signal,\n limits=limits,\n spos=SPOS_TEST[n],\n mpos=mpos,\n absorbtion=absorbtion,\n order=order,\n Fs=Fs,\n stft_args=stft_args,\n shuffle=False)\n STFTS.append(x)\n STFTS = np.array(STFTS)\n \n ds_stft = xr.Dataset()\n STFTS_magphase = np.transpose(np.array([np.abs(STFTS),np.angle(STFTS)]),(1,2,3,4,0))\n ds_stft['STFTS'] = ((\"spos\", \"time\", \"channel\", \"frequency\", \"magphase\"), STFTS_magphase)\n\n ds_stft.to_netcdf(ds_stft_filename)\n \n \n # SS = []\n # for spos in tqdm(SPOS_TESTSPEECH): \n # ss = np.repeat(spos,x.shape[0],axis=0);\n # SS.append(ss)\n # SS = np.array(SS)\n SS = np.repeat(np.expand_dims(SPOS_TESTSPEECH,1),x.shape[0],axis=1)\n \n ds_spos = xr.Dataset()\n ds_spos['SS'] = ((\"spos\", \"time\", \"source\", \"xyz\"), SS)\n\n ds_spos.to_netcdf(ds_spos_filename)\n \n return ds_stft, ds_spos\n\n\nSPOS_TESTSPEECH = xr.load_dataset('CONSISTENT_3SRC_SPOS_100k_TRAIN.nc').to_array().values[0]\n#%%\nif CREATE_STFTS:\n # stft_calc_input_dir = os.path.join(hdf5_dir,speech_dry_files_subdir) # SPEECH\n # ds_stft_filename = 'DATASET_2SRC_STFTS_TESTSPEECH_100.nc' # SPEECH\n # ds_spos_filename = 'DATASET_2SRC_SPOS_TESTSPEECH_100.nc' # SPEECH\n\n stft_calc_input_dir = os.path.join(hdf5_dir,noise_dry_files_subdir) # NOISE\n ds_stft_filename = 'REVISION_DATASET_3SRC_STFTS_NOISE_100k.nc' # NOISE\n ds_spos_filename = 'REVISION_DATASET_3SRC_SPOS_100k.nc' # NOISE\n \n create_stft_ds_from_files(input_dir=stft_calc_input_dir,\n SPOS_TEST=SPOS_TESTSPEECH,\n limits=limits,\n mpos=mpos,\n absorbtion=absorbtion,\n order=order,\n Fs=Fs,\n stft_args=stft_args,\n ds_stft_filename=ds_stft_filename,\n ds_spos_filename=ds_spos_filename,\n train=True)\n\n#%%\n\nSS = xr.load_dataset('REVISION_DATASET_3SRC_SPOS_100k.nc')\nSS = SS.to_array().values[0]\n\nSTFTS = xr.load_dataset('REVISION_DATASET_3SRC_STFTS_NOISE_100k.nc')\nx = STFTS.to_array().values[0][0]\n#%%\nif CREATE_FIELDS:\n for resolution in [5,10,20]:\n for sigma in [5,10,15,20]:\n \n FIELDS = []\n for i in tqdm(range(int(len(SS)/8))):\n # fields = generate_spos_field(spos=spos[0],\n # sposlimits=sposlimits,\n # resolution=resolution,\n # sigma=sigma,\n # x=x)\n fields, doas = generate_doas_and_field(\n SS[i][0],mic_array_center,x,\n resolution_x=resolution,resolution_y=resolution,\n sigma_x=sigma,sigma_y=sigma,sigma_res=False)\n FIELDS.append(fields)\n FIELDS = np.array(FIELDS)\n \n ds = xr.Dataset()\n ds['FIELDS'] = ((\"spos\", \"time\", \"azim\", \"elev\"), FIELDS)\n # ds_filename = 'DATASET_2SRC_FIELDS_TESTSPEECH_100_resolution_{}_sigma_{}.pickle'.format(resolution,sigma) # SPEECH\n ds_filename = 'REVISION_DATASET_3src_100k_resolution_{}_sigma_{}.pickle'.format(resolution,sigma) # NOISE\n # ds.to_netcdf(ds_filename,format='NETCDF3_64BIT ')\n with open(ds_filename, 'wb') as handle:\n pickle.dump(ds, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n#%% test generated fields\n\nsigma = 10\nresolution = 5\n\n# ds_filename = 'DATASET_FIELDS_TESTSPEECH_100_resolution_{}_sigma_{}.pickle'.format(resolution,sigma)\nds_filename = 'REVISION_DATASET_3src_100k_resolution_{}_sigma_{}.pickle'.format(resolution,sigma)\nwith open(ds_filename, \"rb\") as input_file:\n FIELDS = pickle.load(input_file)\nFIELDS = FIELDS.to_array().values[0]\n#%%\nspos_idx = 45\nframe = 4\nfig, ax = plt.subplots(1)\nax.pcolormesh(FIELDS[spos_idx,frame])\n#%%\nss = SS[spos_idx,frame]/resolution\nfor s in ss:\n ax.scatter(s[1],s[0],s[2],color='b')\n\n\n#%% TRAINING\n\nimport os\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n# directory = 'D:\\CNNDOAMAP_DATASETS'\n#%%\ncur_dir = os.path.split(curr_file)[0]\nfor fields_filename in os.listdir(cur_dir):\n if fields_filename.startswith('REVISION_DATASET_3src') and fields_filename.endswith(\".pickle\"): \n# %%\n # hdf5_filename = 'CNN_3D_FIELD_1src_3_resolution_0.25_0.25_sigmaxy_0.5_0.5_dataset.hdf5'\n print(fields_filename)\n # %%\n resolution, sigma = extract_resolution_and_sigma_values_from_filename(fields_filename,reso_string='resolution',sigma_string='sigma')\n \n \n # hdf5_filename='dataset_2src_CNN_3D_FIELD_2src_100epochs_resolution_0.25_0.25_sigmaxy_0.5_0.5_dataset.hdf5'\n stft_filename = 'REVISION_DATASET_3SRC_STFTS_NOISE_100k.nc'\n stft_path = os.path.join(cur_dir,stft_filename)\n model_path = fields_filename[:-7]+\"_model_100epochs.h5\"\n print(model_path)\n if os.path.isfile(model_path):\n print('ALREADY TRAINED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n else:\n print('model not trained, training')\n # %%\n try:\n \n STFTS = xr.load_dataset('REVISION_DATASET_3SRC_STFTS_NOISE_100k.nc')\n STFTS = np.vstack(STFTS.to_array().values[0])\n \n ds_filename = 'REVISION_DATASET_3src_100k_resolution_{}_sigma_{}.pickle'.format(int(resolution),int(sigma))\n with open(ds_filename, \"rb\") as input_file:\n FIELDS = pickle.load(input_file)\n \n FIELDS = np.vstack(FIELDS.to_array().values[0])\n \n t = FIELDS\n \n \n num_of_samples = STFTS.shape[0]\n # %%% extract phase data\n # xphase = np.angle(xx)\n xphase = STFTS[:,:,:,1]\n \n # %%% split dataset\n trtst_split = 0.9\n trvl_split = 0.8\n \n tr_samples = int(num_of_samples*trtst_split)\n trvl_samples = int(tr_samples*trvl_split)\n \n x1 = np.expand_dims(xphase, axis=-1)\n \n x_train = x1[0:trvl_samples]\n t_train = t[0:trvl_samples]\n \n \n x_val = x1[trvl_samples:tr_samples]\n t_val = t[trvl_samples:tr_samples]\n \n \n x_test = x1[tr_samples:-1]\n t_test = t[tr_samples:-1]\n \n \n # %%% define model\n \n inputs = layers.Input(shape=(x_train.shape[1],x_train.shape[2],x_train.shape[3]))\n \n x = layers.Conv2D(config.conv1_units, kernel_size=config.conv1_kernel, strides=1, \n data_format='channels_last', \n padding=\"valid\", \n activation = config.conv1_activ, \n name='Conv_first')(inputs)\n \n x = layers.Conv2D(config.conv2_units, kernel_size=config.conv2_kernel, strides=1, \n padding=\"valid\", \n activation = config.conv2_activ, \n name='Conv_second',\n data_format='channels_last')(x)\n \n x = layers.Conv2D(config.conv3_units, kernel_size=config.conv3_kernel, strides=1, \n padding=\"valid\", \n activation = config.conv3_activ, \n name='Conv_third',\n data_format='channels_last')(x)\n \n \n x = layers.Dropout(config.conv_dropout)(x)\n \n a = layers.Dense(config.dense1_units,\n activation = config.dense1_activ,\n name='Dense_first_a')(x) # was 512\n a = layers.Dense(config.dense2_units,\n activation = config.dense2_activ,\n name='Dense_second_a')(a) # was 512\n a = layers.Dropout(config.dense_dropout)(a)\n a = layers.Flatten()(a)\n a = layers.Dense(t_train.shape[1]*t_train.shape[2],\n activation = 'sigmoid',name='Output_a')(a)\n out_a = layers.Reshape((t_train.shape[1],t_train.shape[2]))(a)\n # %%\n # e = Dense(512,activation = 'relu',name='Dense_first_e')(x) # was 512\n # e = Dense(512,activation = 'relu',name='Dense_second_e')(e) # was 512\n # e = Dropout(0.5)(e)\n # e = Flatten()(e)\n # e = Dense(e_train.shape[1]*e_train.shape[2],\n # activation = 'sigmoid',name='Output_e')(e)\n # out_e = Reshape((e_train.shape[1],e_train.shape[2]))(e)\n \n # model = Model(inputs=[inputs], outputs=[out_a, out_e])\n model = keras.Model(inputs=inputs, outputs=out_a)\n \n print('compiling the model')\n \n optimizer = None\n if config.optimizer_str == 'adam':\n optimizer = keras.optimizers.Adam(lr=config.lr)\n elif config.optimizer_str == 'nadam':\n optimizer = keras.optimizers.Nadam(lr=config.lr)\n elif config.optimizer_str == 'sgd':\n optimizer = keras.optimizers.SGD(lr=config.lr)\n \n model.compile(loss=config.loss,\n optimizer=config.optimizer_str,\n metrics=['accuracy']) \n # plot_model(model, to_file=curr_file+'_model.png', show_shapes=True)\n model.summary()\n #model = keras.models.load_model('CONV2_OK_fast_model_2.h5')\n# #%% TEST LOADED TARGET AND SPOS\n# field = t[0,:,:,:]\n\n# fig = plt.figure()\n# ax = fig.add_subplot(111,projection='3d')\n\n# colors = plt.cm.plasma(field.flatten())\n# alpha = field.flatten()\n\n\n\n# norm_alpha = rescale_linear(alpha,0,1)\n# colors[:,3] = norm_alpha\n\n\n# field_xrange = [sposlimits[0][0],sposlimits[1][0]]\n# field_yrange = [sposlimits[0][1],sposlimits[1][1]]\n# field_zrange = [sposlimits[0][2],sposlimits[1][2]]\n\n# resolution_x = resolution\n# resolution_y = resolution\n# resolution_z = resolution\n\n# x = np.arange(field_xrange[0],field_xrange[1],resolution*2) # coordinate arrays -- make sure they contain 0!\n# y = np.arange(field_yrange[0],field_yrange[1],resolution*2)\n# z = np.arange(field_zrange[0],field_zrange[1],resolution*2)\n# xf, yf, zf = np.meshgrid(x,y,z)\n\n# ax.scatter(xf, yf, zf, c=colors, s=20)\n# ax.scatter(xf, yf, zf, c=field.flatten(), s=20)\n# plt.show()\n \n \n \n # %%% fit model\n # %% \n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n sess_config = tf.compat.v1.ConfigProto()\n sess_config.gpu_options.per_process_gpu_memory_fraction = 0.90\n # %%\n with tf.device('/gpu:0'):\n tick = datetime.now() \n \n # lh = model.fit([x_train], [a_train, e_train],\n lh = model.fit(x_train, t_train,\n batch_size=config.batch_size,\n epochs=config.epochs,\n verbose=1,\n shuffle=True,\n # validation_data=([x_val], [a_val,e_val]))\n # validation_data=([x_val], [t_val]),\n callbacks=[WandbCallback(save_model=False)])\n \n tock = datetime.now()\n diff = tock - tick # the result is a datetime.timedelta object\n print(\"Training took {} seconds ({} hours)\".format(diff.total_seconds(),diff.total_seconds()/3600))\n \n # %%% save model\n \n # model.save(os.path.split(hdf5_path)[-1][:-5]+\"_model.h5\")\n model.save(model_path)\n# %% \n except:\n pass\n#%% TESTING\n\nplt.close('all')\n\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=np.VisibleDeprecationWarning) \nimport xarray as xr\n\nimport os\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nimport pandas as pd\nimport numpy as np\n\n#%%% Define testing data paths\n\nfor signal in ['speech']: \n print(signal)\n\n if signal == 'speech':\n signal_str = 'SPEECH'\n elif signal == 'noise':\n signal_str = 'NOISE'\n\n\n # Load STFTs\n xxr = xr.load_dataset('DATASET_2SRC_STFTS_TEST'+signal_str+'_100.nc')\n xphase = xxr.to_array().values[0,:,:,:,:,1]\n x_test = np.expand_dims(xphase, axis=-1)\n \n # Load spos\n # SS = xr.load_dataset('DATASET_2SRC_SPOS_TEST'+signal_str+'_100.nc').to_array().values[0]\n SS = xr.load_dataset('DATASET_2SRC_SPOS_TESTNOISE_100.nc').to_array().values[0]\n\n \n # for filename in os.listdir(hdf5_dir):\n for filename in ['dataset_2src_CNN_3D_FIELD_2src_100epochs_resolution_0.25_0.25_sigmaxy_0.5_0.5_model_100epochs.h5']:\n if filename.startswith('dataset_2src_CNN_3D_FIELD_2src_') and filename.endswith(\"model_100epochs.h5\"): \n # if filename=='dataset_2src_CNN_3D_FIELD_2src_100epochs_resolution_0.25_0.25_sigmaxy_0.5_0.5_model_100epochs.h5': \n print(filename)\n \n # Load model\n # doares_sigma_string = 'doaresxy_10_10_sigmaxy_10_10'\n # model_filename = 'CNN_3D_FIELD_2src_3_resolution_0.25_0.25_sigmaxy_0.5_0.5_model.h5'\n model_filename = filename\n model_path = os.path.join(hdf5_dir,model_filename)\n if not os.path.isfile(model_path):\n print('No model file')\n continue\n\n \n resolution, sigma = extract_resolution_and_sigma_values_from_model_filename(model_filename)\n \n # Load test fields\n \n # testdataset_filename = model_filename.replace('model.h5','dataset'+signal_str+'.hdf5')\n # testdataset_filename = 'CNN_3D_FIELD_1src_CLEAN_resolution_0.25_0.25_sigmaxy_0.5_0.5_dataset_speech.hdf5'\n # testdataset_filename = 'CNN_3D_FIELD_1src_3_resolution_0.25_0.25_sigmaxy_0.5_0.5_dataset.hdf5'\n \n fields_ds_filename = 'DATASET_2SRC_FIELDS_TESTNOISE_100_resolution_{:g}_sigma_{:g}.pickle'.format(resolution,sigma) \n # fields_ds_filename = 'DATASET_2SRC_FIELDS_TESTNOISE_100_resolution_0.25_sigma_0.5.pickle'\n if not os.path.isfile(fields_ds_filename):\n print('No test dataset file')\n continue\n \n with open(fields_ds_filename, \"rb\") as input_file:\n Y_TEST = pickle.load(input_file)\n\n model = keras.models.load_model(model_path)\n\n X_TEST = []\n # Y_TEST = []\n Y_PRED = []\n PRED_SPOS = []\n GT_FIELD_SPOS = []\n GT_SPOS = SS\n\n # GT_SPOS.append(np.array([ss[i] for ptt in pt]))\n \n pred_centers = []\n PRED_CENTERS = []\n \n for i in tqdm(range(xphase.shape[0]),position=0,leave=True):\n \n raxx = np.array([x_test[i]])\n # tt = np.array([t_test[i]])\n # pt = model.predict(raxx) \n pt = model.predict(x_test[i]) \n \n X_TEST.append(raxx)\n # Y_TEST.append(tt)\n Y_PRED.append(pt)\n \n cc = []\n CC = []\n for pptt in pt:\n C, c, X, l = get_blob_centers_coordinates(field=pptt,\n resolution_clust=resolution,\n thrdiv=[2,3,4],\n n_clusters=2,\n return_mean=True)\n c = c[:,[1,0,2]] # because function actually return in field axis order, and we need the normal axis order\n cc.append(c)\n CC.append(C)\n pred_centers.append(cc)\n PRED_CENTERS.append(CC)\n \n # pe_gt = np.array([get_field_max(z,resolution) for z in Y_TEST.sel(spos=i).to_array()[0]])\n # GT_FIELD_SPOS.append(pe_gt)\n \n # pe_field = np.array([get_field_max(ptt,resolution) for ptt in pt])\n # PRED_SPOS.append(pe_field)\n \n# #%% test 2 source cluster centers vs gt errors\n# ypred = np.array(Y_PRED)\n# ccc = np.array(centers)\n# A = SS[:ccc.shape[0],:ccc.shape[1],:,:]\n# B = ccc\n\n# E = []\n# for i in range(A.shape[0]):\n# E.append([])\n# for j in range(A.shape[1]):\n# dist = scipy.spatial.distance.cdist(A[i,j],B[i,j])\n# flat_dist = dist.flatten()\n# least_dist = flat_dist[np.argsort(flat_dist)[:2]]\n# E[i].append(least_dist)\n# E = np.array(E)\n\n\n# #%%\n# spos_idx = 0\n# frame = 50\n\n# s = SS[spos_idx,frame]/resolution\n# cccc = ccc[spos_idx,frame]/resolution\n\n# ax = plot_3D_field(ypred[spos_idx,frame])\n# ax.scatter(s[:,1],s[:,0],s[:,2],color='g')\n# ax.scatter(cccc[:,1],cccc[:,0],cccc[:,2],color='r')\n\n\n\n\n# %%\n\n# %%\n# %%\n# Y_PRED = np.array(Y_PRED)\n# spos_idx = 30\n# frame = 100\n\n# s = SS[spos_idx,frame]/resolution\n\n# ax = plot_3D_field(Y_PRED[spos_idx,frame])\n# ax.scatter(s[1],s[0],s[2],color='b')\n\n# ax = plot_3D_field(FIELDS[spos_idx,frame])\n# ax.scatter(s[1],s[0],s[2],color='b')\n# %%\n # print('written')\n# %% \n\n ds = xr.Dataset()\n \n ds['X_TEST'] = ((\"sample\", \"time\", \"channel\", \"frequency\", \"complexmagphase\"), \n xxr.to_array().values[0])\n # ds['Y_TEST'] = ((\"sample\", \"time\", \"x\", \"y\", \"z\"), Y_TEST.to_array().values[0])\n ds['Y_PRED'] = ((\"sample\", \"time\", \"x\", \"y\", \"z\"), np.array(Y_PRED))\n \n ds['PRED_SPOS'] = ((\"sample\", \"time\", \"source\", \"xyz\"), np.array(pred_centers))\n ds['PRED_IDX'] = ((\"sample\", \"time\", \"thresh\", \"source\", \"xyz\"), np.array(PRED_CENTERS))\n # ds['GT_FIELD_SPOS'] = ((\"sample\", \"time\", \"xyz\"), np.array(GT_FIELD_SPOS))\n ds['GT_SPOS'] = ((\"sample\", \"time\", \"source\", \"xyz\"), np.array(GT_SPOS))\n \n # %% Calculate prediction errors\n # ERRS_GT__PRED = np.linalg.norm(GT_SPOS-PRED_SPOS,axis=(2))\n # ERRS_GT__GT_FIELD = np.linalg.norm(GT_SPOS-GT_FIELD_SPOS,axis=(2))\n # ERRS_GT_FIELD__PRED = np.linalg.norm(np.array(GT_FIELD_SPOS)-PRED_SPOS,axis=(2))\n \n # ds['GT position - CNN estimation error'] = ((\"sample\", \"time\"), np.array(ERRS_GT__PRED))\n # ds['GT position - GT target max error'] = ((\"sample\", \"time\"), np.array(ERRS_GT__GT_FIELD))\n # ds['GT target max - CNN estimation error'] = ((\"sample\", \"time\"), np.array(ERRS_GT_FIELD__PRED))\n \n # # %% estimate polar error\n # ERRS_AZIM = []\n # ERRS_ELEV = []\n # ERRS_R = []\n \n # ERRS_AZIM_ABS = []\n # ERRS_ELEV_ABS = []\n # ERRS_R_ABS = []\n \n # mpos_center = np.mean(mpos,axis=0)\n \n # for i in tqdm(range(len(GT_SPOS))):\n # p_gt_spos = asSpherical(GT_SPOS[i],np.array([mpos_center]))\n # p_est_spos = asSpherical(PRED_SPOS[i],np.array([mpos_center]))\n \n # polar_error = p_gt_spos-p_est_spos\n # azim_err = polar_error[:,1]\n # elev_err = polar_error[:,2]\n # radial_err = polar_error[:,0]\n \n # ERRS_AZIM.append(azim_err)\n # ERRS_ELEV.append(elev_err)\n # ERRS_R.append(radial_err)\n \n # ERRS_AZIM_ABS.append(np.abs(azim_err))\n # ERRS_ELEV_ABS.append(np.abs(elev_err))\n # ERRS_R_ABS.append(np.abs(radial_err))\n \n # # df_polar = pd.DataFrame()\n # # df_polar['azimuth error'] = ERRS_AZIM\n # # df_polar['elevation error'] = ERRS_ELEV\n # # df_polar['radial error'] = ERRS_R\n # # df_polar['absolute azimuth error'] = ERRS_AZIM_ABS\n # # df_polar['absolute elevation error'] = ERRS_ELEV_ABS\n # # df_polar['absolute radial error'] = ERRS_R_ABS\n \n \n # ds['azimuth error'] = ((\"sample\",\"time\"), np.array(ERRS_AZIM))\n # ds['elevation error'] = ((\"sample\",\"time\"), np.array(ERRS_ELEV))\n # ds['radial error'] = ((\"sample\",\"time\"), np.array(ERRS_R))\n # ds['absolute azimuth error'] = ((\"sample\",\"time\"), np.array(ERRS_AZIM_ABS))\n # ds['absolute elevation error'] = ((\"sample\",\"time\"), np.array(ERRS_ELEV_ABS))\n # ds['absolute radial error'] = ((\"sample\",\"time\"), np.array(ERRS_R_ABS))\n \n # %% global dataset variables\n ds['resolution'] = ((\"sample\", \"time\"), np.tile(resolution,np.array(Y_PRED).shape[0:2]))\n ds['sigma'] = ((\"sample\", \"time\"), np.tile(sigma,np.array(Y_PRED).shape[0:2]))\n ds['numsrc'] = ((\"sample\", \"time\"), np.tile(2,np.array(Y_PRED).shape[0:2]))\n\n evaluation_ds_file_path = os.path.join(hdf5_dir,model_filename.replace('model_100epochs.h5',signal_str+'_evaluation_ds_speech_constant_100epochs.nc'))\n ds.to_netcdf(evaluation_ds_file_path)\n \n \n # text = 'Resolution {}, Sigma {}, STFT: {}'.format(resolution,sigma,str(stft_args))\n \n # # %% plot error distribution\n # plt.figure()\n # with sns.axes_style(\"whitegrid\"):\n # ax = sns.distplot(ERRS_GT__PRED, kde=True, rug=True)\n # ax.set_xlabel('Source position estimation error, m')\n # ax.set_ylabel('Number of samples')\n # plt_title = model_filename+'\\n'+'(GT position - CNN estimation) error, '+signal+' signal, constant speech 100epochs'\n # plt.figtext(0,0,text,size=1,wrap=True)\n # plt.title(plt_title)\n # plt.savefig(os.path.join(hdf5_dir,plt_title.replace(\"\\n\", \"\")+'.pdf'))\n # plt.show(block=False)\n \n # # %% plot polar erros\n # # df = df.set_index('doares')\n # plt.figure()\n # sns.boxplot(data=ds[['azimuth error','elevation error','radial error']].to_dataframe())\n # plt.figtext(0,0,text,size=1,wrap=True)\n # plt.title('Errors')\n # plt.show(block=False)\n \n # plt.figure()\n # g = sns.boxplot(data=ds[['absolute azimuth error','absolute elevation error','absolute radial error']].to_dataframe())\n # plt.figtext(0,0,text,size=1,wrap=True)\n # plt.title('Absolute Errors')\n # plt.show(block=False)\n \n # # %% plot polar error distribution\n # plt.figure()\n # with sns.axes_style(\"whitegrid\"):\n # sns.distplot(ds[['absolute azimuth error']].to_dataframe(), hist=False, rug=True,label='azimth')\n # sns.distplot(ds[['absolute elevation error']].to_dataframe(), hist=False, rug=True,label='elevation')\n # sns.distplot(ds[['absolute radial error']].to_dataframe(), hist=False, rug=True,label='radial')\n # ax.set_ylabel('Number of samples')\n # plt.legend()\n # plt.figtext(0,0,text,size=1,wrap=True)\n # plt_title = model_filename+'\\n'+'(GT position - CNN estimation) polar errors, '+signal+' signal 100epochs'\n # plt.title(plt_title)\n # plt.savefig(os.path.join(hdf5_dir,plt_title.replace(\"\\n\", \"\")+'.pdf'))\n # plt.show(block=False)\n \n # # %% plot result\n # gts = Y_TEST.to_array().values[0]\n # fields = np.array(Y_PRED)\n \n # for i in range(9): \n # sample = i*10+1\n # time = 100\n # # frame = 89\n # gt = gts[sample,time,:,:,:]\n # field = fields[sample,time,:,:,:]\n # s = ds['GT_SPOS'].values[sample,time]\n \n # [ax1, ax2] = plot_3D_2fields(gt,field,alpha=True)\n \n # # def plot_point_on_ax(ax=None,point=None,field=None,resolution=1,color='r'):\n # # point = point/resolution \n # # ax.scatter(point[0],point[1],point[2],s=100,color=color)\n \n # # get field max location\n # pe_gt = get_field_max(gt,resolution); \n # pe_field = get_field_max(field,resolution); \n \n # plot_points_on_ax(ax=ax1,points=pe_gt,color='g',resolution=resolution)\n # plot_points_on_ax(ax=ax2,points=pe_field,color='r',resolution=resolution)\n \n # plot_points_on_ax(ax=ax1,points=s,color=[0,0,1],resolution=resolution)\n # plot_points_on_ax(ax=ax1,points=mpos,color=[1,0,1],resolution=resolution)\n # plot_points_on_ax(ax=ax2,points=s,color=[0,0,1],resolution=resolution)\n # plot_points_on_ax(ax=ax2,points=mpos,color=[1,0,1],resolution=resolution)\n \n # # import qrcode\n # # img = qrcode.make(,box_size=1)\n # # fig = plt.gcf()\n # # fig.figimage(img, 0, 0)\n # plt.figtext(0,0,text,size=1,wrap=True)\n \n # plt_title = model_filename+'\\n'+' GT and Estimation fields, '+signal+' signal'+\"sample {}, time {} 100epochs\".format(sample,time)\n # plt.suptitle(plt_title,wrap=True)\n # plt.savefig(os.path.join(hdf5_dir,os.path.split(curr_file)[-1]+\" \"+plt_title.replace(\"\\n\", \"\")+'.pdf'))\n # plt.show(block=False)\n\n # plt.close('all')\n\n#%% Test on custom spos\n\n# create spos\n\n# spos = np.array([[1,1,1],[5,4,1]])\nspos = np.array([[5,4,1]])\n\n# try smaller array aperture\n\nmpos_orig = True\nmpos_baseline_test_side = 0.1\nif mpos_orig:\n mpos_baseline = mpos\nelse:\n th_side = mpos_baseline_test_side\n th = create_tetrahedron(th_side)\n mpos_center = config.mpos_center # fixed microphone array position\n mpos0 = th\n mpos_baseline = mpos0 + mpos_center # shift microphone array to a position within a room\n\n# generate sample (noise or speech)\nsignal = 'speech'\nif signal == 'speech':\n\n x_demo, t_demo, s_demo, m_demo, d_demo = generate_STFT_LIBRI_speech_sample_2D_spos_mpos(\n DATA_DIR=DATA_DIR, \n limits=limits,\n spos=spos,\n mpos=mpos_baseline,\n duration=duration,\n absorbtion=absorbtion,\n order=config.order,\n Fs=Fs,\n doa_res_x=config.doa_res_x,\n doa_res_y=config.doa_res_x,\n sigma_x=config.sigma_x,\n sigma_y=config.sigma_x,\n sigma_res=False,\n stft_args=stft_args)\n nsmpls = 16\n x_demo = x_demo[:nsmpls]\n t_demo = t_demo[:nsmpls]\n s_demo = s_demo[:nsmpls]\n m_demo = m_demo[:nsmpls]\n d_demo = d_demo[:nsmpls]\n \n \nif signal == 'noise':\n x_demo, t_demo, s_demo, m_demo, d_demo = generate_STFT_noise_sample_2D_spos_mpos(limits=limits,\n spos=spos,\n mpos=mpos_baseline,\n duration=duration,\n absorbtion=absorbtion,\n order=config.order,\n Fs=Fs,\n doa_res_x=config.doa_res_x,\n doa_res_y=config.doa_res_x,\n sigma_x=config.sigma_x,\n sigma_y=config.sigma_x,\n sigma_res=False,\n stft_args=stft_args)\n\nnum_samples_per_position = x_demo.shape[0]\nxxx = x_demo\n\n\n#%%%% Model prediction custom spos\nrax_demo = x_demo\nraxx_demo = np.angle(rax_demo)\n# raxx_demo = rax_demo\n\nPT = []\nfor r in tqdm(raxx_demo):\n pt = model.predict(np.expand_dims(r,axis=(0,-1)))\n PT.append(pt)\nPT = np.array(PT)\n\n#%% 3D blob center finding \n# k-means clustering of multiple blobs \n\nsigma_clust = 0.25\nresolution_clust = 0.25\ncustom_spos = np.array([[1.2,2.1,1.3],[3.1,3.2,2.3],[2.1,1.2,2.3]])\nfield = create_field(spos=custom_spos,sposlimits=sposlimits,resolution=resolution_clust,sigma=sigma_clust)\nax = plot_3D_field(field)\nplt.legend()\n#%%\n\n# or we can use a predicted field\nframe = 33\nfield = fields[frame,0,:,:,:]\ncustom_spos = np.array([GT_SPOS[frame]])\n#%%\n\n\n\n\ndef get_blob_centers_coordinates(field=None,\n resolution_clust=None,\n thrdiv=[2,3,4],\n n_clusters=3,\n return_mean=True):\n '''\n returns \n CENTERS - the element index of field where the blob centers are\n centers - metric (scaled by resolution) of the blob centers\n X - field points above last threshold,\n labels - cluster labels\n '''\n CENTERS, X, labels = get_blob_centers_multiple_thr(field=field,thrdiv=thrdiv,n_clusters=n_clusters)\n centers = np.array(CENTERS)*resolution_clust\n # centers = centers[:,[1,0,2]]\n # CENTERS = CENTERS[:,[1,0,2]]\n # cluster_center = np.mean(np.mean(centers,axis=0),axis=0) # in case we wish only one center\n if return_mean:\n centers = np.mean(centers,axis=0)\n return CENTERS, centers, X, labels\n\nCENTERS, centers, X, labels = get_blob_centers_coordinates(field=field,\n resolution_clust=resolution_clust,\n thrdiv=[2,3,4],\n n_clusters=3,\n return_mean=True)\n\n# ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)\nax = plot_3D_field(field)\nax.scatter(X[:, 0], X[:, 1], X[:, 2],c=labels.astype(float), edgecolor='k',label='thresholded 3D field elements')\n\ns = custom_spos/resolution_clust\nax.scatter(s[:, 1], s[:, 0], s[:, 2],c='g', edgecolor='k',s=100,label='GT source positions')\n\nm = mpos/resolution_clust\nax.scatter(m[:, 1], m[:, 0], m[:, 2],c='r', edgecolor='k',s=100,label='microphone positions')\n\nfor center in CENTERS:\n ax.scatter(center[:, 1], center[:, 0], center[:, 2],c=[1,0,1], edgecolor='k',s=50,label='cluster centers')\n\nplt.legend()\n#%%\n\n# plt_title = 'dummy field with 3 sources, source position location estimation \\n using k-means clustering'\n# plt.title(plt_title)\n# plt.savefig(os.path.join(hdf5_dir,plt_title.replace(\"\\n\", \"\")+'.pdf'))\n\n\n#%% gradient descent local maxima finding\n# TODO\n\n\n#%% check 3D gradient \ngradient = np.gradient(field)\n\nfor g in gradient:\n plot_3D_field(g)\n \n \n \n#%% check dataset fields\ndataset_filename = 'CNN_3D_FIELD_1src_CLEAN_test_speech_auto_resolution_0.25_0.25_sigmaxy_1_1_dataset_speech.hdf5'\ndataset_path = os.path.join(hdf5_dir,dataset_filename)\n\nxx_all,t_all,spos_all = get_all_set_of_samples_STFT(dataset_path,return_spos=True)\n#%%\nplot_3D_field(t_all[1000])\n\n#%% test input feature STE and thresholding\n# xx,t = get_all_set_of_samples_STFT(hdf5_path)\n\nxphase = np.angle(xx)\nxabs = np.abs(xx)\n#%%%\n\nXSTE = []\nfor x in xabs:\n XSTE.append(np.sum(np.power(x,2)))\n \nXSTE = np.array(XSTE)\n#%%\nplt.figure()\nsns.distplot(XSTE)\n","sub_path":"CNN_DOA_MAP_REVISION_2.py","file_name":"CNN_DOA_MAP_REVISION_2.py","file_ext":"py","file_size_in_byte":44416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"45173039","text":"from future import standard_library\nstandard_library.install_aliases()\nfrom builtins import object\nfrom urllib.request import urlopen\nimport json\n\nfrom cardinal.decorators import command, help\n\nURBANDICT_API_PREFIX = 'http://api.urbandictionary.com/v0/define?term='\n\n\nclass UrbanDictPlugin(object):\n @command(['ud', 'urbandict'])\n @help('Returns the top Urban Dictionary definition for a given word.')\n @help('Syntax: .ud ')\n def get_ud(self, cardinal, user, channel, msg):\n try:\n word = msg.split(' ', 1)[1]\n except IndexError:\n cardinal.sendMsg(channel, 'Syntax: .ud ')\n return\n\n try:\n url = URBANDICT_API_PREFIX + word\n f = urlopen(url).read()\n data = json.loads(f)\n\n word_def = data['list'][0]['definition']\n link = data['list'][0]['permalink']\n\n response = 'UD for %s: %s (%s)' % (word, word_def, link)\n\n cardinal.sendMsg(channel, response)\n except Exception:\n cardinal.sendMsg(channel, \"Could not retrieve definition for %s\" % word)\n\n\ndef setup():\n return UrbanDictPlugin()\n","sub_path":"plugins/urbandict/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"395023718","text":"import fcntl\nimport glob\nimport ipaddress\nimport json\nimport logging.config\nimport os\nimport re\nimport shutil\nimport socket\nimport struct\nfrom string import Template\n\nfrom pygluu.containerlib import get_manager\nfrom pygluu.containerlib.persistence import render_hybrid_properties\nfrom pygluu.containerlib.persistence import render_couchbase_properties\nfrom pygluu.containerlib.persistence import sync_couchbase_truststore\nfrom pygluu.containerlib.persistence import render_salt\nfrom pygluu.containerlib.persistence import render_gluu_properties\nfrom pygluu.containerlib.persistence import render_ldap_properties\nfrom pygluu.containerlib.persistence import sync_ldap_truststore\nfrom pygluu.containerlib.persistence import render_sql_properties\nfrom pygluu.containerlib.persistence import render_spanner_properties\nfrom pygluu.containerlib.persistence.couchbase import get_couchbase_mappings\nfrom pygluu.containerlib.persistence.ldap import extract_ldap_host\nfrom pygluu.containerlib.persistence.ldap import resolve_ldap_port\nfrom pygluu.containerlib.persistence.sql import get_sql_password\nfrom pygluu.containerlib.utils import decode_text\nfrom pygluu.containerlib.utils import exec_cmd\nfrom pygluu.containerlib.utils import safe_render\nfrom pygluu.containerlib.utils import cert_to_truststore\nfrom pygluu.containerlib.utils import as_boolean\n\nfrom settings import LOGGING_CONFIG\nfrom jca_sync import sync_with_backoff\n\nlogging.config.dictConfig(LOGGING_CONFIG)\nlogger = logging.getLogger(\"entrypoint\")\n\n\nGLUU_LDAP_URL = os.environ.get(\"GLUU_LDAP_URL\", \"localhost:1636\")\nGLUU_COUCHBASE_URL = os.environ.get(\"GLUU_COUCHBASE_URL\", \"localhost\")\n\n\ndef render_idp3_templates(manager):\n persistence_type = os.environ.get(\"GLUU_PERSISTENCE_TYPE\", \"ldap\")\n ldap_mapping = os.environ.get(\"GLUU_PERSISTENCE_LDAP_MAPPING\", \"default\")\n\n idp_resolver_filter = \"(|(uid=$requestContext.principalName)(mail=$requestContext.principalName))\"\n\n if all([persistence_type in (\"couchbase\", \"hybrid\"),\n \"user\" in get_couchbase_mappings(persistence_type, ldap_mapping)]):\n idp_resolver_filter = \"(&(|(lower(uid)=$requestContext.principalName)(mail=$requestContext.principalName))(objectClass=gluuPerson))\"\n\n bucket_prefix = os.environ.get(\"GLUU_COUCHBASE_BUCKET_PREFIX\", \"gluu\")\n\n ldap_use_ssl = as_boolean(os.environ.get(\"GLUU_LDAP_USE_SSL\", True))\n if ldap_use_ssl:\n ldap_scheme = \"ldaps\"\n else:\n ldap_scheme = \"ldap\"\n\n db_dialect = os.environ.get(\"GLUU_SQL_DB_DIALECT\", \"mysql\")\n\n if db_dialect == \"pgsql\":\n sql_search_filter = \"\"\"\nselect * from \"gluuPerson\" where ((LOWER(\"uid\") = '$requestContext.principalName') OR (LOWER(\"mail\") = '$requestContext.principalName')) AND (\"objectClass\" = 'gluuPerson')\n\"\"\".strip()\n else:\n sql_search_filter = \"\"\"\nselect * from `gluuPerson` where ((LOWER(uid) = \"$requestContext.principalName\") OR (LOWER(mail) = \"$requestContext.principalName\")) AND (objectClass = \"gluuPerson\")\n\"\"\".strip()\n\n ctx = {\n \"hostname\": manager.config.get(\"hostname\"),\n \"shibJksPass\": manager.secret.get(\"shibJksPass\"),\n \"certFolder\": \"/etc/certs\",\n \"ldap_hostname\": extract_ldap_host(GLUU_LDAP_URL),\n \"ldaps_port\": resolve_ldap_port(),\n \"ldap_scheme\": ldap_scheme,\n \"ldap_binddn\": manager.config.get(\"ldap_binddn\"),\n \"ldapPass\": decode_text(\n manager.secret.get(\"encoded_ox_ldap_pw\"),\n manager.secret.get(\"encoded_salt\"),\n ).decode(),\n \"ldap_use_ssl\": str(ldap_use_ssl).lower(),\n \"idp3SigningCertificateText\": load_cert_text(\"/etc/certs/idp-signing.crt\"),\n \"idp3EncryptionCertificateText\": load_cert_text(\"/etc/certs/idp-encryption.crt\"),\n \"orgName\": manager.config.get(\"orgName\"),\n \"ldapCertFn\": \"/etc/certs/opendj.crt\",\n \"couchbase_hostname\": GLUU_COUCHBASE_URL,\n \"couchbase_n1ql_port\": 18093 if as_boolean(os.environ.get(\"GLUU_COUCHBASE_TRUSTSTORE_ENABLE\", True)) else 8093,\n \"couchbaseShibUserPassword\": manager.secret.get(\"couchbase_shib_user_password\"),\n \"idp_attribute_resolver_ldap.search_filter\": idp_resolver_filter,\n \"user_bucket\": f\"{bucket_prefix}_user\",\n \"access_control_ip_range\": get_access_ip_range(),\n \"rdbm_type\": \"postgresql\" if db_dialect == \"pgsql\" else \"mysql\",\n \"rdbm_host\": os.environ.get(\"GLUU_SQL_DB_HOST\", \"localhost\"),\n \"rdbm_port\": os.environ.get(\"GLUU_SQL_DB_PORT\", 3306),\n \"rdbm_db\": os.environ.get(\"GLUU_SQL_DB_NAME\", \"gluu\"),\n \"rdbm_user\": os.environ.get(\"GLUU_SQL_DB_USER\", \"gluu\"),\n \"rdbm_password\": get_sql_password(),\n \"server_time_zone\": os.environ.get(\"GLUU_SQL_DB_TIMEZONE\", \"UTC\"),\n \"rdbm_driver_class\": \"org.postgresql.Driver\" if db_dialect == \"pgsql\" else \"com.mysql.jdbc.Driver\",\n \"sql_search_filter\": sql_search_filter,\n }\n\n for file_path in glob.glob(\"/app/templates/idp3/conf/*\"):\n with open(file_path) as fr:\n rendered_content = safe_render(fr.read(), ctx)\n fn = os.path.basename(file_path)\n with open(\"/opt/shibboleth-idp/conf/{}\".format(fn), 'w') as fw:\n fw.write(rendered_content)\n\n file_path = \"/app/templates/idp3/metadata/idp-metadata.xml\"\n with open(file_path) as fr:\n rendered_content = safe_render(fr.read(), ctx)\n # idp-metadata.xml has Java Velocity template\n tmpl = Template(rendered_content)\n rendered_content = tmpl.substitute({\n \"domain\": ctx[\"hostname\"],\n \"idpHost\": f\"https://{ctx['hostname']}\",\n })\n\n fn = os.path.basename(file_path)\n with open(\"/opt/shibboleth-idp/metadata/{}\".format(fn), 'w') as fw:\n fw.write(rendered_content)\n\n\ndef load_cert_text(path):\n with open(path) as f:\n cert = f.read()\n return cert.replace('-----BEGIN CERTIFICATE-----', '').replace('-----END CERTIFICATE-----', '').strip()\n\n\ndef generate_idp3_sealer(manager):\n cmd = \" \".join([\n \"java\",\n \"-classpath '/app/javalibs/*'\",\n \"net.shibboleth.utilities.java.support.security.BasicKeystoreKeyStrategyTool\",\n \"--storefile /opt/shibboleth-idp/credentials/sealer.jks\",\n \"--versionfile /opt/shibboleth-idp/credentials/sealer.kver\",\n \"--alias secret\",\n \"--storepass {}\".format(manager.secret.get(\"shibJksPass\")),\n ])\n return exec_cmd(cmd)\n\n\ndef sync_sealer(manager):\n jks_fn = \"/opt/shibboleth-idp/credentials/sealer.jks\"\n kver_fn = \"/opt/shibboleth-idp/credentials/sealer.kver\"\n\n if all([os.path.isfile(jks_fn), os.path.isfile(kver_fn)]):\n return\n\n # files are missing, get them from secrets (if any) or generate new ones\n if manager.secret.get(\"sealer_jks_base64\") and manager.secret.get(\"sealer_kver_base64\"):\n manager.secret.to_file(\"sealer_jks_base64\", jks_fn, decode=True, binary_mode=True)\n manager.secret.to_file(\"sealer_kver_base64\", kver_fn, decode=True, binary_mode=True)\n else:\n generate_idp3_sealer(manager)\n manager.secret.from_file(\"sealer_jks_base64\", jks_fn, encode=True, binary_mode=True)\n manager.secret.from_file(\"sealer_kver_base64\", kver_fn, encode=True, binary_mode=True)\n\n\ndef modify_jetty_xml():\n fn = \"/opt/jetty/etc/jetty.xml\"\n with open(fn) as f:\n txt = f.read()\n\n # disable contexts\n updates = re.sub(\n r'',\n r'\\n\\t\\t\\t\\t false\\n\\t\\t\\t ',\n txt,\n flags=re.DOTALL | re.M,\n )\n\n with open(fn, \"w\") as f:\n f.write(updates)\n\n\ndef modify_webdefault_xml():\n fn = \"/opt/jetty/etc/webdefault.xml\"\n with open(fn) as f:\n txt = f.read()\n\n # disable dirAllowed\n updates = re.sub(\n r'(dirAllowed)(\\s*)()true()',\n r'\\1\\2\\3false\\4',\n txt,\n flags=re.DOTALL | re.M,\n )\n\n with open(fn, \"w\") as f:\n f.write(updates)\n\n\ndef saml_persistence_config(persistence_type):\n if persistence_type == \"couchbase\":\n bean_xml_file = \"gluu-couchbase-bean.xml\"\n elif persistence_type == \"sql\":\n bean_xml_file = \"gluu-rdbm-bean.xml\"\n else:\n bean_xml_file = \"\"\n\n if bean_xml_file:\n shutil.copyfile(f\"/app/static/{bean_xml_file}\", f\"/opt/shibboleth-idp/conf/{bean_xml_file}\")\n\n # Add datasource properties to idp.properties\n idp_properties_fn = \"/opt/shibboleth-idp/conf/idp.properties\"\n with open(idp_properties_fn) as f:\n idp3_properties = f.readlines()\n\n for i, l in enumerate(idp3_properties):\n if l.strip().startswith('idp.additionalProperties'):\n datasource_fn = \"/conf/datasource.properties\"\n idp3_properties[i] = l.strip() + f', {datasource_fn}\\n'\n\n if persistence_type == \"sql\":\n shutil.move(\"/opt/shibboleth-idp/conf/datasource.properties.sql\", \"/opt/shibboleth-idp/conf/datasource.properties\")\n\n with open(idp_properties_fn, \"w\") as f:\n new_idp3_props = ''.join(idp3_properties)\n f.write(new_idp3_props)\n\n\ndef main():\n persistence_type = os.environ.get(\"GLUU_PERSISTENCE_TYPE\", \"ldap\")\n manager = get_manager()\n\n if not os.path.isfile(\"/etc/certs/idp-signing.crt\"):\n manager.secret.to_file(\"idp3SigningCertificateText\", \"/etc/certs/idp-signing.crt\")\n\n if not os.path.isfile(\"/etc/certs/idp-signing.key\"):\n manager.secret.to_file(\"idp3SigningKeyText\", \"/etc/certs/idp-signing.key\")\n\n if not os.path.isfile(\"/etc/certs/idp-encryption.crt\"):\n manager.secret.to_file(\"idp3EncryptionCertificateText\", \"/etc/certs/idp-encryption.crt\")\n\n if not os.path.isfile(\"/etc/certs/idp-encryption.key\"):\n manager.secret.to_file(\"idp3EncryptionKeyText\", \"/etc/certs/idp-encryption.key\")\n\n manager.secret.to_file(\"shibIDP_jks_base64\", \"/etc/certs/shibIDP.jks\",\n decode=True, binary_mode=True)\n\n sync_sealer(manager)\n\n render_idp3_templates(manager)\n render_salt(manager, \"/app/templates/salt.tmpl\", \"/etc/gluu/conf/salt\")\n render_gluu_properties(\"/app/templates/gluu.properties.tmpl\", \"/etc/gluu/conf/gluu.properties\")\n\n if persistence_type in (\"ldap\", \"hybrid\"):\n render_ldap_properties(\n manager,\n \"/app/templates/gluu-ldap.properties.tmpl\",\n \"/etc/gluu/conf/gluu-ldap.properties\",\n )\n manager.secret.to_file(\"ldap_ssl_cert\", \"/etc/certs/opendj.crt\", decode=True)\n sync_ldap_truststore(manager)\n\n if persistence_type in (\"couchbase\", \"hybrid\"):\n render_couchbase_properties(\n manager,\n \"/app/templates/gluu-couchbase.properties.tmpl\",\n \"/etc/gluu/conf/gluu-couchbase.properties\",\n )\n sync_couchbase_truststore(manager)\n\n if persistence_type == \"hybrid\":\n render_hybrid_properties(\"/etc/gluu/conf/gluu-hybrid.properties\")\n\n if persistence_type == \"sql\":\n db_dialect = os.environ.get(\"GLUU_SQL_DB_DIALECT\", \"mysql\")\n\n render_sql_properties(\n manager,\n f\"/app/templates/gluu-{db_dialect}.properties.tmpl\",\n \"/etc/gluu/conf/gluu-sql.properties\",\n )\n\n if persistence_type == \"spanner\":\n render_spanner_properties(\n manager,\n \"/app/templates/gluu-spanner.properties.tmpl\",\n \"/etc/gluu/conf/gluu-spanner.properties\",\n )\n\n if not os.path.isfile(\"/etc/certs/gluu_https.crt\"):\n manager.secret.to_file(\"ssl_cert\", \"/etc/certs/gluu_https.crt\")\n\n cert_to_truststore(\n \"gluu_https\",\n \"/etc/certs/gluu_https.crt\",\n \"/usr/java/latest/jre/lib/security/cacerts\",\n \"changeit\",\n )\n\n modify_jetty_xml()\n modify_webdefault_xml()\n configure_logging()\n saml_persistence_config(persistence_type)\n\n # sync files from Jackrabbit immediately to avoid issue\n # https://github.com/GluuFederation/docker-oxshibboleth/issues/44\n sync_with_backoff()\n\n\ndef get_ip_network():\n # default k8s interface is eth0\n iface = os.environ.get(\"GLUU_NETWORK_INTERFACE\") or \"eth0\"\n # default k8s prefix length is 24\n net_prefix = os.environ.get(\"GLUU_NETWORK_PREFIX\") or \"24\"\n\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n ip = socket.inet_ntoa(fcntl.ioctl(\n sock.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', iface[:15].encode())\n )[20:24])\n ifc = ipaddress.ip_interface(f\"{ip}/{net_prefix}\")\n return str(ifc.network)\n except (OSError, ValueError) as exc:\n raise ValueError(f\"Unable to determine IP network from interface {iface} and network prefix {net_prefix}\") from exc\n\n\ndef get_access_ip_range():\n def quote_val(val):\n return f\"'{val}'\"\n\n ip_range = [\n \"127.0.0.1/32\",\n \"::1/128\",\n ]\n\n ip_network = get_ip_network()\n if ip_network:\n ip_range.append(ip_network)\n return \", \".join([quote_val(ip) for ip in ip_range])\n\n\ndef configure_logging():\n # default config\n config = {\n \"idp_log_target\": \"STDOUT\",\n \"idp_log_level\": \"INFO\",\n \"script_log_target\": \"FILE\",\n \"script_log_level\": \"INFO\",\n \"audit_log_target\": \"FILE\",\n \"audit_log_level\": \"ALL\",\n \"consent_audit_log_target\": \"FILE\",\n \"consent_audit_log_level\": \"ALL\",\n \"log_prefix\": \"\",\n \"log_prefix_script\": \"\",\n \"log_prefix_audit\": \"\",\n \"log_prefix_consent_audit\": \"\",\n }\n # Note that idp-warn.log is turned off as the original contains\n # filtered logs from idp-process (WARN as its threshold);\n # users can do filtering from idp-process or stdout directly\n\n # pre-populate custom config; format is JSON string of ``dict``\n try:\n custom_config = json.loads(os.environ.get(\"GLUU_OXSHIBBOLETH_APP_LOGGERS\", \"{}\"))\n except json.decoder.JSONDecodeError as exc:\n logger.warning(f\"Unable to load logging configuration from environment variable; reason={exc}; fallback to defaults\")\n custom_config = {}\n\n # ensure custom config is ``dict`` type\n if not isinstance(custom_config, dict):\n logger.warning(\"Invalid data type for GLUU_OXSHIBBOLETH_APP_LOGGERS; fallback to defaults\")\n custom_config = {}\n\n # logback doesn't support OFF and FATAL levels\n log_levels = (\"ERROR\", \"WARN\", \"INFO\", \"DEBUG\", \"TRACE\",)\n\n # list of supported outputs\n log_targets = (\"STDOUT\", \"FILE\",)\n\n for k, v in custom_config.items():\n if k not in config:\n continue\n\n if k.endswith(\"_log_level\") and v not in log_levels:\n logger.warning(f\"Invalid {v} log level for {k}; fallback to defaults\")\n v = config[k]\n\n if k.endswith(\"_log_target\") and v not in log_targets:\n logger.warning(f\"Invalid {v} log output for {k}; fallback to defaults\")\n v = config[k]\n\n # update the config\n config[k] = v\n\n # mapping between the ``log_target`` value and their appenders\n file_aliases = {\n \"idp_log_target\": \"IDP_PROCESS\",\n \"script_log_target\": \"IDP_SCRIPT\",\n \"audit_log_target\": \"IDP_AUDIT\",\n \"consent_audit_log_target\": \"IDP_CONSENT_AUDIT\",\n }\n for key, value in file_aliases.items():\n if config[key] == \"FILE\":\n config[key] = value\n\n stdout_aliases = {\n \"idp_log_target\": \"STDOUT\",\n \"script_log_target\": \"STDOUT_SCRIPT\",\n \"audit_log_target\": \"STDOUT_AUDIT\",\n \"consent_audit_log_target\": \"STDOUT_CONSENT_AUDIT\",\n }\n for key, value in stdout_aliases.items():\n if config[key] == \"STDOUT\":\n config[key] = value\n\n if as_boolean(custom_config.get(\"enable_stdout_log_prefix\")):\n config[\"log_prefix\"] = \"${log.console.prefix} - \"\n config[\"log_prefix_script\"] = \"${log.console.prefix.script} - \"\n config[\"log_prefix_audit\"] = \"${log.console.prefix.audit} - \"\n config[\"log_prefix_consent_audit\"] = \"${log.console.prefix.consent-audit} - \"\n\n with open(\"/app/templates/logback.xml\") as f:\n txt = f.read()\n\n tmpl = Template(txt)\n logfile = \"/opt/shibboleth-idp/conf/logback.xml\"\n with open(logfile, \"w\") as f:\n f.write(tmpl.safe_substitute(config))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/entrypoint.py","file_name":"entrypoint.py","file_ext":"py","file_size_in_byte":16409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"529530125","text":"from loaders import decode_raw_file\nfrom Bio import SeqIO\nfrom Bio.Alphabet.IUPAC import protein\nfrom io import StringIO\nfrom utils import compress_data\n\n\ndef SequenceLoader(raw_file, fname):\n data = None\n invalid = False\n\n if raw_file is not None:\n\n decoded = decode_raw_file(raw_file)\n fasta = SeqIO.parse(StringIO(decoded), \"fasta\")\n records = [record for record in fasta]\n\n if records is not None and any(records):\n data_raw = list(records[0].seq._data)\n if any([residue not in protein.letters for residue in data_raw]) or len(data_raw) == 0:\n invalid = True\n else:\n data_raw.append(fname)\n data = compress_data(data_raw)\n else:\n invalid = True\n\n return data, invalid\n","sub_path":"loaders/sequenceloader.py","file_name":"sequenceloader.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"234083638","text":"\"\"\"\n================================================\nResources used: http://scikit-learn.org/\n================================================\n\n========================\nPlotting Learning Curves\n========================\n\nOn the left side the learning curve of a naive Bayes classifier is shown for\nthe digits dataset. Note that the training score and the cross-validation score\nare both not very good at the end. However, the shape of the curve can be found\nin more complex datasets very often: the training score is very high at the\nbeginning and decreases and the cross-validation score is very low at the\nbeginning and increases. On the right side we see the learning curve of an SVM\nwith RBF kernel. We can see clearly that the training score is still around\nthe maximum and the validation score could be increased with more training\nsamples.\n\"\"\"\nprint(__doc__)\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom sklearn import cross_validation\nfrom sklearn.neighbors import KNeighborsClassifier\n\nimport time\nimport os\n\ndef get_path(rel_path):\n script_dir = os.path.dirname(__file__) #absolute dir the script is in\n abs_file_path = os.path.join(script_dir, rel_path)\n \n return abs_file_path\n\n# Function used to print cross-validation scores\ndef plot_score(k_range, scores, title, labels, ylim=[0.6, 1.05]):\n plt.figure()\n plt.title(title)\n plt.grid()\n \n plt.plot(k_range, scores[0], label=labels[0])\n plt.plot(k_range, scores[1], label=labels[1])\n #plt.vlines(alpha_optim, plt.ylim()[0], np.max(test_errors), color='k',\n # linewidth=3, label='Optimum on test')\n plt.legend(loc='lower left')\n plt.ylim(ylim)\n plt.xlabel('Number of nearest neighbors K')\n plt.ylabel('Accuracy')\n plt.show()\n\nif __name__ == \"__main__\":\n # My Dataset:\n train_df = pd.read_csv(get_path(\"../../../credit/credit_train.csv\"))\n test_df = pd.read_csv(get_path(\"../../../credit/credit_test.csv\"))\n \n # convert the \"quality\" label column to numpy arrays\n train_Y = train_df.pop('DEFAULT').values\n train_X = train_df.values\n test_Y = test_df.pop('DEFAULT').values\n test_X = test_df.values\n \n # Standartize \n #scaler = StandardScaler()\n #test_X = scaler.fit_transform(test_X)\n #train_X = scaler.fit_transform(train_X)\n \n # Cross-Validation\n cv = cross_validation.StratifiedShuffleSplit(train_Y, n_iter=3,test_size=0.2, random_state=42)\n #examples = np.array([5, 10, 50, 100, 200, 500, 1000, 1100, 2740])\n\n weights_list = ['uniform', 'distance']\n test_scores_uni = list()\n test_scores_dist = list() \n \n for weights in weights_list:\n clf = KNeighborsClassifier(weights=weights).fit(train_X, train_Y)\n k_range = np.array([1, 2, 5, 10, 3, 4, 5, 10, 15, 30, 45, 100, 500])\n \n # emptly lists\n train_scores = list()\n test_scores = list()\n train_time = list()\n \n #iterate over k\n for k in k_range:\n # timed testing\n t0 = time.time() \n clf.set_params(n_neighbors=k)\n t1 = time.time()\n time_passed = t1-t0\n clf.fit(train_X, train_Y)\n \n # append \n train_scores.append(clf.score(train_X, train_Y))\n test_scores.append(clf.score(test_X, test_Y))\n train_time.append(time_passed)\n \n if weights == 'uniform': \n test_scores_uni = test_scores\n else: \n test_scores_dist = test_scores\n \n scores = [train_scores, test_scores]\n labels = ['Train', 'Test']\n title = \"Learning Curves. Credit. KNN, weights='{0}'\".format(weights) \n plot_score(k_range, scores, title, labels, [0.65, 1.01])\n \n scores = [test_scores_uni, test_scores_dist]\n labels = ['Test Uniform','Test Weighted']\n title = \"Learning Curves. Credit. KNN. Weighted vs Uniform\" \n plot_score(k_range, scores, title, labels, [0.72, 0.78])","sub_path":"knn/knn_credit.py","file_name":"knn_credit.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"114483346","text":"from django.contrib import admin\n\n# Register your models here.\nfrom weather.models import Weather, Summary\n\n\nclass SummaryAdmin(admin.ModelAdmin):\n list_display = ['avg_temperature', 'avg_humidity', 'start_date', 'end_date']\n list_filter = ['avg_temperature', 'avg_humidity', 'start_date', 'end_date']\n\n def delete_model(self, request, obj):\n data = Weather.objects.filter(created_at__lte=obj.end_date, created_at__gte=obj.start_date)\n data.delete()\n obj.delete()\n\n def delete_queryset(self, request, queryset):\n for instance in queryset:\n self.delete_model(request, instance)\n queryset.delete()\n\n\nclass WeatherAdmin(admin.ModelAdmin):\n list_display = ['temperature', 'humidity', 'created_at']\n list_filter = ['temperature', 'humidity', 'created_at']\n\n\nadmin.site.register(Weather, WeatherAdmin)\nadmin.site.register(Summary, SummaryAdmin)\n","sub_path":"weather/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"411214843","text":"def findMiden(lis):\n '''\n :param lis:\n :return:\n '''\n #1 中位数位置\n alen = len(lis)/2\n midIndex = [int(alen) + 1] if int(alen)!=alen else [int(alen),int(alen)+1]\n final = midIndex[::]\n count = len(midIndex)\n tag = False\n #2 排序到中位数位置停止\n for i in range(len(lis)):\n for j in range(i,len(lis)):\n if len(midIndex) == 0:\n tag = True\n break\n if lis[i] > lis[j]:\n lis[j],lis[i] = lis[i],lis[j]\n if i == midIndex[0]:midIndex.pop(0)\n\n if tag:break\n res = [lis[i - 1] for i in final]\n print(res)\n return sum(res)/count\n\n\ndef findTwoMedian(nums1,nums2):\n '''\n :param nums1 []:\n :param nums2 []:\n :return number:\n '''\n len1 = len(nums1)\n len2 = len(nums2)\n midLen = (len1 + len2)/2\n midIndex = [int(midLen)] if int(midLen) != midLen else [int(midLen)-1,int(midLen)]\n res = []\n i,j=0,0\n for cIndex in range(len1+len2):\n if i int:\n if key not in self.cache:\n return -1\n\n # When user access a key, it gets the most recent position\n self.set_most_recent_key_of(key)\n return self.cache[key]\n\n def put(self, key: int, value: int) -> None:\n\n # For a new key we will have to check what is the status\n # of the capacity counter\n if key not in self.cache:\n # There is still at least one empty slot\n if self.capacity > 0:\n self.capacity -= 1\n else:\n # There are no more empty slots, we will have\n # to remove the least recent used entry, i.e.,\n # the one in the \"right\" side of the cache\n self.cache.popitem(last=True)\n\n # A new/updated key will go to the most recent position\n self.cache[key] = value\n self.set_most_recent_key_of(key)\n\n def set_most_recent_key_of(self, key):\n # Most recent keys are in the \"left\" side of the cache, e.g.,\n # [(3, 4), (1, 2), (5, 100)] (3, 4) is the most up-to-date\n # (key, value) item in the cache. On the other side, (5, 100)\n # is the oldest and will be the next one to be removed in case\n # the capacity == 0\n self.cache.move_to_end(key, last=False)\n\n\ndef quation():\n '''\n :return:\n '''\n def findTwo(x,y):\n '''\n :param x:\n :param y:\n :return:\n '''\n res = [-1]\n for i in range(1,x//2):\n if i^(x-i)==y:\n return (i,x-i)\n return res\n\n T = int(input())\n\n for i in range(T):\n x,y = list(map(int,input().split()))\n out_ = findTwo(x,y)\n if out_[0]==-1:\n print(out_[0])\n else:\n print(out_,end='')\n print('')\n\n\ndef isMatched(expr):\n '''\n match delimiters\n '''\n lefty = '({['\n righty = ')}]'\n stack = []\n for c in expr:\n if c in lefty:\n stack.append(c)\n elif c in righty:\n if not stack:\n return False\n if righty.index(c) != lefty.index(stack.pop(0)):\n return False\n return not stack","sub_path":"exercises.py","file_name":"exercises.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"239418505","text":"from flask import Flask, session, request\nfrom flask_restful import Resource\nfrom quadcore.manager.data import DataManager\n\nclass ProfileNew(Resource):\n def get(self):\n args = json.loads(request.data.decode(\"utf-8\"))\n if \"github_token\" in session or \"linkedin_token\" in session:\n if not DataManager.is_exist_user(session[\"email\"]):\n result = DataManager.set_user_profile(args)\n if result == None:\n return {\n \"result\": 2,\n \"cause\": \"Not sufficient data, or data has wrong form\"\n }\n else:\n map_info = DataManager.set_user_map(args)\n return {\n \"result\": 0\n }\n else:\n return {\n \"result\": 3,\n \"cause\": \"Exist email address\"\n }\n\n else:\n return {\n \"result\": 1,\n \"cause\": \"No credentials available\"\n }\n","sub_path":"backend/quadcore/restful/user/profile/new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"617000966","text":"import pygame, random, sys\nfrom pygame.locals import *\n\n# Using Python 3.8.5 and pygame==2.0.0.dev12\n\ndef update_score(score, high_score):\n if score > high_score:\n high_score = score\n\n return high_score\n\ndef check_collision(rect_1, rect_2):\n if rect_1.colliderect(rect_2):\n return True\n\n return False\n\npygame.init()\n\nsize = (900, 600)\nscreen = pygame.display.set_mode(size)\n\n\npygame.display.set_caption('Mini-Jam 63')\n\nfps = pygame.time.Clock()\n\nfg = pygame.image.load('files/sprites/fg.png').convert_alpha()\nfg = pygame.transform.scale(fg, (900, 50))\n\nfg_x = (0)\n\nbg = pygame.image.load('files/sprites/background.png').convert_alpha()\nbg = pygame.transform.scale(bg, size)\n\nplayer = pygame.image.load('files/sprites/player.png').convert_alpha()\nplayer_rect = player.get_rect(center = (200, 300))\nplayer_speed = 10\npygame.display.set_icon(player)\n\nbullet = pygame.image.load('files/sprites/bullet.png').convert_alpha()\nbullet_rect = bullet.get_rect(center = (player_rect.centerx, player_rect.centery))\nbullet_speed = 50\n\nasteroid = pygame.image.load('files/sprites/asteroid.png').convert_alpha()\nasteroid_rect = asteroid.get_rect(center = (random.randint(0, 800), random.randint(0, 200)))\n\nenemy = pygame.image.load('files/sprites/enemy_space_ship.png').convert_alpha()\nenemy_rect = enemy.get_rect(center = (random.randint(0, 800), random.randint(0, 200)))\n\nplayer_moving_up = False\nplayer_moving_down = False\nplayer_moving_right = False\nplayer_moving_left = False\n\nplayer_out_of_screen_up = False\nplayer_out_of_screen_down = False\nplayer_out_of_screen_left = False\nplayer_out_of_screen_right = False\n\nasteroid_out_of_screen_left = False\n\nenemy_out_of_screen_x = False\nenemy_out_of_screen_y = False\n\ngame_font = pygame.font.Font('files/freesansbold.ttf', 32)\nwhite = (241, 240, 238)\nred = (151, 63, 63)\n\nscore = 0\nhigh_score = 0\n\nshoot = False\n\nrunning = True\n\nalive = True\n\nmenu = True\n\nplaying = False\n\nclick = False\nclick2 = False\n\n\n\nclick_sound = pygame.mixer.Sound('files/music/click.wav')\n\nshoot_sound = pygame.mixer.Sound('files/music/shoot.wav')\n\nexplosion = pygame.mixer.Sound('files/music/hit.wav')\n\n\nwhile running:\n\n\n while menu and playing != True:\n\n screen.blit(bg, (0,0))\n\n mx, my = pygame.mouse.get_pos()\n\n menu_text = game_font.render(\"Main Menu\", False, white)\n\n play_text = game_font.render(\"Play Game\", False, red)\n\n screen.blit(menu_text, (size[0] / 2 - 100, size[1] / 2 - 100))\n\n button = pygame.Rect(350, 300, 200, 50)\n\n if button.collidepoint((mx, my)):\n if click:\n click_sound.set_volume(0.1)\n click_sound.play()\n menu = False\n playing = True\n\n\n pygame.draw.rect(screen, white, button)\n screen.blit(play_text, (360, 300))\n\n\n quit_text = game_font.render(\"Quit Game\", False, red)\n\n button_2 = pygame.Rect(350, 380, 200, 50)\n\n if button_2.collidepoint((mx, my)):\n if click:\n sys.exit()\n\n\n pygame.draw.rect(screen, white, button_2)\n screen.blit(quit_text, (360, 380))\n\n click = False\n\n for event in pygame.event.get():\n if event.type == QUIT:\n sys.exit()\n\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n sys.exit()\n\n if event.type == MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n\n\n pygame.display.update()\n fps.tick(120)\n\n\n while playing and menu != True:\n\n screen.blit(bg, (0,0))\n\n fg_x -= 6\n screen.blit(fg, (fg_x, 580))\n screen.blit(fg, (fg_x + size[0], 580))\n\n if fg_x <= -900:\n fg_x = 0\n\n pygame.draw.line(screen, white, [0, 577], [900, 577], 7)\n\n high_score = update_score(score, high_score)\n\n asteroid_collision = check_collision(bullet_rect, asteroid_rect)\n player_collision = check_collision(player_rect, asteroid_rect)\n player_collision2 = check_collision(player_rect, enemy_rect)\n enemy_collision = check_collision(bullet_rect, enemy_rect)\n\n if asteroid_out_of_screen_left:\n asteroid_rect.centerx = 900\n\n\n if asteroid_rect.centerx <= 0:\n asteroid_out_of_screen_left = True\n\n else:\n asteroid_out_of_screen_left = False\n\n\n\n\n asteroid_rect.centerx -= 7\n\n if enemy_rect.centery < 0:\n enemy_out_of_screen_y = True\n\n else:\n enemy_out_of_screen_y = False\n\n if enemy_rect.centerx < 0:\n enemy_out_of_screen_x = True\n\n else:\n enemy_out_of_screen_x = False\n\n if enemy_out_of_screen_y:\n enemy_rect.centery = 600\n\n\n\n if enemy_out_of_screen_x:\n enemy_rect.centerx = 900\n enemy_rect.centery -= 100\n\n\n enemy_rect.centerx -= 7\n\n\n\n\n screen.blit(asteroid, asteroid_rect)\n screen.blit(enemy, enemy_rect)\n\n if player_collision == False and player_collision2 == False and alive == True:\n screen.blit(player, player_rect)\n\n\n if player_collision == True:\n explosion.set_volume(0.5)\n explosion.play()\n alive = False\n score = 0\n\n if player_collision2 == True:\n explosion.set_volume(0.5)\n explosion.play()\n alive = False\n score = 0\n\n if alive == False:\n over = game_font.render(\"Press Space to Play Again\", False, white)\n screen.blit(over, (size[0] / 2 - 200, size[1] / 2 - 100))\n\n score_text = game_font.render(\"Score: \" + str(score), True, white)\n high_score_text = game_font.render(\"High Score: \" + str(high_score), False, white)\n\n screen.blit(score_text, (707, 50))\n screen.blit(high_score_text, (615, 10))\n\n\n if asteroid_collision == True:\n explosion.set_volume(0.5)\n explosion.play()\n screen.blit(asteroid, asteroid_rect)\n asteroid_rect = asteroid.get_rect(center = (random.randint(0, 800), random.randint(0, 200)))\n shoot = False\n score += 1\n\n if enemy_collision == True:\n explosion.set_volume(0.5)\n explosion.play()\n screen.blit(enemy, enemy_rect)\n enemy_rect = enemy.get_rect(center = (random.randint(0, 800), random.randint(0, 200)))\n shoot = False\n score += 1\n\n\n if player_out_of_screen_up:\n player_rect.centery = 580\n\n if player_out_of_screen_down:\n player_rect.centery = 10\n\n if player_out_of_screen_left:\n player_rect.centerx = 900\n\n if player_out_of_screen_right:\n player_rect.centerx = 0\n\n if player_rect.centerx < 0:\n player_out_of_screen_left = True\n\n else:\n player_out_of_screen_left = False\n\n\n if player_rect.centerx > 900:\n player_out_of_screen_right = True\n\n else:\n player_out_of_screen_right = False\n\n if player_rect.centery <= -5:\n player_out_of_screen_up = True\n\n else:\n player_out_of_screen_up = False\n\n if player_rect.centery >= 605:\n player_out_of_screen_down = True\n\n else:\n player_out_of_screen_down = False\n\n\n if bullet_rect.centerx > 900:\n bullet_rect = bullet.get_rect(center = (player_rect.centerx, player_rect.centery))\n shoot = False\n\n if shoot:\n screen.blit(bullet, bullet_rect)\n shoot_sound.set_volume(0.25)\n shoot_sound.play()\n bullet_rect.centerx += bullet_speed\n\n if player_moving_up:\n player_rect.centery -= player_speed\n\n if player_moving_down:\n player_rect.centery += player_speed\n\n if player_moving_left:\n player_rect.centerx -= player_speed\n\n if player_moving_right:\n player_rect.centerx += player_speed\n\n for event in pygame.event.get():\n if event.type == QUIT:\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_w or event.key == K_UP and alive == True:\n player_moving_up = True\n\n if event.key == K_s or event.key == K_DOWN and alive == True:\n player_moving_down = True\n\n if event.key == K_d or event.key == K_RIGHT and alive == True:\n player_moving_right = True\n\n if event.key == K_a or event.key == K_LEFT and alive == True:\n player_moving_left = True\n\n if event.key == K_SPACE and alive == True:\n shoot = True\n\n if event.key == K_SPACE and alive == False:\n alive = True\n player_rect = player.get_rect(center = (200, 300))\n\n if event.key == K_ESCAPE:\n menu = True\n playing = False\n\n if event.type == KEYUP:\n if event.key == K_w or event.key == K_UP:\n player_moving_up = False\n\n if event.key == K_s or event.key == K_DOWN:\n player_moving_down = False\n\n if event.key == K_d or event.key == K_RIGHT:\n player_moving_right = False\n\n if event.key == K_a or event.key == K_LEFT:\n player_moving_left = False\n\n pygame.display.update()\n fps.tick(120)\n","sub_path":"Python-GameDev/Destroy-the-Space-Ships/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"563540938","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom django.core.mail import EmailMessage\nfrom .forms import FormularioContacto\n\n# Create your views here.\n\n\n\n\ndef contacto(request):\n\n formulariocontacto=FormularioContacto()\n\n if request.method==\"POST\":\n formulariocontacto=FormularioContacto(data=request.POST)\n\n if formulariocontacto.is_valid():\n nombre=request.POST.get(\"nombre\")\n email=request.POST.get(\"email\")\n contenido=request.POST.get(\"contenido\")\n\n email_new=EmailMessage(\"Mensaje desde app django\", \n \"El usuario con nombre {} con la direccion {} escribe lo siguiente:\\n\\n {}\".format(nombre, email, contenido),\n \"\",[\"arielleal2206@gmail.com\"], reply_to=[email])\n\n try:\n\n email_new.send()\n\n return redirect(\"/contacto/?valido\")\n \n except:\n return redirect(\"/contacto/?novalido\") \n\n\n return render(request, \"contacto/contacto.html\", { \"formulario\" : formulariocontacto})","sub_path":"Proyectoweb/contacto/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"369892389","text":"# -*- coding: utf-8 -*-\ndef curve_info_generator():\n line_style_flag = True\n\n def _template_generator(method_info: dict, method_name: str, line_color: str = None, line_width: int = 2) -> dict:\n nonlocal line_style_flag\n template_info = dict(\n path_dict=method_info,\n curve_setting=dict(\n line_style=\"-\" if line_style_flag else \"--\",\n line_label=method_name,\n line_width=line_width,\n ),\n )\n if line_color is not None:\n template_info[\"curve_setting\"][\"line_color\"] = line_color\n\n line_style_flag = not line_style_flag\n return template_info\n\n return _template_generator\n\n\ndef simple_info_generator():\n def _template_generator(method_info: dict, method_name: str) -> dict:\n template_info = dict(path_dict=method_info, label=method_name)\n return template_info\n\n return _template_generator\n","sub_path":"configs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"369144394","text":"import re\nimport argparse\n \nparser = argparse.ArgumentParser(description='')\nparser.add_argument(\"-f\", \"--file\", type=str, required=True)\nargs = parser.parse_args()\n\nf = open(args.file,\"rb\")\ndata = f.read()\nf.close()\n\npattern = \"\\xC6\\x85.\\xFC\\xFF\\xFF.\"\npattern2 = \"\\xC6\\x85.\\xF2\\xFF\\xFF.\"\n\nmatches = re.findall(pattern, data)\nmatches2 = re.findall(pattern2, data)\nformatted = ''\nfor match in matches:\n\tformatted += re.sub(\"\\xC6\\x85.\\xFC\\xFF\\xFF\",\"\", match)\nfor match in matches2:\n\tformatted += re.sub(\"\\xC6\\x85.\\xF2\\xFF\\xFF\",\"\",match)\nprint(re.sub(\"\\x00\",\"\\n\",formatted))\n","sub_path":"de_stackstr.py","file_name":"de_stackstr.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"249230862","text":"import argparse\nfrom itertools import repeat\n\nfrom utils.file_handler import read_file_pickle, read_file_sources, write_file_json\n\nfrom utils.scraper import fetch_articles\n\nfrom utils.db_interface import insert_records\n\nimport nltk\nimport ssl\nimport multiprocessing\n\n\ndef processing_job(security, sources):\n print(\"scrapping security: \".format(security['symbol']))\n list_articles = fetch_articles(sources, security)\n if list_articles:\n write_file_json(path_root_dir, list_articles, security)\n insert_records(list_articles)\n\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n pass\nelse:\n ssl._create_default_https_context = _create_unverified_https_context\n# Downloading nltk dependency for scrapping\nnltk.download('punkt')\n\nparser = argparse.ArgumentParser(description='Run news scrapper')\nparser.add_argument('--root_dir', help='Output Directory')\nparser.add_argument('--source_list', help='File containing news sites')\nargs = parser.parse_args()\n\n# fetching the arguments\npath_root_dir = args.root_dir\npath_source_list = args.source_list\n\n# max_processes 2 less than cpu_count to accomodate other system actions\nmax_processes = multiprocessing.cpu_count() - 2\n\nlist_securities = read_file_pickle()\nlist_sources = read_file_sources(path_source_list)\n\nprocess_pool = multiprocessing.Pool(max_processes)\n\n# parallel scrapping\nprocess_pool.starmap_async(processing_job, zip(list_securities, repeat(list_sources)))\n\nprocess_pool.close()\n","sub_path":"news_scrapper.py","file_name":"news_scrapper.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"571147347","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 2 11:44:57 2020\r\n\r\n@author: uni tech\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom tensorflow import keras\r\nfrom keras.datasets import cifar10\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Input, Conv2D, MaxPooling2D, Dense, Flatten,Activation, Dropout, BatchNormalization\r\nfrom keras.callbacks import EarlyStopping\r\nfrom keras.optimizers import Adam\r\nfrom keras.utils import np_utils \r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\n\r\n\r\n# Loading the dataset\r\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\r\n\r\n\r\n\r\n\r\nX_train = X_train.astype('float32')\r\nX_test = X_test.astype('float32')\r\n\r\n\r\n# Normalizing \r\nX_train /= 255\r\nX_test /= 255\r\n\r\n\r\n\r\n# Converting iamges to grayscale\r\nX_train_gray = np.zeros(X_train.shape[:-1])\r\nfor i in range(X_train.shape[0]):\r\n X_train_gray[i] = cv2.cvtColor( X_train[i], cv2.COLOR_BGR2GRAY) \r\n\r\n\r\n\r\nX_test_gray = np.zeros(X_test.shape[:-1])\r\nfor i in range(X_test.shape[0]):\r\n X_test_gray[i] = cv2.cvtColor( X_test[i], cv2.COLOR_BGR2GRAY)\r\n \r\n\r\nX_train_gray = X_train_gray.reshape(X_train.shape[0],32,32,1)\r\nX_test_gray = X_test_gray.reshape(X_test.shape[0], 32,32,1)\r\n\r\n\r\n \r\n# One hot encoding outputs\r\ny_train = np_utils.to_categorical(y_train)\r\ny_test = np_utils.to_categorical(y_test)\r\n\r\n\r\n\r\n\r\n# Defining callbacks function \r\nearly_stoppings = EarlyStopping(monitor='val_loss',\r\n patience = 5,\r\n verbose = 1,\r\n restore_best_weights = True) \r\n\r\n\r\n\r\n\r\n\r\n# Defining the model and adding layers to it\r\nmodel = Sequential()\r\nmodel.add(Conv2D(32, input_shape=(32, 32, 1), kernel_size=(4,4),padding='same', activation='relu'))\r\nmodel.add(BatchNormalization())\r\n\r\n\r\nmodel.add(Conv2D(64,kernel_size=(4,4),padding='same',activation='relu'))\r\nmodel.add(BatchNormalization())\r\nmodel.add(MaxPooling2D())\r\n\r\n\r\nmodel.add(Conv2D(64,kernel_size=(4,4),padding='same',activation='relu'))\r\nmodel.add(BatchNormalization())\r\nmodel.add(MaxPooling2D())\r\n\r\n\r\nmodel.add(Flatten())\r\nmodel.add(Dense(128))\r\nmodel.add(BatchNormalization())\r\nmodel.add(Activation('relu'))\r\n\r\n\r\nmodel.add(Dense(128))\r\nmodel.add(BatchNormalization())\r\nmodel.add(Activation('relu'))\r\n\r\n\r\nmodel.add(Dense(10, activation='softmax'))\r\n\r\n\r\n\r\nprint(model.summary())\r\n\r\n\r\n\r\n\r\n\r\n# model compilation\r\nadam = Adam(learning_rate=0.1, beta_1=0.9, beta_2=0.999, amsgrad=False)\r\nmodel.compile(optimizer = adam, loss='categorical_crossentropy', metrics=['accuracy'])\r\n\r\n\r\n# Model training\r\nmodel.fit(X_train_gray, y_train ,batch_size=500, epochs=10, validation_split=0.2 , callbacks=[early_stoppings])\r\n\r\n\r\n# Saving the model\r\nfrom keras.models import load_model \r\nmodel.save('image_recognition_model.h5')\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":"image_recognition.py","file_name":"image_recognition.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"154425025","text":"from models.bottle import BottleModel\nfrom util.logger import Logger\n\nclass BottleController():\n logger = Logger(__name__)\n @classmethod\n def make_bottle(cls, data):\n if not BottleController.check_bottle_type(data['type']):\n return \"Bottle types would be either 'rollon' or 'spray'\", 400, None\n try:\n new_bottle = BottleModel(data['volume'], data['type'], data['cost'], data['price'], data['inventory'], data['images'])\n new_bottle.save_to_db()\n except:\n cls.logger.exception(\"Error in creating a new bottle\")\n return \"Internal Server Error\", 500, None\n\n return \"\", 201, None\n\n @classmethod\n def check_bottle_type(cls, type):\n correct_types = ['rollon', 'spray', 'Spray', 'Roll On', 'Spray Sample']\n if type not in correct_types:\n return False\n return True\n\n @classmethod\n def edit_bottle(cls, data):\n if not BottleModel.find_by_id(data['id']):\n return \"Bottle with given id does not exists\", 400, None\n\n try:\n target_bottle = BottleModel.find_by_id(data['id'])\n target_bottle.volume = data['volume']\n target_bottle.type = data['type']\n target_bottle.cost = data['cost']\n target_bottle.price = data['price']\n target_bottle.inventory = data['inventory']\n target_bottle.images = data['images']\n except:\n cls.logger.exception(\"Error in editing an existing bottle\")\n return \"Internal Server Error\", 500, None\n\n return \"\", 200, None\n\n @classmethod\n def get_all(cls):\n try:\n all_bottles = BottleModel.get_all()\n except:\n cls.logger.exception(\"Error in getting all bottles\")\n return \"Internal Server Error\", 500, None\n\n return \"\", 200, all_bottles\n\n @classmethod\n def get_bottle_by_id(cls, id):\n if not BottleModel.find_by_id(id):\n return \"Bottle with given id does not exists\", 400, None\n\n target_bottle = BottleModel.find_by_id(id)\n\n return \"\", 200, target_bottle\n\n @classmethod\n def delete_bottle_by_id(cls, id):\n if not BottleModel.find_by_id(id):\n return \"Bottle with given id does not exists\", 400, None\n\n try:\n target_bottle = BottleModel.find_by_id(id)\n target_bottle.delete_from_db()\n except:\n cls.logger.exception(\"Failed to delete a existing bottle\")\n return \"Internal Server Error\", 500, None\n\n return \"\", 200, None\n","sub_path":"controllers/bottle.py","file_name":"bottle.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"247731695","text":"from logging import StreamHandler\nimport logging\nimport os\nimport click\nfrom flask_migrate import Migrate, upgrade\nfrom app import create_app, db\nfrom app.models import User, Role\nimport psycopg2\n\n\napp = create_app(os.getenv('FLASK_CONFIG') or 'default')\nmigrate = Migrate(app, db)\n\n\n@app.shell_context_processor\ndef make_shell_context():\n return dict(db=db, User=User, Role=Role)\n\n\n@app.cli.command()\n@click.argument('test_names', nargs=-1)\ndef test(test_names):\n \"\"\"Run the unit tests.\"\"\"\n import unittest\n if test_names:\n tests = unittest.TestLoader().loadTestsFromNames(test_names)\n else:\n tests = unittest.TestLoader().discover('tests')\n unittest.TextTestRunner(verbosity=2).run(tests)\n\n\n@classmethod\ndef init_app(cls, app):\n Config.init_app(app)\n # email errors to the administrators\n import logging\n from logging.handlers import SMTPHandler\n credentials = None\n secure = None\n if getattr(cls, 'MAIL_USERNAME', None) is not None:\n credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)\n if getattr(cls, 'MAIL_USE_TLS', None):\n secure = ()\n mail_handler = SMTPHandler(\n mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),\n fromaddr=cls.FLASKY_MAIL_SENDER,\n toaddrs=[cls.FLASKY_MAIL_SENDER],\n subject=cls.FLASKY_MAIL_SUBJECT_PREFIX + ' Application Error',\n credentials=credentials,\n secure=secure)\n mail_handler.setLevel(logging.ERROR)\n app.logger.addHandler(mail_handler)\n\n\ndef deploy():\n \"\"\"Run deployment tasks.\"\"\"\n # migrate database to latest revision\n upgrade()\n","sub_path":"flasky.py","file_name":"flasky.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"467903948","text":"import unittest\nimport os\nimport yaml\nfrom Helper.HTMLTestRunner import HTMLTestRunner\nimport importlib\n\neutDir = os.path.dirname(__file__)\nglobalConfFile = os.path.join(eutDir, \"Conf\", \"running.yaml\")\n\nwith open(globalConfFile, \"r\") as f:\n globalConf = yaml.load(f)\nrunningProject = globalConf[\"project\"]\ncasesDir = os.path.join(eutDir, \"Projects\", runningProject, \"Cases\")\nlogPath = os.path.join(eutDir, \"Log\", \"log.txt\")\nreportPath = os.path.join(eutDir, \"Report\", \"report.html\")\nprojectConfigPath = os.path.join(eutDir, \"Projects\", runningProject, \"%s.yaml\" % runningProject)\nwith open(projectConfigPath, \"r\") as f:\n projectConfig = yaml.load(f) \n\npagesToRun = projectConfig[\"pagesToRun\"]\nif pagesToRun:\n print(\"Modules will run: %s\" % pagesToRun)\nelse:\n print(\"pagesToRun has NOT been set, so all the Modules will run.\")\n\nmodules = []\nfor fileName in os.listdir(casesDir):\n if fileName.startswith(\"test_\") and fileName.endswith(\".py\"):\n moduleName = fileName[:-3]\n modules.append(moduleName)\nclass Test:\n def suite(self): #Function stores all the modules to be tested\n su = unittest.TestSuite()\n if modules:\n for i in modules:\n m = \"Projects.%s.Cases.%s\" % (runningProject, i)\n s = importlib.import_module(m)\n clss = getattr(s,i)\n className = clss.__name__\n if pagesToRun:\n for j in pagesToRun.split(\", \"):\n if j == className:\n for c in dir(clss):\n if c.startswith(\"test_\"):\n su.addTest(clss(c)) \n else:\n for c in dir(clss):\n if c.startswith(\"test_\"):\n su.addTest(clss(c))\n return su\n \nif __name__ == '__main__':\n MyTests = Test()\n with open(reportPath, \"wb\") as f: \n runner = HTMLTestRunner(stream=f,title='Automation Test Report',description='Project: %s' % runningProject)\n runner.run(MyTests.suite())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"85109796","text":"\n # -*- coding: utf-8 -*-\nfrom odoo import api, fields, models, SUPERUSER_ID, _\nfrom datetime import datetime, timedelta\nfrom functools import partial\nfrom itertools import groupby\n\nfrom odoo.exceptions import AccessError, UserError, ValidationError\nfrom odoo.tools.misc import formatLang, get_lang\nfrom odoo.osv import expression\nfrom odoo.tools import float_is_zero, float_compare\nimport logging\n_logger = logging.getLogger(__name__)\nfrom datetime import date\n\nclass fleximaticsale(models.Model):\n _inherit = 'sale.order'\n x_approve = fields.Selection([\n ('por aprobar','To Approve'),\n ('aprobado','Approved'),\n ('no aprobado','Not approved')],\n string='Approve')\n state = fields.Selection(selection_add=[('por aprobar','To Approve'),\n ('aprobado','Approved'),\n ('no aprobado','Not approved')],readonly=True, copy=False, index=True, tracking=3, default='draft')\n x_credit = fields.Monetary(related='partner_id.x_credit',string='Available Credit')\n x_credit_after_sale = fields.Monetary('Credit After Sale',compute = 'compute_credit_after_sale')\n points = fields.Float('Points',digits=(32, 2), compute='_compute_total_points',store=True)\n r_points = fields.Float('Remaining points',digits=(32,2), compute='_compute_total_remaining_points')\n \n def _get_reward_values_free_shipping(self, program):\n delivery_line = self.order_line.filtered(lambda x: x.is_delivery)\n taxes = delivery_line.product_id.taxes_id\n _logger.info(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXX XD\")\n if self.fiscal_position_id:\n taxes = self.fiscal_position_id.map_tax(taxes)\n return {\n 'name': _(\"Discount: xDDDDDD \") + program.name,\n 'product_id': program.discount_line_product_id.id,\n 'price_unit': delivery_line and - delivery_line.price_unit or 0.0,\n 'product_uom_qty': 1.0,\n 'product_uom': program.discount_line_product_id.uom_id.id,\n 'order_id': self.id,\n 'is_reward_line': True,\n 'tax_id': [(4, tax.id, False) for tax in taxes],\n 'cupon_id':program.id,\n 'promotions_applied_mx':[(0, 0, { 'name':str(line.id) ,'ref_sol':line.id } ) for line in delivery_line ]\n } \n #REWARD MEX\n def _update_existing_reward_lines(self):\n '''Update values for already applied rewards'''\n def update_line(order, lines, values):\n '''Update the lines and return them if they should be deleted'''\n lines_to_remove = self.env['sale.order.line']\n # Check commit 6bb42904a03 for next if/else\n # Remove reward line if price or qty equal to 0\n \n if values['product_uom_qty'] and values['price_unit']:\n if lines.promotions_applied_mx:\n lines.promotions_applied_mx = False\n lines.write(values)\n else:\n if program.reward_type != 'free_shipping':\n # Can't remove the lines directly as we might be in a recordset loop\n lines_to_remove += lines\n else:\n if lines.promotions_applied_mx:\n lines.promotions_applied_mx = False\n values.update(price_unit=0.0)\n lines.write(values)\n return lines_to_remove\n\n self.ensure_one()\n order = self\n applied_programs = order._get_applied_programs_with_rewards_on_current_order()\n for program in applied_programs:\n values = order._get_reward_line_values(program)\n lines = order.order_line.filtered(lambda line: line.product_id == program.discount_line_product_id)\n if program.reward_type == 'discount' and program.discount_type == 'percentage':\n lines_to_remove = lines\n # Values is what discount lines should really be, lines is what we got in the SO at the moment\n # 1. If values & lines match, we should update the line (or delete it if no qty or price?)\n # 2. If the value is not in the lines, we should add it\n # 3. if the lines contains a tax not in value, we should remove it\n for value in values:\n value_found = False\n for line in lines:\n # Case 1.\n if not len(set(line.tax_id.mapped('id')).symmetric_difference(set([v[1] for v in value['tax_id']]))):\n value_found = True\n # Working on Case 3.\n lines_to_remove -= line\n lines_to_remove += update_line(order, line, value)\n continue\n # Case 2.\n if not value_found:\n order.write({'order_line': [(0, False, value)]})\n # Case 3.\n lines_to_remove.unlink()\n else:\n update_line(order, lines, values[0]).unlink()\n #REWARD MEX\n def _get_reward_values_discount(self, program):\n if program.discount_type == 'fixed_amount':\n return [{\n 'name': _(\"Discount: \") + program.name,\n 'product_id': program.discount_line_product_id.id,\n 'price_unit': - self._get_reward_values_discount_fixed_amount(program),\n 'product_uom_qty': 1.0,\n 'product_uom': program.discount_line_product_id.uom_id.id,\n 'is_reward_line': True,\n 'tax_id': [(4, tax.id, False) for tax in program.discount_line_product_id.taxes_id],\n 'cupon_id':program.id\n }]\n reward_dict = {}\n lines = self._get_paid_order_lines()\n if program.discount_apply_on == 'cheapest_product':\n line = self._get_cheapest_line()\n if line:\n discount_line_amount = line.price_reduce * (program.discount_percentage / 100)\n if discount_line_amount:\n taxes = line.tax_id\n if self.fiscal_position_id:\n taxes = self.fiscal_position_id.map_tax(taxes)\n\n reward_dict[line.tax_id] = {\n 'name': _(\"Discount: \") + program.name,\n 'product_id': program.discount_line_product_id.id,\n 'price_unit': - discount_line_amount,\n 'product_uom_qty': 1.0,\n 'product_uom': program.discount_line_product_id.uom_id.id,\n 'is_reward_line': True,\n 'tax_id': [(4, tax.id, False) for tax in taxes],\n 'cupon_id':program.id,\n 'promotions_applied_mx':[(0, 0, { 'name':str(line.id) ,'ref_sol':line.id } ) ] \n \n\n }\n elif program.discount_apply_on in ['specific_products', 'on_order']:\n if program.discount_apply_on == 'specific_products':\n # We should not exclude reward line that offer this product since we need to offer only the discount on the real paid product (regular product - free product)\n free_product_lines = self.env['sale.coupon.program'].search([('reward_type', '=', 'product'), ('reward_product_id', 'in', program.discount_specific_product_ids.ids)]).mapped('discount_line_product_id')\n lines = lines.filtered(lambda x: x.product_id in (program.discount_specific_product_ids | free_product_lines))\n\n for line in lines:\n discount_line_amount = self._get_reward_values_discount_percentage_per_line(program, line)\n\n if discount_line_amount:\n\n if line.tax_id in reward_dict:\n reward_dict[line.tax_id]['price_unit'] -= discount_line_amount\n reward_dict[line.tax_id]['promotions_applied_mx'].append( (0, 0, { 'name':str(line.id) ,'line_id':line.id } ) )\n else:\n taxes = line.tax_id\n if self.fiscal_position_id:\n taxes = self.fiscal_position_id.map_tax(taxes)\n\n tax_name = \"\"\n if len(taxes) == 1:\n tax_name = \" - \" + _(\"On product with following tax: \") + ', '.join(taxes.mapped('name'))\n elif len(taxes) > 1:\n tax_name = \" - \" + _(\"On product with following taxes: \") + ', '.join(taxes.mapped('name'))\n\n reward_dict[line.tax_id] = {\n 'name': _(\"Discount: \") + program.name + tax_name,\n 'product_id': program.discount_line_product_id.id,\n 'price_unit': - discount_line_amount,\n 'product_uom_qty': 1.0,\n 'product_uom': program.discount_line_product_id.uom_id.id,\n 'is_reward_line': True,\n 'tax_id': [(4, tax.id, False) for tax in taxes],\n 'cupon_id':program.id,\n 'promotions_applied_mx':[(0, 0, { 'name':str(line.id) ,'ref_sol':line.id } ) ] \n }\n\n # If there is a max amount for discount, we might have to limit some discount lines or completely remove some lines\n max_amount = program._compute_program_amount('discount_max_amount', self.currency_id)\n if max_amount > 0:\n amount_already_given = 0\n for val in list(reward_dict):\n amount_to_discount = amount_already_given + reward_dict[val][\"price_unit\"]\n if abs(amount_to_discount) > max_amount:\n reward_dict[val][\"price_unit\"] = - (max_amount - abs(amount_already_given))\n add_name = formatLang(self.env, max_amount, currency_obj=self.currency_id)\n reward_dict[val][\"name\"] += \"( \" + _(\"limited to \") + add_name + \")\"\n amount_already_given += reward_dict[val][\"price_unit\"]\n if reward_dict[val][\"price_unit\"] == 0:\n del reward_dict[val]\n return reward_dict.values()\n #REWARD MEX\n def _get_reward_values_product(self, program):\n price_unit = self.order_line.filtered(lambda line: program.reward_product_id == line.product_id)[0].price_reduce\n\n order_lines = (self.order_line - self._get_reward_lines()).filtered(lambda x: program._is_valid_product(x.product_id))\n max_product_qty = sum(order_lines.mapped('product_uom_qty')) or 1\n # Remove needed quantity from reward quantity if same reward and rule product\n if program._is_valid_product(program.reward_product_id):\n # number of times the program should be applied\n program_in_order = max_product_qty // (program.rule_min_quantity + program.reward_product_quantity)\n # multipled by the reward qty\n reward_product_qty = program.reward_product_quantity * program_in_order\n else:\n reward_product_qty = min(max_product_qty, self.order_line.filtered(lambda x: x.product_id == program.reward_product_id).product_uom_qty)\n\n reward_qty = min(int(int(max_product_qty / program.rule_min_quantity) * program.reward_product_quantity), reward_product_qty)\n # Take the default taxes on the reward product, mapped with the fiscal position\n taxes = program.reward_product_id.taxes_id\n if self.fiscal_position_id:\n taxes = self.fiscal_position_id.map_tax(taxes)\n return {\n 'cupon_id':program.id,\n 'product_id': program.discount_line_product_id.id,\n 'price_unit': - price_unit,\n 'product_uom_qty': reward_qty,\n 'is_reward_line': True,\n 'name': _(\"Free Product\") + \" - \" + program.reward_product_id.name,\n 'product_uom': program.reward_product_id.uom_id.id,\n 'tax_id': [(4, tax.id, False) for tax in taxes],\n 'promotions_applied_mx':[(0, 0, { 'name':str(line.id) ,'ref_sol':line.id } ) for line in order_lines if line.product_id == program.reward_product_id ] \n }\n \n \n \n \n #Reward MEX\n def _create_invoices(self, grouped=False, final=False):\n res = super(fleximaticsale, self)._create_invoices(grouped,final)\n for order in self:\n inv = res.filtered(lambda t: t.invoice_origin == order.name)\n if inv:\n #Coupon avaible\n changes_line={}\n changes_line['invoice_line_ids'] = []\n have_coupouns = order.order_line.filtered(lambda ol: ol.is_reward_line and ol.cupon_id)\n #\"Free product\"\n for cup in have_coupouns.filtered(lambda ol: ol.cupon_id.reward_type == 'product'): \n #Get related lines to cupon\n for lines_to_apply in cup.promotions_applied_mx:\n ref_id = lines_to_apply.ref_sol\n #Find sale line with related lines cupon\n real_line = inv.invoice_line_ids.filtered(lambda il: ref_id.id in [ sl.id for sl in il.sale_line_ids ] )\n remove_line_reward = inv.invoice_line_ids.filtered(lambda il: cup.id in [ sl.id for sl in il.sale_line_ids ] )\n changes_line['invoice_line_ids'].append( (2, remove_line_reward.id) )\n if cup.cupon_id.reward_product_quantity == real_line.quantity :\n changes_line['invoice_line_ids'].append( ( 1, real_line.id, { 'price_unit':0.1 } ) )\n else:\n #Dist all discount to specific line , being 2 x 1 , 3 x 1 , 2x3 ... \n real_amount = real_line.quantity * real_line.price_unit\n \n res_amount = remove_line_reward.quantity * remove_line_reward.price_unit\n \n real_amount = real_amount + res_amount\n \n changes_line['invoice_line_ids'].append( ( 1, real_line.id, { 'price_unit': (real_amount/real_line.quantity) } ) )\n #Free shipping\n for cup in have_coupouns.filtered(lambda ol: ol.cupon_id.reward_type == 'free_shipping'):\n for lines_to_apply in cup.promotions_applied_mx:\n ref_id = lines_to_apply.ref_sol\n #Find sale line with related lines cupon\n real_line = inv.invoice_line_ids.filtered(lambda il: ref_id.id in [ sl.id for sl in il.sale_line_ids ] )\n remove_line_reward = inv.invoice_line_ids.filtered(lambda il: cup.id in [ sl.id for sl in il.sale_line_ids ] )\n changes_line['invoice_line_ids'].append( (2, remove_line_reward.id) )\n if cup.cupon_id.reward_product_quantity == real_line.quantity :\n changes_line['invoice_line_ids'].append( ( 1, real_line.id, { 'price_unit':0.1 } ) )\n else:\n #Dist all discount to specific line , being 2 x 1 , 3 x 1 , 2x3 ... \n real_amount = real_line.quantity * real_line.price_unit\n \n res_amount = remove_line_reward.quantity * remove_line_reward.price_unit\n \n real_amount = real_amount + res_amount\n \n changes_line['invoice_line_ids'].append( ( 1, real_line.id, { 'price_unit': (real_amount/real_line.quantity) } ) )\n #Reward disc % and fix amount products\n for cup in have_coupouns.filtered(lambda ol: ol.cupon_id.reward_type == 'free_shipping'):\n pass \n\n\n \n inv.update( changes_line ) \n inv._onchange_invoice_line_ids() \n\n\n\n def action_multi_confirm(self):\n sales = self.filtered(lambda t: t.state == 'draft')\n sales.action_confirm()\n def action_draft(self):\n orders = self.filtered(lambda s: s.state in ['cancel', 'sent'])\n return orders.write({\n 'x_approve': False,\n 'state': 'draft',\n 'signature': False,\n 'signed_by': False,\n 'signed_on': False,\n }) \n def show_pricelistAvaible(self):\n if self.order_line: \n view_id = self.env.ref('fleximatic.view_sale_pricelist_wizard').id\n view = {\n 'name': ('Descuento'),\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'fleximatic.sale.pricelist.wizard',\n 'views': [(view_id,'form')],\n 'type': 'ir.actions.act_window',\n 'target': 'new',\n 'context':{'default_sale':self.id,'default_date_order':self.date_order,'default_product_id':self.order_line[0].product_id.id},\n }\n return view \n\n @api.depends('order_line','state')\n def _compute_total_points(self):\n for sale in self:\n puntos = 0.0\n if sale.order_line:\n for line in sale.order_line:\n if line.is_promotional == False:\n puntos += line.price_subtotal *(line.product_id.puntos_genera/100)\n if sale.state in ['done','cancel']: \n sale.points = 0\n else:\n sale.points = puntos\n\n @api.depends('x_credit_after_sale','x_credit','amount_total')\n def compute_credit_after_sale(self):\n for record in self:\n record['x_credit_after_sale'] = record.x_credit - record.amount_total\n\n def open_wizard_promotional(self):\n view_id = self.env.ref('fleximatic.view_sale_products_wizard').id\n promotionals = [ (0,0,{'product_id':item.product_id.id,\n 'product_template_id':item.product_template_id.id,\n 'qty':item.product_uom_qty,\n 'uom_id':item.product_uom.id,\n 'price_points':item.product_id.puntos_venta,\n 'total':item.product_uom_qty*item.product_id.puntos_venta\n } ) for item in self.order_line if item.is_promotional ]\n\n view = {\n 'name': ('Agregar productos promocionales'),\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'product.promotional',\n 'type': 'ir.actions.act_window',\n 'target':'new',\n 'context':{'default_sale_id':self.id,\n 'default_points':self.points,\n 'default_promotional_line':promotionals,\n 'default_points_to_sale':sum([x[2]['total'] for x in promotionals])\n }\n }\n return view\n \n\n\n @api.depends('points','order_line','state') \n def _compute_total_remaining_points(self):\n for sale in self:\n puntos_gastados = 0\n if sale.order_line and sale.state not in ['done','cancel']:\n for line in sale.order_line:\n if line.is_promotional == True:\n puntos_gastados += line.puntos_venta * line.product_uom_qty\n sale.r_points = sale.points - puntos_gastados\n else:\n sale.r_points = sale.points\n\n \n def write(self, vals):\n status = ['draft','sent','por aprobar','aprobado','no aprobado']\n if 'x_approve' in vals and self.state in status and self.x_credit_after_sale < 0 and self.payment_term_id != 1 :\n vals['state'] = vals['x_approve'] \n res = super(fleximaticsale, self).write(vals)\n if self.r_points < 0:\n raise ValidationError(('Error! Not enough points to complete the sale'))\n else:\n return res\n \n def remove_promotional_products(self):\n if self.order_line:\n for products in self.order_line:\n if products.is_promotional == True:\n pass\n #products.with_context(allow_delete=True).unlink()\n\n\n def days_between(self,d1, d2):\n d1 = datetime.strptime(d1, \"%Y-%m-%d\")\n d2 = datetime.strptime(d2, \"%Y-%m-%d\")\n return abs((d2 - d1).days)\n\n def notify_deadline(self):\n today = datetime.today()\n orders = self.env['sale.order'].search([])\n if orders:\n for o in orders:\n if type(o.commitment_date) is datetime:\n ddif = o.expected_date - today\n if ddif.days == 2 or o.name == 'S00093':\n _logger.info(\"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \")\n _logger.info(o.name)\n _logger.info(today)\n _logger.info(o.commitment_date)\n _logger.info(ddif.days)\n _logger.info(o.user_id.name)\n _logger.info(o.user_id.login)\n \n prod_qty = 0\n prod_deli = 0\n if o.order_line:\n for ol in o.order_line:\n prod_qty = prod_qty + ol.product_uom_qty\n prod_deli = prod_deli + ol.qty_delivered\n _logger.info(prod_qty)\n _logger.info(prod_deli)\n if prod_qty != prod_deli:\n _logger.info(\"No ha sido entregado.\")\n\n deadline_template=self.env.ref('fleximatic.deadline_mail_template').id\n template = self.env['mail.template'].browse(deadline_template)\n template.send_mail(o.id, force_send=True) \n\n","sub_path":"fleximatic/models/sale/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":22152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"335134333","text":"from cs50 import get_float, get_int\n\nx = get_float(\"x: \")\ny = get_float(\"y: \")\n\nif y == 0:\n print(\"You can't divide by 0\")\n quit()\n\ndivisible = \"x is divisible by y\" if x % y == 0 else \"x is not divisible by y\"\nprint(divisible)\n\ndiv = x / y\nif div == int(div):\n print(int(div))\nelse:\n prec = get_int(\"Decimals: \") # ex4\n if prec < 0:\n print(\"Number of decimals must be higher than zero\")\n quit()\n else:\n r = \"{0:.\" + str(prec) + \"f}\"\n div= r.format(x/y + 0)\n print(\"x/y = \" + div)\n","sub_path":"lab2/ex3_4.py","file_name":"ex3_4.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"436002339","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('videoinfo', '0004_auto_20150617_1448'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='video',\n name='user',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='videos1', verbose_name='user'),\n ),\n ]\n","sub_path":"python/pyvideo_project/pyvideo/apps/videoinfo/migrations/0005_auto_20150710_1654.py","file_name":"0005_auto_20150710_1654.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"426368928","text":"import simplegui\nimport random\n\nCARD_SIZE = (72, 96)\nCARD_CENTER = (36, 48)\ncard_images = simplegui.load_image(\"http://storage.googleapis.com/codeskulptor-assets/cards_jfitz.png\")\nCARD_BACK_SIZE = (72, 96)\nCARD_BACK_CENTER = (36, 48)\ncard_back = simplegui.load_image(\"http://storage.googleapis.com/codeskulptor-assets/card_jfitz_back.png\") \nin_play = False\nscore = 0\nSUITS = ('C', 'S', 'H', 'D')\nRANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')\nVALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10}\nmessage = \"\"\n# define card class\nclass Card:\n def __init__(self, suit, rank):\n if (suit in SUITS) and (rank in RANKS):\n self.suit = suit\n self.rank = rank\n else:\n self.suit = None\n self.rank = None\n def __str__(self):\n return self.suit + self.rank\n def get_suit(self):\n return self.suit\n def get_rank(self):\n return self.rank\n def draw(self, canvas, pos):\n card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), \n CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit))\n canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0], pos[1] + CARD_CENTER[1]], CARD_SIZE)\n# define hand class \nclass Hand:\n def __init__(self):\n self.cards = [] \n def __str__(self):\n ret = ''\n for i in self.cards:\n ret += i.get_suit() + i.get_rank()\n return \"Hand Contains \" + ret\n def add_card(self, card):\n self.cards.append(card)\t\n def get_value(self):\n value = 0\n aces_count = 0\n for each_card in self.cards:\n if each_card.get_rank() == 'A':\n aces_count += 1 \n value += VALUES[each_card.get_rank()] \n if aces_count == 0:\n return value\n else:\n if (value + 10) < 21:\n return value + 10\n else:\n return value\n \n def draw(self, canvas, pos):\n for each_card in self.cards:\n pos[0] += CARD_SIZE[0]\n each_card.draw(canvas, pos) \n# define deck class \nclass Deck:\n def __init__(self):\n self.deck_cards = [Card(suit, rank) for suit in SUITS for rank in RANKS] \n def shuffle(self):\n random.shuffle(self.deck_cards) \n def deal_card(self):\n return self.deck_cards.pop() \n def __str__(self): \n string = ''\n for i in self.deck_cards:\n string += str(i) + ' '\n return 'Deck Contains: ' + string\n#define event handlers for buttons\ndef deal():\n global in_play, message, score\n global player_hand, dealer_hand, deck\n message = 'Hit or Stand?'\n if in_play:\n score -= 1 \n deck = Deck()\n player_hand = Hand()\n dealer_hand = Hand()\n deck.shuffle()\n player_hand.add_card(deck.deal_card())\n dealer_hand.add_card(deck.deal_card())\n player_hand.add_card(deck.deal_card())\n dealer_hand.add_card(deck.deal_card())\n in_play = True\n\ndef hit():\n global in_play, message, score\n if in_play and player_hand.get_value() <= 21:\n player_hand.add_card(deck.deal_card()) \n if player_hand.get_value() > 21:\n message = 'You lose! New deal?'\n in_play = False\n score -= 1\n \ndef stand():\n global in_play, message, score \n if in_play:\n while dealer_hand.get_value() < 17:\n if in_play:\n dealer_hand.add_card(deck.deal_card()) \n if dealer_hand.get_value() > 21:\n message = 'You win! New deal?'\n in_play = False\n score += 1\n elif dealer_hand.get_value() > player_hand.get_value():\n message = 'You lose! New deal?'\n in_play = False\n score -= 1 \n elif player_hand.get_value() > dealer_hand.get_value():\n message = 'You win! New deal?'\n in_play = False\n score += 1 \n elif player_hand.get_value() == dealer_hand.get_value():\n message = 'You lose! New deal?'\n in_play = False\n score -= 1\n# draw handler \ndef draw(canvas):\n canvas.draw_text('Blackjack', [250,50], 35, 'Black')\n canvas.draw_text('Score: ' + str(score), [30, 90], 25, 'Black') \n player_value = player_hand.get_value()\n canvas.draw_text('Player rate = ' + str(player_value), [30, 360], 25, 'Black')\n canvas.draw_text('Dealer rate', [30, 130], 25, 'Black')\n canvas.draw_text(message, [200, 300], 35, 'Red') \n player_hand.draw(canvas, [0,370])\n dealer_hand.draw(canvas, [0,140]) \n if in_play:\n hole_center_canvas = [CARD_SIZE[0], 188]\n canvas.draw_image(card_back, CARD_BACK_CENTER, CARD_BACK_SIZE, hole_center_canvas , CARD_BACK_SIZE)\n else:\n dealer_value = dealer_hand.get_value()\n canvas.draw_text(' = ' + str(dealer_value), [140, 130], 25, 'Black')\n# initialization frame\nframe = simplegui.create_frame(\"Blackjack\", 600, 600)\nframe.set_canvas_background(\"Green\")\nframe.add_button(\"Deal\", deal, 200)\nframe.add_button(\"Hit\", hit, 200)\nframe.add_button(\"Stand\", stand, 200)\nframe.set_draw_handler(draw)\n\ndeal()\nframe.start()\n","sub_path":"Homework06/Blackjack.py","file_name":"Blackjack.py","file_ext":"py","file_size_in_byte":5275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"439546860","text":"# -*- coding: utf-8 -*-\n\n# The day constants\nSUNDAY = 0\nMONDAY = 1\nTUESDAY = 2\nWEDNESDAY = 3\nTHURSDAY = 4\nFRIDAY = 5\nSATURDAY = 6\n\n# Number of X in Y.\nYEARS_PER_CENTURY = 100\nYEARS_PER_DECADE = 10\nMONTHS_PER_YEAR = 12\nWEEKS_PER_YEAR = 52\nDAYS_PER_WEEK = 7\nHOURS_PER_DAY = 24\nMINUTES_PER_HOUR = 60\nSECONDS_PER_MINUTE = 60\nSECONDS_PER_HOUR = MINUTES_PER_HOUR * SECONDS_PER_MINUTE\nSECONDS_PER_DAY = HOURS_PER_DAY * SECONDS_PER_HOUR\n\n# Formats\nATOM = '%Y-%m-%dT%H:%M:%S%_z'\nCOOKIE = '%A, %d-%b-%Y %H:%M:%S %Z'\nISO8601 = '%Y-%m-%dT%H:%M:%S%_z'\nISO8601_EXTENDED = '%Y-%m-%dT%H:%M:%S.%f%_z'\nRFC822 = '%a, %d %b %y %H:%M:%S %z'\nRFC850 = '%A, %d-%b-%y %H:%M:%S %Z'\nRFC1036 = '%a, %d %b %y %H:%M:%S %z'\nRFC1123 = '%a, %d %b %Y %H:%M:%S %z'\nRFC2822 = '%a, %d %b %Y %H:%M:%S %z'\nRFC3339 = '%Y-%m-%dT%H:%M:%S%_z'\nRFC3339_EXTENDED = '%Y-%m-%dT%H:%M:%S.%f%_z'\nRSS = '%a, %d %b %Y %H:%M:%S %z'\nW3C = '%Y-%m-%dT%H:%M:%S%_z'\n","sub_path":"pendulum/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"344001369","text":"from django.shortcuts import render\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef index(request):\n urlweather = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&APPID=4665a8e9f1e1caa5d2633278871afb11'\n urlflood = 'https://www.orc.govt.nz/managing-our-environment/water/water-monitoring-and-alerts/upper-clutha/lake-wanaka'\n city = 'Wanaka'\n\n rweather = requests.get(urlweather.format(city)).json()\n rflood = requests.get(urlflood)\n\n soup = BeautifulSoup(rflood.content)\n \n all_flood_data = []\n for item in soup.find_all('div', {'class': 'result-list--item result-list--item-content'}):\n flood_data = {\n 'location' : item.contents[1].text,\n 'data' : item.contents[3].text\n }\n \n all_flood_data.append(flood_data)\n img_src = []\n for item in soup.find_all('img'):\n img_src.append(item['src'])\n\n print(img_src)\n \n city_weather = {\n 'city' : city,\n 'temperature' : rweather['main']['temp'],\n 'description' : rweather['weather'][0]['description'],\n 'icon' : rweather['weather'][0]['icon'],\n }\n \n\n context = {'all_flood_data' : all_flood_data, 'city_weather': city_weather, 'img_src' : img_src}\n return render(request, 'weather.html', context)","sub_path":"src/wanaflood/weather/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"598929378","text":"from flask import Flask, request, jsonify\nfrom RecognitionLib import *\napp = Flask(__name__)\n\n@app.route('/predict', methods=['GET', 'POST'])\ndef add_message():\n content = request.json\n path = (content['path'])\n clf = loadModel(\"trainedModel.sav\")\n #print(predict(clf, path))\n #return jsonify({\"parkison\":predict(clf, path)})\n return predict(clf, path)\n\nif __name__ == '__main__':\n app.run(host= '0.0.0.0',debug=True)","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"154924238","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom CTS.FireDynamics import steel_specific_heat_carbon_steel\nfrom CTS.FireDynamics import stress_strain_elevated_temperature_carbon_steel\nimport CTS.FireDynamics as fd_eurocode\n\nclass UnprotectedSteel(object):\n \"\"\"\n DESCRIPTION:\n ATTRIBUTES:\n timeArray {ndarray, s}\n temperatureArray {ndarray, K}\n sectionPerimeter {m}\n sectionArea {m2}\n densitySteel {kg/m3}\n convectiveHeatTransferCoefficient {W/m2/K}\n resultantEmissivity {-}\n REMARKS:\n 1. Steel temperature is limited within 20C <= T_s <= 1200, due to specific heat\n \"\"\"\n def __init__(self, timeArray, temperatureArray,\n sectionPerimeter, sectionArea, boxPerimeter, boxArea,\n densitySteel,\n convectiveHeatTransferCoefficient, resultantEmissivity):\n # Assign attributes\n self.timeArray = timeArray\n self.temperatureArray = temperatureArray\n self.sectionPerimeter = float(sectionPerimeter)\n self.sectionArea = float(sectionArea)\n self.boxPerimeter = float(boxPerimeter)\n self.boxArea = float(boxArea)\n self.densitySteel = float(densitySteel)\n self.convectiveHeatTransferCoefficient = float(convectiveHeatTransferCoefficient)\n self.resultantEmissivity = float(resultantEmissivity)\n\n self.steelTemperatureArray = None\n self.steelTemperatureChangeArray = None\n self.heatFluxNet = None\n self.steelSpecificHeat = None\n\n def proceed(self):\n # Create steel temperature change array\n steelTemperatureChangeArray = np.zeros(np.shape(self.timeArray), dtype=float)\n steelTemperatureArray = np.zeros(np.shape(self.timeArray), dtype=float)\n heat_flux_net = np.zeros(np.shape(self.timeArray), dtype=float)\n steel_specific_heat = np.zeros(np.shape(self.timeArray), dtype=float)\n\n k_sh = 0.9 * (self.boxPerimeter / self.sectionArea) / (self.sectionPerimeter / self.sectionArea) # BS EN 1993-1-2:2005 (e4.26a)\n F = self.sectionPerimeter\n V = self.sectionArea\n rho_s = self.densitySteel\n h_c = self.convectiveHeatTransferCoefficient\n sigma = 56.7e-9\n epsilon = self.resultantEmissivity\n\n index = np.arange(1, np.size(self.timeArray), 1)\n steelTemperatureArray[0] = self.temperatureArray[0]\n for i in index:\n T_f = self.temperatureArray[i]\n T_s = steelTemperatureArray[i-1]\n steel_specific_heat[i] = float(steel_specific_heat_carbon_steel(steelTemperatureArray[i-1]))\n\n # BS EN 1993-1-2:2005 (e4.25)\n a = h_c * (T_f - T_s)\n b = sigma * epsilon * (np.power(T_f,4) - np.power(T_s,4))\n c = k_sh * F / V / rho_s / steel_specific_heat[i]\n d = self.timeArray[i] - self.timeArray[i-1]\n\n heat_flux_net[i] = a + b\n\n steelTemperatureChangeArray[i] = c * (a + b) * d\n steelTemperatureArray[i] = steelTemperatureArray[i-1] + steelTemperatureChangeArray[i]\n\n self.steelTemperatureArray = steelTemperatureArray\n self.steelTemperatureChangeArray = steelTemperatureChangeArray\n self.heatFluxNet = heat_flux_net\n self.steelSpecificHeat = steel_specific_heat\n\nclass ProtectedSteel_Buchanan(object):\n \"\"\"\n DESCRIPTION:\n\n ATTRIBUTES:\n timeArray {ndarray, s}\n temperatureArray {ndarray, K}\n sectionPerimeter {m}\n sectionArea {m2}\n insulationThermalConductivity {W/m/K}\n insulationDensity {kg/m3}\n insulationSpecificHeat {J/kg/K}\n insulationDepth {m}\n \"\"\"\n def __init__(self, timeArray, temperatureArray,\n sectionPerimeter, sectionArea,\n insulationThermalConductivity, insulationDensity, insulationSpecificHeat, insulationDepth,\n steelDensity):\n self.timeArray = timeArray\n self.temperatureArray = temperatureArray\n self.sectionPerimeter = float(sectionPerimeter)\n self.sectionArea = float(sectionArea)\n self.insulationThermalConductivity = float(insulationThermalConductivity)\n self.insulationDensity = float(insulationDensity)\n self.insulationSpecificHeat = float(insulationSpecificHeat)\n self.insulationDepth = float(insulationDepth)\n self.steelDensity = float(steelDensity)\n\n self.steelTemperatureArray = None\n self.steelTemperatureChangeArray = None\n\n def proceed(self):\n # Create steel temperature change array\n steelTemperatureChangeArray = np.zeros(np.shape(self.timeArray), dtype=float)\n steelTemperatureArray = np.zeros(np.shape(self.timeArray), dtype=float)\n\n # Assign variables for readability\n F = self.sectionPerimeter\n V = self.sectionArea\n d_i = self.insulationDepth\n k_i = self.insulationThermalConductivity\n rho_i = self.insulationDensity\n c_i = self.insulationSpecificHeat\n rho_s = self.steelDensity\n\n index = np.arange(1, np.size(self.timeArray), 1)\n steelTemperatureArray[0] = self.temperatureArray[0]\n for i in index:\n c_s = steel_specific_heat_carbon_steel(steelTemperatureArray[i-1])\n a = (F / V) * (k_i / d_i / rho_s / c_s)\n b = (rho_s * c_s) / (rho_s * c_s + (F / V) * (d_i * rho_i * c_i / 2))\n c = self.temperatureArray[i] - steelTemperatureArray[i-1]\n d = self.timeArray[i] - self.timeArray[i-1]\n steelTemperatureChangeArray[i] = a * b * c * d\n steelTemperatureArray[i] = steelTemperatureArray[i-1] + steelTemperatureChangeArray[i]\n\n self.steelTemperatureArray = steelTemperatureArray\n self.steelTemperatureChangeArray = steelTemperatureChangeArray\n\n @staticmethod\n def thermal_conductivity(temperature):\n T = temperature - 273.15\n if 20 <= T <= 800:\n return 54 - 0.0333 * T\n elif 800 <= T <= 1200:\n return 27.3\n\nclass ProtectedSteel_Eurocode(object):\n \"\"\"\n DESCRIPTION:\n [BS EN 1993-1-2:2005]\n Calculates protected steel internal temperature, strength variation based on given time-temperature curve\n PARAMETERS:\n steel_yield_stress f_y_theta {float, N/m2} Effective yield strength\n protectionArea A_p {float, m2/m} The appropriate area of fire protection material per\n unit length of the member.\n sectionVolume V {float, m3/m} The volume of the member per unit length.\n specificHeatSteel c_a {float, J/kg/K} Temperature dependent specific heat of steel.\n specificHeatProtection c_p {float, J/kg/K} Temperature independent specific heat of protection\n material.\n protectionDepth d_p {float, m} The thickness of the fire protection material.\n timeStep s {float, s} Time interval\n steelTemperature T_a {ndarray, C} Steel temperature array, {float}.\n gasTemperature T_g {ndarray, C} Ambient temperature array, {float}.\n thermalConductivityProtection lamda_p {float, C} Thermal conductivity of the fire protection system.\n densitySteel rho_a {float, kg/m3} Steel density.\n densityProtection rho_p {float, kg/m3} Protection material density.\n gamma_m_fi - {float, -} Partial safety factor for fire situation\n REMARKS:\n\n \"\"\"\n \n def __init__(self, time_array, temperature_array,\n steel_yield_stress, steel_proportional_stress, steel_elastic_modulus,\n section_volume, slenderness, density_steel,\n specific_heat_protection, thermal_conductivity_protection,\n density_protection, protection_depth, protection_area):\n self.timeArray = time_array\n self.temperatureArray = temperature_array\n self.steelYieldStress = float(steel_yield_stress)\n self.steelProportionalStress = float(steel_proportional_stress)\n self.steelElasticModulus = float(steel_elastic_modulus)\n self.sectionVolume = float(section_volume)\n self.slenderness = float(slenderness)\n self.densitySteel = float(density_steel)\n # self.memberLength = float(member_length)\n self.specificHeatProtection = float(specific_heat_protection)\n self.thermalConductivityProtection = float(thermal_conductivity_protection)\n self.densityProtection = float(density_protection)\n self.protectionDepth = float(protection_depth)\n self.protectionArea = float(protection_area)\n \n self.steelTemperatureArray = None\n self.steelTemperatureChangeArray = None\n self.steelSpecificHeat = None\n\n self.steelEffectiveYieldReductionFactor = None\n self.steelProportionalLimitReductionFactor = None\n self.steelElasticModulusReductionFactor = None\n self.steelSlendernessTemperatureDependent = None\n\n self.steelStrength = None\n self.steelThermalStrain = None\n self.steelThermalStress = None\n \n def proceed(self):\n self.get_steel_temperature()\n self.get_steel_properties_variation()\n\n def get_steel_temperature(self):\n # --------------------------------------------------------------------------------------------------------------\n # steel temperature calculation procedure\n # --------------------------------------------------------------------------------------------------------------\n V = self.sectionVolume\n rho_a = self.densitySteel\n lamda_p = self.thermalConductivityProtection\n rho_p = self.densityProtection\n d_p = self.protectionDepth\n A_p = self.protectionArea\n c_p = self.specificHeatProtection\n\n steelTemperatureArray = np.zeros(np.shape(self.timeArray),dtype=float)\n steelTemperatureChangeArray = np.zeros(np.shape(self.timeArray),dtype=float)\n steelSpecificHeat = np.zeros(np.shape(self.timeArray),dtype=float)\n\n steelTemperatureArray[0] = self.temperatureArray[0] # initial steel temperature is equel to ambient\n iterTemperatureArray = iter(self.temperatureArray) # skip the first item\n next(iterTemperatureArray) # skip the first item\n for i, currentGasTemperature in enumerate(iterTemperatureArray):\n i += 1 # the first item had been skipped.\n\n steelSpecificHeat[i] = steel_specific_heat_carbon_steel(temperature=steelTemperatureArray[i-1]+273.15)\n\n # Steel temperature equation followed [BS EN 1993-1-2:2005, Clauses 4.2.5.2]\n\n phi = (c_p * rho_p / steelSpecificHeat[i] / rho_a) * d_p * A_p / V\n\n a = (lamda_p * A_p / V) / (d_p * steelSpecificHeat[i] * rho_a)\n b = (currentGasTemperature - steelTemperatureArray[i-1]) / (1 + phi/3)\n c = (np.exp(phi/10)-1) * (currentGasTemperature - self.temperatureArray[i-1])\n d = self.timeArray[i] - self.timeArray[i-1]\n\n steelTemperatureChangeArray[i] = a * b * d - c\n\n if steelTemperatureChangeArray[i] < 0 and currentGasTemperature - steelTemperatureArray[i-1] > 0:\n steelTemperatureChangeArray[i] = 0\n steelTemperatureArray[i] = steelTemperatureArray[i-1] + steelTemperatureChangeArray[i]\n\n self.steelTemperatureArray = steelTemperatureArray\n self.steelTemperatureChangeArray = steelTemperatureChangeArray\n self.steelSpecificHeat = steelSpecificHeat\n\n def get_steel_properties_variation(self):\n # --------------------------------------------------------------------------------------------------------------\n # steel strength variation according to temperature\n # --------------------------------------------------------------------------------------------------------------\n\n # variable assignment - for strength calculation\n section_area = self.sectionVolume\n stress_yield = self.steelYieldStress\n k_y_theta = np.zeros(shape = np.shape(self.timeArray), dtype=float)\n k_p_theta = np.zeros(shape = np.shape(self.timeArray), dtype=float)\n k_E_theta = np.zeros(shape = np.shape(self.timeArray), dtype=float)\n lamda_theta = np.zeros(shape = np.shape(self.timeArray), dtype=float)\n\n # variable assignment - for thermal stress calculation\n strain_theta = np.zeros(shape = np.shape(self.timeArray), dtype=float)\n stress_theta = np.zeros(shape = np.shape(self.timeArray), dtype=float)\n\n for i, temperature_i in enumerate(self.steelTemperatureArray):\n # calculate strength\n a, b, c = \\\n fd_eurocode.reduction_factor_carbon_steel(steel_temperature = temperature_i + 273.15)\n k_y_theta[i] = a\n k_p_theta[i] = b\n k_E_theta[i] = c\n lamda_theta[i] = fd_eurocode.reduction_factor_buckling_fire_carbon_steel(\n stress_yield=stress_yield,lambda_=self.slenderness,k_y_theta=k_y_theta[i],k_E_theta=k_E_theta[i])\n\n # calculate thermal expansion\n strain_theta[i] = fd_eurocode.relative_thermal_elongation_carbon_steel(steel_temperature= temperature_i + 273.5)\n # calculate thermal stress\n stress_theta[i] = fd_eurocode.stress_strain_elevated_temperature_carbon_steel(\n steel_strain=strain_theta[i],\n stress_proportional=k_p_theta[i] * self.steelProportionalStress,\n stress_yield=self.steelYieldStress,\n elastic_modulus=k_E_theta[i] * self.steelElasticModulus)\n\n # return reduction factors\n self.steelEffectiveYieldReductionFactor = k_y_theta\n self.steelProportionalLimitReductionFactor = k_p_theta\n self.steelElasticModulusReductionFactor = k_E_theta\n\n # return strength variation\n gamma_m_fi = 1.0 # from national annex, recommended as 1.0 for fire\n self.steelStrength = lamda_theta * self.steelYieldStress * k_y_theta / gamma_m_fi\n self.steelSlendernessTemperatureDependent = lamda_theta\n\n # return thermal stress\n self.steelThermalStrain = strain_theta\n self.steelThermalStress = stress_theta\n","sub_path":"project/zone_model_1/CTS/SteelTemperature.py","file_name":"SteelTemperature.py","file_ext":"py","file_size_in_byte":14826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"146480752","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/ztfy/blog/security.py\n# Compiled at: 2012-06-26 16:33:07\n__docformat__ = 'restructuredtext'\nfrom hurry.query.interfaces import IQuery\nfrom zope.authentication.interfaces import IAuthentication\nfrom ztfy.security.interfaces import IGrantedRoleEvent, IRevokedRoleEvent\nfrom hurry.query.set import AnyOf\nfrom zope.component import adapter, getUtility, getUtilitiesFor\nfrom ztfy.security.indexer import ALL_ROLES_INDEX_NAME\n\n@adapter(IGrantedRoleEvent)\ndef handleGrantedOperatorRole(event):\n if event.role in ('ztfy.BlogManager', 'ztfy.BlogContributor'):\n for _name, auth in getUtilitiesFor(IAuthentication):\n operators = auth.get('groups', {}).get('operators', None)\n if operators is not None and event.principal not in operators.principals:\n operators.principals = operators.principals + (event.principal,)\n\n return\n\n\n@adapter(IRevokedRoleEvent)\ndef handleRevokedOperatorRole(event):\n if event.role in ('ztfy.BlogManager', 'ztfy.BlogContributor'):\n query = getUtility(IQuery)\n objects = query.searchResults(AnyOf(('SecurityCatalog', ALL_ROLES_INDEX_NAME), (\n event.principal,)))\n if not objects or len(objects) == 1 and event.object in objects:\n for _name, auth in getUtilitiesFor(IAuthentication):\n operators = auth.get('groups', {}).get('operators', None)\n if operators is not None and event.principal in operators.principals:\n principals = list(operators.principals)\n principals.remove(event.principal)\n operators.principals = tuple(principals)\n\n return","sub_path":"pycfiles/ztfy.blog-0.6.2-py2.7/security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"286074100","text":"# <>\n# Copyright 2022, Lawrence Livermore National Security, LLC.\n# See the top-level COPYRIGHT file for details.\n# \n# SPDX-License-Identifier: BSD-3-Clause\n# <>\n\n\"\"\"Uncorrelated double differential distribution classes.\"\"\"\n\nimport math\nfrom fudge.core.math import fudgemath\n\nfrom PoPs import IDs as IDsPoPsModule\n\nfrom LUPY import ancestry as ancestryModule\n\nfrom xData import enums as xDataEnumsModule\nfrom xData import values as valuesModule\n\nfrom . import angular as angularModule\nfrom . import energy as energyModule\nfrom . import energyAngular as energyAngularModule\nfrom . import angularEnergy as angularEnergyModule\n\nfrom . import base as baseModule\nfrom . import miscellaneous as miscellaneousModule\n\n\nclass Subform( ancestryModule.AncestryIO ) :\n\n ancestryMembers = ( 'data', )\n\n def __init__( self, data, dataSubform ) :\n\n ancestryModule.AncestryIO.__init__( self )\n\n if( not isinstance( data, dataSubform ) ) : raise TypeError( \"Needed %s distribution subform\" % self.moniker )\n self.data = data\n self.data.setAncestor( self )\n\n @property\n def productFrame( self ) :\n\n return( self.ancestor.productFrame )\n\n def convertUnits( self, unitMap ) :\n \"See documentation for reactionSuite.convertUnits.\"\n\n self.data.convertUnits( unitMap )\n\n def copy( self ) :\n\n return self.__class__(self.data.copy())\n\n def fixDomains(self, energyMin, energyMax, domainsToFix):\n \"\"\"\n Calls the *fixDomains* method on the *data* member.\n \"\"\"\n\n return self.data.fixDomains(energyMin, energyMax, domainsToFix)\n\n def toXML_strList( self, indent = '', **kwargs ) :\n\n indent2 = indent + kwargs.get( 'incrementalIndent', ' ' )\n\n xmlStringList = [ \"%s<%s>\" % ( indent, self.moniker ) ]\n xmlStringList += self.data.toXML_strList( indent2, **kwargs )\n xmlStringList[-1] += \"\" % self.moniker\n return( xmlStringList )\n\n def to_xs_pdf_cdf1d( self, style, tempInfo, indent ) :\n\n data = self.data.to_xs_pdf_cdf1d( style, tempInfo, indent )\n if( data is None ) : return( None )\n return self.__class__(data)\n\n def findEntity(self, entityName, attribute=None, value=None):\n \"\"\"\n Override ancestry.findEntity for angularSubform and energySubform\n \"\"\"\n\n if self.data.moniker == entityName:\n return self.data\n return ancestryModule.Ancestry.findEntity(self, entityName, attribute, value)\n\n @classmethod\n def parseNodeUsingClass(cls, element, xPath, linkData, **kwargs):\n\n pass\n\nclass AngularSubform( Subform ) :\n\n moniker = 'angular'\n\n def __init__( self, data ) :\n\n Subform.__init__( self, data, angularModule.Subform )\n\nclass EnergySubform( Subform ) :\n\n moniker = 'energy'\n\n def __init__( self, data ) :\n\n Subform.__init__( self, data, energyModule.Subform )\n\nclass Form( baseModule.Form ) :\n \"\"\"\n Contains uncorrelated distributions for outgoing angle and outgoing energy. Use when the correlations\n between angle and energy are unknown.\n \"\"\"\n\n moniker = 'uncorrelated'\n subformAttributes = ( 'angularSubform', 'energySubform' )\n ancestryMembers = subformAttributes\n\n def __init__( self, label, productFrame, _angularSubform, _energySubform ) :\n\n if( not isinstance( _angularSubform, AngularSubform ) ) : raise TypeError( \"Needed angular distribution subform, got %s\" %str(_angularSubform.__class__) )\n if( not isinstance( _energySubform, EnergySubform ) ) : raise TypeError( \"Needed energy distribution subform, got %s\" % str(_energySubform.__class__) )\n\n baseModule.Form.__init__( self, label, productFrame, ( _angularSubform, _energySubform ) )\n\n @property\n def domainUnit( self ) :\n\n return( self.angularSubform.data.domainUnit )\n\n def calculateAverageProductData( self, style, indent = '', **kwargs ) :\n\n if( isinstance( self.angularSubform.data, angularModule.Regions2d ) ) :\n raise Exception( 'Regions2d angular is currently not supported' )\n\n if( isinstance( self.energySubform.data, energyModule.Regions2d ) ) :\n aveEnergies = []\n aveMomenta = []\n EMax = kwargs['EMax']\n for i1, energySubform in enumerate( self.energySubform.data ) :\n kwargs['EMax'] = energySubform.domainMax\n if( i1 == ( len( self.energySubform.data ) - 1 ) ) : kwargs['EMax'] = EMax\n aveEnergy, aveMomentum = calculateAverageProductData( self.productFrame, self.angularSubform.data, energySubform,\n style, indent, **kwargs )\n aveEnergies.append( aveEnergy )\n aveMomenta.append( aveMomentum )\n kwargs['EMin'] = kwargs['EMax']\n return( aveEnergies, aveMomenta )\n\n aveEnergy, aveMomentum = calculateAverageProductData( self.productFrame, self.angularSubform.data, self.energySubform.data, style, indent, **kwargs )\n return( [ aveEnergy ], [ aveMomentum ] )\n\n def energySpectrumAtEnergy(self, energyIn, frame, **kwargs):\n '''\n Returns the energy spectrum at projectile energy *energyIn* in frame *frame*. Currently,\n if frame='lab' and the product is a photon then its data are treated as being in the lab frame.\n The domain of angular integration can be set with the muMin and muMax keys in *kwargs*. Default angular integration\n is from -1 to 1.\n '''\n\n class AngualarAtEnergyCOM:\n\n def __init__(self, angular):\n\n self.angular = angular\n\n def probabilityCOM(self, energyPrimeCOM, muCOM):\n\n return self.angular.evaluate(muCOM)\n\n muMin = kwargs.get('muMin', -1.0)\n muMax = kwargs.get('muMax', 1.0)\n\n if self.productFrame == frame:\n energySpectrum = self.energySubform.data.energySpectrumAtEnergy(energyIn)\n if muMin != -1.0 or muMax != 1.0:\n energySpectrum *= self.angularSubform.data.evaluate(energyIn).integrate(domainMin=muMin, domainMax=muMax)\n return energySpectrum\n\n if self.productFrame == xDataEnumsModule.Frame.lab:\n TypeError('Lab to center-of-mass translation not supported.')\n\n if self.product.pid != IDsPoPsModule.photon:\n energyProbabilityAtEnergy = self.energySubform.data.evaluate(energyIn)\n angularProbabilityAtEnergy = self.angularSubform.data.evaluate(energyIn)\n xys2d = miscellaneousModule.energyAngularSpectrumFromCOMSpectrumToLabAtEnergy(self, energyIn, energyProbabilityAtEnergy, \n AngualarAtEnergyCOM(angularProbabilityAtEnergy))\n data = [[xys1d.outerDomainValue, xys1d.integrate(domainMin=muMin, domainMax=muMax)] for xys1d in xys2d]\n return energyModule.XYs1d(data=data, axes=energyModule.defaultAxes(self.domainUnit))\n else: # Ignore centerOfMass corrections for photons, for now anyway.\n energySpectrum = self.energySubform.data.energySpectrumAtEnergy(energyIn)\n if muMin != -1.0 or muMax != 1.0:\n energySpectrum *= self.angularSubform.data.evaluate(energyIn).integrate(domainMin=muMin, domainMax=muMax)\n return energySpectrum\n\n def getSpectrumAtEnergy(self, energy):\n '''\n This method is deprecated, please use energySpectrumAtEnergy instead.\n Returns the energy spectrum for self at projectile energy in the lab frame.\n '''\n\n return self.energySpectrumAtEnergy(energy, xDataEnumsModule.Frame.lab)\n\n def findEntity( self, entityName, attribute = None, value = None ):\n \"\"\"\n Overrides ancestry.findEntity. uncorrelated contains both energy and angular form,\n need to check both to find desired entity\n \"\"\"\n\n if self.energySubform.moniker == entityName: return self.energySubform\n elif self.angularSubform.moniker == entityName: return self.angularSubform\n return ancestryModule.Ancestry.findEntity( self, entityName, attribute, value )\n\n def fixDomains(self, energyMin, energyMax, domainsToFix):\n \"\"\"\n Calls the *fixDomains* method on the *energy* and *angular* members.\n \"\"\"\n\n numberOfFixes = self.energySubform.fixDomains(energyMin, energyMax, domainsToFix)\n numberOfFixes += self.angularSubform.fixDomains(energyMin, energyMax, domainsToFix)\n\n return numberOfFixes\n\n def integrate( self, reaction_suite, energyIn, energyOut = None, muOut = None, phiOut = None, frame = xDataEnumsModule.Frame.product, LegendreOrder = 0 ) :\n\n angularEvaluate = 1.0\n angularData = self.angularSubform.data\n if( muOut is None ) :\n angularEvaluate = angularData.evaluate( energyIn ).LegendreCoefficient( LegendreOrder )\n else :\n angular1d = angularData.evaluate( energyIn )\n muMin, muMax = miscellaneousModule.domainLimits( muOut, angular1d.domainMin, angular1d.domainMax )\n try :\n if( muMax is None ) :\n angularEvaluate = angular1d.evaluate( muMin )\n else :\n angularEvaluate = angular1d.integrate( muMin, muMax )\n except :\n print( type( angularData ) )\n raise\n\n energyPartialIntegral = 0.0\n energyData = self.energySubform.data\n if( isinstance( energyData, ( energyModule.DiscreteGamma, energyModule.PrimaryGamma ) ) ) :\n energyPartialIntegral = energyData.integrate( energyIn, energyOut )\n else :\n energyData1d = energyData.evaluate( energyIn )\n energyOutMin, energyOutMax = miscellaneousModule.domainLimits( energyOut, energyData1d.domainMin, energyData1d.domainMax )\n if( energyOutMax is None ) :\n energyPartialIntegral = energyData1d.evaluate( energyOutMin )\n else :\n if( isinstance( energyData1d, energyModule.Regions1d ) ) :\n limits = { energyData1d.axes[1].label : ( energyOutMin, energyOutMax ) }\n energyPartialIntegral = energyData1d.integrate(**limits)\n else :\n energyPartialIntegral = energyData1d.integrate(energyOutMin, energyOutMax)\n\n phiEvaluate = miscellaneousModule.muPhiEvaluate( None, phiOut )\n\n return( phiEvaluate * angularEvaluate * energyPartialIntegral )\n\n def processMC_cdf( self, style, tempInfo, indent ) :\n\n _angularSubform = self.angularSubform.to_xs_pdf_cdf1d( style, tempInfo, indent )\n _energySubform = self.energySubform.to_xs_pdf_cdf1d( style, tempInfo, indent )\n if( ( _angularSubform is not None ) or ( _energySubform is not None ) ) :\n if( _angularSubform is None ) : _angularSubform = self.angularSubform.copy( )\n if( _energySubform is None ) : _energySubform = self.energySubform.copy( )\n _form = Form( style.label, self.productFrame, _angularSubform, _energySubform )\n else :\n _form = None\n return( _form )\n\n def processMultiGroup( self, style, tempInfo, indent ) :\n\n from fudge.processing import group as groupModule\n from fudge.processing.deterministic import transferMatrices as transferMatricesModule\n\n verbosity = tempInfo['verbosity']\n indent2 = indent + tempInfo['incrementalIndent']\n productLabel = tempInfo['productLabel']\n\n angularSubform = self.angularSubform.data\n energySubform = self.energySubform.data\n energyUnit = tempInfo['incidentEnergyUnit']\n massUnit = energyUnit + '/c**2'\n\n if( verbosity > 2 ) : print('%sGrouping %s' % (indent, self.moniker))\n\n crossSection = tempInfo['crossSection']\n product = tempInfo['product']\n if( isinstance( energySubform, energyModule.DiscreteGamma ) ) :\n if( product.pid == IDsPoPsModule.photon ) :\n Ep = float( energySubform.value )\n TM_1, TM_E = transferMatricesModule.discreteGammaAngularData( style, tempInfo, Ep, crossSection,\n angularSubform, multiplicity = product.multiplicity.evaluated,\n comment = tempInfo['transferMatrixComment'] + ' outgoing data for %s' % productLabel )\n else :\n raise Exception( 'See Bret' )\n else :\n if( isinstance( energySubform, energyModule.NBodyPhaseSpace ) ) :\n totalMass = energySubform.mass.getValueAs( massUnit )\n Q = tempInfo['reaction'].getQ( energyUnit, final = False )\n TM_1, TM_E = transferMatricesModule.NBodyPhaseSpace( style, tempInfo, crossSection, \n energySubform.numberOfProducts, totalMass, Q, tempInfo['multiplicity'], \n comment = tempInfo['transferMatrixComment'] + ' outgoing data for %s' % productLabel )\n else :\n TM_1, TM_E = transferMatricesModule.uncorrelated_EMuP_EEpP_TransferMatrix( style, tempInfo, crossSection, \n self.productFrame, angularSubform, energySubform, tempInfo['multiplicity'], \n comment = tempInfo['transferMatrixComment'] + ' outgoing data for %s' % productLabel )\n\n return( groupModule.TMs2Form( style, tempInfo, TM_1, TM_E ) )\n\n def spectrum( self, frame, **kwargs ) :\n\n if( frame == self.productFrame ) : return( self.toPointwise_withLinearXYs( **kwargs ) )\n\n if frame == xDataEnumsModule.Frame.centerOfMass:\n raise Exception( 'Conversion of distribution from %s to %s not supported' % ( self.productFrame, frame ) )\n\n energiesIn = self.angularSubform.data.domainGrid + self.energySubform.data.domainGrid\n energiesIn = valuesModule.Values.sortAndThin( energiesIn, rel_tol = 1e-12 )\n xys3d = energyAngularModule.XYs3d( axes = energyAngularModule.defaultAxes( self.domainUnit ) )\n for energy in energiesIn : xys3d.append( self.spectrumAtEnergy( energy, frame ) )\n\n return( xys3d )\n\n def spectrumAtEnergy( self, energyIn, frame ) :\n\n class AngualarAtEnergyCOM :\n\n def __init__( self, angular ) :\n\n self.angular = angular\n\n def probabilityCOM( self, energyPrimeCOM, muCOM ) :\n\n return( self.angular.evaluate( muCOM ) )\n\n angularSubform = self.angularSubform.data.toPointwise_withLinearXYs( )\n angularProbability = angularSubform.getAtEnergy( energyIn ) # FIXME why doesn't getSpectrumAtEnergy work here?\n\n energySubform = self.energySubform.data.toPointwise_withLinearXYs( )\n energyProbability = energySubform.getSpectrumAtEnergy( energyIn )\n\n if( frame == self.productFrame ) :\n probability = energyAngularModule.XYs2d( outerDomainValue = energyIn )\n for energyOut, P in energyProbability :\n efp = energyAngularModule.XYs1d( P * angularProbability, outerDomainValue = energyOut )\n probability.append( efp )\n\n return( probability )\n\n if frame == xDataEnumsModule.Frame.centerOfMass:\n raise Exception( 'Conversion of distribution from %s to %s not supported' % ( self.productFrame, frame ) )\n\n return( miscellaneousModule.energyAngularSpectrumFromCOMSpectrumToLabAtEnergy( self, energyIn, energyProbability, AngualarAtEnergyCOM( angularProbability ) ) )\n\n def toPointwise_withLinearXYs( self, **kwargs ) :\n\n angularSubform = self.angularSubform.data.toPointwise_withLinearXYs( **kwargs )\n energySubform = self.energySubform.data.toPointwise_withLinearXYs( **kwargs )\n grid = angularSubform.domainGrid\n for e in energySubform.domainGrid :\n if( e not in grid ) : grid.append( e )\n grid.sort( )\n axes = angularEnergyModule.defaultAxes( energyUnit = energySubform.axes[-1].unit )\n f_E_mu_Ep = angularEnergyModule.XYs3d( axes = axes )\n for e in grid :\n f_mu_Ep = angularEnergyModule.XYs2d( outerDomainValue = e )\n af = angularSubform.getAtEnergy( e ) # FIXME why doesn't getSpectrumAtEnergy work here?\n ef = energySubform.getSpectrumAtEnergy( e )\n for mu, P in af :\n efp = P * ef\n efp.__class__ = angularEnergyModule.XYs1d # FIXME better way to assign class?\n efp.outerDomainValue = mu\n f_mu_Ep.append( efp )\n f_E_mu_Ep.append( f_mu_Ep )\n return( f_E_mu_Ep )\n\n def toXML_strList( self, indent = '', **kwargs ) :\n\n indent2 = indent + kwargs.get( 'incrementalIndent', ' ' )\n\n attributeStr = ''\n if( self.label is not None ) : attributeStr += ' label=\"%s\"' % self.label\n if( self.productFrame is not None ) : attributeStr += ' productFrame=\"%s\"' % self.productFrame\n xmlString = [ '%s<%s%s>' % ( indent, self.moniker, attributeStr ) ]\n\n xmlString += self.angularSubform.toXML_strList( indent2, **kwargs )\n xmlString += self.energySubform.toXML_strList( indent2, **kwargs )\n xmlString[-1] += '' % self.moniker\n\n return( xmlString )\n\n @classmethod\n def parseNodeUsingClass(cls, element, xPath, linkData, **kwargs):\n \"\"\"Translate element from xml. Must contain one and one component.\"\"\"\n \n xPath.append( element.tag )\n for child in element :\n if( child.tag == angularModule.Form.moniker ) :\n _angularSubform = AngularSubform(angularModule.Form.parseNodeUsingClass(child[0], xPath, linkData, **kwargs))\n elif( child.tag == energyModule.Form.moniker ) :\n _energySubform = EnergySubform(energyModule.Form.parseNodeUsingClass(child[0], xPath, linkData, **kwargs))\n else :\n raise ValueError( 'unsupported tag = \"%s\"' % child.tag )\n uncorrelated = cls( element.get( 'label' ), element.get( 'productFrame' ), _angularSubform, _energySubform )\n xPath.pop( )\n return( uncorrelated )\n\ndef calculateAverageProductData( productFrame, angularSubform, energySubform, style, indent, **kwargs ) :\n\n def fixLimits( EMin, EMax, Es ) :\n\n if( EMin not in Es ) : Es.append( EMin )\n if( EMax not in Es ) : Es.append( EMax )\n Es.sort( )\n while( Es[0] < EMin ) : del Es[0]\n while( Es[-1] > EMax ) : del Es[-1]\n return( valuesModule.Values.sortAndThin( Es, 1e-6 ) )\n\n def calculateAverageEnergy( self, Ein ) :\n\n averageEp = self.energySubform.averageEp( Ein )\n if self.productFrame == xDataEnumsModule.Frame.centerOfMass:\n A_Ein = self.massRatio * Ein\n if( not( self.angularSubform.isIsotropic( ) ) ) : averageEp += 2 * math.sqrt( A_Ein * averageEp ) * self.angularSubform.averageMu( Ein )\n averageEp += A_Ein\n averageEp *= self.multiplicity.evaluate( Ein )\n return( averageEp )\n\n def calculateAverageMomentum( self, Ein ) :\n\n pp, averageMu = 0., self.angularSubform.averageMu( Ein )\n if( averageMu != 0. ) : pp = energySubform.sqrtEp_AverageAtE( Ein ) * averageMu\n if self.productFrame == xDataEnumsModule.Frame.centerOfMass:\n pp += math.sqrt( self.massRatio * Ein )\n return( multiplicity.evaluate( Ein ) * math.sqrt( 2. * self.productMass ) * pp )\n\n def calculateAverageMomentumForPhoton( self, Ein ) :\n\n muAverage = angularSubform.averageMu( Ein )\n if( muAverage == 0. ) : return( 0. )\n return( multiplicity.evaluate( Ein ) * energySubform.averageEp( Ein ) * muAverage )\n\n class CalculateDepositionInfo :\n\n def __init__( self, productFrame, productMass, massRatio, angularSubform, energySubform, multiplicity ) :\n\n self.productFrame = productFrame\n self.productMass = productMass\n self.massRatio = massRatio\n self.angularSubform = angularSubform\n self.energySubform = energySubform\n self.multiplicity = multiplicity\n\n def evaluateAtX( self, E ) :\n\n return( self._evaluateAtX( self, E ) )\n\n def setEvaluateAtX( self, evaluateAtX ) :\n\n self._evaluateAtX = evaluateAtX\n\n def setTolerances( self, relativeTolerance, absoluteTolerance ) :\n\n self.relativeTolerance = relativeTolerance\n self.absoluteTolerance = absoluteTolerance\n\n class NBodyPhaseSpace :\n\n def __init__( self, energySubform, massUnit, projectileMass, targetMass, productMass, Q ) :\n\n self.energySubform = energySubform\n self.massUnit = massUnit\n self.projectileMass = projectileMass\n self.targetMass = targetMass\n self.productMass = productMass\n self.Q = Q\n\n def averageEp( self, Ein ) :\n\n return( self.energySubform.averageEp( Ein, self.massUnit, self.projectileMass, self.targetMass, self.productMass, self.Q ) )\n\n def getEnergyArray( self, EMin = None, EMax = None ) :\n\n return( [ EMin, EMax ] )\n\n energyUnit = kwargs['incidentEnergyUnit']\n massUnit = kwargs['massUnit']\n multiplicity = kwargs['multiplicity'] # BRB - FIXME; Handle gamma data with 1 point for multiplicity weight until it is fixed.\n energyAccuracy = kwargs['energyAccuracy']\n momentumAccuracy = kwargs['momentumAccuracy']\n projectileMass = kwargs['projectileMass']\n targetMass = kwargs['targetMass']\n product = kwargs['product']\n productMass = kwargs['productMass']\n\n EMin = kwargs['EMin']\n EMax = kwargs['EMax']\n\n if( product.pid == IDsPoPsModule.photon ) : productFrame = xDataEnumsModule.Frame.lab # All gamma data treated as in lab frame.\n if( isinstance( energySubform, energyModule.NBodyPhaseSpace ) ) :\n Q = kwargs['reaction'].getQ( energyUnit, final = False )\n energySubform = NBodyPhaseSpace( energySubform, massUnit, projectileMass, targetMass, productMass, Q )\n\n if( kwargs['isInfiniteTargetMass'] ) :\n aveEnergy = [ [ functional1d.outerDomainValue, functional1d.integrateWithWeight_x( ) ] for functional1d in energySubform ]\n else :\n Es = energySubform.getEnergyArray( )\n if( Es[0] is None ) : Es[0] = EMin\n if( Es[-1] is None ) : Es[-1] = EMax\n if( EMin < Es[0] ) : EMin = Es[0]\n if( EMax > Es[-1] ) : EMax = Es[-1]\n Es = sorted( set( energySubform.getEnergyArray( EMin, EMax ) + multiplicity.domainGrid ) )\n Es = fixLimits( EMin, EMax, Es )\n massRatio = projectileMass * productMass / ( projectileMass + targetMass )**2\n calculationData = CalculateDepositionInfo( productFrame, productMass, massRatio, angularSubform, energySubform, multiplicity )\n calculationData.setEvaluateAtX( calculateAverageEnergy )\n aveEnergy = [ [ E, calculationData.evaluateAtX( E ) ] for E in Es ]\n absoluteTolerance = 1e-3 * energyAccuracy * max( [ Ep for E, Ep in aveEnergy ] )\n calculationData.setTolerances( energyAccuracy, absoluteTolerance )\n aveEnergy = fudgemath.thickenXYList( aveEnergy, calculationData )\n\n if isinstance(angularSubform, angularModule.Isotropic2d) and productFrame == xDataEnumsModule.Frame.lab:\n aveMomentum = [ [ aveEnergy[0][0], 0. ], [ aveEnergy[-1][0], 0. ] ]\n else :\n if( product.pid == IDsPoPsModule.photon ) :\n calculationData.setEvaluateAtX( calculateAverageMomentumForPhoton )\n else :\n calculationData.setEvaluateAtX( calculateAverageMomentum )\n Es = sorted( set( Es + angularSubform.getEnergyArray( EMin, EMax ) ) )\n Es = fixLimits( EMin, EMax, Es )\n aveMomentum = [ [ E, calculationData.evaluateAtX( E ) ] for E in Es ]\n absoluteTolerance = 1e-3 * momentumAccuracy * max( [ pp for E, pp in aveMomentum ] )\n calculationData.setTolerances( momentumAccuracy, absoluteTolerance )\n aveMomentum = fudgemath.thickenXYList( aveMomentum, calculationData )\n\n return( aveEnergy, aveMomentum )\n","sub_path":"fudge/productData/distributions/uncorrelated.py","file_name":"uncorrelated.py","file_ext":"py","file_size_in_byte":24030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"193485523","text":"import discord, datetime, time\nimport json\nimport os\nfrom discord.ext import commands, tasks\nfrom itertools import cycle\nimport asyncio\nimport datetime as DT\nimport requests\nfrom dotenv import load_dotenv\n\nload_dotenv()\ntoken = os.getenv('BOT_TOKEN')\nstart_time = time.time()\ntime_date_now = DT.datetime.now().strftime('Date: %d-%m-%Y\\nTime: %H:%M:%S')\n\ndef get_prefix(client, message):\n with open('prefixes.json', 'r') as f:\n prefixes = json.load(f)\n\n return prefixes[str(message.guild.id)]\n\n\"\"\"\nLink to youtube tutorials; https://www.youtube.com/channel/UCR-zOCvDCayyYy1flR5qaAg\nLink to discord.py doc; https://discordpy.readthedocs.io/en/latest/index.html\nLink to discord dev portal; https://discordapp.com/developers/applications\nLink to learn more python; https://realpython.com/\n\"\"\"\n\n\"\"\"\nDefault prefix is '*'\n\"\"\"\nclient = commands.Bot(command_prefix = get_prefix)\nclient.remove_command('help')\nversion = '0.0.4'\n\n@client.event\nasync def on_ready():\n change_status.start()\n print('/-/-/-/-/-/-/-/-/-/-/-/-/-/')\n print(time_date_now)\n print('Created by #OrionAF#6983')\n print(f'Running on version: {version}')\n print('Bot is ready to RUMBLE!')\n print('---------------------------')\n\n@client.event\nasync def on_guild_join(guild):\n with open('prefixes.json', 'r') as f:\n prefixes = json.load(f)\n\n prefixes[str(guild.id)] = '*'\n\n with open('prefixes.json', 'w') as f:\n json.dump(prefixes, f, indent=4)\n\n@client.event\nasync def on_guild_remove(guild):\n with open('prefixes.json', 'r') as f:\n prefixes = json.load(f)\n\n prefixes.pop(str(guild.id))\n\n with open('prefixes.json', 'w') as f:\n json.dump(prefixes, f, indent=4)\n\n@tasks.loop(seconds=30)\nasync def change_status():\n time_date_now = DT.datetime.now().strftime('Date: %d-%m-%Y\\nTime: %H:%M:%S')\n await client.change_presence(activity=discord.Game(f'Ping: {round(client.latency * 1000)}ms'))\n time_date_now = DT.datetime.now().strftime('Date: %d-%m-%Y\\nTime: %H:%M:%S')\n print(time_date_now)\n print(f'Ping: {round(client.latency * 1000)}ms\\n---------------------------')\n\n@client.command()\nasync def load(ctx, extension):\n client.load_extension(f'cogs.{extension}')\n await ctx.send(f'The extension ``{extension}`` has been loaded successfully.')\n\n@client.command()\nasync def unload(ctx, extension):\n client.unload_extension(f'cogs.{extension}')\n await ctx.send(f'The extension ``{extension}`` has been unloaded successfully.')\n\n@client.command()\nasync def reload(ctx, extension):\n client.unload_extension(f'cogs.{extension}')\n client.load_extension(f'cogs.{extension}')\n await ctx.send(f'The extension ``{extension}`` has been reloaded successfully.')\n\nfor filename in os.listdir('./cogs'):\n if filename.endswith('.py'):\n client.load_extension(f'cogs.{filename[:-3]}')\n\n\ndef owner(ctx):\n return ctx.author.id == 221070014252449792\n\n@client.command()\n@commands.check(owner)\nasync def shutdown(ctx):\n print('Bot has been shutdown successfully.')\n current_time = time.time()\n difference = int(round(current_time - start_time))\n text = str(datetime.timedelta(seconds=difference))\n embed = discord.Embed(colour=discord.Colour(1080748), description=f'{ctx.author.mention} told me to go to sleep. **Apparently** bots need to sleep as well.\\n Oh well, nap time.')\n embed.add_field(name=\"Uptime before shutdown: \", value=text)\n try:\n await ctx.send(embed=embed)\n except discord.HTTPException:\n await ctx.send(\"Uptime before shutdown: \")\n await ctx.bot.close()\n\n@client.command(aliases=['prefix'])\nasync def changeprefix(ctx, prefix):\n with open('prefixes.json', 'r') as f:\n prefixes = json.load(f)\n\n prefixes[str(ctx.guild.id)] = prefix\n\n with open('prefixes.json', 'w') as f:\n json.dump(prefixes, f, indent=4)\n await ctx.send(f'My prefix has been changed to: ``{prefix}``')\n\n#@client.event\n#async def on_command_error(ctx, error):\n# if isinstance(error, commands.CommandNotFound):\n# await ctx.send(f'That is an invalid command.')\n\nclient.run(token)\n","sub_path":"tutorial/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"99104733","text":"# Write a program that sums a series of (positive) integers entered by the user,\n# excluding all numbers that are greater than 100.\n\n# Author: Enes Kemal Ergin\n\nn = 0\ntotal = 0\nwhile n < 5:\n inp_num = int(input(\"Enter integer: \"))\n n += 1\n if 0 < inp_num <= 100:\n total = total + inp_num\n else:\n continue\n\nprint(\"The total of 5 numbers is: \", inp_num)\n","sub_path":"exercise_scripts/Enes/4_P_3.py","file_name":"4_P_3.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"123376592","text":"# __author__ = 'tusharmakkar08'\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport warnings\n\nfrom models import base_network\nfrom models.rate_card import RateCard\nfrom services import constants as const\n\nwarnings.filterwarnings(\"ignore\")\n\n\nclass InitNetwork:\n def __init__(self, logger):\n self.logger = logger\n self.nodes = const.LOCS\n self.zones = list(const.Zone.__members__)\n self.nodes_to_zones_dict = const.NODE_TO_ZONE_DICT\n self.mode_rate_dict = {\n const.TravelMode.TUBE.name: const.TUBE_JOURNEY_ZONE_RATES,\n const.TravelMode.BUS.name: const.BUS_JOURNEY_ZONE_RATES\n }\n\n @staticmethod\n def _set_network_edges(network, rate_card):\n network.add_edges(rate_card)\n return network\n\n @staticmethod\n def _draw_graph(network):\n nx.draw_networkx_edge_labels(network.get_graph(), nx.spring_layout(network.get_graph()),\n edge_labels=nx.get_edge_attributes(network.get_graph(), 'weight'))\n nx.draw_networkx(network.get_graph(), with_labels=True)\n plt.show()\n\n def _set_rate_card(self, rc_obj, mode):\n [rc_obj.set_rate(src_z, dst_z, self.mode_rate_dict[mode][(const.Zone[src_z].value, const.Zone[dst_z].value)])\n for dst_z in self.zones for src_z in self.zones]\n return rc_obj\n\n def _set_zones(self, network):\n [node.set_zones(self.nodes_to_zones_dict[node.name]) for node in network.get_graph().nodes()]\n return network\n\n def _set_network_nodes(self, network):\n network.add_nodes(self.nodes)\n return self._set_zones(network)\n\n def _init_network(self, mode, draw_network):\n rate_card = RateCard()\n rate_card = self._set_rate_card(rate_card, mode)\n base_network_ = base_network.BaseNetwork(mode)\n base_network_ = self._set_network_nodes(base_network_)\n self._set_network_edges(base_network_, rate_card)\n if draw_network:\n self._draw_graph(base_network_)\n return base_network_\n\n def init_bus_and_tube_network(self, draw_network):\n bus_network_ = self._init_network(const.TravelMode.BUS.name, draw_network)\n tube_network_ = self._init_network(const.TravelMode.TUBE.name, draw_network)\n return bus_network_, tube_network_\n","sub_path":"services/init_network.py","file_name":"init_network.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"459093203","text":"# Imports\nfrom linesearch import LineSearch, default\nfrom _problems.problems2d import Rosenbrock\n\n\n# BFGS\nbfgs_options = default\nbfgs_options[\"direction\"][\"method\"] = \"quasi\"\nbfgs_options[\"direction\"][\"quasi\"][\"method\"] = \"bfgs\"\nbfgs_options[\"initial\"][\"method\"] = \"quadratic\"\nbfgs_options[\"bracket\"][\"method\"] = \"constant-factor\"\nbfgs_options[\"select\"][\"method\"] = \"bisection\"\nbfgs_options[\"terminate-inexact\"][\"method\"] = \"strong-wolfe\"\n\n# DFP\ndfp_options = default\ndfp_options[\"direction\"][\"method\"] = \"quasi\"\ndfp_options[\"direction\"][\"quasi\"][\"method\"] = \"dfp\"\ndfp_options[\"initial\"][\"method\"] = \"quadratic\"\ndfp_options[\"bracket\"][\"method\"] = \"constant-factor\"\ndfp_options[\"select\"][\"method\"] = \"bisection\"\ndfp_options[\"terminate-inexact\"][\"method\"] = \"strong-wolfe\"\n\n# Broyden\nbroyden_options = default\nbroyden_options[\"direction\"][\"method\"] = \"quasi\"\nbroyden_options[\"direction\"][\"quasi\"][\"method\"] = \"broyden\"\nbroyden_options[\"initial\"][\"method\"] = \"quadratic\"\nbroyden_options[\"bracket\"][\"method\"] = \"constant-factor\"\nbroyden_options[\"select\"][\"method\"] = \"bisection\"\nbroyden_options[\"terminate-inexact\"][\"method\"] = \"strong-wolfe\"\n\n# SR1\nsr1_options = default\nsr1_options[\"direction\"][\"method\"] = \"quasi\"\nsr1_options[\"direction\"][\"quasi\"][\"method\"] = \"sr1\"\nsr1_options[\"initial\"][\"method\"] = \"quadratic\"\nsr1_options[\"bracket\"][\"method\"] = \"constant-factor\"\nsr1_options[\"select\"][\"method\"] = \"bisection\"\nsr1_options[\"terminate-inexact\"][\"method\"] = \"strong-wolfe\"","sub_path":"linesearch/algorithms/quasi_newton.py","file_name":"quasi_newton.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"34066416","text":"# SCORING OF CHROMOSOMES\n\nfrom answer import get_answer\n\ndef get_score(chrom):\n key = get_answer()\n # TODO: implement the scoring function\n # * compare the chromosome with the solution (how many character are in the correct position?)\n score = 0\n counter = 0\n for i in key:\n if key[counter] == chrom[counter]:\n score += 1\n counter += 1\n return (score/20)\n\n\n# CHROMOSOME SELECTION\n\nimport random\nfrom answer import get_score\n \ndef score(chrom):\n # floating number between 0 and 1. The better the chromosome, the closer to 1\n # We coded the get_score(chrom) in the previous exercise\n return get_score(chrom)\n \ndef selection(chromosomes_list):\n GRADED_RETAIN_PERCENT = 0.3 # percentage of retained best fitting individuals\n NONGRADED_RETAIN_PERCENT = 0.2 # percentage of retained remaining individuals (randomly selected)\n # TODO: implement the selection function\n # * Sort individuals by their fitting score\n # * Select the best individuals\n # * Randomly select other individuals\n \n selection = []\n \n scores = list(map(lambda c: [score(c), c], chromosomes_list))\n \n scores.sort(reverse = True, key = lambda s: s[0])\n \n g_retain = int(len(scores) * 0.3)\n \n while g_retain > 0:\n toSelect = scores.pop(0)\n selection.append(toSelect)\n g_retain -= 1\n \n \n ng_retain = int(len(scores) * 0.2)\n print(ng_retain)\n \n while ng_retain > 0:\n rand_int = random.randint(0, len(scores)-1)\n selection.append(scores.pop(rand_int))\n ng_retain -= 1\n \n selected_c = list(map(lambda list: list[1], selection))\n print(selected_c)\n \n return selected_c\n\n\n# Chromosone Crossover\n\ndef crossover(parent1, parent2):\n # TODO: implement the crossover function\n # * Select half of the parent genetic material\n # * child = half_parent1 + half_parent2\n # * Return the new chromosome\n # * Genes should not be moved\n \n half_len_p1 = int(len(parent1) / 2)\n half_len_p2 = int(len(parent2) / 2)\n \n half_p1 = parent1[:half_len_p1]\n half_p2 = parent2[half_len_p2:]\n \n child = half_p1 + half_p2\n print(child)\n \n return child\n\n\n# Mutation\n\nimport random\nfrom answer import alphabet\n\ndef get_letter():\n return random.choice(alphabet)\n \ndef mutation(chrom):\n # TODO: implement the mutation function\n # * Random gene mutation : a character is replaced\n \n c_len = len(chrom)\n \n index = random.randint(0,c_len-1)\n \n chrom = chrom[:index] + get_letter() + chrom[index+1:]\n \n return chrom","sub_path":"genetic_algorithms.py","file_name":"genetic_algorithms.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"232234640","text":"def run():\n import numpy as np\n import pandas as pd\n import seaborn\n import matplotlib.pyplot as pyplot\n import seaborn as sns\n from sklearn.model_selection import train_test_split\n from sklearn.ensemble import GradientBoostingClassifier\n from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_curve, roc_auc_score\n\n df = pd.read_table(\"./data/australian.csv\", sep='\\s+', header=None)\n y = df[14]\n X = df.drop(columns = 14)\n y.value_counts()\n # Split features and target into train and test sets\n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y, test_size = 0.4)\n # Instantiate and fit the GradientBoostingClassifier\n reg = GradientBoostingClassifier()\n reg.fit(X_train, y_train)\n # Make predictions for the test set\n y_pred_test = reg.predict(X_test)\n\n\n # View accuracy score\n \n print(classification_report(y_test, y_pred_test))\n\n gbdt_probs = reg.predict_proba(X_test)\n # keep probabilities for the positive outcome only\n gbdt_probs = gbdt_probs[:, 1]\n # calculate scores\n gbdt_auc = roc_auc_score(y_test, gbdt_probs)\n # summarize scores\n print('GBDT: ROC AUC=%.3f' % (gbdt_auc))\n print(\"accuracy_score is %.3f\" % (accuracy_score(y_test, y_pred_test, normalize=True)))\n # calculate roc curves\n gbdt_fpr, gbdt_tpr, _ = roc_curve(y_test, gbdt_probs)\n # plot the roc curve for the model\n pyplot.plot(gbdt_fpr, gbdt_tpr, marker='.', label='gbdt')\n # axis labels\n pyplot.xlabel('False Positive Rate')\n pyplot.ylabel('True Positive Rate')\n # show the legend\n pyplot.legend()\n # show the plot\n pyplot.show()\n","sub_path":"scripts/gbdt.py","file_name":"gbdt.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"55461368","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nTESTS = ['plotting']\nh5DataPath = \"sample_data/testData.h5\"\ntifDataPath = \"sample_data/testData.tif\"\n\n#------------ tools.readWrite module Demos\nif 'readWrite' in TESTS:\n readWrite_TESTS = ['loadData']\n\n from tools import readWrite as rw\n\n if 'loadData' in readWrite_TESTS:\n # loadData(outputFilename, frames=None, ycrop=None, xcrop=None, transpose=False, datatype=np.float64):\n yroi = [175,250]\n xroi = [100,150]\n hdfData1 = rw.loadData(h5DataPath, frames=[0,16], ycrop=yroi, xcrop=xroi)\n hdfData2 = rw.loadData(tifDataPath, datatype=np.float32)\n\n if 'mkGif' in readWrite_TESTS:\n # mkGif(data, begin=0, end=-1, delay=25, **kwargs):\n from matplotlib.pyplot import cm\n rw.mkGif(hdfData1, \"sample.gif\", begin=3, end=25, delay=30, cmap=cm.Greys_r)\n\n#------------ tools.plotting module Demos\nif 'plotting' in TESTS:\n plotting_TESTS = ['roiSelector']\n\n from tools.readWrite import loadData\n data = loadData(h5DataPath)\n\n from tools import plotting\n\n if 'roiSelector' in plotting_TESTS:\n plotting.roiSelector(data)\n\n#------------ tools.misc module Demos\nif 'misc' in TESTS:\n\n from tools import misc\n","sub_path":"tools/toolsDemo.py","file_name":"toolsDemo.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"256204052","text":"import cv2\nimport threading\nimport numpy as np\nimport configparser\nfrom gpiozero import Motor\nimport time\nimport math\n\nclass camThread(threading.Thread):\n def __init__(self, previewName, camID):\n threading.Thread.__init__(self)\n self.previewName = previewName\n self.camID = camID\n def run(self):\n print(\"Starting \" + self.previewName)\n camPreview(self.previewName, self.camID)\n\ndef camPreview(previewName, camID):\n cap = cv2.VideoCapture(camID)\n config = configparser.ConfigParser()\n config.read('test.ini')\n motor1 = Motor(20, 21)\n motor2 = Motor(19, 26)\n print(\"running\")\n\n while True:\n time.sleep(0.005)\n ret, img = cap.read()\n status_val = config.get('section_a', 'status_val')\n canny_min = config.getint('section_a', 'canny_min')\n canny_max = config.getint('section_a', 'canny_max')\n rho = config.getfloat('section_a', 'rho')\n l_threshold = config.getint('section_a', 'l_threshold')\n min_line_length = config.getint('section_a', 'min_line_length')\n max_line_gap = config.getint('section_a', 'max_line_gap')\n\n if status_val == \"test\":\n start_time = time.time()\n\n while ret == False:\n time.sleep(1)\n\n if status_val == \"test\":\n print(\"kamera baglantisi kopuk..\")\n cv2.destroyWindow(previewName)\n\n if camID == cam0:\n motor1.stop()\n elif camID == cam1:\n motor2.stop()\n\n cap = cv2.VideoCapture(camID)\n ret, img = cap.read()\n\n\n if ret:\n x_crop = img.shape[1] / 2\n img = img[0:int(img.shape[0]),\n int(x_crop - 50):int(x_crop + 50)] # crop_img = img[y:y+h, x:x+w] y->dikey, x->yatay\n\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, ksize=(3, 3), sigmaX=0)\n edged = cv2.Canny(blur, canny_min,canny_max) # Perform Edge detection\n\n rho = rho # distance resolution in pixels of the Hough grid\n theta = np.pi / 180 # angular resolution in radians of the Hough grid\n threshold = l_threshold # minimum number of votes (intersections in Hough grid cell)\n min_line_length = min_line_length # minimum number of pixels making up a line\n max_line_gap = max_line_gap # maximum gap in pixels between connectable line segments\n line_image = np.copy(img) * 0 # creating a blank to draw lines on\n\n # Run Hough on edge detected image\n # Output \"lines\" is an array containing endpoints of detected line segments\n lines = cv2.HoughLinesP(edged, rho, theta, threshold, np.array([]),\n min_line_length, max_line_gap)\n\n i = 0\n y_values = 0\n if lines is not None:\n for line in lines:\n for x1, y1, x2, y2 in line:\n slope = (y2 - y1) / (x2 - x1) # <-- Calculating the slope.\n if math.fabs(slope) < 0.2:\n cv2.line(line_image, (x1, y1), (x2, y2), (0, 0, 255), 3)\n i = i + 1\n y_values = y_values + y1 + y2\n i = i * 2\n if i != 0:\n y_median = y_values / i\n else:\n y_median = img.shape[0] / 2\n\n\n lines_edges = cv2.addWeighted(img, 0.8, line_image, 1, 0)\n\n h_value = lines_edges.shape[0]\n w_value = lines_edges.shape[1]\n h_value = h_value / 2\n\n if status_val == \"test\":\n lines_edges = cv2.line(lines_edges, (0, int(h_value)), (w_value, int(h_value)), (0, 255, 0), 3)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n cv2.imshow('Resized Window', lines_edges)\n\n else:\n cv2.destroyAllWindows()\n\n h_median_alt = h_value - 5\n h_median_ust = h_value + 5\n\n if y_median < h_median_alt:\n if status_val == \"test\":\n print(\"{} down\".format(camID))\n else:\n if camID == cam0:\n motor1.forward()\n elif camID == cam1:\n motor2.forward()\n elif y_median > h_median_ust:\n if status_val == \"test\":\n print(\"{} up\".format(camID))\n else:\n if camID == cam0:\n motor1.backward()\n elif camID == cam1:\n motor2.backward()\n else:\n if status_val == \"test\":\n print(\"{} middle\".format(camID))\n else:\n if camID == cam0:\n motor1.stop()\n elif camID == cam1:\n motor2.stop()\n\n if status_val == \"test\":\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Create threads as follows\n\n\ncam0 = 0\ncam1 = 1\nthread1 = camThread(\"Camera 1\", cam0)\nthread2 = camThread(\"Camera 2\", cam1)\n\nthread1.start()\nthread2.start()\nprint()\nprint(\"Active threads\", threading.activeCount())\n","sub_path":"poset8.py","file_name":"poset8.py","file_ext":"py","file_size_in_byte":5304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"243159852","text":"# Login messages.\nusernames = ['admin', 'mike', 'jon', 'mellisa', 'jane']\nusers = ['Mike']\n\nfor user in users:\n\tif user == 'admin':\n\t\tprint('Hello Admin, would you like to see a status report?')\n\telif user.lower() in usernames:\n\t\tprint(f\"Welcome back to work {user.title()}. Have a good day!\")\n\telse:\n\t\tprint(\"You are not an authorized user. Locking Building Down Now!\")\nif (usernames == []) and (users == []):\n\tprint(\"We need some users!\")\n\n# Checking user names against current list before they can create.\ncurrent_users = ['jon', 'mike', 'mellisa', 'jane', 'neil']\nnew_users = ['wally', 'Mike', 'frank', 'JANE', 'amber']\n\nprint(\"\\nInput a username to see if it is available.\")\nfor new_user in new_users:\n\tif new_user.lower() in current_users:\n\t\tprint(f\"{new_user.title()} is taken plese create a new name.\")\n\telif new_user.lower() not in current_users:\n\t\tprint(f\"{new_user.title()} is available.\")\n\t\tcurrent_users.append(new_user.lower())\n\nif user == 'admin':\n\tprint(\"\\nThe current list of users are:\")\n\tfor current_user in current_users:\n\t\tprint(current_user.title())\n\n# Ordinal Numbers with line spacing between each output.\nordinal_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nfor numbers in ordinal_numbers:\n\tif numbers == 1:\n\t\tprint('\\n1st')\n\telif numbers == 2:\n\t\tprint('\\n2nd')\n\telif numbers == 3:\n\t\tprint('\\n3rd')\n\telse:\n\t\tprint(f'\\n{numbers}th')\n","sub_path":"hello_admin.py","file_name":"hello_admin.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"247928342","text":"import math\nimport typing\nfrom functools import partial\n\nfrom qtpy.QtCore import QEvent, QModelIndex, QPoint, QPointF, QRect, QRectF, QSize, Qt, Signal\nfrom qtpy.QtGui import QColor, QMouseEvent, QPainter, QPainterPath, QPaintEvent, QPen, QPolygonF, QShowEvent\nfrom qtpy.QtWidgets import (\n QCheckBox,\n QComboBox,\n QDoubleSpinBox,\n QGridLayout,\n QHBoxLayout,\n QLabel,\n QListView,\n QStyle,\n QStyledItemDelegate,\n QStyleOptionViewItem,\n QWidget,\n)\n\nfrom PartSeg.common_gui.numpy_qimage import create_colormap_image\nfrom PartSegCore.color_image import ColorMap\nfrom PartSegCore.image_operations import NoiseFilterType\n\nfrom ..common_backend.base_settings import ViewSettings\nfrom .collapse_checkbox import CollapseCheckbox\nfrom .universal_gui_part import CustomSpinBox, EnumComboBox\n\nimage_dict = {} # dict to store QImages generated from colormap\n\nColorMapDict = typing.MutableMapping[str, typing.Tuple[ColorMap, bool]]\n\n\nclass ColorStyledDelegate(QStyledItemDelegate):\n \"\"\"\n Class for paint :py:class:`~.ColorComboBox` elements when list trigger\n\n :param base_height: height of single list element\n :param color_dict: Dict mapping name to colors\n \"\"\"\n\n def __init__(self, base_height: int, color_dict: ColorMapDict, **kwargs):\n super().__init__(**kwargs)\n self.base_height = base_height\n self.color_dict = color_dict\n\n def paint(self, painter: QPainter, style: QStyleOptionViewItem, model: QModelIndex):\n if model.data() not in image_dict:\n image_dict[model.data()] = create_colormap_image(model.data(), self.color_dict)\n rect = QRect(style.rect.x(), style.rect.y() + 2, style.rect.width(), style.rect.height() - 4)\n painter.drawImage(rect, image_dict[model.data()])\n if int(style.state & QStyle.State_HasFocus):\n painter.save()\n pen = QPen()\n pen.setWidth(5)\n painter.setPen(pen)\n painter.drawRect(rect)\n painter.restore()\n\n def sizeHint(self, style: QStyleOptionViewItem, model: QModelIndex):\n res = super().sizeHint(style, model)\n # print(res)\n res.setHeight(self.base_height)\n res.setWidth(max(500, res.width()))\n return res\n\n\nclass ColorComboBox(QComboBox):\n \"\"\"\n Combobox showing colormap instead of text\n\n :param id_num: id which be emit in signals. Designed to inform which channel information is changed\n :param colors: list of colors which should be able to chose. All needs to be keys in `color_dict`\n :param color_dict: dict from name to colormap definition\n :param colormap: initial colormap\n :param base_height: initial height of widgethow information that\n :param lock: show lock padlock to inform that fixed range is used\n :param blur: show info about blur selected\n \"\"\"\n\n triangle_width = 20\n\n clicked = Signal(int)\n \"\"\"Information about mouse click event on widget\"\"\"\n channel_visible_changed = Signal(int, bool)\n \"\"\"Signal with information about change of channel visibility (ch_num, visible)\"\"\"\n channel_colormap_changed = Signal(int, str)\n \"\"\"Signal with information about colormap change. (ch_num, name_of_colorma)\"\"\"\n\n def __init__(\n self,\n id_num: int,\n colors: typing.List[str],\n color_dict: ColorMapDict,\n colormap: str = \"\",\n base_height=50,\n lock=False,\n blur=NoiseFilterType.No,\n gamma=1,\n ):\n super().__init__()\n self.id = id_num\n self.check_box = QCheckBox() # ColorCheckBox(parent=self)\n self.check_box.setChecked(True)\n self.lock = LockedInfoWidget(base_height - 10)\n self.lock.setVisible(lock)\n self.blur = BlurInfoWidget(base_height - 10)\n self.blur.setVisible(blur != NoiseFilterType.No)\n self.gamma = GammaInfoWidget()\n self.gamma.setVisible(gamma != 1)\n self.color_dict = color_dict\n self.colors = colors\n self.addItems(self.colors)\n if colormap:\n self.color = colormap\n else:\n self.color = self.itemText(0)\n self.setCurrentText(self.color)\n self.currentTextChanged.connect(self._update_image)\n self.base_height = base_height\n self.show_arrow = False\n self.show_frame = False\n view = QListView()\n view.setMinimumWidth(200)\n view.setItemDelegate(ColorStyledDelegate(self.base_height, color_dict))\n self.setView(view)\n self.image = None # only for moment, to reduce code repetition\n\n layout = QHBoxLayout()\n layout.setContentsMargins(7, 0, 0, 0)\n layout.addWidget(self.check_box)\n layout.addWidget(self.lock)\n layout.addWidget(self.blur)\n layout.addWidget(self.gamma)\n layout.addStretch(1)\n\n self.setLayout(layout)\n self.check_box.stateChanged.connect(partial(self.channel_visible_changed.emit, self.id))\n self.currentTextChanged.connect(partial(self.channel_colormap_changed.emit, self.id))\n self._update_image()\n\n def change_colors(self, colors: typing.List[str]):\n \"\"\"change list of colormaps to choose\"\"\"\n self.colors = colors\n current_color = self.currentText()\n try:\n index = colors.index(current_color)\n prev = self.blockSignals(True)\n except ValueError:\n index = -1\n prev = self.signalsBlocked()\n\n self.clear()\n self.addItems(colors)\n if index != -1:\n self.setCurrentIndex(index)\n self.blockSignals(prev)\n else:\n self._update_image()\n self.repaint()\n\n def _update_image(self):\n self.color = self.currentText()\n if self.color not in image_dict:\n image_dict[self.color] = create_colormap_image(self.color, self.color_dict)\n self.image = image_dict[self.color]\n self.show_arrow = False\n\n def enterEvent(self, event: QEvent):\n self.show_arrow = True\n self.repaint()\n\n def mouseMoveEvent(self, _):\n self.show_arrow = True\n\n def leaveEvent(self, event: QEvent):\n self.show_arrow = False\n self.repaint()\n\n def showEvent(self, _event: QShowEvent):\n self.show_arrow = False\n\n def paintEvent(self, event: QPaintEvent):\n painter = QPainter(self)\n painter.drawImage(self.rect(), self.image)\n if self.show_frame:\n painter.save()\n pen = QPen()\n pen.setWidth(2)\n pen.setColor(QColor(\"black\"))\n painter.setPen(pen)\n rect = QRect(1, 1, self.width() - 2, self.height() - 2)\n painter.drawRect(rect)\n pen.setColor(QColor(\"white\"))\n painter.setPen(pen)\n rect = QRect(3, 3, self.width() - 6, self.height() - 6)\n painter.drawRect(rect)\n painter.restore()\n if self.show_arrow:\n painter.save()\n triangle = QPolygonF()\n dist = 4\n point1 = QPoint(self.width() - self.triangle_width, 0)\n size = QSize(20, self.height() // 2)\n rect = QRect(point1, size)\n painter.fillRect(rect, QColor(\"white\"))\n triangle.append(point1 + QPoint(dist, dist))\n triangle.append(point1 + QPoint(size.width() - dist, dist))\n triangle.append(point1 + QPoint(size.width() // 2, size.height() - dist))\n painter.setBrush(Qt.black)\n painter.drawPolygon(triangle, Qt.WindingFill)\n painter.restore()\n\n def mousePressEvent(self, event: QMouseEvent):\n if event.x() > self.width() - self.triangle_width:\n super().mousePressEvent(event)\n self.clicked.emit(self.id)\n\n def minimumSizeHint(self):\n size: QSize = super().minimumSizeHint()\n return QSize(size.width(), max(size.height(), self.base_height))\n\n def is_checked(self):\n \"\"\"check if checkbox on widget is checked\"\"\"\n return self.check_box.isChecked()\n\n @property\n def is_lock(self):\n \"\"\"check if lock property is set\"\"\"\n return self.lock.isVisible\n\n @property\n def is_blur(self):\n \"\"\"check if blur property is set\"\"\"\n return self.blur.isVisible\n\n @property\n def set_lock(self) -> typing.Callable[[bool], None]:\n \"\"\"set lock property\"\"\"\n return self.lock.setVisible\n\n @property\n def set_gamma(self) -> typing.Callable[[bool], None]:\n \"\"\"set lock property\"\"\"\n return self.gamma.setVisible\n\n @property\n def set_blur(self) -> typing.Callable[[bool], None]:\n \"\"\"set blur property\"\"\"\n return self.blur.setVisible\n\n @property\n def colormap_changed(self):\n \"\"\"alias for signal, return color name \"\"\"\n return self.currentTextChanged\n\n def set_selection(self, val: bool):\n \"\"\"set element selected (add frame)\"\"\"\n self.show_frame = val\n self.repaint()\n\n def set_color(self, val: str):\n \"\"\"set current colormap\"\"\"\n self.setCurrentText(val)\n\n\nclass ChannelProperty(QWidget):\n \"\"\"\n For manipulate chanel properties.\n 1. Apply gaussian blur to channel\n 2. Fixed range for coloring\n\n In future should be extended\n\n :param settings: for storing internal state. allow keep state between sessions\n :param start_name: name used to select proper information from settings object.\n Introduced for case with multiple image view.\n \"\"\"\n\n def __init__(self, settings: ViewSettings, start_name: str):\n super().__init__()\n if start_name == \"\":\n raise ValueError(\"ChannelProperty should have non empty start_name\")\n self.current_name = start_name\n self.current_channel = 0\n self._settings = settings\n self.widget_dict: typing.Dict[str, ColorComboBoxGroup] = {}\n\n self.minimum_value = CustomSpinBox(self)\n self.minimum_value.setRange(-(10 ** 6), 10 ** 6)\n self.minimum_value.valueChanged.connect(self.range_changed)\n self.maximum_value = CustomSpinBox(self)\n self.maximum_value.setRange(-(10 ** 6), 10 ** 6)\n self.maximum_value.valueChanged.connect(self.range_changed)\n self.fixed = QCheckBox(\"Fix range\")\n self.fixed.stateChanged.connect(self.lock_channel)\n self.use_filter = EnumComboBox(NoiseFilterType)\n self.use_filter.setToolTip(\"Only current channel\")\n self.filter_radius = QDoubleSpinBox()\n self.filter_radius.setSingleStep(0.1)\n self.filter_radius.valueChanged.connect(self.gauss_radius_changed)\n self.use_filter.currentIndexChanged.connect(self.gauss_use_changed)\n self.gamma_value = QDoubleSpinBox()\n self.gamma_value.setRange(0.01, 100)\n self.gamma_value.setSingleStep(0.1)\n self.gamma_value.valueChanged.connect(self.gamma_value_changed)\n\n self.collapse_widget = CollapseCheckbox(\"Channel property\")\n self.collapse_widget.add_hide_element(self.minimum_value)\n self.collapse_widget.add_hide_element(self.maximum_value)\n self.collapse_widget.add_hide_element(self.fixed)\n self.collapse_widget.add_hide_element(self.use_filter)\n self.collapse_widget.add_hide_element(self.filter_radius)\n\n layout = QGridLayout()\n layout.setContentsMargins(0, 0, 0, 0)\n layout.addWidget(self.collapse_widget, 0, 0, 1, 4)\n label1 = QLabel(\"Min bright:\")\n layout.addWidget(label1, 1, 0)\n layout.addWidget(self.minimum_value, 1, 1)\n label2 = QLabel(\"Max bright:\")\n layout.addWidget(label2, 2, 0)\n layout.addWidget(self.maximum_value, 2, 1)\n layout.addWidget(self.fixed, 1, 2, 1, 2)\n label3 = QLabel(\"Filter:\")\n layout.addWidget(label3, 3, 0, 1, 1)\n layout.addWidget(self.use_filter, 3, 1, 1, 1)\n layout.addWidget(self.filter_radius, 3, 2, 1, 1)\n label4 = QLabel(\"Gamma:\")\n layout.addWidget(label4, 4, 0, 1, 1)\n layout.addWidget(self.gamma_value, 4, 1, 1, 1)\n self.setLayout(layout)\n\n self.collapse_widget.add_hide_element(label1)\n self.collapse_widget.add_hide_element(label2)\n\n def send_info(self):\n \"\"\"send info to \"\"\"\n widget = self.widget_dict[self.current_name]\n widget.parameters_changed(self.current_channel)\n\n def register_widget(self, widget: \"ColorComboBoxGroup\"):\n if widget.name in self.widget_dict:\n raise ValueError(f\"name {widget.name} already register\")\n self.widget_dict[widget.name] = widget\n self.change_current(widget.name, 0)\n\n def change_current(self, name, channel):\n if name not in self.widget_dict:\n raise ValueError(f\"name {name} not in register\")\n self.current_name = name\n self.current_channel = channel\n block = self.blockSignals(True)\n self.minimum_value.blockSignals(True)\n self.minimum_value.setValue(\n self._settings.get_from_profile(f\"{self.current_name}.range_{self.current_channel}\", (0, 65000))[0]\n )\n self.minimum_value.blockSignals(False)\n self.maximum_value.setValue(\n self._settings.get_from_profile(f\"{self.current_name}.range_{self.current_channel}\", (0, 65000))[1]\n )\n self.use_filter.set_value(\n self._settings.get_from_profile(\n f\"{self.current_name}.use_filter_{self.current_channel}\", NoiseFilterType.No\n )\n )\n self.filter_radius.setValue(\n self._settings.get_from_profile(f\"{self.current_name}.filter_radius_{self.current_channel}\", 1)\n )\n self.fixed.setChecked(\n self._settings.get_from_profile(f\"{self.current_name}.lock_{self.current_channel}\", False)\n )\n self.gamma_value.setValue(\n self._settings.get_from_profile(f\"{self.current_name}.gamma_value_{self.current_channel}\", 1)\n )\n self.blockSignals(block)\n\n def gamma_value_changed(self):\n self._settings.set_in_profile(\n f\"{self.current_name}.gamma_value_{self.current_channel}\", self.gamma_value.value()\n )\n self.send_info()\n\n def gauss_radius_changed(self):\n self._settings.set_in_profile(\n f\"{self.current_name}.filter_radius_{self.current_channel}\", self.filter_radius.value()\n )\n if self.use_filter.get_value() != NoiseFilterType.No:\n self.send_info()\n\n def gauss_use_changed(self):\n self._settings.set_in_profile(\n f\"{self.current_name}.use_filter_{self.current_channel}\", self.use_filter.get_value()\n )\n if self.use_filter.get_value() == NoiseFilterType.Median:\n self.filter_radius.setDecimals(0)\n self.filter_radius.setSingleStep(1)\n else:\n self.filter_radius.setDecimals(2)\n self.filter_radius.setSingleStep(0.1)\n\n self.send_info()\n\n def lock_channel(self, value):\n self._settings.set_in_profile(f\"{self.current_name}.lock_{self.current_channel}\", value)\n self.send_info()\n\n def range_changed(self):\n self._settings.set_in_profile(\n f\"{self.current_name}.range_{self.current_channel}\",\n (self.minimum_value.value(), self.maximum_value.value()),\n )\n if self.fixed.isChecked():\n self.send_info()\n\n\nclass ColorComboBoxGroup(QWidget):\n \"\"\"\n Group of :class:`.ColorComboBox` for control visibility and chose colormap for channels.\n \"\"\"\n\n coloring_update = Signal()\n \"\"\"information about global change of coloring\"\"\"\n change_channel = Signal([str, int])\n \"\"\"information which channel change\"\"\"\n\n def __init__(\n self,\n settings: ViewSettings,\n name: str,\n channel_property: typing.Optional[ChannelProperty] = None,\n height: int = 40,\n ):\n super().__init__()\n self.name = name\n self.height = height\n self.settings = settings\n self.settings.colormap_changes.connect(self.update_color_list)\n self.active_box = 0\n layout = QHBoxLayout()\n layout.setContentsMargins(0, 0, 0, 0)\n self.setLayout(layout)\n if channel_property is not None:\n channel_property.register_widget(self)\n self.change_channel.connect(channel_property.change_current)\n\n def update_color_list(self, colors: typing.Optional[typing.List[str]] = None):\n \"\"\"update list\"\"\"\n if colors is None:\n colors = self.settings.chosen_colormap\n for i in range(self.layout().count()):\n el: ColorComboBox = self.layout().itemAt(i).widget()\n el.change_colors(colors)\n\n def update_channels(self):\n \"\"\"update number of channels base on settings\"\"\"\n self.set_channels(self.settings.channels)\n\n @property\n def channels_count(self):\n return self.layout().count()\n\n @property\n def selected_colormaps(self) -> typing.List[ColorMap]:\n resp = []\n for i in range(self.layout().count()):\n el: ColorComboBox = self.layout().itemAt(i).widget()\n resp.append(self.settings.colormap_dict[el.currentText()][0])\n\n return resp\n\n @property\n def channel_visibility(self) -> typing.List[bool]:\n resp = []\n for i in range(self.layout().count()):\n el: ColorComboBox = self.layout().itemAt(i).widget()\n resp.append(el.is_checked())\n return resp\n\n @property\n def current_colors(self) -> typing.List[typing.Optional[str]]:\n \"\"\"\"\"\"\n resp = []\n for i in range(self.layout().count()):\n el: ColorComboBox = self.layout().itemAt(i).widget()\n if el.is_checked():\n resp.append(el.currentText())\n else:\n resp.append(None)\n return resp\n\n @property\n def current_colormaps(self):\n resp = []\n for i in range(self.layout().count()):\n el: ColorComboBox = self.layout().itemAt(i).widget()\n if el.is_checked():\n resp.append(self.settings.colormap_dict[el.currentText()][0])\n else:\n resp.append(None)\n return resp\n\n def change_selected_color(self, index, color):\n self.settings.set_channel_info(self.name, index, str(color))\n self.coloring_update.emit()\n self.change_channel.emit(self.name, index)\n\n def active_channel(self, chanel):\n return self.layout().itemAt(chanel).widget().is_checked()\n\n def set_channels(self, num: int):\n \"\"\"Set number of channels to display\"\"\"\n self.settings.set_in_profile(f\"{self.name}.channels_count\", num)\n if num >= self.layout().count():\n for i in range(self.layout().count(), num):\n el = ColorComboBox(\n i,\n self.settings.chosen_colormap,\n self.settings.colormap_dict,\n self.settings.get_channel_info(self.name, i),\n base_height=self.height,\n lock=self.settings.get_from_profile(f\"{self.name}.lock_{i}\", False),\n blur=self.settings.get_from_profile(f\"{self.name}.use_filter_{i}\", NoiseFilterType.No),\n gamma=self.settings.get_from_profile(f\"{self.name}.gamma_value_{i}\", 1),\n )\n el.clicked.connect(self.set_active)\n el.channel_visible_changed.connect(self.change_selected_color)\n el.channel_colormap_changed.connect(self.change_selected_color)\n self.layout().addWidget(el)\n else:\n for i in range(self.layout().count() - num):\n el = self.layout().takeAt(num).widget()\n el.colormap_changed.disconnect()\n el.channel_colormap_changed.disconnect()\n el.clicked.disconnect()\n el.channel_visible_changed.disconnect()\n el.deleteLater()\n if num <= self.active_box:\n self.set_active(num - 1)\n self.change_channel.emit(self.name, self.active_box)\n\n def set_active(self, pos: int):\n self.active_box = pos\n for i in range(self.layout().count()):\n el = self.layout().itemAt(i).widget()\n if i == self.active_box:\n el.show_frame = True\n else:\n el.show_frame = False\n self.change_channel.emit(self.name, pos)\n self.repaint()\n\n def get_filter(self) -> typing.List[typing.Tuple[NoiseFilterType, float]]:\n resp = []\n for i in range(self.layout().count()):\n resp.append(\n (\n self.settings.get_from_profile(f\"{self.name}.use_filter_{i}\", NoiseFilterType.No),\n self.settings.get_from_profile(f\"{self.name}.filter_radius_{i}\", 1),\n )\n )\n return resp\n\n def get_limits(self) -> typing.List[typing.Union[typing.Tuple[int, int], None]]:\n resp: typing.List[typing.Union[typing.Tuple[int, int], None]] = [(0, 0)] * self.layout().count() #\n for i in range(self.layout().count()):\n if not self.settings.get_from_profile(f\"{self.name}.lock_{i}\", False):\n resp[i] = None\n else:\n resp[i] = self.settings.get_from_profile(f\"{self.name}.range_{i}\", (0, 65000))\n return resp\n\n def get_gamma(self) -> typing.List[float]:\n resp = []\n for i in range(self.layout().count()):\n resp.append(self.settings.get_from_profile(f\"{self.name}.gamma_value_{i}\", 1))\n return resp\n\n def parameters_changed(self, channel):\n \"\"\"for ChannelProperty to inform about change of parameters\"\"\"\n if self.layout().itemAt(channel) is None:\n return\n widget: ColorComboBox = self.layout().itemAt(channel).widget()\n widget.set_blur(\n self.settings.get_from_profile(f\"{self.name}.use_filter_{channel}\", NoiseFilterType.No)\n != NoiseFilterType.No\n )\n widget.set_lock(self.settings.get_from_profile(f\"{self.name}.lock_{channel}\", False))\n widget.set_gamma(self.settings.get_from_profile(f\"{self.name}.gamma_value_{channel}\", 1) != 1)\n if self.active_channel(channel):\n self.coloring_update.emit()\n if self.active_box == channel:\n self.change_channel.emit(self.name, channel)\n\n\nclass LockedInfoWidget(QWidget):\n \"\"\"\n Widget used to present info about lock selection in class :py:class:`~.ColorComboBox`.\n \"\"\"\n\n def __init__(self, size=25, margin=2):\n super().__init__()\n self.margin = margin\n self.setFixedWidth(size)\n self.setFixedHeight(size)\n\n def paintEvent(self, a0: QPaintEvent) -> None:\n super().paintEvent(a0)\n painter = QPainter(self)\n painter.save()\n painter.setRenderHint(QPainter.Antialiasing)\n pen2 = QPen()\n\n rect = QRectF(self.margin, self.height() / 2, self.width() - self.margin * 2, self.height() / 2 - self.margin)\n rect2 = QRectF(3 * self.margin, 2 * self.margin, self.width() - self.margin * 6, self.height())\n\n pen2.setWidth(6)\n painter.setPen(pen2)\n painter.drawArc(rect2, 0, 180 * 16)\n pen2.setWidth(3)\n pen2.setColor(Qt.white)\n painter.setPen(pen2)\n painter.drawArc(rect2, 0, 180 * 16)\n\n painter.fillRect(rect, Qt.white)\n pen2.setWidth(2)\n pen2.setColor(Qt.black)\n painter.setPen(pen2)\n painter.drawRect(rect)\n\n painter.restore()\n\n\nclass BlurInfoWidget(QWidget):\n \"\"\"\n Widget used to present info about blur selection in class :py:class:`~.ColorComboBox`.\n \"\"\"\n\n def __init__(self, size=25, margin=2):\n super().__init__()\n self.margin = margin\n self.setFixedWidth(size)\n self.setFixedHeight(size)\n\n def paintEvent(self, a0: QPaintEvent) -> None:\n super().paintEvent(a0)\n painter = QPainter(self)\n painter.save()\n painter.setRenderHint(QPainter.Antialiasing)\n rect = QRectF(self.margin, self.margin, self.width() - self.margin * 2, self.height() - 2 * self.margin)\n painter.setBrush(Qt.white)\n painter.setPen(Qt.white)\n painter.drawEllipse(rect)\n\n painter.restore()\n painter.save()\n painter.setRenderHint(QPainter.Antialiasing)\n pen = QPen()\n pen.setWidth(2)\n painter.setPen(pen)\n mid_point = QPointF(a0.rect().width() / 2, a0.rect().height() / 2)\n radius = min(a0.rect().height(), a0.rect().width()) / 3\n rays_num = 10\n for i in range(rays_num):\n point = QPointF(\n math.sin(math.pi / (rays_num / 2) * i) * radius, math.cos(math.pi / (rays_num / 2) * i) * radius\n )\n painter.drawLine(mid_point + (point * 0.4), mid_point + point)\n painter.restore()\n\n\nclass GammaInfoWidget(QWidget):\n def __init__(self, size=25, margin=2):\n super().__init__()\n self.margin = margin\n self.setFixedWidth(size)\n self.setFixedHeight(size)\n\n def paintEvent(self, a0: QPaintEvent) -> None:\n\n super().paintEvent(a0)\n painter = QPainter(self)\n painter.save()\n painter.setRenderHint(QPainter.Antialiasing)\n rect = QRectF(self.margin, self.margin, self.width() - self.margin * 2, self.height() - 2 * self.margin)\n painter.setBrush(Qt.white)\n painter.setPen(Qt.white)\n painter.drawRect(rect)\n painter.restore()\n painter.save()\n painter.setRenderHint(QPainter.Antialiasing)\n pen = QPen()\n pen.setWidth(3)\n painter.setPen(pen)\n path = QPainterPath()\n height, width = rect.height() + self.margin, rect.width() + self.margin\n path.moveTo(self.margin, height)\n path.cubicTo(height * 0.5, width * 0.9, height * 0.9, width * 0.5, height, self.margin)\n painter.drawPath(path)\n painter.restore()\n","sub_path":"package/PartSeg/common_gui/channel_control.py","file_name":"channel_control.py","file_ext":"py","file_size_in_byte":25979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"577348926","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib import messages\nfrom django.conf import settings\nfrom users.models import Profile\nfrom .backend.backend import *\nfrom .forms import *\n\n\n@login_required\ndef pin_post(request, classroom_id, forum_id, post_id):\n print(\"request\", request)\n print(Post.objects.all().count())\n for p in Post.objects.all():\n p.unpin()\n post = Post.objects.filter(id=post_id).first()\n post.pin()\n return redirect('/dashboard/classroom/' + str(classroom_id) + '/' + str(forum_id))\n\n\n@login_required\ndef unpin_post(request, classroom_id, forum_id, post_id):\n print(\"request\", request)\n post = get_object_or_404(Post, id=post_id)\n post.unpin()\n return redirect('/dashboard/classroom/' + str(classroom_id) + '/' + str(forum_id))\n\n\ndef home(request):\n return render(request, 'blog/home.html')\n\n\ndef about(request):\n return render(request, 'blog/about.html', {'title': 'About'})\n\n\n@login_required()\ndef dashboard(request):\n return render(request, 'blog/dashboard.html', {'classrooms': get_classrooms(request.user),\n 'type': Profile.objects.get(user_id=request.user).type})\n\n\n@login_required()\ndef classroom(request, classroom_id):\n if match(user=request.user, classroom_id=classroom_id):\n classroom = Classroom.objects.get(id=classroom_id)\n return render(request, 'blog/classroom.html',\n {'exams': get_exams(classroom), 'forums': get_forums(classroom), 'classroom': classroom})\n else:\n messages.error(request, 'Sorry, We found out that you are not a member of the classroom!')\n return redirect('dashboard')\n\n\n@login_required()\ndef create_classroom(request):\n if request.method == 'POST':\n form = ClassCreationForm(request.POST)\n if form.is_valid():\n form = form.save()\n form.teacher = Profile.objects.get(user_id=request.user).user\n form.save()\n messages.success(request, f'Class has been created!')\n return redirect('dashboard') # TODO except dashboard it should redirect to class's page\n else:\n form = ClassCreationForm()\n if Profile.objects.get(user_id=request.user).type == 'teacher':\n return render(request, 'blog/create_classroom.html', {'form': form})\n else:\n return render(request, 'blog/404.html', {})\n\n\n@login_required()\ndef join_classroom(request):\n if request.method == 'POST':\n id = request.POST.get('id')\n if request.user in Classroom.objects.get(id=id).students.all():\n messages.error(request, 'you are already in this class!')\n return redirect('dashboard') # TODO except dashboard it should redirect to class's page\n else:\n Classroom.objects.get(id=id).students.add(request.user)\n messages.success(request, 'you have been successfully added!')\n return redirect('dashboard') # TODO except dashboard it should redirect to class's page\n else:\n if Profile.objects.get(user_id=request.user).type == 'student':\n return render(request, 'blog/join_classroom.html', {'classrooms': Classroom.objects.all()})\n else:\n return render(request, 'blog/404.html', {})\n\n\n@login_required()\ndef forum(request, classroom_id, forum_id):\n if request.method == 'POST':\n content = request.POST.get('content')\n if request.FILES:\n file_filed = request.FILES['file']\n else:\n file_filed = None\n create_post(content, request.user, forum_id, file_filed)\n\n if match(user=request.user, classroom_id=classroom_id, forum_id=forum_id):\n forum = get_forums(Classroom.objects.get(id=classroom_id)).get(id=forum_id)\n return render(request, 'blog/forum.html', {'posts': get_posts(forum), 'url': settings.MEDIA_ROOT})\n else:\n messages.error(request, 'Something went wrong!')\n return redirect('dashboard')\n\n\n@login_required()\ndef reply(request, classroom_id, forum_id, post_id):\n if request.method == 'POST':\n content = request.POST.get('content')\n create_reply(content, request.user, forum_id, post_id)\n\n if match(user=request.user, classroom_id=classroom_id, forum_id=forum_id):\n forum = get_forums(Classroom.objects.get(id=classroom_id)).get(id=forum_id)\n return render(request, 'blog/forum.html', {'posts': get_posts(forum), 'url': settings.MEDIA_ROOT})\n else:\n messages.error(request, 'Something went wrong!')\n return redirect('dashboard')\n\n\n@login_required()\ndef create_forum(request, classroom_id):\n if request.method == 'POST':\n form = ForumCreationForm(request.POST)\n if form.is_valid():\n form = form.save()\n form.classroom = Classroom.objects.get(id=classroom_id)\n form.save()\n messages.success(request, f'Forum has been created!')\n return redirect('/dashboard/classroom/' + str(classroom_id))\n else:\n form = ForumCreationForm()\n return render(request, 'blog/create_forum.html', {'form': form})\n\n\n@login_required()\ndef create_exam(request, classroom_id):\n if request.method == 'POST':\n form = ExamCreationForm(request.POST, request.FILES)\n if form.is_valid():\n form = form.save()\n form.classroom = Classroom.objects.get(id=classroom_id)\n form.save()\n messages.success(request, f'exam has been created!')\n return redirect('/dashboard/classroom/' + str(classroom_id))\n else:\n form = ExamCreationForm()\n if Profile.objects.get(user_id=request.user).type == 'teacher':\n return render(request, 'blog/create_exam.html', {'form': form})\n else:\n return render(request, 'blog/404.html', {})\n\n\n@login_required()\ndef submit_score(request, classroom_id, exam_id, response_id):\n if request.method == 'POST' and Profile.objects.get(user_id=request.user).type == 'teacher':\n response = Response.objects.get(id=response_id)\n if response is None:\n return render(request, 'blog/404.html', {})\n response.score = int(request.POST[\"score\"])\n response.save()\n return redirect(exam_page, classroom_id, exam_id)\n else:\n return render(request, 'blog/404.html', {})\n\n\n@login_required()\ndef exam_page(request, classroom_id, exam_id):\n if request.method == 'GET':\n if match(user=request.user, classroom_id=classroom_id, exam_id=exam_id):\n if Profile.objects.get(user_id=request.user).type == 'student':\n exam = get_exams(Classroom.objects.get(id=classroom_id)).get(id=exam_id)\n form = ResponseForm()\n return render(request, 'blog/exam.html',\n {'response': get_response_belongs_student(exam, request.user), 'exam': exam,\n 'url': settings.MEDIA_ROOT, 'form': form})\n elif Profile.objects.get(user_id=request.user).type == 'teacher':\n exam = get_exams(Classroom.objects.get(id=classroom_id)).get(id=exam_id)\n return render(request, 'blog/teacher_exam.html',\n {'exam': exam, 'url': settings.MEDIA_ROOT, 'responses': get_responses(exam)})\n else:\n messages.error(request, 'Something went wrong!')\n return redirect('dashboard')\n elif request.method == 'POST':\n form = ResponseForm(request.POST, request.FILES)\n if form.is_valid() or match(user=request.user, classroom_id=classroom_id, exam_id=exam_id):\n form = form.save(commit=False)\n form.student = request.user\n form.exam = get_exams(Classroom.objects.get(id=classroom_id)).get(id=exam_id)\n form.save()\n messages.success(request, f'your response sent successfully!')\n return redirect('/dashboard/classroom/' + str(classroom_id))\n else:\n messages.error(request, 'Something went wrong!')\n return redirect('dashboard')\n","sub_path":"django_project/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"516020039","text":"class Person():\n\n def __init__(self,name,age,money):\n self.name = name\n self.age = age\n\n # 属性前加__双下划线,则是一个私有属性,类的外部如法通过实例名.私有属性的方式获取值\n self.__money = money\n\n\n def __str__(self):\n\n # 在类的方法内部可以直接获取私有属性的值\n return \"My name is %s,I am %d years old, I hava %d yuan\" %(self.name, self.age, self.__money)\n\n '''\n 成员属性的get set方法\n '''\n\n def eat(self, food):\n\n print(self.name + \"吃\" + food)\n\n def getMoney(self):\n\n return self.__money\n\n def setMoney(self,money):\n\n if money < 0:\n money = 0\n self.__money = money\n\n '''\n 私有属性的另一种访问方式,这种方式可以允许通过实例变量名.属性的方式直接获取和设置属性\n '''\n\n # 定义与私有属性同名(舍去双下划线)的方法,结合@property提示(装饰器),来实现get方法\n @property\n def money(self):\n\n return self.__money\n\n # 定义私有属性同名(舍去双下划线)带参方法,结合@属性.setter提示来实现set方法\n @money.setter\n def money(self, money):\n\n if money < 0:\n money = 0\n self.__money = money\n\n\nif __name__ == \"__main__\":\n p1 = Person(\"cuixd\",33,200)\n\n print(p1)\n\n # 类的外部如法通过实例���.私有属性的方式获取值,也就是无法获取该变量,pycharm甚至都没有提示该属性\n # print(p1.__money)\n\n # 而这里可以赋值和获取值,是因为python是解释型动态语言,\n # 可以动态的为对象添加属性,这里的__money并不是类中的那个私有属性\n p1.__money = 10\n print(p1.__money)\n\n # 再次打印对象的信息,可以发现对象的私有属性__money依然是200\n print(p1)\n\n # 只能通过set方法修改私有属性的值\n p1.setMoney(10)\n print(p1)\n\n # 私有成员属性被Python解释器改名为, _类名__属性名,如下方式还是可以直接访问到私有属性并可以直接修改,不建议使用\n print(p1._Person__money)\n\n # 使用实例.属性(舍去双下划线)的方式访问和设置私有属性\n print(p1.money)\n p1.money = -100\n print(p1.money)\n","sub_path":"11.面向对象类的属性、继承/private_attr.py","file_name":"private_attr.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"510228565","text":"from ips.services.calculations.sas_rounding import ips_rounding\nimport math\nimport numpy as np\nimport pandas as pd\n\nOUTPUT_TABLE_NAME = 'SAS_REGIONAL_IMP'\nMAXIMUM_LEVEL = 4\nSTAY_VARIABLE = 'STAY'\nSPEND_VARIABLE = 'SPEND'\nSTAY_WEIGHT_VARIABLE = 'STAY_WT'\nVISIT_WEIGHT_VARIABLE = 'VISIT_WT'\nEXPENDITURE_WEIGHT_VARIABLE = 'EXPENDITURE_WT'\nSTAY_WEIGHTK_VARIABLE = 'STAY_WTK'\nVISIT_WEIGHTK_VARIABLE = 'VISIT_WTK'\nEXPENDITURE_WEIGHTK_VARIABLE = 'EXPENDITURE_WTK'\nELIGIBLE_FLAG_VARIABLE = 'REG_IMP_ELIGIBLE_PV'\n\nSTRATA_LEVELS = [\n ['FLOW', 'PURPOSE_PV', 'STAYIMPCTRYLEVEL1_PV'],\n ['FLOW', 'PURPOSE_PV', 'STAYIMPCTRYLEVEL2_PV'],\n ['FLOW', 'PURPOSE_PV', 'STAYIMPCTRYLEVEL3_PV'],\n ['FLOW', 'PURPOSE_PV', 'STAYIMPCTRYLEVEL4_PV']\n]\n\nTOWN_CODE_VARIABLE = 'TOWNCODE'\nNIGHTS_VARIABLE = 'NIGHTS'\nINFO_PRESENT_MARKER = 'INFO_PRESENT_MKR'\nFLOW_VARIABLE = 'FLOW'\nTOWN_CODE1_VARIABLE = 'TOWNCODE1'\nNUMBER_OF_NIGHTS = 9\n\n\ndef ips_correct_regional_nights(row):\n \"\"\"\n Author : Thomas Mahoney\n Date : 12 / 03 / 2018\n Purpose : Corrects the regional nights data.\n Parameters : df_input - the IPS survey records for the period.\n Returns : NA\n Requirements : NA\n Dependencies : NA\n \"\"\"\n\n # Adjust regional night figures so that they match overall STAY_VARIABLE\n if row[INFO_PRESENT_MARKER] == 1:\n known_town_nk_nights = 0\n nights_sum = 0\n\n # Compute nights_sum and known_town_nk_nights for this record\n for x in range(1, NUMBER_OF_NIGHTS):\n if row[TOWN_CODE_VARIABLE + str(x)] != 99999 and not math.isnan(row[TOWN_CODE_VARIABLE + str(x)]):\n if not math.isnan(row[NIGHTS_VARIABLE + str(x)]):\n nights_sum = nights_sum + row[NIGHTS_VARIABLE + str(x)]\n else:\n known_town_nk_nights = known_town_nk_nights + 1\n\n if known_town_nk_nights == 0:\n # Check if sum of nights is not equal to stay\n if nights_sum != row[STAY_VARIABLE]:\n stay_sum = (row[STAY_VARIABLE] / nights_sum)\n\n for x in range(1, NUMBER_OF_NIGHTS):\n if row[TOWN_CODE_VARIABLE + str(x)] != 99999 and not math.isnan(\n row[TOWN_CODE_VARIABLE + str(x)]):\n row[NIGHTS_VARIABLE + str(x)] = row[NIGHTS_VARIABLE + str(x)] * stay_sum\n row[STAY_VARIABLE + str(x) + 'K'] = 'K'\n else:\n # If town has known code add STAY_VARIABLE to total nights_sum\n # if town is null adds 1 to unknown\n if nights_sum >= row[STAY_VARIABLE]:\n for x in range(1, NUMBER_OF_NIGHTS):\n if row[TOWN_CODE_VARIABLE + str(x)] != 99999 and not math.isnan(\n row[TOWN_CODE_VARIABLE + str(x)]) and math.isnan(row[NIGHTS_VARIABLE + str(x)]):\n row[NIGHTS_VARIABLE + str(x)] = 1\n nights_sum = nights_sum + row[NIGHTS_VARIABLE + str(x)]\n\n # Calculate nights uplift factor\n stay_sum = (row[STAY_VARIABLE] / nights_sum)\n\n for x in range(1, NUMBER_OF_NIGHTS):\n if row[TOWN_CODE_VARIABLE + str(x)] != 99999 and not math.isnan(\n row[TOWN_CODE_VARIABLE + str(x)]):\n row[NIGHTS_VARIABLE + str(x)] = row[NIGHTS_VARIABLE + str(x)] * stay_sum\n row[STAY_VARIABLE + str(x) + 'K'] = 'L'\n\n else:\n for x in range(1, NUMBER_OF_NIGHTS):\n if row[TOWN_CODE_VARIABLE + str(x)] != 99999 and not math.isnan(\n row[TOWN_CODE_VARIABLE + str(x)]) and math.isnan(row[NIGHTS_VARIABLE + str(x)]):\n row[NIGHTS_VARIABLE + str(x)] = (row[STAY_VARIABLE] - nights_sum) / known_town_nk_nights\n row[STAY_VARIABLE + str(x) + 'K'] = 'M'\n\n return row\n\n\ndef do_ips_regional_weight_calculation(df_input_data, serial_num, final_weight):\n \"\"\"\n Author : Thomas Mahoney\n Date : 12 / 03 / 2018\n Purpose : Calculates regional weights for IPS.\n Parameters : df_input_data - the IPS survey records for the period\n var_serial - Variable holding the record serial number\n var_final_weight - the name of the final weight variable\n Returns : NA\n Requirements : NA\n Dependencies : NA\n \"\"\"\n\n night_columns = [NIGHTS_VARIABLE + str(i) for i in range(1, NUMBER_OF_NIGHTS)]\n stay_columns = [STAY_VARIABLE + str(i) + 'K' for i in range(1, NUMBER_OF_NIGHTS)]\n\n df_input_data[night_columns] = df_input_data[night_columns].fillna(np.NaN)\n\n df_input_data[stay_columns] = df_input_data[stay_columns].fillna('')\n\n for x in range(1, NUMBER_OF_NIGHTS):\n df_input_data[TOWN_CODE_VARIABLE + str(x)] = df_input_data[TOWN_CODE_VARIABLE + str(x)].fillna(np.NaN)\n\n # Extract only eligible rows\n df_impute_towns = df_input_data[df_input_data[ELIGIBLE_FLAG_VARIABLE] == 1]\n\n # Set initial values for wt and wkt columns\n df_impute_towns.loc[:, STAY_WEIGHT_VARIABLE] = 1\n df_impute_towns.loc[:, STAY_WEIGHTK_VARIABLE] = ''\n\n df_impute_towns.loc[:, VISIT_WEIGHT_VARIABLE] = 1\n df_impute_towns.loc[:, VISIT_WEIGHTK_VARIABLE] = ''\n\n df_impute_towns.loc[:, EXPENDITURE_WEIGHT_VARIABLE] = 1\n df_impute_towns.loc[:, EXPENDITURE_WEIGHTK_VARIABLE] = ''\n\n # Check if towncode information is present for the input data\n def check_info(row):\n\n if row[TOWN_CODE1_VARIABLE] == 99999 or math.isnan(row[TOWN_CODE1_VARIABLE]):\n row[INFO_PRESENT_MARKER] = 0\n else:\n row[INFO_PRESENT_MARKER] = 1\n\n return row\n\n df_impute_towns = df_impute_towns.apply(check_info, axis=1)\n\n # Correct nights information so that it matches stay\n df_temp1 = df_impute_towns.apply(ips_correct_regional_nights, axis=1)\n\n # Extract the corrected data and sort\n df_temp1 = df_temp1[[FLOW_VARIABLE, serial_num] + night_columns + stay_columns].sort_values(serial_num)\n\n df_impute_towns_ext = df_impute_towns.sort_values(serial_num)\n\n # Update df_impute_towns_ext info with the corrected data.\n df_impute_towns_ext.update(df_temp1)\n\n # Generate lists to hold the loop data frames\n seg: list = [0] * 4\n df_temp2: list = [0] * 4\n df_temp3: list = [0] * 4\n segment: list = [0] * 4\n cseg: list = [0] * 4\n trunc_segment: list = [0] * 4\n\n # Loop over imputation levels\n for level in range(1, MAXIMUM_LEVEL + 1):\n strata = STRATA_LEVELS[level - 1]\n\n df_impute_towns_ext['VISIT_WTK_NONMISS'] = \\\n np.where(df_impute_towns_ext[VISIT_WEIGHTK_VARIABLE] != '', 1, np.nan)\n df_impute_towns_ext['VISIT_WTK_ALL'] = 1\n\n # Sort df_impute_towns_ext by strata\n df_impute_towns_ext = df_impute_towns_ext.sort_values(strata)\n\n # Replace blank values with -1 as python drops blanks during the aggregation process.\n df_impute_towns_ext[strata] = df_impute_towns_ext[strata].fillna(-1)\n\n # Calculate the number of records in each segment that have previously\n # been uplifted and the total number of records in each segment\n df_impute_towns_ext1 = df_impute_towns_ext.groupby(strata)['VISIT_WTK_NONMISS'].agg(['count'])\n df_impute_towns_ext1.rename(columns={'count': 'VISIT_WT_COUNT', }, inplace=True)\n\n df_impute_towns_ext2 = df_impute_towns_ext.groupby(strata)['VISIT_WTK_ALL'].agg(['count'])\n df_impute_towns_ext2.rename(columns={'count': 'TOTAL_COUNT', }, inplace=True)\n\n # Flatten the column structure after adding the new columns above\n df_impute_towns_ext1 = df_impute_towns_ext1.reset_index()\n df_impute_towns_ext2 = df_impute_towns_ext2.reset_index()\n\n # Merge the two data sets generated\n seg[level - 1] = pd.merge(df_impute_towns_ext1, df_impute_towns_ext2, on=strata, how='inner')\n\n # Replace the previously added -1 values with their original blank values\n df_impute_towns_ext[strata] = df_impute_towns_ext[strata].replace(-1, np.NaN)\n seg[level - 1][strata] = seg[level - 1][strata].replace(-1, np.NaN)\n\n # Copy the data and calculate the visit, stay and expenditure weights\n df_impute_towns_ext_mod = df_impute_towns_ext.copy()\n\n df_impute_towns_ext_mod['FIN'] = df_impute_towns_ext_mod[final_weight] * df_impute_towns_ext_mod[\n VISIT_WEIGHT_VARIABLE]\n df_impute_towns_ext_mod['STY'] = df_impute_towns_ext_mod[STAY_VARIABLE] * df_impute_towns_ext_mod[\n final_weight] * df_impute_towns_ext_mod[STAY_WEIGHT_VARIABLE]\n df_impute_towns_ext_mod['EXP'] = df_impute_towns_ext_mod[SPEND_VARIABLE] * df_impute_towns_ext_mod[\n final_weight] * df_impute_towns_ext_mod[EXPENDITURE_WEIGHT_VARIABLE]\n\n # Compute weight totals over good records\n df_temp2[level - 1] = df_impute_towns_ext_mod.loc[df_impute_towns_ext_mod[INFO_PRESENT_MARKER] == 1]\n\n # Replace blank values with -1 as python drops blanks during the aggregation process.\n df_temp2[level - 1][strata] = df_temp2[level - 1][strata].fillna(-1)\n\n df_temp2_count = df_temp2[level - 1].groupby(strata)['FIN'].agg(['count'])\n df_temp2_count.rename(columns={'count': 'TOWN_COUNT', }, inplace=True)\n\n df_temp2_fin = df_temp2[level - 1].groupby(strata)['FIN'].agg(['sum'])\n df_temp2_fin.rename(columns={'sum': 'KNOWN_FINAL_WEIGHTS', }, inplace=True)\n\n df_temp2_sty = df_temp2[level - 1].groupby(strata)['STY'].agg(['sum'])\n df_temp2_sty.rename(columns={'sum': 'KNOWN_STAY', }, inplace=True)\n\n df_temp2_exp = df_temp2[level - 1].groupby(strata)['EXP'].agg(['sum'])\n df_temp2_exp.rename(columns={'sum': 'KNOWN_EXPEND', }, inplace=True)\n\n # Flatten the column structure after generating the new columns above\n df_temp2_count = df_temp2_count.reset_index()\n df_temp2_fin = df_temp2_fin.reset_index()\n df_temp2_sty = df_temp2_sty.reset_index()\n df_temp2_exp = df_temp2_exp.reset_index()\n\n # Merge the generated values into one data frame\n df_temp2[level - 1] = pd.merge(df_temp2_count, df_temp2_fin, on=strata, how='inner')\n df_temp2[level - 1] = pd.merge(df_temp2[level - 1], df_temp2_sty, on=strata, how='inner')\n df_temp2[level - 1] = pd.merge(df_temp2[level - 1], df_temp2_exp, on=strata, how='inner')\n\n # Replace the previously added -1 values with their original blank values\n df_temp2[level - 1][strata] = df_temp2[level - 1][strata].replace(-1, np.NaN)\n\n # Compute weight totals over bad records\n df_temp3[level - 1] = df_impute_towns_ext_mod[df_impute_towns_ext_mod[INFO_PRESENT_MARKER] == 0]\n\n # Replace blank values with -1 as python drops blanks during the aggregation process.\n df_temp3[level - 1][strata] = df_temp3[level - 1][strata].fillna(-1)\n\n df_temp3_count = df_temp3[level - 1].groupby(strata)['FIN'].agg(['count'])\n df_temp3_count.rename(columns={'count': 'NO_TOWN_COUNT', }, inplace=True)\n\n df_temp3_fin = df_temp3[level - 1].groupby(strata)['FIN'].agg(['sum'])\n df_temp3_fin.rename(columns={'sum': 'UNKNOWN_FINAL_WEIGHT', }, inplace=True)\n\n df_temp3_sty = df_temp3[level - 1].groupby(strata)['STY'].agg(['sum'])\n df_temp3_sty.rename(columns={'sum': 'UNKNOWN_STAY', }, inplace=True)\n\n df_temp3_exp = df_temp3[level - 1].groupby(strata)['EXP'].agg(['sum'])\n df_temp3_exp.rename(columns={'sum': 'UNKNOWN_EXPEND', }, inplace=True)\n\n # Flatten the column structure after generating the new columns above\n df_temp3_count = df_temp3_count.reset_index()\n df_temp3_fin = df_temp3_fin.reset_index()\n df_temp3_sty = df_temp3_sty.reset_index()\n df_temp3_exp = df_temp3_exp.reset_index()\n\n # Merge the generated values into one data frame\n df_temp3[level - 1] = pd.merge(df_temp3_count, df_temp3_fin, on=strata, how='inner')\n df_temp3[level - 1] = pd.merge(df_temp3[level - 1], df_temp3_sty, on=strata, how='inner')\n df_temp3[level - 1] = pd.merge(df_temp3[level - 1], df_temp3_exp, on=strata, how='inner')\n\n # Replace the previously added -1 values with their original blank values\n df_temp3[level - 1][strata] = df_temp3[level - 1][strata].replace(-1, np.NaN)\n\n # Sort the generated data frames by strata before merging them together\n seg[level - 1] = seg[level - 1].sort_values(strata)\n df_temp2[level - 1] = df_temp2[level - 1].sort_values(strata)\n df_temp3[level - 1] = df_temp3[level - 1].sort_values(strata)\n\n # Merge good and bad totals into the data\n segment[level - 1] = pd.merge(seg[level - 1], df_temp2[level - 1], on=strata, how='left')\n segment[level - 1] = pd.merge(segment[level - 1], df_temp3[level - 1], on=strata, how='left')\n\n # Account for missing values by setting weights to zero\n segment[level - 1].loc[segment[level - 1]['UNKNOWN_FINAL_WEIGHT'].isnull(), 'UNKNOWN_FINAL_WEIGHT'] = 0\n segment[level - 1].loc[segment[level - 1]['UNKNOWN_STAY'].isnull(), 'UNKNOWN_STAY'] = 0\n segment[level - 1].loc[segment[level - 1]['UNKNOWN_EXPEND'].isnull(), 'UNKNOWN_EXPEND'] = 0\n segment[level - 1].loc[segment[level - 1]['TOTAL_COUNT'].isnull(), 'TOTAL_COUNT'] = 0\n segment[level - 1].loc[segment[level - 1]['TOWN_COUNT'].isnull(), 'TOWN_COUNT'] = 0\n segment[level - 1].loc[segment[level - 1]['NO_TOWN_COUNT'].isnull(), 'NO_TOWN_COUNT'] = 0\n\n # Replace blank values with -1 and sort the data by strata\n segment[level - 1][strata] = segment[level - 1][strata].fillna(-1)\n segment[level - 1] = segment[level - 1].sort_values(strata)\n\n # Replace the previously added -1 values with their original blank values\n segment[level - 1][strata] = segment[level - 1][strata].replace(-1, np.NaN)\n\n # Look for records that still need to be uplifted\n cseg[level - 1] = segment[level - 1].loc[\n segment[level - 1]['TOWN_COUNT'] != segment[level - 1]['VISIT_WT_COUNT']]\n\n # Count the number of records found that still need uplifting\n record_count = len(cseg[level - 1].index)\n\n if record_count > 0:\n # Remove invalid groups from the imputation set\n\n # Check current level, as level 4 thresholds are different to 1-3\n if level < 4:\n trunc_segment[level - 1] = segment[level - 1].loc[\n (segment[level - 1]['VISIT_WT_COUNT'] < segment[level - 1]['TOTAL_COUNT'])]\n\n condition = (\n (trunc_segment[level - 1]['TOWN_COUNT'] >= 20)\n & (trunc_segment[level - 1]['NO_TOWN_COUNT'] < trunc_segment[level - 1]['TOWN_COUNT'])\n & (trunc_segment[level - 1]['KNOWN_EXPEND'] != 0)\n & (trunc_segment[level - 1]['KNOWN_STAY'] != 0)\n & (trunc_segment[level - 1]['KNOWN_FINAL_WEIGHTS'] != 0)\n & (trunc_segment[level - 1]['KNOWN_FINAL_WEIGHTS'].notnull())\n & (((trunc_segment[level - 1]['KNOWN_FINAL_WEIGHTS']\n + trunc_segment[level - 1]['UNKNOWN_FINAL_WEIGHT'])\n / trunc_segment[level - 1]['KNOWN_FINAL_WEIGHTS']) <= 2)\n & (((trunc_segment[level - 1]['KNOWN_STAY'] + trunc_segment[level - 1]['UNKNOWN_STAY'])\n / trunc_segment[level - 1]['KNOWN_STAY']) <= 2)\n & (((trunc_segment[level - 1]['KNOWN_EXPEND'] + trunc_segment[level - 1]['UNKNOWN_EXPEND'])\n / trunc_segment[level - 1]['KNOWN_EXPEND']) <= 2)\n )\n\n trunc_segment[level - 1] = trunc_segment[level - 1].loc[condition]\n\n if level > 3:\n trunc_segment[level - 1] = segment[level - 1].loc[\n (segment[level - 1]['VISIT_WT_COUNT'] < segment[level - 1]['TOTAL_COUNT'])]\n\n condition = ((trunc_segment[level - 1]['KNOWN_EXPEND'] != 0)\n & (trunc_segment[level - 1]['KNOWN_STAY'] != 0)\n & (trunc_segment[level - 1]['KNOWN_FINAL_WEIGHTS'] != 0))\n\n trunc_segment[level - 1] = trunc_segment[level - 1].loc[condition]\n\n # Sort trunc_segment before merging into the df_impute_towns_ext data frame\n trunc_segment[level - 1] = trunc_segment[level - 1].sort_values(strata)\n\n # Select data to be merged\n trunc_segment[level - 1] = trunc_segment[level - 1][strata + ['VISIT_WT_COUNT', 'TOTAL_COUNT',\n 'KNOWN_FINAL_WEIGHTS', 'KNOWN_STAY',\n 'KNOWN_EXPEND', 'UNKNOWN_FINAL_WEIGHT',\n 'UNKNOWN_STAY', 'UNKNOWN_EXPEND']]\n\n # Sort df_impute_towns_ext before merge\n df_impute_towns_ext = df_impute_towns_ext.sort_values(strata)\n\n # Join the known and unknown weights onto the original data\n df_impute_towns_ext = pd.merge(df_impute_towns_ext, trunc_segment[level - 1], on=strata, how='left')\n\n # Calculate the revised weights\n def calculate_revised_weights(row):\n\n if row['KNOWN_FINAL_WEIGHTS'] != 0 and not math.isnan(row['KNOWN_FINAL_WEIGHTS']):\n\n if row[VISIT_WEIGHTK_VARIABLE] == '':\n row[VISIT_WEIGHTK_VARIABLE] = str(level)\n row[STAY_WEIGHTK_VARIABLE] = str(level)\n row[EXPENDITURE_WEIGHTK_VARIABLE] = str(level)\n\n if row[INFO_PRESENT_MARKER] == 1 and row[VISIT_WEIGHTK_VARIABLE] == str(level):\n row[VISIT_WEIGHT_VARIABLE] = row[VISIT_WEIGHT_VARIABLE] * (\n row['KNOWN_FINAL_WEIGHTS'] + row['UNKNOWN_FINAL_WEIGHT']) / row[\n 'KNOWN_FINAL_WEIGHTS']\n row[STAY_WEIGHT_VARIABLE] = row[STAY_WEIGHT_VARIABLE] * (\n row['KNOWN_STAY'] + row['UNKNOWN_STAY']) / row['KNOWN_STAY']\n row[EXPENDITURE_WEIGHT_VARIABLE] = row[EXPENDITURE_WEIGHT_VARIABLE] * (\n row['KNOWN_EXPEND'] + row['UNKNOWN_EXPEND']) / row['KNOWN_EXPEND']\n\n elif row[INFO_PRESENT_MARKER] == 0:\n\n row[VISIT_WEIGHT_VARIABLE] = 0\n row[STAY_WEIGHT_VARIABLE] = 0\n row[EXPENDITURE_WEIGHT_VARIABLE] = 0\n pass\n\n return row\n\n df_impute_towns_ext = df_impute_towns_ext.apply(calculate_revised_weights, axis=1)\n\n # Drop the no longer needed columns\n df_impute_towns_ext = df_impute_towns_ext.drop(columns=['KNOWN_FINAL_WEIGHTS', 'KNOWN_STAY',\n 'KNOWN_EXPEND', 'UNKNOWN_FINAL_WEIGHT',\n 'UNKNOWN_STAY', 'UNKNOWN_EXPEND'])\n\n # if record_count > 0\n\n # Loop end\n\n # Extract the required data from the looped dataset\n df_output_data = df_impute_towns_ext[[serial_num,\n VISIT_WEIGHT_VARIABLE, STAY_WEIGHT_VARIABLE, EXPENDITURE_WEIGHT_VARIABLE,\n VISIT_WEIGHTK_VARIABLE, STAY_WEIGHTK_VARIABLE, EXPENDITURE_WEIGHTK_VARIABLE] +\n night_columns + stay_columns]\n\n def round_wts(row):\n row['VISIT_WTK'] = pd.to_numeric(row['VISIT_WTK'], errors=\"coerce\")\n row['STAY_WTK'] = pd.to_numeric(row['STAY_WTK'], errors=\"coerce\")\n row['EXPENDITURE_WTK'] = pd.to_numeric(row['EXPENDITURE_WTK'], errors=\"coerce\")\n\n row['VISIT_WTK'] = ips_rounding(row['VISIT_WTK'], 1)\n row['STAY_WTK'] = ips_rounding(row['STAY_WTK'], 1)\n row['EXPENDITURE_WTK'] = ips_rounding(row['EXPENDITURE_WTK'], 1)\n\n row[VISIT_WEIGHT_VARIABLE] = ips_rounding(row[VISIT_WEIGHT_VARIABLE], 3)\n row[STAY_WEIGHT_VARIABLE] = ips_rounding(row[STAY_WEIGHT_VARIABLE], 3)\n row[EXPENDITURE_WEIGHT_VARIABLE] = ips_rounding(row[EXPENDITURE_WEIGHT_VARIABLE], 3)\n\n row[stay_columns] = pd.to_numeric(row[stay_columns], errors=\"ignore\")\n\n return row\n\n df_output_data = df_output_data.apply(round_wts, axis=1)\n\n df_output_data[stay_columns].fillna(np.nan, inplace=True)\n df_output_data['STAY_WTK'].fillna(np.nan, inplace=True)\n df_output_data['EXPENDITURE_WTK'].fillna(np.nan, inplace=True)\n df_output_data['VISIT_WTK'].fillna(np.nan, inplace=True)\n\n # Sort the output data frame\n df_output_data = df_output_data.sort_values(serial_num)\n\n return df_output_data\n","sub_path":"ips/services/calculations/calculate_regional_weights.py","file_name":"calculate_regional_weights.py","file_ext":"py","file_size_in_byte":20976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"218770820","text":"# 1. imports of your dash app\nimport dash\nimport dash_html_components as html\n\n\n# 2. give each testcase a tcid, and pass the fixture\n# as a function argument, less boilerplate\ndef test_bsly001_falsy_child(dash_duo):\n\n # 3. define your app inside the test function\n app = dash.Dash(__name__)\n app.layout = html.Div(id=\"nully-wrapper\", children=0)\n\n # 4. host the app locally in a thread, all dash server configs could be\n # passed after the first app argument\n dash_duo.start_server(app)\n\n # 5. use wait_for_* if your target element is the result of a callback,\n # keep in mind even the initial rendering can trigger callbacks\n dash_duo.wait_for_text_to_equal(\"#nully-wrapper\", \"0\", timeout=4)\n\n # 6. use this form if its present is expected at the action point\n assert dash_duo.find_element(\"#nully-wrapper\").text == \"0\"\n\n # 7. to make the checkpoint more readable, you can describe the\n # acceptance criterion as an assert message after the comma.\n assert dash_duo.get_logs() == [], \"browser console should contain no error\"\n\n # 8. visual testing with percy snapshot\n dash_duo.percy_snapshot(\"bsly001-layout\")\n","sub_path":"tests/dash_simple.py","file_name":"dash_simple.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"111657439","text":"import os\nimport sys\n\nsys.path.insert(0, \"../../util/python\")\nimport Cons\nimport Util\n\nimport Conf\n\ndef Gen():\n\t_LoadData()\n\t_GenPlotData()\n\n\n_fn_plot_data = None\n_latencies = []\n\ndef _LoadData():\n\t#storage_types = [\"local-ssd\", \"ebs-ssd-iop\", \"ebs-ssd-gp2\", \"ebs-mag\"]\n\tstorage_types = [\"local-ssd\", \"ebs-ssd-gp2\", \"ebs-mag\"]\n\tc_or_d = [\"cached\", \"direct\"]\n\n\twith Cons.MeasureTime(\"Reading data files ...\"):\n\t\tfor st in storage_types:\n\t\t\tfor cd in c_or_d:\n\t\t\t\t#Cons.P(\"%s %s\" % (cd, s))\n\t\t\t\t_latencies.append(ReadLat(cd, st))\n\n\ndef _GenPlotData():\n\tglobal _fn_plot_data\n\twith Cons.MeasureTime(\"Generating plot data ...\"):\n\t\t_fn_plot_data = \"data/stg-cost-latency-%s.%s\" % (Conf.Get(\"exp_hostname\"), Conf.Get(\"exp_datetime\"))\n\t\twith open(_fn_plot_data, \"w\") as fo:\n\t\t\tfmt = \"%13s %9.3f %7.1f %7.1f %8.6f\"\n\t\t\t#Cons.P(Util.BuildHeader(fmt, \"storage_type avg_read_us read_1p_us read_99p_us cost($/GB/Month)\"))\n\t\t\tfo.write(\"%s\\n\" % Util.BuildHeader(fmt, \"storage_type avg_read_us read_1p_us read_99p_us cost($/GB/Month)\"))\n\t\t\tfor l in _latencies:\n\t\t\t\tif l.c_or_d == \"cached\":\n\t\t\t\t\tcontinue\n\t\t\t\t#Cons.P(fmt % (l.storage_type, l.read_avg, l.read_1, l.read_99, _StgCost(l.storage_type)))\n\t\t\t\tfo.write((fmt + \"\\n\") % (\"\\\"%s\\\"\" % l.plot_label, l.read_avg, l.read_1, l.read_99, _StgCost(l.storage_type)))\n\t\tCons.P(\"Created file %s %d\" % (_fn_plot_data, os.path.getsize(_fn_plot_data)))\n\n\ndef _StgCost(storage_type):\n\t#Cons.P(Conf.Get(\"stg_cost\"))\n\treturn Conf.Get(\"stg_cost\")[storage_type]\n\n\nclass ReadLat(object):\n\tdef __init__(self, c_or_d, storage_type):\n\t\tself.c_or_d = c_or_d\n\t\tself.storage_type = storage_type\n\t\tself.fn = \"data/%s.%s.%s-%s\" % (Conf.Get(\"exp_hostname\"), Conf.Get(\"exp_datetime\"), storage_type, c_or_d)\n\t\tself.read_times_us = []\n\t\tself.plot_label = None\n\t\tif storage_type == \"local-ssd\":\n\t\t\tself.plot_label = \"Ins SSD\"\n\t\telif storage_type == \"ebs-ssd-iop\":\n\t\t\tself.plot_label = \"EBS SSD PIO\"\n\t\telif storage_type == \"ebs-ssd-gp2\":\n\t\t\tself.plot_label = \"EBS SSD\"\n\t\telif storage_type == \"ebs-mag\":\n\t\t\tself.plot_label = \"EBS Mag\"\n\n\t\tself.ReadFile()\n\t\n\tdef ReadFile(self):\n\t\t#with Cons.MeasureTime(\"Reading file %s ...\" % self.fn):\n\t\t#Cons.P(\"%s %d\" % (self.fn, os.path.getsize(self.fn)))\n\t\twith open(self.fn) as fo:\n\t\t\tfor line in fo.readlines():\n\t\t\t\t# 4.0 KiB from /mnt/ebs-mag/ioping-test (ext4 /dev/xvdc): request=14 time=1 us\n\t\t\t\ttokens = line.split(\"time=\")\n\t\t\t\tif len(tokens) != 2:\n\t\t\t\t\tcontinue\n\t\t\t\tt1 = tokens[1].split()\n\t\t\t\tif len(t1) != 2:\n\t\t\t\t\traise RuntimeError(\"Unexpected format [%s]\" % line)\n\t\t\t\tread_time_us = float(t1[0])\n\t\t\t\tif t1[1] == \"us\":\n\t\t\t\t\tpass\n\t\t\t\telif t1[1] == \"ms\":\n\t\t\t\t\tread_time_us *= 1000.0\n\t\t\t\telif t1[1] == \"s\":\n\t\t\t\t\tread_time_us *= 1000000.0\n\t\t\t\telse:\n\t\t\t\t\traise RuntimeError(\"Unexpected format [%s]\" % line)\n\t\t\t\t#sys.stdout.write(\"%f \" % read_time_us)\n\t\t\t\tself.read_times_us.append(read_time_us)\n\t\tself.CalcStat()\n\t\n\tdef CalcStat(self):\n\t\t#Cons.P(\"%d\" % len(self.read_times_us))\n\t\tself.read_avg = sum(self.read_times_us) / float(len(self.read_times_us))\n\t\tself.read_times_us.sort()\n\t\tidx = int(0.01 * len(self.read_times_us))\n\t\tself.read_1 = self.read_times_us[idx]\n\t\tidx = int(0.99 * len(self.read_times_us))\n\t\tself.read_99 = self.read_times_us[idx]\n\t\t#Cons.P(\"avg=%9.3f 1%%=%9.3f 99%%=%9.3f\" % (self.read_avg, self.read_1, self.read_99))\n","sub_path":"mtdb/misc/storage-type-cost-latency/PlotData.py","file_name":"PlotData.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"14092523","text":"import collections\r\nimport math\r\n# debug=False\r\n# with open('A-small-practice.in') as f:\r\ndebug=True\r\nwith open('A-large.in') as f:\r\n\tcontent = f.readlines()\r\n\r\ndef GetLastNumberBeforeSleep(N):\t\r\n\tif(N==0):\r\n\t\treturn \"INSOMNIA\"\r\n\tdigit,currentNumber={'0','1','2','3','4','5','6','7','8','9'},N\r\n\twhile len(digit)!=0:\r\n\t\ttempDigit=set(digit)\r\n\t\tstrCurrentNumber=str(currentNumber)\r\n\t\tfor x in digit:\r\n\t\t\tif(x in strCurrentNumber):\r\n\t\t\t\ttempDigit.remove(x)\r\n\t\tif(len(tempDigit)==0):\r\n\t\t\treturn currentNumber\r\n\t\telse: \r\n\t\t\tcurrentNumber+=N\r\n\t\t\tdigit=tempDigit\r\n\t\t\r\n\r\n\r\nnumOfTestCase=int(content.pop(0))\r\nfor x in range(numOfTestCase):\r\n\tN=int(content.pop(0))\r\n\t# print(\"N: \"+str(N))\r\n\tprint(\"Case #%d: %s\"%(x+1,GetLastNumberBeforeSleep(N)))\r\n","sub_path":"codes/CodeJamCrawler/16_0_1/astr/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"652612163","text":"import xmlschema\nfrom pprint import pprint\nfrom lxml import etree\nimport os\nimport pdfx\nfrom threading import Thread\nfrom queue import Queue\nfrom pymongo import MongoClient\nfrom optparse import OptionParser\n\nparser = OptionParser()\nparser.add_option(\"-r\", \"--recover\", action='store_true', dest=\"recovery\", default=True,\n help=\"resume downloading data from the last inserted document of mongo\")\n(options, args) = parser.parse_args()\n\nrecovery_id=0\n\nMAX_FETCH_THREADS=50\nWORKER_THREADS=5\n\n\nq = Queue(maxsize=0)\nthread_pool = []\n\nclass DataInsertThread(Thread):\n\n database = None\n thread_id = 1\n\n def __init__(self, db, queue, _element_tree, recovery_id_offset=0):\n self.data = False\n self._element_tree = _element_tree\n self.database = db\n self.queue = queue\n self.arxiv_id = None\n\n if _element_tree is not None:\n self.thread_id = DataInsertThread.thread_id + recovery_id_offset\n DataInsertThread.thread_id += 1\n\n Thread.__init__(self)\n\n def _getData(self):\n # ensure we only do work when we need to\n if self.data:\n return\n\n element_tree = etree.XML(etree.tostring(self._element_tree))\n arxiv_id = element_tree.xpath(\"//*[local-name()='id']/text()\")[0]\n self.arxiv_id = arxiv_id\n arxiv_abstract = element_tree.xpath(\"//*[local-name()='abstract']/text()\")[0]\n\n arxiv_pdf_link = self.get_pdf_link_from_arxiv_id(arxiv_id)\n arxiv_pdf_contents = pdfx.PDFx(arxiv_pdf_link)\n \n arxiv_pdf_contents_text = arxiv_pdf_contents.get_text()\n arxiv_pdf_contents_references = arxiv_pdf_contents.get_references_as_dict()\n arxiv_pdf_contents_metadata = arxiv_pdf_contents.get_metadata()\n\n _data = {\n \"id\" : arxiv_id,\n \"abstract\" : arxiv_abstract,\n \"text\" : arxiv_pdf_contents_text,\n \"references\" : arxiv_pdf_contents_references,\n \"metadata\" : arxiv_pdf_contents_metadata,\n \"recovery_id\" : self.thread_id\n }\n\n self.data = True\n print('thread about to queue data')\n self.queue.put(_data)\n print (\"THREAD CLEAN-UP: \"+ self.arxiv_id)\n\n def _getQueueItemsAndInsert(self):\n print(\"worker thread initialized\")\n while True:\n queue_data = self.queue.get()\n\n # if the thread doesn't complete, we don't store the data\n if queue_data is None:\n print(\"data was none...\")\n self.queue.task_done()\n return\n \n print(\"storing data from queue\")\n self.database.papers.insert(queue_data, check_keys=False)\n self.queue.task_done()\n\n def run(self):\n # if the thread doesn't have an element tree, it's a worker thread\n if self._element_tree is None:\n self._getQueueItemsAndInsert()\n\n # otherwise its a getter thread\n else:\n self._getData()\n\n def get_pdf_link_from_arxiv_id(self, arxiv_id):\n base = \"https://arxiv.org/pdf/{0}.pdf\"\n return base.format(arxiv_id)\n\n\ndef get_last_inserted_arxiv_id():\n global recovery_id\n last_inserted_paper = databaseObject.papers.find().sort([('recovery_id', -1)]).limit(1)\n if last_inserted_paper.count() == 0:\n return None\n recovery_id = last_inserted_paper[0][\"recovery_id\"]\n return last_inserted_paper[0][\"id\"]\n\n\ndef iterate_xml(xmlfile):\n global options\n last_inserted_arxiv_id = None\n\n if options.recovery:\n skip_iter = True\n last_inserted_arxiv_id = get_last_inserted_arxiv_id()\n print (\"----------------RECOVERY IN PROGRESS----------------\")\n\n else:\n skip_iter = False\n\n doc = etree.iterparse(xmlfile, events=('start', 'end'))\n _, root = next(doc)\n start_tag = None\n for event, element in doc:\n if event == 'start' and start_tag is None:\n start_tag = element.tag\n if event == 'end' and element.tag == start_tag:\n if skip_iter:\n # need to compare arxiv id of current _element tree of arxiv id to last mongo\n if last_inserted_arxiv_id is None:\n print('could not find any arxiv id in DB')\n skip_iter = False\n yield element\n\n else:\n element_tree = etree.XML(etree.tostring(element))\n arxiv_id = element_tree.xpath(\"//*[local-name()='id']/text()\")[0]\n if arxiv_id.strip().lower() == last_inserted_arxiv_id.strip().lower():\n print ('arxiv id matched: ' + arxiv_id)\n print (\"----------------RECOVERY SUCCESSFUL----------------\")\n skip_iter = False\n else:\n print ('skipping iteration. arxiv id: ' + arxiv_id)\n\n else:\n yield element\n\n start_tag = None\n root.clear()\n\n\ndef check_thread_completion():\n global thread_pool\n for t in thread_pool:\n if not t.isAlive():\n print('clean-up dead thread')\n thread_pool = [t for t in thread_pool if t.isAlive()]\n\nmongoClient = MongoClient(\"mongodb://localhost:27017/\",\n maxPoolSize=MAX_FETCH_THREADS, # connection pool size\n waitQueueTimeoutMS=1000, # how long a thread can wait for a connection\n waitQueueMultiple=MAX_FETCH_THREADS # when the pool is fully used N threads can wait\n )\n\n# Get the database object\ndatabaseObject = mongoClient.ThoughtDB_ARXIV\n\narxiv_metadata_local_source = './arxiv-bulk-metadata/arxiv_biblio_arXiv.2018-01-19.xml'\n\n# these threads will get from the queue and put data into mongo\nfor i in range(WORKER_THREADS):\n worker = DataInsertThread(databaseObject, q, None)\n worker.setDaemon(True)\n worker.start()\n\n# these threads will fetch data from arxiv\n# parse the PDF and add to the queue\nfor _element_tree in iterate_xml(arxiv_metadata_local_source):\n # block when our thread pool is full until a thread is finished\n while (len(thread_pool) >= MAX_FETCH_THREADS):\n check_thread_completion()\n\n print(\"starting getter thread\")\n getter = DataInsertThread(databaseObject, q, _element_tree, recovery_id_offset=recovery_id)\n getter.setDaemon(True)\n getter.start()\n thread_pool.append(getter)\n\nwhile True:\n pass\n\n\n","sub_path":"parse_arxiv_metadata_threaded.py","file_name":"parse_arxiv_metadata_threaded.py","file_ext":"py","file_size_in_byte":6377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397882768","text":"import cv2\r\nimport dlib\r\n\r\nwebcam = cv2.VideoCapture(0)\r\nwhile True:\r\n s, imagem = webcam.read()\r\n detector = dlib.get_frontal_face_detector()\r\n imagemCinza = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY)\r\n facesDetectadas = detector(imagemCinza)\r\n for faces in facesDetectadas:\r\n e, t, d, b = (int(faces.left()), int(faces.top()), int(faces.right()), int(faces.bottom()))\r\n cv2.rectangle(imagem, (e, t), (d,b), (0,255,0), 2)\r\n cv2.imshow(\"Faces Detectadas\", imagem)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n\r\nwebcam.release()\r\ncv2.destroyAllWindows()","sub_path":"facialDetectorHog.py","file_name":"facialDetectorHog.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"528990949","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom typing import List\n\n\nclass Solution:\n def majorityElement(self, nums: List[int]) -> int:\n votes = 0\n for num in nums:\n if votes == 0: x = num\n votes += 1 if num == x else -1\n return x\n\n\nif __name__ == '__main__':\n mylist = [1, 2, 3, 2, 2, 2, 5, 4, 2]\n s = Solution()\n res = s.majorityElement(mylist)\n print(res)\n","sub_path":"algorithm/sword/剑指 Offer 39. 数组中出现次数超过一半的数字.py","file_name":"剑指 Offer 39. 数组中出现次数超过一半的数字.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"173522130","text":"# encoding: utf8\nimport unittest\nfrom dueros.directive.Display.template.ListTemplate2 import ListTemplate2\nfrom dueros.directive.Display.template.ListTemplateItem import ListTemplateItem\n\n\nclass ListTemplate2Test(unittest.TestCase):\n '''\n ListTemplate2 单元测试\n '''\n\n def setUp(self):\n self.listTemplate2 = ListTemplate2()\n\n def testGetData(self):\n '''\n 测试getData\n :return:\n '''\n\n self.listTemplate2.set_background_image('http://back-img.com')\n\n listTemplateItem1 = ListTemplateItem()\n listTemplateItem1.set_image('http://item-img1.com', '123', '345')\n listTemplateItem1.set_plain_primary_text('Plain Primary Text')\n listTemplateItem1.set_plain_secondary_text('Plain Secondary Text')\n listTemplateItem1.set_tertiary_text('Plain Tertiary Text')\n\n listTemplateItem1.data['token'] = 'token'\n\n listTemplateItem2 = ListTemplateItem()\n listTemplateItem2.set_image('http://item-img2.com', '12', '45')\n listTemplateItem2.set_plain_primary_text('Plain Primary Text')\n listTemplateItem2.set_plain_secondary_text('Plain Secondary Text')\n listTemplateItem2.set_tertiary_text('Plain Tertiary Text')\n\n listTemplateItem2.data['token'] = 'token'\n\n self.listTemplate2.add_item(listTemplateItem1)\n self.listTemplate2.add_item(listTemplateItem2)\n data = self.listTemplate2.get_data()\n data['token'] = 'token'\n ret = {\n 'type': 'ListTemplate2',\n 'token': 'token',\n 'backgroundImage': {\n 'url': 'http://back-img.com'\n },\n 'listItems': [\n {\n 'token': 'token',\n 'image': {\n 'url': 'http://item-img1.com',\n 'widthPixels': '123',\n 'heightPixels': '345'\n },\n 'textContent': {\n 'primaryText': {\n 'type': 'PlainText',\n 'text': 'Plain Primary Text'\n },\n 'secondaryText': {\n 'type': 'PlainText',\n 'text': 'Plain Secondary Text'\n },\n 'tertiaryText': {\n 'type': 'PlainText',\n 'text': 'Plain Tertiary Text'\n }\n }\n },\n {\n 'token': 'token',\n 'image': {\n 'url': 'http://item-img2.com',\n 'widthPixels': '12',\n 'heightPixels': '45'\n },\n 'textContent': {\n 'primaryText': {\n 'type': 'PlainText',\n 'text': 'Plain Primary Text'\n },\n 'secondaryText': {\n 'type': 'PlainText',\n 'text': 'Plain Secondary Text'\n },\n 'tertiaryText': {\n 'type': 'PlainText',\n 'text': 'Plain Tertiary Text'\n }\n }\n }\n ]\n }\n\n self.assertEqual(self.listTemplate2.get_data(), ret)\n\n pass\n","sub_path":"dueros/tests/directive/display/template/ListTemplate2Test.py","file_name":"ListTemplate2Test.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"234054067","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BOARD) # Para numerar os pinos fisicos\nPIN_TRIGGER = 3 # Define o pino do sensor que emitira a onda sonora\nPIN_ECHO = 5 # Define o pino do sensor que receberá a onda sonora\nGPIO.setup(PIN_TRIGGER, GPIO.OUT) # Enviar a onda, OUT\nGPIO.setup(PIN_ECHO, GPIO.IN) # Receber a onda, IN\n\n\nwhile True:\n try:\n # Garante que o sensor estará desligado, para maior precisão do mensuramento da distancia do objeto\n GPIO.output(PIN_TRIGGER, False)\n print(\"Esperando o sensor estabilizar\")\n time.sleep(2) # Tempo para o mesmo estabilizar\n\n # Começo do processo para calcular a distancia, aviso para o usuario\n print(\"Calculando distância\")\n\n # Liga o sensor que enviara a onda sonora\n GPIO.output(PIN_TRIGGER, True)\n\n time.sleep(0.00001) # O sensor requer um de 1 nanosegundo para ativar\n\n GPIO.output(PIN_TRIGGER, False) # Desligamos novamente\n\n while GPIO.input(PIN_ECHO) == 0: # Checaremos se o receptor da onda está desligado (não recebeu o sinal). Caso não, enviaremos para a variavel o tempo atual até que a condição se torne falsa (ou seja, 1, HIGH)\n tempo_inicial = time.time() # Tempo de saida da onda\n # Checaremos se o receptor da onda está ligado (recebeu o sinal). Caso sim, gravará em uma variavel o tempo atual até o pin ECHO estiver desligado novamente.\n while GPIO.input(PIN_ECHO) == 1:\n tempo_final = time.time() # Tempo de chegada da onda\n\n # Calcula a diferença do tempo de chegada e envio da onda sonora\n duracao_onda = tempo_final - tempo_inicial\n distancia = round(duracao_onda * 17150, 2) # Calcula a distancia da onda, em centimetros, e arredonda a mesma para printar ao usuario. A velocidade ultrassonica do som: 34300 cm/s. Como so queremos a distancia percorrida até o objeto, devemos dividir esse valor por 2, dando o valor de 17.150cm/s, no qual devemos multiplicar pela duraçao do impulso da onda (diferença entre saida e chegada) para obtermos o resultado da distancia em centimetros\n print(f'Distancia {distancia}')\n finally:\n GPIO.cleanup() # Limpa as portas GPIO para não entrar em conflito com nenhum sensor\n","sub_path":"sensores/HCSR04.py","file_name":"HCSR04.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"360840527","text":"#!/usr/bin/env python3\nimport sys\nimport os\n\nfrom PyQt5 import QtCore\n\nfrom signmud2.ipc import send_message\n\n\ndef main():\n app = QtCore.QCoreApplication(sys.argv)\n parser = QtCore.QCommandLineParser()\n parser.addHelpOption()\n opt_socket = QtCore.QCommandLineOption(\"s\", \n \"Socket/fifo to send the message to\", \"SOCKET\")\n opt_socket.setDefaultValue(os.path.expanduser(\"~/.signmud2/socket\"))\n parser.addOption(opt_socket)\n parser.addPositionalArgument(\"message\", \"message to send\")\n parser.process(app)\n\n args = parser.positionalArguments()\n if not args:\n raise Exception(\"must specify the message\")\n if len(args) > 1:\n raise Exception(\"must specify only one message\")\n\n message = args[0]\n send_message(parser.value(opt_socket), message)\n sys.exit(0)\n\n \nif __name__ == '__main__':\n main()\n","sub_path":"notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"532829038","text":"import dlib\r\nimport cv2\r\nimport numpy as np\r\nfrom datetime import datetime\r\n\r\n#C:\\Users\\haneu\\fin_pro\r\ndetector = dlib.get_frontal_face_detector()\r\npredictor = dlib.shape_predictor('C:/Users/haneu/fin_pro/modle/shape_predictor_68_face_landmarks.dat')\r\nface_recog = dlib.face_recognition_model_v1('C:/Users/haneu/fin_pro/modle/dlib_face_recognition_resnet_model_v1.dat')\r\n\r\n#인코딩이 되어있거 가져옴\r\n#print(\"20개의 인코딩\")\r\n#descs = np.load('C:/Users/haneu/fin_pro/a_project/a_descs.npy', allow_pickle=True)[()]\r\n#descs = np.load('C:/Users/haneu/fin_pro/a_project/a5_descs.npy', allow_pickle=True)[()]\r\n#descs = np.load('C:/Users/haneu/fin_pro/a_project/a10_descs.npy', allow_pickle=True)[()]\r\ndescs = np.load('C:/Users/haneu/fin_pro/a_project/a20_descs.npy', allow_pickle=True)[()]\r\n\r\n#들어온 영상에서 이미지 찾기 \r\ndef encode_faces(image):\r\n\r\n faces = detector(image,1)\r\n\r\n if len(faces) == 0:\r\n return np.empty(0)\r\n\r\n for k, d in enumerate(faces):\r\n land = predictor(image, d)\r\n face_decriptor = face_recog.compute_face_descriptor(image, land)\r\n\r\n return np.array(face_decriptor)\r\n\r\n#실시간으로 해보자\r\n#stream_cap = cv2.VideoCapture(\"http://172.30.1.40:8090/?action=stream\")\r\nstream_cap = cv2.VideoCapture(0)\r\n\r\n\r\n#show the time\r\ndef get_time():\r\n #tm = time.localtime()\r\n #tm_p = time.strftime('%Y-%m-%d-%H-%M-%S-%f', tm)\r\n now = datetime.now()\r\n tm_p = now.strftime('%Y-%m-%d-%H-%M-%S-%f')\r\n print(\"time : \",tm_p)\r\n return tm_p\r\n\r\n#text_w = open('C:/Users/haneu/fin_pro/a_project/a_result.txt', 'w')\r\n#check the score\r\nchs = 0\r\nch_sum = 0\r\n\r\n\r\nwhile True:\r\n ret, img_bgr = stream_cap.read()\r\n\r\n if not ret:\r\n break\r\n\r\n #img_bgr = cv2.resize(img_bgr, video_size)\r\n img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)\r\n\r\n faces = detector(img_rgb, 1)\r\n\r\n for k, d in enumerate(faces):\r\n #사각형위치 찾아놓기\r\n rect = ( (d.left(), d.top()), (d.right(), d.bottom()) )\r\n\r\n land = predictor(img_rgb, d)\r\n face_descriptor = face_recog.compute_face_descriptor(img_rgb, land)\r\n\r\n last_found = {'name': 'unknown', 'dist': 0.6, 'color': (0,0,255)} \r\n\r\n for name, saved_desc in descs.items():\r\n dist = np.linalg.norm([face_descriptor] - saved_desc, axis=1)\r\n\r\n if dist < last_found['dist']:\r\n last_found = {'name': name, 'dist': dist, 'color': (255,255,255)}\r\n #tm_p = get_time() #인식될때 시간을 찍음\r\n #print(\"오차 : \", dist)\r\n #print('name : ' + last_found['name']+' time : ' + tm_p+' dist : ' + dist)\r\n \r\n \r\n cv2.rectangle(img_bgr, pt1=(d.left(), d.top()), pt2=(d.right(), d.bottom()), color=last_found['color'], thickness=2)\r\n cv2.putText(img_bgr, last_found['name'], org=(d.left(), d.top()), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, color=last_found['color'], thickness=2)\r\n\r\n tm_p=get_time()\r\n print('name : ', last_found['name'])\r\n #print(\"오차 : \", dist) \r\n\r\n #text_w.write(last_found['name'] +\" \" + tm_p + '\\n')\r\n\r\n if (chs == 0):\r\n first_name = last_found['name']\r\n\r\n\r\n if (ch_sum < 3):\r\n if (first_name == last_found['name']):\r\n ch_sum +=1\r\n chs +=1\r\n else:\r\n chs = 0\r\n ch_sum = 0\r\n\r\n else:\r\n if (first_name ==last_found['name']):\r\n print('find check user')\r\n print('name : ', last_found['name'])\r\n tm_p=get_time()\r\n\r\n else: #unkown\r\n print('find unuser\\n')\r\n\r\n chs=0\r\n ch_sum=0\r\n \r\n\r\n\r\n #writer.write(img_bgr)\r\n\r\n cv2.imshow('img', img_bgr)\r\n if cv2.waitKey(1) == ord('q'):\r\n break\r\n\r\n#text_w.close()\r\nstream_cap.release()\r\ncv2.destroyAllWindows()\r\n#writer.release()\r\n\r\n \r\n\r\n\r\n","sub_path":"face-recog-test/check_camera.py","file_name":"check_camera.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"543653083","text":"#!/usr/bin/env python\n\n\"\"\"\ninput_interpreter.py\n\nActs as the user-input interpreter for the application.\n\"\"\"\n\nimport utilities.common as common\nfrom resources.var_manager import variable_interpreter, list_variables\n\n__author__ = \"terratenff\"\n__credits__ = [\"terratenff\"]\n\n__license__ = \"MIT\"\n__version__ = \"0.0.1\"\n__maintainer__ = \"terratenff\"\n__status__ = \"Prototype\"\n\nSUPPORTED_COMMANDS = (\"quit\", \"help\", \"test\", \"var\", \"move\", \"back\", \"return\", \"list\", \"run\")\n\nMODULE_NAME = \"input_interpreter\"\n\nHELP = {\n MODULE_NAME: \"Operates as the interpreter for user input.\",\n \"quit\": \"Shuts down the application.\",\n \"help\": \"Provides information on how to use something. Note that root module cannot be tested.\",\n \"test\": \"Runs the unit tests of the current module.\\n\\n\"\n \"Additional parameters indicate specific functions to test instead of all of them.\\n\"\n \"Add the parameters in the following manner:\\n\\n\"\n \"test \\n\\n\"\n \"Note that in order to test module functions, you must 'move' to it first.\",\n \"var\": \"Creates, or re-defines an existing variable.\\n\\n\"\n \"There are two different methods of defining a variable.\\n\\n\"\n \"1. Via Text File manipulation. Variables exist within the program as text files.\\n\"\n \" Any rows are separated with line breaks, and columns are separated with whitespace.\\n\"\n \" The name of the text file acts as the name of the variable.\\n\"\n \" 'var ' can be used to view specified variable.\\n\"\n \"2. Via Manual Input. Using the following format, a variable can be defined in the program:\\n\"\n \" var = \\n\"\n \" Note that whitespace between the equal sign must exist!\\n\"\n \" A (column) vector can be defined by separating multiple values with hyphens (;).\\n\"\n \" A row vector can be defined by separating multiple values with commas (,).\\n\"\n \" A matrix can be defined by separating multiple row vectors with hyphens.\\n\"\n \" NOTE 1: Do not leave any whitespace between numbers, hyphens and commas!\\n\"\n \" NOTE 2: Do not perform computations while defining a variable; they are not supported.\\n\"\n \" NOTE 3: Using Python Console/Shell to define variables? Use the function 'store_variable' that\\n\"\n \" can be found from 'resources.var_manager'. It will save the variable as a text file.\\n\\n\"\n \"Mathematics Module 'matrices' can be used to define matrix variables of larger scale.\\n\",\n \"move\": \"Moves you to the specified sub-module if it exists within the current module.\\n\\n\"\n \"For example, you can go from root to matrices using 'move matrices'.\\n\"\n \"Existing sub-modules can be listed with the 'list' command.\",\n \"back\": \"Moves you back by one module, unless you are on root module, in which case it does nothing.\",\n \"return\": \"Takes you back to the root module.\",\n \"list\": \"Lists various items of specified target of interest.\\n\\n\"\n \"The following targets of interest can be listed:\\n\"\n \"- Variables ('list var')\\n\"\n \"- Base Commands ('list command')\\n\"\n \"- Functions of Current Module ('list function')\\n\"\n \"- Available Sub-Modules ('list module')\",\n \"run\": \"Runs specified function if it is available to you.\\n\\n\"\n \"If no input/output variables are provided, the function may or may not work, depending on how the \"\n \"function is implemented.\\n\"\n \"The following format shows how to use the 'run' command:\\n\"\n \"run (,,,)\\n\\n\"\n \"If the function does not take any parameters, the 'run' command is used as follows:\\n\"\n \"run ()\"\n}\n\n\ndef read_input(user_path, args):\n \"\"\"\n User input interpreter. If user input is valid, passes it over for operation selection.\n :param user_path: User's current path\n :param args: User inputs\n :return: loop_status, exit_code, action, user_path\n\n Action Integer represents the following:\n 0 = No action. Also applies for integers not in [1, 4].\n 1 = Help - Get help text for a specific item.\n 2 = Move - Move to specified module, if it exists within current module.\n 3 = List - Print a set of something.\n 4 = Run - Run a specific function, available to the current module.\n \"\"\"\n\n # common.pr(MODULE_NAME, \"Checking for supported command...\")\n if args[0] in SUPPORTED_COMMANDS:\n return _interpret(user_path, args)\n else:\n common.pr(MODULE_NAME, \"Unsupported command '\" + args[0] + \"'.\")\n return 0, 0, 0, user_path\n\n\ndef _interpret(user_path, args):\n \"\"\"\n Interprets user input in more detail, and performs an appropriate course of action.\n :param user_path: User's current path\n :param args: User inputs\n :return: loop_status, exit_code, action, user_path\n \"\"\"\n # common.pr(MODULE_NAME, \"Recognized args: \" + str(args))\n keyword = args[0]\n arg_count = len(args)\n\n if keyword == \"quit\":\n return 0, -1, 0, \"\"\n\n elif keyword == \"help\":\n if arg_count == 2:\n help_outcome = common.pr_help(HELP, args[1], MODULE_NAME)\n if help_outcome is False:\n return 0, 0, 1, user_path\n else:\n if arg_count > 2:\n common.pr(MODULE_NAME, \"Too many arguments: 'help' command only takes 1 argument.\")\n else:\n common.pr(MODULE_NAME, \"Please specify what you'd like help with.\")\n common.pr(MODULE_NAME, \"For example, you could use 'list command' to view every supported command.\")\n\n elif keyword == \"var\":\n variable_interpreter(args)\n\n elif keyword == \"move\":\n if arg_count == 2:\n return 0, 0, 2, user_path\n elif arg_count == 1:\n common.pr(MODULE_NAME, \"Please specify which module you would like to move to.\")\n else:\n common.pr(MODULE_NAME, \"Too many arguments: 'move' only takes 1 argument.\")\n\n elif keyword == \"back\":\n return -1, 0, 0, user_path\n\n elif keyword == \"return\":\n return -2, 0, 0, user_path\n\n elif keyword == \"list\":\n if arg_count == 2:\n if args[1] == \"var\":\n list_variables()\n elif args[1] == \"command\":\n common.pr(MODULE_NAME, \"List of primary commands:\\n\\n\" + \"\\n\".join(SUPPORTED_COMMANDS) + \"\\n\")\n elif args[1] == \"module\" or args[1] == \"function\":\n return 0, 0, 3, user_path\n else:\n common.pr(MODULE_NAME, \"Target '\" + args[1] + \"' cannot be listed.\")\n elif arg_count > 2:\n common.pr(MODULE_NAME, \"Too many arguments: 'list' only takes 1 argument.\")\n else:\n common.pr(MODULE_NAME, \"Please specify what should be listed.\")\n\n elif keyword == \"run\":\n if arg_count == 1:\n common.pr(MODULE_NAME, \"Please specify what function should be run.\")\n elif arg_count > 2:\n common.pr(MODULE_NAME, \"Too many arguments. Are you providing parameters? Separate them with commas, \"\n \"and do not use whitespace at all!\")\n else:\n left_par = args[1].find(\"(\")\n right_par = args[1].find(\")\")\n left_count = args[1].count(\"(\")\n right_count = args[1].count(\")\")\n if left_par == -1 or right_par == -1:\n common.pr(MODULE_NAME, \"Function call is missing parentheses. Example case: 'run function_name()'\")\n elif left_count != 1 or right_count != 1:\n common.pr(MODULE_NAME, \"Invalid syntax.\")\n elif left_par > right_par or left_par == 0:\n common.pr(MODULE_NAME, \"Incorrect use of parentheses.\")\n else:\n return 0, 0, 4, user_path\n\n elif keyword == \"test\":\n return 0, 0, 5, user_path\n\n return 0, 0, 0, user_path\n","sub_path":"input_interpreter.py","file_name":"input_interpreter.py","file_ext":"py","file_size_in_byte":8079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"479555347","text":"# PEP 249\nimport config\n\ncursor = config.db.cursor()\n\n# list all rows\n\n\ndef list_rows():\n cursor.execute(\"\"\"SELECT * FROM table\"\"\")\n return list(cursor)\n\n# delete by id\n\n\ndef delete(id):\n try:\n cursor.execute(\"\"\"DELETE FROM `table`\n WHERE id = %s\"\"\",\n (id,)\n )\n config.db.commit()\n print(\"complete delete\")\n except:\n config.db.rollback()\n print(\"error while delete row\")\n\n# insert tuple\n\n\ndef insert(tuple):\n try:\n cursor.execute(\"\"\"INSERT INTO `table`\n (`param1`,`param2`,`param3`,`param4`,`param5`,`param6`)\n VALUES(%s,%s,%s,%s,%s,%s)\"\"\", tuple)\n config.db.commit()\n return cursor.lastrowid\n except:\n config.db.rollback()\n print(\"error while insert row\")\n\n# update name\n\n\ndef update(id, param):\n try:\n cursor.execute(\"\"\"UPDATE `table`\n SET param = %s\n WHERE id = %s\"\"\",\n (param, id))\n config.db.commit()\n return cursor.lastrowid\n except:\n config.db.rollback()\n print(\"error while update row\")\n\n# get row by id\n\n\ndef get_row(id):\n try:\n cursor.execute(\"\"\"SELECT *\n FROM `table`\n WHERE id = %s\"\"\", (id,)\n )\n config.db.commit()\n return list(cursor)\n except:\n config.db.rollback()\n print(\"error while get row\")\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"455028387","text":"# Author: Porter Zach\n# Python 3.9\n\nimport cv2\nimport numpy as np\nimport argparse\n\n# path = \"test_cases/easy/easy_0.mp4\"\n# path = \"test_cases/hard/hard_1.mp4\"\n# path = \"test_cases/hard/hard_0.mp4\"\n\nparser = argparse.ArgumentParser(description=\"\")\n\nparser.add_argument(action=\"append\", dest=\"paths\", nargs=\"?\", help=\"The path to the video to remove the logo from and the path to save the edited video to (default: \\'_edit.avi\\').\")\nparser.add_argument(\"--scalar\", action=\"store\", dest=\"scalar\", default=1, type=float, help=\"The scalar to resize the labeling image by (in case it's too big or small).\")\n\nargs = parser.parse_args()\n\nsavePath = args.paths[1] if len(args.paths) > 1 else (args.paths[0] + \"_edit.avi\")\n\nvideo = cv2.VideoCapture(args.paths[0])\n\nopacity = .3\n\nix, iy = 0, 0\ndrawing = False\nrect = { \"x1\": 0, \"y1\": 0, \"x2\": 0, \"y2\": 0 }\ndone_drawing = False\n\nret, img = video.read()\noverlay = img.copy()\n\n#region Initial Labeling\n\ndef scaleMouse(x, y):\n \"\"\"Scales the mouse in case a scalar was specified.\n\n Args:\n x (int): The X coordinate of the mouse.\n y (int): The Y coordinate of the mouse.\n\n Returns:\n int, int: The scaled X and Y mouse coordinates.\n \"\"\"\n return int(x / args.scalar), int(y / args.scalar)\n\ndef handleMouse(event, x, y, flags, param):\n \"\"\"Handles mouse actions. Begins drawing on mouse down, sets label on mouse up.\n\n Args:\n event (int): The type of mouse event.\n x (int): The X coordinate of the mouse.\n y (int): The Y coordinate of the mouse.\n flags (int): Flags relevant to the mouse action.\n param (obj): Parameters regarding the mouse action.\n \"\"\"\n # get global variables\n global drawing, ix, iy, done_drawing\n \n x, y = scaleMouse(x, y)\n\n # if the mouse was pressed:\n if event == cv2.EVENT_LBUTTONDOWN:\n # start drawing\n drawing = True\n # set initial values\n ix, iy = x, y\n # if the mouse was moved:\n elif event == cv2.EVENT_MOUSEMOVE:\n # update the rect if drawing\n if drawing:\n rect[\"x1\"] = min(ix, x)\n rect[\"y1\"] = min(iy, y)\n rect[\"x2\"] = max(ix, x)\n rect[\"y2\"] = max(iy, y)\n # if the mouse was released:\n elif event == cv2.EVENT_LBUTTONUP:\n if drawing:\n done_drawing = True\n\n# def jump(frames):\n# \"\"\"Jumps the video by the specified amount of frames.\n\n# Args:\n# frames (int): The number of frames to jump by.\n# \"\"\"\n# # get global variables\n# global video, img\n\n# # get the position in the video\n# pos = video.get(cv2.CAP_PROP_POS_FRAMES)\n\n# # jump to the new position\n# video.set(cv2.CAP_PROP_POS_FRAMES, pos + frames)\n\n# # read the new frame \n# ret, temp = video.read()\n# if ret:\n# img = temp\n# else:\n# # reset if it is out of the video bounds\n# print(\"New frame position \" + str(pos + frames) + \" is invalid.\")\n# video.set(cv2.CAP_PROP_POS_FRAMES, pos)\n\n# initialize the window\ncv2.namedWindow(\"Window\")\ncv2.setMouseCallback(\"Window\", handleMouse)\n\ntry:\n while not done_drawing:\n cv2.rectangle(overlay, (rect[\"x1\"], rect[\"y1\"]), (rect[\"x2\"], rect[\"y2\"]), (0, 255, 0), thickness=-1)\n\n cv2.addWeighted(overlay, opacity, img, 1 - opacity, 0, overlay)\n\n # resize image if specified\n if args.scalar != 1:\n overlay = cv2.resize(overlay, \n (int(overlay.shape[1] * args.scalar), int(overlay.shape[0] * args.scalar)), \n interpolation=cv2.INTER_AREA)\n \n cv2.imshow(\"Window\", overlay)\n\n k = cv2.waitKey(1) & 0xFF\n # # handle frame jumps\n # if k == 44 & 0xFF: # ,\n # jump(-5)\n # if k == 46 & 0xFF: # .\n # jump(5)\n # exit if escape is pressed\n if k == 27:\n exit()\nexcept KeyboardInterrupt:\n print(\"Editing interrupted. Not saving.\")\n cv2.destroyAllWindows()\n video.release()\n exit()\n \ncv2.destroyAllWindows()\n\n#endregion\n\nfeature_params = dict( maxCorners = 500,\n qualityLevel = 0.3,\n minDistance = 7,\n blockSize = 7 )\n\nlk_params = dict( winSize = (31, 31),\n maxLevel = 2,\n criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 30, 0.1))\n\ntrack_length = 10\ndetect_interval = 1\ntracks = []\nframe_index = 0\nprev_gray = None\n\ndef getRect():\n return min(rect[\"x1\"], rect[\"x2\"]), min(rect[\"y1\"], rect[\"y2\"]), max(rect[\"x1\"], rect[\"x2\"]), max(rect[\"y1\"], rect[\"y2\"])\ndef setRect(x1, y1, x2, y2):\n global rect\n rect = { \"x1\": x1, \"y1\": y1, \"x2\": x2, \"y2\": y2 }\n\ndef avg(points):\n ax = 0\n ay = 0\n p = np.int32(points).reshape(-1, 2)\n for x, y in p:\n ax += x\n ay += y\n return (int(ax / p.shape[0]), int(ay / p.shape[0]))\n\ndef moveRect(center):\n x1, y1, x2, y2 = getRect()\n w = x2 - x1\n h = y2 - y1\n x1 = center[0] - w / 2\n x2 = center[0] + w / 2\n y1 = center[1] - h / 2\n y2 = center[1] + h / 2\n setRect(x1, y1, x2, y2)\n\ndef rectMask(img):\n r = getRect()\n w = img.shape[1]\n h = img.shape[0]\n o = .02\n return int(r[0] - w * o), int(r[1] - h * o), int(r[2] + w * o), int(r[3] + h * o)\n\ndef drawRect(img):\n x1, y1, x2, y2 = map(int, rectMask(img))\n overlay = img.copy()\n cv2.rectangle(overlay, (x1, y1), (x2, y2), (0, 255, 0), thickness=-1)\n\n img = cv2.addWeighted(overlay, .3, img, 1 - .3, 0, overlay)\n return img\n\ntry:\n while True:\n ret, img = video.read()\n if not ret:\n break\n \n minBlack = np.array([0, 0, 0])\n maxBlack = np.array([360, 255, 75])\n\n minWhite = np.array([0, 0, 150])\n maxWhite = np.array([360, 50, 255])\n\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n mask_black = cv2.inRange(hsv, minBlack, maxBlack)\n mask_white = cv2.inRange(hsv, minWhite, maxWhite)\n\n img_black = cv2.bitwise_and(img, img, mask = mask_black)\n img_white = cv2.bitwise_and(img, img, mask = mask_white)\n \n kernel_small = np.ones((3,3), np.uint8)\n kernel_5 = np.ones((5,5), np.uint8)\n kernel_big = np.ones((7,7),np.uint8)\n kernel_9 = np.ones((13,13),np.uint8)\n\n black_grayscale = cv2.cvtColor(img_black, cv2.COLOR_BGR2GRAY)\n _, black_threshed = cv2.threshold(black_grayscale, 5, 255, cv2.THRESH_BINARY)\n\n black_threshed_dilated = cv2.morphologyEx(black_threshed, cv2.MORPH_DILATE, kernel_big)\n\n img_white_masked = cv2.bitwise_and(img_white, img_white, mask = black_threshed_dilated)\n\n result_morph = cv2.cvtColor(img_white_masked, cv2.COLOR_BGR2GRAY)\n _, result_morph = cv2.threshold(result_morph, 10, 255, cv2.THRESH_BINARY)\n\n orb = cv2.ORB_create()\n kp = orb.detect(result_morph)\n\n # kp_mask = np.zeros_like(mask_black)\n # avg = (0, 0)\n # for keypoint in kp:\n # avg = (avg[0] + keypoint.pt[0], avg[1] + keypoint.pt[1])\n # kp_mask[int(keypoint.pt[1]), int(keypoint.pt[0])] = 255\n # avg = (int(avg[0] / len(kp)), int(avg[1] / len(kp)))\n\n # avg_mask = np.zeros_like(kp_mask)\n # cv2.circle(avg_mask, avg, 100, (255,255,255), thickness=-1)\n\n # kp_mask = cv2.bitwise_and(kp_mask, kp_mask, mask=avg_mask)\n \n # kp_mask = cv2.morphologyEx(kp_mask, cv2.MORPH_CLOSE, kernel_big)\n # kp_mask = cv2.morphologyEx(kp_mask, cv2.MORPH_OPEN, kernel_small)\n # kp_mask = cv2.morphologyEx(kp_mask, cv2.MORPH_DILATE, kernel_9)\n\n # result_morph = cv2.bitwise_and(result_morph, result_morph, mask=kp_mask)\n\n frame_gray = result_morph\n if prev_gray is None:\n prev_gray = frame_gray\n\n if frame_index == 0:\n mask = np.zeros_like(frame_gray)\n x1,y1,x2,y2 = rectMask(mask)\n mask[y1:y2, x1:x2] = 255\n p = cv2.goodFeaturesToTrack(frame_gray, mask=mask, **feature_params)\n if p is not None:\n for x, y in np.float32(p).reshape(-1, 2):\n tracks.append([(x, y)])\n\n overlay = img.copy()\n\n if len(tracks) > 0:\n # get quick refs to previous and new frames\n img0, img1 = prev_gray, frame_gray\n p0 = np.float32([tr[-1] for tr in tracks]).reshape(-1, 1, 2)\n # get the current frame's optical flow\n p1, _, _ = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)\n # get the flow from this frame to the previous\n p0r, _, _ = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)\n d = abs(p0-p0r).reshape(-1, 2).max(-1)\n good = d < 1\n new_tracks = []\n for tr, (x, y), good_flag in zip(tracks, p1.reshape(-1, 2), good):\n if not good_flag:\n continue\n tr.append((x, y))\n if len(tr) > track_length:\n del tr[0]\n new_tracks.append(tr)\n cv2.circle(overlay, (int(x), int(y)), 2, (0, 255, 0), -1)\n tracks = new_tracks\n cv2.polylines(overlay, [np.int32(tr) for tr in tracks], False, (0, 255, 0))\n\n if frame_index % detect_interval == 0:\n mask = np.zeros_like(frame_gray)\n x1,y1,x2,y2 = rectMask(mask)\n mask[y1:y2, x1:x2] = 255\n for x, y in [np.int32(tr[-1]) for tr in tracks]:\n cv2.circle(mask, (x, y), 15, 255, -1)\n p = cv2.goodFeaturesToTrack(frame_gray, mask=mask, **feature_params)\n if p is not None:\n a = avg(p)\n moveRect(a)\n for x, y in np.float32(p).reshape(-1, 2):\n tracks.append([(x, y)])\n \n frame_index += 1\n prev_gray = frame_gray\n\n \n\n overlay = drawRect(overlay)\n result_morph = cv2.cvtColor(result_morph, cv2.COLOR_GRAY2BGR)\n result_morph = cv2.drawKeypoints(result_morph, kp, None, color = (0, 255, 0), flags = 0)\n # cv2.rectangle(overlay, (rect[\"x1\"], rect[\"y1\"]), (rect[\"x2\"], rect[\"y2\"]), (0, 255, 0), thickness=-1)\n\n # cv2.addWeighted(overlay, opacity, img, 1 - opacity, 0, overlay)\n\n cv2.imshow(\"output\", result_morph)\n\n if cv2.waitKey(1) == 27:\n break\nexcept KeyboardInterrupt:\n pass\n\ncv2.destroyAllWindows()\n\n# hard 1 and 3","sub_path":"failures/remove_logo2.py","file_name":"remove_logo2.py","file_ext":"py","file_size_in_byte":10424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"78805591","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QApplication\nimport os, sys\nimport mainWindow\n\n\n\n# this is the main window\nclass Truck(QtWidgets.QMainWindow, mainWindow.Ui_MainWindow):\n def __init__(self, parent=None):\n super(Truck, self).__init__(parent)\n self.setupUi(self)\n self.light = 2 # 0 is red, 1 is yellow, 2 is green, 3 is green-left\n self.changeLight(2)\n self.move = 0 # 0 is nothing, 1 is forward, 2 is left, 3 is right, 4 is stop\n # listen for the buttons\n self.redButton.clicked.connect(self.handleRedButton)\n self.yellowButton.clicked.connect(self.handleYellowButton)\n self.greenButton.clicked.connect(self.handleGreenButton)\n self.leftGreenButton.clicked.connect(self.handleLeftGreenButton)\n self.fowardButton.clicked.connect(self.handleFowardButton)\n self.leftButton.clicked.connect(self.handleLeftButton)\n self.rightButton.clicked.connect(self.handleRightButton)\n self.runOverButton.clicked.connect(self.handleRunOverButton)\n self.output(\"SUV is fueled and ready for some road rage!\")\n\n\n # handle if the red button is clicked\n def handleRedButton(self):\n self.changeLight(0)\n\n # handle if the yellow button is clicked\n def handleYellowButton(self):\n self.changeLight(1)\n\n # handle if the green button is clicked\n def handleGreenButton(self):\n self.changeLight(2)\n\n # handle if the left green button is clicked\n def handleLeftGreenButton(self):\n self.changeLight(3)\n\n # handle if the forward button is clicked\n def handleFowardButton(self):\n if (self.move == 1):\n self.output(\"ERROR: The SUV is already moving forward!\")\n self.resetLight()\n return\n elif (self.light == 0):\n self.output(\"ERROR: You can't go through a red light!\")\n self.resetLight()\n return\n elif (self.light == 1):\n self.output(\"Phew! Squeezed through that one!\")\n elif (self.light == 2):\n self.output(\"Went foward through the green light.\")\n elif (self.light == 3):\n self.output(\"ERROR: You can't go forward through a left-turn green light!\")\n self.resetLight()\n return\n self.move = 1\n self.resetLight()\n\n # handle if the left button is clicked\n def handleLeftButton(self):\n if (self.light == 0):\n self.output(\"ERROR: You can't turn left on a red light!\")\n self.resetLight()\n return\n elif (self.light == 1):\n self.output(\"ERROR: You can't turn left on a yellow light!\")\n self.resetLight()\n return\n elif (self.light == 2):\n self.output(\"ERROR: You can't turn left on a green light!\")\n self.resetLight()\n return\n elif (self.light == 3):\n self.output(\"You turned left on the left-turn green light.\")\n self.move = 2\n self.resetLight()\n\n # handle if the right button is clicked\n def handleRightButton(self):\n if (self.light == 0):\n self.output(\"You turn right after looking for oncoming traffic.\")\n elif (self.light == 1):\n self.output(\"Phew! Squeezed through that one!\")\n elif (self.light == 2):\n self.output(\"You turned right on the green light.\")\n elif (self.light == 3):\n self.output(\"ERROR: You can't turn right on a left-turn green light!\")\n self.resetLight()\n return\n self.move = 3\n self.resetLight()\n\n # handle if the stop button is clicked\n def handleRunOverButton(self):\n if (self.move != 1):\n self.output(\"ERROR: You must be moving forward to run over the Ford Pinto.\")\n self.resetLight()\n return\n self.output(\"The puny Ford Pinto is crushed like a tin can by the might of your SUV.\")\n self.move = 4\n self.resetLight()\n\n # output to the list\n def output(self, string):\n self.outputList.addItem(string)\n\n # function to streamline changing the light\n def changeLight(self, number):\n self.light = number\n if (number == 0):\n self.redLabel.setText(\"Red\")\n self.yellowLabel.setText(\"\")\n self.greenLabel.setText(\"\")\n self.leftGreenLabel.setText(\"\")\n elif (number == 1):\n self.redLabel.setText(\"\")\n self.yellowLabel.setText(\"Yellow\")\n self.greenLabel.setText(\"\")\n self.leftGreenLabel.setText(\"\")\n elif (number == 2):\n self.redLabel.setText(\"\")\n self.yellowLabel.setText(\"\")\n self.greenLabel.setText(\"Green\")\n self.leftGreenLabel.setText(\"\")\n elif (number == 3):\n self.redLabel.setText(\"\")\n self.yellowLabel.setText(\"\")\n self.greenLabel.setText(\"\")\n self.leftGreenLabel.setText(\"<---Green\")\n\n # reset the light to green\n def resetLight(self):\n self.changeLight(2)\n\n# this is the main driver for the GUI and client\ndef main():\n # make the app\n app = QApplication(sys.argv)\n # make the main window form\n form = Truck()\n # show the main window\n form.show()\n # exit the program after it's done (closes or runs to end)\n exit(app.exec())\n\n# if the script is run directly, run the main function\nif __name__=='__main__':\n main()","sub_path":"PythonGUI/SUV/suv.py","file_name":"suv.py","file_ext":"py","file_size_in_byte":5482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"7791025","text":"import discord\r\nimport os\r\nimport asyncio\r\nimport json\r\nfrom discord.ext import commands\r\n\r\nTOKEN = 'NTM2Mjk0MTQ5MDg3OTUyODk4.DyUm6A.EC44IQFiYIc4pzLpfekeIof0g4Y'\r\nclient = commands.Bot(command_prefix = '~')\r\nclient.remove_command('help')\r\n\r\n@client.event\r\nasync def on_ready():\r\n print('Ready to begin matchmaking')\r\n await client.change_presence(game=discord.Game(name='surviv.io'))\r\n\r\n@client.event\r\nasync def on_message(message):\r\n await client.process_commands(message)\r\n author = message.author\r\n content = message.content\r\n Channel = message.channel\r\n embed = discord.Embed(\r\n color = discord.Color.green(),\r\n title = 'would you like to play surviv.io with someone?',\r\n )\r\n if 'surviv' in content:\r\n embed.set_author(name='{}'.format(author))\r\n embed.add_field(name='Yes?', value='Type \"~yes\"', inline=True)\r\n embed.add_field(name='No?', value='Type \"~no\"', inline=True)\r\n\r\n await client.send_message(Channel, embed=embed)\r\n\r\n\r\n if message.content.startswith('~yes'):\r\n await client.process_commands(message)\r\n await client.send_message(Channel, 'Added you to the \"Looking For Players\" list, {}! :white_check_mark:'.format(author.mention))\r\n await client.send_message(Channel, 'Type \"~leave\" to leave the list.')\r\n user = message.author\r\n role = discord.utils.get(user.server.roles, name=\"Looking For Players\")\r\n await client.add_roles(user, role)\r\n nickname = 'Looking For Players'\r\n await client.change_nickname(message.author, nickname)\r\n\r\n if message.content.startswith('~join'):\r\n await client.process_commands(message)\r\n await client.send_message(Channel, 'Added you to the \"Looking For Players\" list, {}! :white_check_mark:'.format(author.mention))\r\n await client.send_message(Channel, 'Type \"~leave\" to leave the list.')\r\n user = message.author\r\n role = discord.utils.get(user.server.roles, name=\"Looking For Players\")\r\n await client.add_roles(user, role)\r\n nickname = 'Looking For Players'\r\n await client.change_nickname(message.author, nickname)\r\n\r\n\r\n if message.content.startswith('~no'):\r\n await client.process_commands(message)\r\n await client.send_message(Channel, 'Okay!')\r\n\r\n\r\n if message.content.startswith('~leave'):\r\n await client.send_message(Channel, 'Removed you from the \"Looking for Players\" list, {}! :white_check_mark:'.format(author.mention))\r\n nickname = ''\r\n await client.change_nickname(message.author, nickname)\r\n\r\n user = message.author\r\n role = discord.utils.get(user.server.roles, name=\"Looking For Players\")\r\n await client.remove_roles(user, role)\r\n\r\n if message.content.startswith('~start'):\r\n if message.author.id == \"125016735660113920\":\r\n await client.create_role(author.server, name=\"Looking For Players\", color = discord.Color.green())\r\n await client.send_message(Channel, 'A new session has started.')\r\n\r\n@client.event\r\nasync def on_message_delete(message):\r\n await client.process_commands(message)\r\n channel = client.get_channel('534866561870331914')\r\n author = message.author\r\n content = message.content\r\n embed = discord.Embed(\r\n title = '{}'.format(content),\r\n color = discord.Color.green()\r\n )\r\n\r\n embed.set_author(name='Deleted message from {}'.format(author))\r\n\r\n await client.send_message(channel, embed=embed)\r\n\r\n@client.command(pass_context=True)\r\nasync def help(ctx):\r\n author = ctx.message.author\r\n embed = discord.Embed(\r\n title = 'Here is a list of all commands:',\r\n color = discord.Color.green()\r\n )\r\n\r\n embed.set_author(name='Help')\r\n embed.add_field(name='~join', value='Joins the \"Looking For Players\" list.', inline=False)\r\n embed.add_field(name='~leave', value='Leaves the \"Looking For Players\" list.', inline=False)\r\n embed.add_field(name='~suggest', value='Sends a suggestion to the bot creator.', inline=False)\r\n\r\n await client.say('Okay! I sent you a DM!')\r\n await client.send_message(author, embed=embed)\r\n await client.process_commands(message)\r\n\r\n@client.command(pass_context=True)\r\nasync def suggest(ctx, *args):\r\n Channel = client.get_channel('536931772924035093')\r\n output = ''\r\n for word in args:\r\n output += word\r\n output += ' '\r\n author = ctx.message.author\r\n embed = discord.Embed(\r\n title = '{}'.format(author),\r\n color = discord.Color.green()\r\n )\r\n\r\n embed.set_author(name='{}'.format(output))\r\n await client.send_message(Channel, embed=embed)\r\n\r\n@client.command(pass_context=True)\r\nasync def yes(ctx):\r\n Channel = client.get_channel('536926205048258560')\r\n author = ctx.message.author\r\n embed = discord.Embed(\r\n title = '{} has joined the \"Looking For Players\" list'.format(author),\r\n color = discord.Color.green()\r\n )\r\n\r\n await client.send_message(Channel, embed=embed)\r\n\r\n@client.command(pass_context=True)\r\nasync def join(ctx):\r\n Channel = client.get_channel('536926205048258560')\r\n author = ctx.message.author\r\n embed = discord.Embed(\r\n title = '{} has joined the \"Looking For Players\" list'.format(author),\r\n color = discord.Color.green()\r\n )\r\n\r\n await client.send_message(Channel, embed=embed)\r\n\r\n@client.command(pass_context=True)\r\nasync def leave(ctx):\r\n Channel = client.get_channel('536926205048258560')\r\n author = ctx.message.author\r\n embed = discord.Embed(\r\n title = '{} has left the \"Looking For Players\" list\"'.format(author),\r\n color = discord.Color.red()\r\n )\r\n\r\n await client.send_message(Channel, embed=embed)\r\n\r\n@client.command(pass_context = True)\r\nasync def eat(ctx, userName: discord.User):\r\n Channel = client.get_channel('537047748898193429')\r\n author = ctx.message.author\r\n if author.id == '125016735660113920':\r\n await client.kick(userName)\r\n await client.send_message(Channel, '{} was kicked from iHASYOU'.format(userName))\r\n\r\n@client.command(pass_context=True)\r\nasync def warn(ctx, userName, *args):\r\n author = ctx.message.author\r\n Channel = client.get_channel('537047053281263616')\r\n if author.id == '125016735660113920':\r\n output = ''\r\n for word in args:\r\n output += word\r\n output += ' '\r\n await client.say('{} has been warned for `{}`'.format(userName, output))\r\n await client.send_message(Channel, '{} was warned for `{}`'.format(userName, output))\r\n else:\r\n await client.say(\"Looks like you can't do that, {}\".format(ctx.message.author.mention))\r\n\r\nclient.run(TOKEN)\r\n","sub_path":"matchmakingbot.py","file_name":"matchmakingbot.py","file_ext":"py","file_size_in_byte":6681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"102657867","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 9 16:45:39 2018\n\n@author: cu-pwfa\n\"\"\"\n\nfrom processes.process import Process\nimport daq\n\nclass SRSDG645(Process):\n def __init__(self, instr):\n \"\"\" Setup the conversion array. \n \n Parameters\n ----------\n instr : instr object\n The object representing the instrument the process will control.\n \"\"\"\n self.channels = ['T0', 'T1', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n self.index = {'T0':0, 'T1':1, 'A':2, 'B':3, 'C':4, 'D':5, 'E':6, 'F':7,\n 'G':8, 'H':9}\n self.save = False\n super().__init__(instr)\n \n def get_settings(self):\n \"\"\"Place the current settings on the SDG into the response queue.\"\"\"\n settings = {}\n sdg = self.device\n for i in range(10):\n # Output is only defined for T0, AB, BC, CD, EF, so set it the same for both\n ref, delay = sdg.get_delay(i)\n settings[self.channels[i]] = {\n 'delay' : delay,\n 'output' : sdg.get_output(int(i/2)),\n 'ref' : self.channels[ref],\n 'polarity' : sdg.get_polarity(int(i/2))\n }\n meta = self.create_meta()\n if self.save: response = 'save'\n else: response = 'output'\n rsp = daq.Rsp(response, info=settings, meta=meta)\n self.r_queue.put(rsp)\n \n def save_settings(self):\n \"\"\" Set save to true and place the settings in the response queue. \"\"\"\n self.save = True\n self.get_settings()\n self.save = False\n \n def set_settings(self, settings, save=False):\n \"\"\" Set the delay settings for a one or more channels.\n \n Parameters\n ----------\n settings : dict\n The dictionary containing the settings.\n save : bool, optional\n Specify if the new settings should be saved to file.\n \"\"\"\n sdg = self.device\n for key in settings:\n delay = settings[key]['delay']\n output = settings[key]['output']\n ref = settings[key]['ref']\n polarity = settings[key]['polarity']\n sdg.set_delay([ref, key, delay])\n if key == 'T0':\n sdg.set_output(['T0', output], pol=polarity)\n elif key == 'A':\n sdg.set_output(['AB', output], pol=polarity)\n elif key == 'C':\n sdg.set_output(['CD', output], pol=polarity)\n elif key == 'E':\n sdg.set_output(['EF', output], pol=polarity)\n elif key == 'G':\n sdg.set_output(['GH', output], pol=polarity)\n \n if save:\n meta = self.create_meta()\n rsp = daq.Rsp('save', settings, meta)\n self.r_queue.put(rsp)\n \n def set_chA_delay(self, delay):\n \"\"\" Set the delay for channel A keeping the same reference. \n \n Parameters\n ----------\n delay : float\n The delay in seconds for the channel.\n \"\"\"\n sdg = self.device\n ref, temp = sdg.get_delay(2)\n ref = self.channels[ref]\n sdg.set_delay([ref, 'A', delay])\n \n def set_chB_delay(self, delay):\n \"\"\" Set the delay for channel A keeping the same reference. \n \n Parameters\n ----------\n delay : float\n The delay in seconds for the channel.\n \"\"\"\n sdg = self.device\n ref, temp = sdg.get_delay(3)\n ref = self.channels[ref]\n sdg.set_delay([ref, 'B', delay])\n \n def set_chC_delay(self, delay):\n \"\"\" Set the delay for channel A keeping the same reference. \n \n Parameters\n ----------\n delay : float\n The delay in seconds for the channel.\n \"\"\"\n sdg = self.device\n ref, temp = sdg.get_delay(4)\n ref = self.channels[ref]\n sdg.set_delay([ref, 'C', delay])\n \n def get_datatype(self):\n \"\"\"Return the type of data. \"\"\"\n return \"SET\"\n \n def get_type(self):\n \"\"\" Return the instrument type. \"\"\"\n return \"SRSDG645\"","sub_path":"processes/SRSDG645.py","file_name":"SRSDG645.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"634170291","text":"import nltk.tag\nimport nltk.stem\nfrom nltk.corpus import stopwords\nimport re\nimport pickle\nimport MeCab\n\n\n\n#メールの本文の前処理を行う\nclass Pretreatment:\n # ---------------------------------------\n # 本文から取り除く正規表現\n\n email_quote = re.compile(r\"\\s*[>].*\")\n email_signature = re.compile(r\"-- \\r?\\n(.*\\S+.*\\n)+\")\n email_re = re.compile(r\"^>.*\")\n email_url = re.compile(r\"https?://[\\w/:%#\\$&\\?\\(\\)~\\.=\\+\\-]+\")\n email_start_other = re.compile(r\"^[^a-zA-Z].*\")\n emai_path = re.compile(r\"[a-zA-Z]:\\\\[\\w\\\\\\.]*\")\n email_kigou = re.compile(r\"[!-,.-/:-@\\[-\\^'{-~]\")\n email_number = re.compile(r\"[0-9]\")\n\n\n\n def clean_body(self,body):\n clean_text = []\n text_list = body.split(\"\\n\")\n for text in text_list:\n text = text.replace(\"\\r\\n\", \"\\n\")\n text = self.email_re.sub(\"\",text)\n text = self.email_signature.sub(\"\", text)\n text = self.email_url.sub(\"\", text)\n text = self.email_start_other.sub(\"\", text)\n text = self.emai_path.sub(\"\",text)\n text = self.email_number.sub(\"\",text)\n text = self.email_kigou.sub(\"\",text)\n clean_text.append(text)\n return (\" \").join(clean_text)\n\n\n#形態素解析を行うクラス\nclass TermTokenizer:\n html_tag = re.compile(r\"(<\\w+( [^>]*)?/?>||]*>|&#?\\w+;)\")\n term_tags = set([\"NN\", \"NNS\", \"NNP\", \"NNPS\", \"UNKONWN\", \"PRP\"])\n max_term_length = 10\n\n def __init__(self):\n self.nktk_stemmer = nltk.stem.PorterStemmer()\n self.nltk_lemmatizer = nltk.stem.WordNetLemmatizer()\n #f = open(\"/Users/katsu/Project/Program/E-ajSearcher/Sethourus_LDA/synonymAbbreviation_manualCheck.txt\")\n #se_list = []\n #self.se_thesaurus_list = []\n\n\n #for row in f:\n # row = row.replace(\"\\n\", \"\")\n # row = row.split(\",\")\n # self.se_thesaurus_list.append(row)\n # for word in row:\n # se_list.append(word)\n\n #self.se_word_list = se_list\n\n with open('/Users/katsu/Project/Program/E-ajSearcher/module/mysql_stopwords_list.pickle', mode='rb') as f:\n self.mysql_stopwords = pickle.load(f)\n\n\n\n def torkenize(self,text):\n word_list = nltk.word_tokenize(text)\n token = []\n #flag = 1\n\n for nltk_tag in nltk.pos_tag(word_list):\n\n if nltk_tag[1] in self.term_tags:\n #if flag == 1:\n tmp_term = nltk_tag[0]\n term = self.nktk_stemmer.stem(tmp_term.lower())\n if tmp_term in stopwords.words('english'):\n continue\n if term.isdigit() or not (4 <= len(term) <= self.max_term_length):\n continue\n token.append(term)\n else:\n continue\n return token\n\n def stopword_torkenize(self,text,stopword_list):\n word_list = nltk.word_tokenize(text)\n token = []\n for nltk_tag in nltk.pos_tag(word_list):\n\n if nltk_tag[1] in self.term_tags:\n tmp_term = nltk_tag[0]\n term = self.nktk_stemmer.stem(tmp_term.lower())\n\n if term in stopwords.words('english'):\n continue\n if term in self.mysql_stopwords:\n continue\n if term in stopword_list:\n continue\n if term.isdigit() or not (4 <= len(term) <= self.max_term_length):\n continue\n\n token.append(term)\n else:\n continue\n return token\n\n #SEthesaurusを利用,さらにシソーラスを統一\n def torkenize_NN(self,text):\n word_list = nltk.word_tokenize(text)\n token = []\n #flag == 1\n self.term_tags = set([\"NN\", \"NNS\", \"NNP\", \"NNPS\", \"UNKONWN\"])\n\n for nltk_tag in nltk.pos_tag(word_list):\n\n if nltk_tag[1] in self.term_tags:\n #if flag == 1:\n tmp_term = nltk_tag[0]\n term = self.nktk_stemmer.stem(tmp_term.lower())\n if tmp_term in stopwords.words('english'):\n continue\n if term.isdigit() or not (3 <= len(term) <= self.max_term_length):\n continue\n\n for thesaurus in self.se_thesaurus_list:\n if tmp_term in thesaurus:\n term = thesaurus[1]\n token.append(term)\n\n else:\n continue\n return token\n\n def plane_torken(self,text):\n\n\n text_list = list(text.split())\n\n return list(text_list)\n\n def se_word_torken(self,text):\n text_list = list(text.split())\n se_word_token = []\n for word in text_list:\n if word in self.se_word_list:\n se_word_token.append(word)\n\n return se_word_token\n\n#Mecabを用いてわかち書きまたは名詞のみ抽出する用\nclass MorphologicAlnalysis:\n def __init__(self):\n self.tagger_wakati = MeCab.Tagger(\"-Owakati\")\n self.tagger = MeCab.Tagger()\n #surfaceでmecabの文字が取得できないバグの対処\n self.tagger.parse(\"\") \n\n\n #分かち書き取得\n def Wakati(self,text):\n wakati = self.tagger_wakati.parse(text)\n return wakati\n\n #名詞のみ分かち書きで取得\n def ExtractNoun(self,text):\n node = self.tagger.parseToNode(text)\n nouns = []\n while node:\n pos = node.feature.split(\",\")[0]\n word = node.surface\n if pos == \"名詞\":\n nouns.append(word)\n node = node.next\n \n noun_wakati = \" \".join(nouns)\n return nouns\n\n\n","sub_path":"module/token_module.py","file_name":"token_module.py","file_ext":"py","file_size_in_byte":5752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"177793144","text":"# ! /usr/bin/env python\n# coding: utf-8\n\n\nimport pytest\nimport sys\nsys.path.append('.')\nfrom models import Translations\nfrom init import create_app\n\n\n@pytest.fixture(scope='module')\ndef translation1():\n translation = Translations('I speak English', '',\n 'en', 'es', '123456', 'new')\n return translation\n\n\n@pytest.fixture(scope='module')\ndef translation2():\n translation = Translations('My', '',\n 'es', 'pt', '123fasdewdfcv234523', 'pending')\n return translation\n\n\n@pytest.fixture(scope='module')\ndef translation3():\n translation = Translations('I am 14 years old ! My name is Vélèràê.', '',\n 'cn', 'portugggS', '1a', 'Translating')\n return translation\n\n@pytest.fixture(scope='module')\ndef translation4():\n translation = Translations('', '',\n 'cn', 'portugggS', '1a', 'Translating')\n return translation\n\n@pytest.fixture\ndef app():\n app = create_app()\n return app\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"161239282","text":"# Modified from wire3d_animation.py.\n\nfrom matplotlib._pylab_helpers import Gcf\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nbackend = plt.rcParams[\"backend\"]\nplt.rcdefaults()\nplt.rcParams[\"backend\"] = backend\n\n\ndef generate(X, Y, phi):\n R = 1 - np.hypot(X, Y)\n return np.cos(2 * np.pi * X + phi) * R\n\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\n# Make the X, Y meshgrid.\nxs = np.linspace(-1, 1, 50)\nys = np.linspace(-1, 1, 50)\nX, Y = np.meshgrid(xs, ys)\n\n# Begin plotting.\ntstart = time.process_time()\n# Keep track of plotted frames, so that FPS estimate stays reasonable even\n# after a ctrl-C's.\nfor i, phi in enumerate(np.linspace(0, 180. / np.pi, 100)):\n if not Gcf.get_num_fig_managers():\n break\n for line in [*ax.lines]:\n line.remove()\n Z = generate(X, Y, phi)\n ax.plot(X.flat, Z.flat, \"ok\")\n plt.pause(.001)\n\nprint(\"Average FPS: {}\".format((i + 1) / (time.process_time() - tstart)))\n","sub_path":"examples/circle_markers.py","file_name":"circle_markers.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"590009765","text":"# EXERCÍCIO 45\n# JOGO DE PEDRA, PAPEL E TESOURA com strings e estrutura if\n\n# lembrete de regras do jogo:\n# pedra ganha da tesoura\n# tesoura ganha do papel\n# papel ganha da pedra\n\nfrom random import randint # importação do módulo randint que permite ao computador escolher o número aleatoriamente\nfrom time import sleep # pausa no programa antes de fechar sozinho\n\nprint('-' * 5, 'JO KEN PO!', '-' * 5)\nuser_option = int(input( # sua opção\n'''\nEscolha uma opção:\n[1] Pedra\n[2] Papel\n[3] Tesoura\n''')\n)\npc_option = randint(1, 3) # opção do computador, seu adversário\n\nif user_option != 1 and user_option != 2 and user_option != 3:\n print('Opção inválida! Digite apenas [1], [2] ou [3] para começar seu jogo. ')\n\nif user_option == 1:\n print('Você escolheu PEDRA!')\nelif user_option == 2:\n print('Você escolheu PAPEL!')\nelse:\n print('Você escolheu TESOURA!')\n\nif pc_option == 1:\n print('O computador escolheu PEDRA!')\nelif pc_option == 2:\n print('O computador escolheu PAPEL!')\nelse:\n print('O computador escolheu TESOURA!')\n\nif user_option == pc_option: # os dois escolhem a mesma opção\n print('EMPATE!')\n\nif pc_option == 1: # PEDRA\n if user_option == 2: # PEDRA x PAPEL\n print('Você ganhou!') \n elif user_option == 3: # PEDRA x TESOURA\n print('Você perdeu!')\n\nif pc_option == 2: # PAPEL\n if user_option == 1: # PAPEL x PEDRA\n print('Você perdeu!')\n elif user_option == 3: # PAPEL x TESOURA\n print('Você ganhou!')\n\nif pc_option == 3: # TESOURA\n if user_option == 1: # TESOURA x PEDRA\n print('Você perdeu!')\n elif user_option == 2: # TESOURA x PAPEL\n print('Você ganhou!')\n\nsleep(2)\nquit()","sub_path":"Python/curso-em-video/45.py","file_name":"45.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"307770224","text":"__author__ = 'Боян'\n\nn = input(\"Enter a number\")\nnumber = int(n)\n\ncounter = 1\ntotal = 0\n\nwhile counter <= number:\n if counter % 2 != 0:\n print(counter)\n total += counter\n counter += 1\n\nprint(\"The sum of all odd numbers between 1 and {0} is: {1}\".format(number, total))","sub_path":"Programming0/week1/5-Saturday-Tasks/sum_of_odds.py","file_name":"sum_of_odds.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"583265708","text":"# -*- coding: utf-8 -*- #\n# Copyright 2015 Google 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.\n\"\"\"Test of the 'workflow template create' command.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk import calliope\n\nfrom googlecloudsdk.core import properties\nfrom tests.lib.surface.dataproc import compute_base\nfrom tests.lib.surface.dataproc import unit_base\n\n\nclass WorkflowTemplateCreateUnitTest(unit_base.DataprocUnitTestBase,\n compute_base.BaseComputeUnitTest):\n \"\"\"Tests for workflow template create.\"\"\"\n\n def ExpectCreateWorkflowTemplate(self,\n workflow_template=None,\n response=None,\n parent=None,\n region=None,\n exception=None):\n if not parent:\n parent = self.WorkflowTemplateParentName()\n if not workflow_template:\n workflow_template = self.MakeWorkflowTemplate()\n if not (response or exception):\n response = workflow_template\n self.mock_client.projects_regions_workflowTemplates.Create.Expect(\n self.messages.DataprocProjectsRegionsWorkflowTemplatesCreateRequest(\n workflowTemplate=workflow_template, parent=parent),\n response=response,\n exception=exception)\n\n\nclass WorkflowTemplateCreateUnitTestBeta(WorkflowTemplateCreateUnitTest):\n\n def SetUp(self):\n self.SetupForReleaseTrack(calliope.base.ReleaseTrack.BETA)\n\n def testCreateWorkflowTemplates(self):\n workflow_template = self.MakeWorkflowTemplate()\n self.ExpectCreateWorkflowTemplate(workflow_template, workflow_template)\n result = self.RunDataproc(\n 'workflow-templates create {0}'.format(self.WORKFLOW_TEMPLATE))\n self.AssertMessagesEqual(workflow_template, result)\n\n def testCreateWorkflowTemplatesWithRegion(self):\n properties.VALUES.dataproc.region.Set('us-test1')\n parent = self.WorkflowTemplateParentName(region='us-test1')\n template_name = self.WorkflowTemplateName(region='us-test1')\n workflow_template = self.MakeWorkflowTemplate(name=template_name)\n self.ExpectCreateWorkflowTemplate(workflow_template, workflow_template,\n parent)\n result = self.RunDataproc(\n 'workflow-templates create {0}'.format(self.WORKFLOW_TEMPLATE))\n self.AssertMessagesEqual(workflow_template, result)\n\n def testCreateWorkflowTemplatesWithLabels(self):\n labels = {'k1': 'v1'}\n workflow_template = self.MakeWorkflowTemplate(labels=labels)\n self.assertTrue(workflow_template.labels is not None)\n self.ExpectCreateWorkflowTemplate(workflow_template, workflow_template)\n result = self.RunDataproc('workflow-templates create {0} --labels=k1=v1'.\n format(self.WORKFLOW_TEMPLATE))\n self.assertTrue(result.labels is not None)\n self.assertEqual(workflow_template.labels, result.labels)\n self.AssertMessagesEqual(workflow_template, result)\n","sub_path":"google-cloud-sdk/lib/tests/unit/surface/dataproc/workflow_templates/create_test.py","file_name":"create_test.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"597403562","text":"from sklearn import svm,metrics\nimport pandas as pd\n\n\"\"\"\n붓꽃 데이터 분류(머신러닝)\n- 개요 : 150개 붓꽃 정보(꽃받침길이, 꽃받침폭, 꽃잎 길이, 꽃잎 폭)\n- 종류 : 3개(Iris-sentosa, Iris-versicolor, Iris-virginica)\n- csv 파일 : 검색 iris.csv\n\"\"\"\n\n\n#0. 훈련데이터 테스트 데이터 준비\ncsv = pd.read_csv(\"C:/PythonExample/CSV/iris.csv\")\ntrain_data = csv.iloc[0:120,0:-1] #행의 위치에 따라 불러옴, csv.loc[]는 행의 이름이 0인것을 찾아옴.\ntrain_label = csv.iloc[0:120,[-1]]\ntest_data = csv.iloc[120:,0:-1]\ntest_label = csv.iloc[120:,[-1]]\n\n##1. classifier 생성(선택) --> 머신러닝 알고리즘 선택\nclf = svm.SVC(gamma=\"auto\")\n## 데이터로 학습 시키기\n#clf.fit([훈련데이터], [정답])\nclf.fit(train_data,train_label)\n\n#예측하기\n#clf.predict([예측할 데이터])\n\nresult = clf.predict(test_data)\n#print(result)\nscore = metrics.accuracy_score(result,test_label)\nprint(\"정확도 ==> {0:.2f}%\".format(score*100))\n\n\n","sub_path":"Python/Machine_learning/Code11-03 Machine Learning 03(붓꽃).py","file_name":"Code11-03 Machine Learning 03(붓꽃).py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"43432571","text":"\nfrom libs.config_service import ConfigService\nfrom libs.effects import Effects\nfrom libs.effects_enum import EffectsEnum\nfrom libs.notification_enum import NotificationEnum\nfrom libs.notification_service import NotificationService\nfrom libs.server_service import ServerService\nfrom libs.audio_process_service import AudioProcessService\n\nimport numpy as np\nfrom multiprocessing import Process, Queue, Manager, Lock\nfrom time import sleep\n\nclass Main():\n \"\"\"\n This is the main class. It control everything.\n Its the first starting point of the programm.\n \"\"\"\n\n def start(self):\n \"\"\"\n This function will start all neccesary components.\n Let's go :-D\n \"\"\"\n \n print(\"Init the programm...\")\n\n # We need a lock to prevent too fast save and load actions of the config\n self._config_lock = Lock()\n\n # Create the instance of the config\n self._config_instance = ConfigService.instance(self._config_lock)\n self._config = self._config_instance.config \n\n # Prepare the queue for the output\n self._effects_queue = Queue(2)\n self._audio_queue_lock = Lock()\n self._audio_queue = Queue(2)\n self._server_queue_lock = Lock()\n self._server_queue = Queue(2)\n\n # Prepare all notification queues\n self._notification_queue_effects_in = Queue(2)\n self._notification_queue_effects_out = Queue(2)\n\n self._notification_queue_audio_in = Queue(2)\n self._notification_queue_audio_out = Queue(2)\n\n self._notification_queue_server_in = Queue(2)\n self._notification_queue_server_out = Queue(2)\n\n # Start Notification Service\n self._notification_service = NotificationService()\n self._notification_service_process = Process(\n target=self._notification_service.start, \n args=(\n self._config_lock, \n self._notification_queue_effects_in, \n self._notification_queue_effects_out, \n ))\n self._notification_service_process.start()\n \n\n #Start Server\n self._server = ServerService()\n self._server_process = Process(\n target=self._server.start, \n args=(\n self._config_lock, \n self._notification_queue_server_in, \n self._notification_queue_server_out,\n self._server_queue,\n self._server_queue_lock\n ))\n self._server_process.start()\n\n\n # Start the Effect Service\n self._effects = Effects()\n self._effects_process = Process(\n target=self._effects.start, \n args=(\n self._config_lock, \n self._notification_queue_effects_in, \n self._notification_queue_effects_out, \n self._effects_queue,\n self._server_queue,\n self._server_queue_lock,\n self._audio_queue,\n self._audio_queue_lock\n \n ))\n self._effects_process.start()\n\n\n #Start audio process\n self._audio = AudioProcessService()\n self._audio_process = Process(\n target=self._audio.start, \n args=(\n self._config_lock, \n self._notification_queue_server_in, \n self._notification_queue_server_out,\n self._audio_queue,\n self._audio_queue_lock\n ))\n self._audio_process.start()\n\n\n \n \n\n print(\"Init finished\")\n\n try:\n\n print(\"Programm started...\")\n\n self._cancel_token = False\n\n # Do nothing with this thread. Just wait for the exit.\n while not self._cancel_token:\n sleep(10)\n \n except KeyboardInterrupt:\n print(\"Stop the programm...\")\n \n self._server_process.terminate()\n self._effects_process.terminate()\n self._audio_process.terminate()\n self._notification_service_process.terminate()\n\n print(\"Programm stopped\")\n\n\nif __name__ == \"__main__\":\n\n main = Main()\n main.start()","sub_path":"client/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"504404085","text":"import ipaddress\nimport paris.poke\ndef scan(ip_range:str):\n result = {}\n for ip in ipaddress.ip_network(ip_range):\n print('%s -> ' % str(ip), flush=True, end='')\n poke = paris.poke(str(ip))\n if poke is not None:\n result[str(ip)] = poke\n print(result[str(ip)])\n else:\n print('...')\n return result\n","sub_path":"paris/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"541254199","text":"import threading\nimport queue\n\n# 全局变量\nlock = threading.Lock()\njob_object_queue = queue.Queue()\nproxies = queue.Queue()\nproxy = {}\nurl_to_check = 'https://jobs.51job.com/'\nurl_proxy = 'http://45.76.218.205:8000'\n\n\nclass job_object:\n 'job描述对象'\n __slots__ = ('tag_href', \"job\", 'company', 'address', 'salary', 'tag')\n","sub_path":"gloSetting/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"62292086","text":"import utils\r\nimport argparse\r\nimport os\r\nimport inlab4_tasks as stud\r\nimport numpy as np\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--task', type=str, default='all')\r\nparser.add_argument('--tcdir', type=str, default='testcases')\r\n\r\nif __name__=='__main__':\r\n args = parser.parse_args()\r\n task = args.task\r\n tasklist = []\r\n if task == \"all\":\r\n tasklist = list(range(1,6))\r\n elif task not in map(str, range(1,6)):\r\n print(\"task should be between 1 and 5 (both inclusive. given task: {}\".format(task))\r\n else:\r\n tasklist = [int(task)]\r\n print(\"tasklist:\", tasklist)\r\n tcdir = args.tcdir\r\n task_fnmap = {\r\n 1: 'checkerboard',\r\n 2: 'SimpleNonLinearity',\r\n 3: 'normalise',\r\n 4: 'top_k',\r\n 5: 'is_magic_square'\r\n }\r\n\r\n for task in tasklist:\r\n taskfn = getattr(stud, task_fnmap[task])\r\n tcfilename = os.path.join(tcdir, 'task{}.pkl'.format(task))\r\n tcdict = utils.load(filename=tcfilename)\r\n for i in tcdict.keys(): \r\n vals = list(tcdict[i])\r\n retval = vals[-1]\r\n argss = vals[:-1]\r\n student_retval = taskfn(*argss)\r\n if task < 5:\r\n try:\r\n iscorrect = np.allclose(student_retval, retval)\r\n except Exception as e:\r\n # print(\"exception thrown\", e)\r\n iscorrect = False\r\n else:\r\n iscorrect = retval == student_retval\r\n if not iscorrect:\r\n print(\"Task {}: testcase# {} failed!\".format(task, i))\r\n else:\r\n print(\"Task {}: testcase# {} passed!\".format(task, i))\r\n","sub_path":"inlab4-Numpy Scipy matplotlib/autograder.py","file_name":"autograder.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"386578756","text":"'''\nCreated on Jan 3, 2018\n\n@author: Alexei Figueroa\n\nThis module holds the classes related to views in the synthesizer application.\n'''\nimport pygame,abc,CONSTANTS\n\nclass View(metaclass=abc.ABCMeta):\n \"\"\"\n Abstract class specifying the method signatures of a View\n \"\"\"\n def __init__(self, screen):\n self.screen=screen\n @abc.abstractmethod\n def draw(self):\n \"\"\"\n This method should enable the View to be rendered on\n the screen.\n \"\"\"\n\n\nclass KeyboardView(View):\n '''\n This class draws the synthesizer keyboard on the screen\n it implements the View interface.\n '''\n\n def __init__(self, screen):\n '''\n Constructor\n @screen: pygame.display \n Canvas where the keyboard will be rendered\n '''\n super().__init__(screen)\n self.__pressed={}\n \n def draw(self):\n '''\n This method renders the each key, set's a label for \n each one of them depending on the state of the View.\n '''\n x0=90\n y0=40\n \n label_font = pygame.font.SysFont(\"monospace\", 15)\n #Render white keys\n for code,k,label,x in CONSTANTS.whites:\n width=20\n height=200\n x_i=10+x*(width+2)+x0\n color_i=CONSTANTS.color_white if code not in self.pressed else CONSTANTS.color_pressed\n pygame.draw.rect(self.screen, color_i, [x_i, y0, width, height])\n k_label = label_font.render(k, 1, CONSTANTS.color_black)\n self.screen.blit(k_label, (x_i+width/3, height-20+y0))\n #Render black keys \n for code,k,label,x in CONSTANTS.blacks:\n color_i=CONSTANTS.color_black if code not in self.pressed else CONSTANTS.color_pressed\n width=15\n height=130\n x_i=10+(20+2)*x-width/2+x0\n pygame.draw.rect(self.screen, color_i, [x_i, y0, width, height])\n k_label = label_font.render(k, 1, CONSTANTS.color_white)\n self.screen.blit(k_label, (x_i+width/5, height-20+y0))\n \"\"\"\n Getters and setters, properties\n \"\"\"\n #Property holding the state of the pressed keys in the View.\n def set_pressed(self,pressed):\n self.__pressed=pressed\n def get_pressed(self):\n return self.__pressed\n pressed=property(get_pressed,set_pressed)\n\nclass VibratoView(View):\n \"\"\"\n This class draws the vibrato control on the screen, it implements\n the View interface\n \"\"\"\n def __init__(self, screen):\n '''\n Constructor\n @screen: pygame.display \n Canvas where the vibrato control will be rendered\n '''\n super().__init__(screen)\n self.__vibrato=False\n def draw(self):\n label_font = pygame.font.SysFont(\"monospace\", 15)\n vibrato_state={False:\"Toggle vibrato with V (off)\",\n True:\"Toggle vibrato with V (on)\"}\n vibrato_label = label_font.render(vibrato_state[self.__vibrato], 1, CONSTANTS.color_white)\n pygame.draw.rect(self.screen,CONSTANTS.color_black,[20,280,400,20])\n self.screen.blit(vibrato_label, (20, 280))\n \"\"\"\n Getters and setters, properties\n \"\"\"\n #Property holding the state of the vibrato being displayed. \n def get_vibrato(self):\n return self.__vibrato\n def set_vibrato(self,vibrato):\n self.__vibrato=vibrato\n vibrato=property(get_vibrato,set_vibrato)\n \n ","sub_path":"view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"377650984","text":"\"\"\"Custom Logger implementation based loguru.\n\nResources:\nhttps://medium.com/1mgofficial/how-to-override-uvicorn-logger-in-fastapi-using-loguru-124133cdcd4e\nhttps://gist.github.com/nkhitrov/a3e31cfcc1b19cba8e1b626276148c49\nhttps://pawamoy.github.io/posts/unify-logging-for-a-gunicorn-uvicorn-app/#uvicorn-only-version\n\"\"\"\nimport logging\nimport sys\nfrom pprint import pformat\n\n# Type hints with loguru:\n# https://loguru.readthedocs.io/en/stable/api/type_hints.html\nimport loguru\nfrom loguru import logger # noqa: WPS458\nfrom loguru._defaults import LOGURU_FORMAT # noqa: WPS436\n\n\nclass InterceptHandler(logging.Handler):\n \"\"\"Custom handler to integrate with standard lib `logging`.\n\n Based on example from loguru docs:\n https://loguru.readthedocs.io/en/stable/overview.html\n \"\"\"\n\n loglevel_mapping = {\n 50: 'CRITICAL',\n 40: 'ERROR',\n 30: 'WARNING',\n 20: 'INFO',\n 10: 'DEBUG',\n 0: 'NOTSET',\n }\n\n def emit(self, record: logging.LogRecord):\n \"\"\"Pass log record to loguru.\n\n Args:\n record: A logging.LogRecord instance to be emitted to the logs.\n \"\"\"\n # Get corresponding loguru level if it exists\n try:\n level = logger.level(record.levelname).name\n except AttributeError:\n level = self.loglevel_mapping[record.levelno]\n\n # Find caller from where originated the logged message\n frame, depth = logging.currentframe(), 2\n while frame.f_code.co_filename == logging.__file__: # noqa: WPS609\n frame = frame.f_back # type: ignore\n depth += 1\n\n logger.opt(\n depth=depth,\n exception=record.exc_info,\n ).log(\n level,\n record.getMessage(),\n )\n\n\ndef _format_record(\n record: 'loguru.Record',\n log_format: str,\n) -> str:\n \"\"\"Format loguru log record according to specified format.\n\n Args:\n record: A loguru.Record instance to get formatted.\n log_format: A str with the desired log format.\n\n Returns:\n A str representing the formatted log entry.\n\n Uses pprint.pformat() to log any additional data passed in as extra\n payload. Example:\n >>> payload = [{\"users\":[{\"name\": \"Nick\", \"age\": 87}], \"count\": 1}]\n >>> logger.bind(payload=payload).debug(\"users payload\")\n >>> [ { 'count': 1,\n >>> 'users': [ {'age': 87, 'name': 'Nick'}]}]\n \"\"\"\n format_string = log_format\n if record.get('extra', {}).get('payload'):\n record['extra']['payload'] = pformat(\n record['extra']['payload'], indent=4, compact=True, width=100,\n )\n format_string = '{0}{1}'.format(\n format_string,\n '{extra[payload]}\\n',\n )\n return format_string\n\n\ndef setup_logging(log_level: str, log_format: str = LOGURU_FORMAT):\n \"\"\"Set up loguru to be the sole logging mechanism.\n\n Args:\n log_level: A str to set the desired log level.\n log_format: A str for custom log format. Defaults to loguru default.\n\n Register a custom InterceptHandler based on loguru as sole handler for the\n root logger. Further, remove all registered logger handlers and set\n corresponding loggers to propogate up the the root logger now handled by\n loguru. A custom dict can be passed as payload to the log for debugging\n purposes.\n \"\"\"\n # Intercept everything at the root logger\n logging.root.handlers = [InterceptHandler()]\n logging.root.setLevel(log_level.upper())\n\n # Remove every other logger's handlers and propagate to root logger\n for name in logging.root.manager.loggerDict.keys(): # type: ignore\n logging.getLogger(name).handlers = []\n logging.getLogger(name).propagate = True\n\n # Configure loguru\n logger.configure(\n handlers=[{\n 'sink': sys.stdout,\n 'format': lambda record: _format_record(record, log_format),\n 'enqueue': True,\n 'backtrace': True,\n }])\n","sub_path":"guglhupf/core/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"366651294","text":"from mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\n# Silly example data\nX = np.arange(-5, 5, 0.25)\nY = np.arange(-5, 5, 0.25)\nX, Y = np.meshgrid(X, Y)\nR = np.sqrt(X**2 + Y**2)\nZ = np.sin(R)\n\n# Make the plot\nfig = plt.figure()\nax = fig.gca(projection=\"3d\")\nsurf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\nax.set_zlim(-1.01, 1.01)\nfig.colorbar(surf, shrink=0.5, aspect=5)\nplt.show()","sub_path":"example_snippets/multimenus_snippets/Snippets/Matplotlib/Example plots/3-d plot.py","file_name":"3-d plot.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"522653088","text":"import spidev\nimport sys\nimport time\nimport RPi.GPIO as GPIO\n\nfrom vfd import VFD\nfrom stock_market import Stocks\nfrom weather import Weather\nfrom datetime import datetime\nfrom datetime import timedelta\n\ndisplaySize = 16\nvfd = VFD(0,0)\nstepDelay = 0.15\ntickerEndPause = 3 \n\n# Configure PIR motion detector\nPIRport = 18\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(PIRport, GPIO.IN)\n\n# Stocks config\nstockM = Stocks()\nstock_symbols = {'^GSPC':'S&P 500','^DJI':'Dow 30','^IXIC':'Nasdaq','^RUT':'Rusell 2000','NKE':'Nike, Inc.'}\nlastStockDay = 5 # firday=5\n\n# Weather config\nweatherI = Weather()\nlocation='Beaverton, OR'\nweatherLatencyMinutes = 10\nnextWeatherCheckTime = datetime.now() - timedelta(seconds=1) \n\ntry:\n\n while True:\n \n inputState = GPIO.input(PIRport)\n \n if inputState == True:\n\n print('Motion detected')\n\n # check latest stock info, if it is a weekday \n if datetime.now().weekday() < lastStockDay:\n ticker = stockM.getStockInfo(stock_symbols)\n \n # check latest weather info\n if datetime.now() > nextWeatherCheckTime : \n weatherTicker = weatherI.getWeatherInfo(location)\n nextWeatherCheckTime = datetime.now() + timedelta(minutes=weatherLatencyMinutes)\n \n # Update current time\n vfd.setPosition(0,0)\n vfd.writeStr(datetime.strftime(datetime.now(), '%b/%d %I:%M %p')) \n\n if datetime.now().weekday() < lastStockDay:\n \n if len(ticker) <= displaySize :\n vfd.setPosition(0,1)\n vfd.writeStr(ticker)\n time.sleep(tickerEndPause)\n\n else:\n for n in range (0, len(' ' + ticker)-displaySize):\n vfd.setPosition(0,1)\n vfd.writeStr((' '+ticker)[n:n+displaySize])\n time.sleep(stepDelay)\n\n time.sleep(tickerEndPause)\n\n if len(weatherTicker) <= displaySize :\n vfd.setPosition(0,1)\n vfd.writeStr(weatherTicker.center(displaySize))\n time.sleep(tickerEndPause)\n\n else:\n for n in range (0, len(' '+weatherTicker)-displaySize):\n vfd.setPosition(0,1)\n vfd.writeStr((' '+weatherTicker)[n:n+displaySize])\n time.sleep(stepDelay)\n \n time.sleep(tickerEndPause)\n \n vfd.cls()\n\n else:\n if datetime.now() > nextWeatherCheckTime :\n weatherTicker = weatherI.getWeatherInfo(location)\n nextWeatherCheckTime = datetime.now() + timedelta(minutes=weatherLatencyMinutes) \n time.sleep(1)\nfinally:\n vfd.cls()\n","sub_path":"clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"351173152","text":"#lists\ncourses=['Painting','Computational_Physics','Programming','Python','C++']\nfor index,course in enumerate(courses, start=1):\n print(index, course)\n#sets\ncourse_Str = ' - '.join(courses) # join is a function\nnew_list = course_Str.split(' - ') # split is a method\na=set(new_list);\nb={'Drawing','Painting','History','Math','Computer Science','Physics','Python','Math'};\nc=a.intersection(b) #methods\nd=b.difference(a)\ne=a.union(b)\nprint(d)\n\n\n#tuples areimmutable, if you copy, only a copy will change\n\n","sub_path":"Python/split_join_enumerate.py","file_name":"split_join_enumerate.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"104047099","text":"from django.contrib.gis.geos import GEOSGeometry\nfrom django.forms.models import model_to_dict\nfrom wells.models import (ActivitySubmission, FieldsProvided)\nfrom wells.serializers import CasingSummarySerializer, ScreenSerializer, LinerPerforationSerializer, \\\n DecommissionDescriptionSerializer, LithologyDescriptionSummarySerializer\nfrom submissions.serializers import WellStaffEditSubmissionSerializer\nfrom wells.stack import KEY_VALUE_LOOKUP, MANY_TO_MANY_LOOKUP\n\n\ndef get_well_history(well):\n\n well_history = {\n 'history': None,\n 'create_user': well.create_user,\n 'create_date': well.create_date\n }\n\n submissions = ActivitySubmission.objects.filter(well=well.well_tag_number).order_by('filing_number')\n legacy_record = submissions.filter(well_activity_type='LEGACY').first()\n\n # We use a copy of the legacy record as our composite stacker\n if legacy_record:\n legacy_copy = WellStaffEditSubmissionSerializer(legacy_record).data\n else:\n return well_history # Return empty history if a legacy record hasn't been created yet\n\n history = []\n for submission in submissions: # Loop through all submission for a well to build the history\n history_item = []\n if submission.well_activity_type.code == 'LEGACY':\n continue\n fields_provided = FieldsProvided.objects.filter(activity_submission=submission.filing_number).first()\n if fields_provided is None:\n continue\n else:\n fields_provided_dict = model_to_dict(fields_provided)\n for key, value in fields_provided_dict.items():\n if value and key != 'activity_submission':\n # clean and transform our history values\n submission_value = clean_attrs(getattr(submission, key), key)\n legacy_value = clean_attrs(legacy_copy.get(key, None), key)\n\n if submission_value is None and legacy_value is None:\n continue\n\n item = {\n \"diff\": submission_value,\n \"prev\": legacy_value,\n \"type\": key,\n \"action\": action_type(submission_value, legacy_value),\n \"user\": submission.update_user,\n \"date\": submission.update_date\n }\n \n if item['diff'] != item['prev']:\n history_item.append(item)\n\n legacy_copy[key] = item['diff'] # update the composite each loop\n\n if history_item:\n history.append(history_item)\n\n well_history['history'] = history[::-1] # we reverse the list to put newest edits at the top\n\n return well_history\n\n\n# transforms data between different relatioship types\ndef clean_attrs(obj, key):\n if obj is None or obj is [] or obj is '':\n return None\n\n # Geo Point lookup\n elif isinstance(obj, GEOSGeometry): # convert geo point type to string\n round5 = (round(obj[0], 5), round(obj[1], 5))\n return ', '.join(map(str, round5))\n\n # Key Value lookup\n elif key in KEY_VALUE_LOOKUP:\n if type(obj) == str:\n return obj\n else:\n return getattr(obj, KEY_VALUE_LOOKUP[key], None)\n\n # Foreign Key lookup\n elif key in FOREIGN_KEY_SERIALIZER_LOOKUP:\n if hasattr(obj, 'instance'):\n Serializer = FOREIGN_KEY_SERIALIZER_LOOKUP[key]\n return Serializer(obj, many=True).data\n else:\n return obj\n\n # Many To Many lookup\n elif key in MANY_TO_MANY_LOOKUP:\n converted = []\n if hasattr(obj, 'instance'):\n for item in obj.all():\n converted.append({'code': getattr(item, MANY_TO_MANY_LOOKUP[key], None)})\n else:\n for item in obj:\n converted.append(item)\n return converted if len(converted) > 0 else None\n\n # return original object if no type checks caught\n return obj\n\n\ndef action_type(diff, prev):\n empty_diff = diff is None or diff is [] or diff is ''\n empty_prev = prev is None or prev is [] or prev is ''\n if empty_diff:\n return 'Removed'\n elif not empty_diff and empty_prev:\n return 'Added'\n elif not empty_diff and not empty_prev:\n return 'Updated'\n else:\n return 'Edited'\n\n\nFOREIGN_KEY_SERIALIZER_LOOKUP = {\n 'casing_set': CasingSummarySerializer,\n 'screen_set': ScreenSerializer,\n 'linerperforation_set': LinerPerforationSerializer,\n 'decommission_description_set': DecommissionDescriptionSerializer,\n 'lithologydescription_set': LithologyDescriptionSummarySerializer\n}\n","sub_path":"app/backend/wells/change_history.py","file_name":"change_history.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"511899163","text":"import jwt\nfrom functools import wraps\nfrom flask import request, Response\nfrom airflow.models import Variable\n\n\nJWT_BACKEND_PUBLIC_KEY = \"jwt_backend_public_key\"\nJWT_BACKEND_CRYPT_ALGORITHM = \"jwt_backend_crypt_algorithm\"\n\n\nclient_auth = None\n\n\ndef init_app(app):\n pass\n\n\ndef requires_authentication(function):\n @wraps(function)\n def decorated(*args, **kwargs):\n try:\n json_data = {k: v for k, v in request.get_json(force=True).copy().items() if k != \"check_payload\"}\n check_payload = jwt.decode(request.get_json(force=True)[\"check_payload\"], Variable.get(JWT_BACKEND_PUBLIC_KEY), algorithms=Variable.get(JWT_BACKEND_CRYPT_ALGORITHM))\n assert (json_data == check_payload)\n except Exception:\n return Response(\"Failed to decrypt or data is corrupted\", 403)\n return function(*args, **kwargs)\n return decorated\n","sub_path":"cwl_airflow_parser/utils/jwt_backend.py","file_name":"jwt_backend.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"424906061","text":"__author__ = 'thiagocastroferreira'\n\n\"\"\"\nAuthor: Thiago Castro Ferreira\nDate: 28/02/2019\nDescription:\n This script aims to extract profile information from ProfileREG API.\n\n ARGS:\n [1] Path to the folder where ACL format from WebNLG corpus is available (versions/v1.5)\n [2] Path to the folder where the data will be saved (Folder will be created in case it does not exist)\n\n EXAMPLE:\n python3 preprocess_profile.py '../data/v1.5' '../eval/data/profilereg/references/'\n\"\"\"\n\nimport json\nimport os\nimport sys\nimport pickle\n\nsys.path.append('./')\nsys.path.append('../')\nprofilereg_path = '../eval/data/profilereg/references/v1.0'\n\n\ndef load_data(train_path, dev_path, test_path):\n with open(train_path, 'rb') as file:\n train_data = pickle.load(file)\n\n with open(dev_path, 'rb') as file:\n dev_data = pickle.load(file)\n\n with open(test_path, 'rb') as file:\n test_data = pickle.load(file)\n\n reference_data = list(train_data) + list(dev_data) + list(test_data)\n\n return list(reference_data)\n\n\nclass REGPrecProfileREG:\n def __init__(self, data_path, write_path):\n self.data_path = data_path\n self.write_path = write_path\n\n self.profile_data = self.process(train_path=os.path.join(profilereg_path, 'train.pickle'),\n dev_path=os.path.join(profilereg_path, 'dev.pickle'),\n test_path=os.path.join(profilereg_path, 'test.pickle'))\n\n json.dump(self.profile_data, open(os.path.join(write_path, 'profile.json'), 'w'))\n\n def process(self, train_path, dev_path, test_path):\n profile_set = load_data(train_path, dev_path, test_path)\n data, size = [], 0\n\n for i, reference in enumerate(profile_set):\n entity = {'entity': reference['entity'],\n 'profile': reference['profile']}\n\n if entity not in data:\n data.append(entity)\n size += 1\n\n return data\n\n\nif __name__ == '__main__':\n # data_path = '../data/v1.5'\n # write_path = '../eval/data/profilereg/references/'\n\n data_path = sys.argv[1]\n write_path = sys.argv[2]\n s = REGPrecProfileREG(data_path=data_path, write_path=write_path)\n","sub_path":"profilereg/preprocess_profile.py","file_name":"preprocess_profile.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"530610034","text":"from itertools import combinations\nT = int(input())\nN, J = list(map(int, input().split()))\n\nodd = (1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31)\neven = (2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)\n\npairs = []\n\nfor o1, o2 in combinations(odd, 2):\n for e1, e2 in combinations(even, 2):\n pairs.append((o1,o2,e1,e2))\n if len(pairs) > 500:\n break\n\npairs = pairs[:500]\n\nfor t in range(1, T + 1):\n print('Case #{0}:'.format(t))\n for o1, o2, e1, e2 in pairs:\n num = '{0:b}'.format(2**31 + 1 + 2**o1 + 2**o2 + 2**e1 + 2**e2)\n print(num, end=' ')\n for i in range(2, 10):\n base_rep = int(num, i)\n assert(base_rep % (i + 1) == 0)\n print(i + 1, end=' ')\n assert(int(num, 10) % 11 == 0)\n print(11)\n","sub_path":"codes/CodeJamCrawler/16_0_3/gnarula/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"56287459","text":"import os\nimport torch as t\nfrom utils.config import opt\nfrom data.dataset import Dataset, TestDataset\nfrom torch.utils import data as data_\nfrom tqdm import tqdm\nfrom model import FasterRCNNVGG16\nfrom trainer import FasterRCNNTrainer\nfrom data.util import read_image\nfrom utils.vis_tool import vis_bbox\nfrom utils import array_tool as at\nfrom utils.eval_tool import calc_detection_voc_prec_rec\nimport numpy as np\n\ndef eval_detection_voc(\n pred_bboxes, pred_labels, pred_scores, gt_bboxes, gt_labels,\n gt_difficults=None,\n iou_thresh=0.5):\n\n prec, rec = calc_detection_voc_prec_rec(\n pred_bboxes, pred_labels, pred_scores,\n gt_bboxes, gt_labels, gt_difficults,\n iou_thresh)\n\n return prec, rec\n\ndef eval(dataloader, faster_rcnn, test_num=10000):\n total = 0\n pred_bboxes, pred_labels, pred_scores = list(), list(), list()\n gt_bboxes, gt_labels, gt_difficults = list(), list(), list()\n for ii, (imgs, sizes, gt_bboxes_, gt_labels_, gt_difficults_) in tqdm(enumerate(dataloader)):\n sizes = [sizes[0][0].item(), sizes[1][0].item()]\n pred_bboxes_, pred_labels_, pred_scores_ = faster_rcnn.predict(imgs, [sizes])\n gt_bboxes += list(gt_bboxes_.numpy())\n gt_labels += list(gt_labels_.numpy())\n gt_difficults += list(gt_difficults_.numpy())\n pred_bboxes += pred_bboxes_\n pred_labels += pred_labels_\n pred_scores += pred_scores_\n if ii == test_num: break\n\n # for target,predict in zip(gt_labels,pred_labels):\n # print('target:',target,'predict',predict)\n # total += len(i)\n # print('labels:',len(total))\n\n result = eval_detection_voc(\n pred_bboxes, pred_labels, pred_scores,\n gt_bboxes, gt_labels, gt_difficults)\n\n return result\n\nfaster_rcnn = FasterRCNNVGG16()\ntrainer = FasterRCNNTrainer(faster_rcnn).cuda()\ntrainer.load('/home/kdd/Documents/simple-faster-rcnn-pytorch/checkpoints/fasterrcnn_11101036_0.5348237306784394')\nopt.caffe_pretrain=True\n\n# get dataloader\ntestset = TestDataset(opt)\ntest_dataloader = data_.DataLoader(testset,\n batch_size=1,\n num_workers=opt.test_num_workers,\n shuffle=False, \\\n pin_memory=True\n )\nresult = eval(test_dataloader,faster_rcnn)\nprec, recall = result[0], result[1]\n","sub_path":"infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"98382054","text":"# -*- coding: utf-8 -*- \n# 파이썬을 활용한 금융데이터 크롤링 \n# 기본 문법 \n\n# print(\"Practice\")\n# print(\"Practice\")\n#print(\"Practice\")\n\n'''\nprint(\"Practice\")\nprint(\"Practice\")\nprint(\"Practice\")\nprint(\"Practice\")\n'''\n\n# Conditional Expression \n'''\na=5\nif a < 3:\n print(\"a is smaller than 3\")\nelif a > 7:\n print(\"a is greater than 7\")\nelse:\n print(\"a is greater than 3 and smaller than 7\")\n\n# Loop 1\n# for 문은 최소한으로,,\n# QUIZ\n\ns = \"There are 30 people in class, and no one answers my question.\"\n\nfor x in range(1,11):\n if s.find(\"30 people\"):\n print(s[10:19])\n'''\ndef addition(num1, num2):\n result = num1 + num2\n print(str(num1) + \" 과 \" + str(num2) + \"의 합은 \" + str(result) + \"입니다!\")\n # print(\"{}과 {}의 합은 {}입니다.\".format(num1, num2, result)) # format 함수를 사용한 예\n\n# addition(3,5)\n\ndef subtration(num1, num2):\n result = num1 - num2\n print(result)\n\n# subtration(120, 30)\n\n\n\ndef chage_str(s1, s2, s3):\n lst = s1.split()\n result = \"\"\n length = len(s2)\n\n for word in lst:\n if s2 in word:\n location = word.find(s2)\n word = word[0:location] + s3 + word[location + length:]\n result = result + word + \" \"\n else:\n result = result + word + \" \"\n return result\n\ns1 = \"There aren`t 30 people in class, and no one answers my question. and, i am sad...\"\ns2 = \"re\"\ns3 = \"_+_\"\n\n# answer = chage_str(s1,s2,s3)\n# print(answer)\n\n# List Comprehension\nnumbers = [i*3 for i in range(0, 10)]\n# print(numbers)\n\n#List comprehension 이용해서, crawl할 주소 url 주소 list 만들기.\n\n# site = [(\"www.example.com/search?page=\" + str(i)) for i in range(0, 110, 10)]\nsite = [\"www.example.com/search?page={}\".format(str(i)) for i in range(0, 110, 10)]\n# print(site)\n\nmygenerator = (x*x for x in range(3))\nfor i in mygenerator:\n print(i)","sub_path":"python/fintech/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"494479967","text":"# coding: utf-8\n\nimport os\nimport ismrmrd\nimport ismrmrd_xsd\nimport numpy as np\nfrom numpy.fft import ifft, fftshift\nimport matplotlib.pyplot as plt\n\n# Load file\nfilename = 'testdata.h5'\nif not os.path.isfile(filename):\n print(\"%s is not a valid file\" % filename)\n raise SystemExit\ndset = ismrmrd.IsmrmrdDataset(filename, 'dataset', create_if_needed=False)\n\nheader = ismrmrd_xsd.CreateFromDocument(dset.readHeader())\nenc = header.encoding[0]\n\n# Matrix size\neNx = enc.encodedSpace.matrixSize.x\neNy = enc.encodedSpace.matrixSize.y\neNz = enc.encodedSpace.matrixSize.z\nrNx = enc.reconSpace.matrixSize.x\nrNy = enc.reconSpace.matrixSize.y\nrNz = enc.reconSpace.matrixSize.z\n\n# Field of View\neFOVx = enc.encodedSpace.fieldOfView_mm.x\neFOVy = enc.encodedSpace.fieldOfView_mm.y\neFOVz = enc.encodedSpace.fieldOfView_mm.z\nrFOVx = enc.reconSpace.fieldOfView_mm.x\nrFOVy = enc.reconSpace.fieldOfView_mm.y\nrFOVz = enc.reconSpace.fieldOfView_mm.z\n\n# Number of Slices, Reps, Contrasts, etc.\nnslices = enc.encodingLimits.slice.maximum + 1\nncoils = header.acquisitionSystemInformation.receiverChannels\nnreps = enc.encodingLimits.repetition.maximum + 1\nncontrasts = enc.encodingLimits.contrast.maximum + 1\n\n# TODO: Ignore noise scans\nfor acqnum in range(dset.getNumberOfAcquisitions()):\n acq = dset.readAcquisition(acqnum)\n if acq.getHead().flags & ismrmrd.ACQ_IS_NOISE_MEASUREMENT:\n print(\"Found noise measurement @ %d\" % acqnum)\n\nall_data = np.zeros((eNx, eNy, eNz, ncoils, nslices, ncontrasts, nreps), dtype=np.complex64)\nfor acqnum in range(dset.getNumberOfAcquisitions()):\n acq = dset.readAcquisition(acqnum)\n head = acq.getHead()\n rep = head.idx.repetition\n contrast = head.idx.contrast\n slice = head.idx.slice\n y = head.idx.kspace_encode_step_1\n z = head.idx.kspace_encode_step_2\n floatdata = acq.getData()\n data = np.array([complex(elem[0], elem[1]) for elem in zip(floatdata[::2], floatdata[1::2])])\n data = data.reshape((eNx, ncoils))\n all_data[:, y, z, :, slice, contrast, rep] = data\n\nfig = plt.figure()\nh, w = nreps * ncontrasts, eNz * nslices\ni = 0\nfor rep in range(nreps):\n for contrast in range(ncontrasts):\n for slice in range(nslices):\n for z in range(eNz):\n K = all_data[:,:,z,:,slice, contrast, rep]\n comb = np.sqrt(np.sum(np.abs(K) ** 2, 2))\n a = fig.add_subplot(h, w, i)\n plt.imshow(comb)\n i += 1\nfig.set_size_inches(16, 16)\n\nimages = []\nfor rep in range(nreps):\n for contrast in range(ncontrasts):\n for slice in range(nslices):\n K = all_data[:,:,:,:,slice, contrast, rep]\n K = fftshift(ifft(fftshift(K, axes=0), axis=0), axes=0)\n\n # chop if needed\n if eNx != rNx:\n i0 = (eNx - rNx) / 2\n i1 = (eNx - rNx) / 2 + rNx\n im = K[i0:i1,:,:,:]\n else:\n im = K\n\n im = fftshift(ifft(fftshift(im, axes=1), axis=1), axes=1)\n if np.size(im, 2) > 1:\n im = fftshift(ifft(fftshift(im, axes=2), axis=2), axes=2)\n\n im = np.squeeze(np.sqrt(np.sum(np.abs(im) ** 2, 3)))\n images.append(im)\n\nl = len(images)\nfig = plt.figure()\nfor n, im in enumerate(images):\n a = fig.add_subplot(1, 5, n)\n plt.imshow(im)\nfig.set_size_inches(16, 4)\n\n# grab the first acquisition for extra info\nacqh = dset.readAcquisition(0).getHead()\n\nfor n, img in enumerate(images):\n hdr = ismrmrd.ImageHeader()\n hdr.acquisition_time_stamp = acqh.acquisition_time_stamp\n hdr.flags = 0\n hdr.measurement_uid = acqh.measurement_uid\n hdr.phase_dir = acqh.phase_dir\n hdr.physiology_time_stamp = acqh.physiology_time_stamp\n hdr.position = acqh.position\n hdr.read_dir = acqh.read_dir\n hdr.slice_dir = acqh.slice_dir\n hdr.channels = 1\n hdr.image_data_type = ismrmrd.DATA_FLOAT\n hdr.image_type = ismrmrd.TYPE_MAGNITUDE\n hdr.image_index = n\n hdr.slice = n\n\n dset.appendImageHeader(hdr, \"image_%d.hdr\" % n)\n dset.appendArray(img, \"image_%d.img\" % n)\n","sub_path":"examples/python/ismrmrd_recon_dataset.py","file_name":"ismrmrd_recon_dataset.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"61327120","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport sparse\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.cross_validation import train_test_split\n# import module to calculate model perfomance metrics\nfrom sklearn import metrics\n\n\ndata = pd.read_csv(\"data.csv\")\n\nX = data[['square_feet']]\nY = data[['price']]\n\nX_train, X_test, y_train, y_test = train_test_split(X, Y, random_state=1)\n\n# Linear Regression Model\n# Create linear regression object\nlinreg = LinearRegression()\n\nprint(X_test)\nprint(y_test)\n\n# fit the model to the training data (learn the coefficients)\nlinreg.fit(X_train, y_train)\n\n# make predictions on the testing set\ny_pred = linreg.predict(X_test)\n\nprint (X_test, y_test)\n\n\n\n############################################################## Plot data\n\nplt.scatter(X_train, y_train, color='black')\nplt.title('Test Data')\nplt.xlabel('square_feet')\nplt.ylabel('price')\nplt.xticks(())\nplt.yticks(())\n\n# Plot outputs\nplt.plot(X_test, linreg.predict(X_test), color='red',linewidth=3)\nplt.show()\n\n","sub_path":"modeltraining.py","file_name":"modeltraining.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"422762742","text":"import jsonfield.fields\nfrom django.db import migrations, models\n\nimport openslides.utils.models\n\n\ndef add_default_projector(apps, schema_editor):\n \"\"\"\n Adds default projector, welcome slide and activates clock and welcome\n slide.\n \"\"\"\n # We get the model from the versioned app registry;\n # if we directly import it, it will be the wrong version.\n CustomSlide = apps.get_model('core', 'CustomSlide')\n custom_slide = CustomSlide.objects.create(\n title='Welcome to OpenSlides',\n weight=-500)\n Projector = apps.get_model('core', 'Projector')\n projector_config = [\n {'name': 'core/clock', 'stable': True},\n {'name': 'core/customslide', 'id': custom_slide.id}]\n Projector.objects.create(config=projector_config)\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='CustomSlide',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('title', models.CharField(max_length=256, verbose_name='Title')),\n ('text', models.TextField(blank=True, verbose_name='Text')),\n ('weight', models.IntegerField(verbose_name='Weight', default=0)),\n ],\n options={\n 'ordering': ('weight', 'title'),\n },\n bases=(openslides.utils.models.RESTModelMixin, models.Model),\n ),\n migrations.CreateModel(\n name='Projector',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('config', jsonfield.fields.JSONField()),\n ],\n options={\n 'permissions': (\n ('can_see_projector', 'Can see the projector'),\n ('can_manage_projector', 'Can manage the projector'),\n ('can_see_dashboard', 'Can see the dashboard'),\n ('can_use_chat', 'Can use the chat')),\n },\n bases=(openslides.utils.models.RESTModelMixin, models.Model),\n ),\n migrations.CreateModel(\n name='Tag',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('name', models.CharField(max_length=255, verbose_name='Tag', unique=True)),\n ],\n options={\n 'ordering': ('name',),\n 'permissions': (('can_manage_tags', 'Can manage tags'),),\n },\n bases=(openslides.utils.models.RESTModelMixin, models.Model),\n ),\n migrations.CreateModel(\n name='ConfigStore',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('key', models.CharField(max_length=255, db_index=True, unique=True)),\n ('value', jsonfield.fields.JSONField()),\n ],\n options={\n 'permissions': (('can_manage_config', 'Can manage configuration'),),\n },\n bases=(models.Model,),\n ),\n migrations.RunPython(\n code=add_default_projector,\n reverse_code=None,\n atomic=True,\n ),\n ]\n","sub_path":"openslides/core/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"387316096","text":"#################################################################\n# #\n# Welcome to the ARIEL follow-up Simulator #\n# #\n# This file is the main file that runs the simulator #\n# It copies an unused database file, populates with telescopes, #\n# and runs the simulation #\n# Requires an accuracy threshold in minutes, a csv file with #\n# telescope data, and an operating mode #\n# Generates a csv file with running total data once finished #\n# #\n# Hamish Caines 07-2019 #\n#################################################################\n\n\ndef parse_arguments():\n \"\"\"\n Allows arguments to be parsed when this method is called. These arguments specify the setup for the simulation\n :return: threshold: accuracy threshold to be used as the cutoff in the simulation\n :return: telescope_file: name of the .csv file containing the telescopes to be used in the simulation\n :return: mode: operating mode for the simulation, controls the amount of telescope time to be used\n \"\"\"\n import argparse\n parser = argparse.ArgumentParser(description='Run simulation')\n # specify arguments to be collected\n parser.add_argument('threshold', type=int, help='Accuracy threshold') # name of file, not location\n parser.add_argument('telescopes', type=str, help='file containing telescope data for simulation')\n parser.add_argument('mode', type=str, help='Operating mode')\n args = parser.parse_args() # collect arguments\n telescope_file = '../telescopes/' + args.telescopes # add location of telescope file to name\n mode = args.mode\n threshold = args.threshold\n print('Target threshold: ' + str(threshold))\n print('Operating mode: ' + str(mode))\n print('Obtaining telescopes from \"' + telescope_file + '\"')\n return threshold, telescope_file, mode\n\n\ndef create_simulation_name(telescope_file, threshold, mode):\n \"\"\"\n Generates folder name based on simulation settings\n :param telescope_file: name of the .csv file containing the telescopes to be used in the simulation\n :param threshold: accuracy threshold to be used as the cutoff in the simulation\n :param mode: operating mode for the simulation, controls the amount of telescope time to be used\n :return: name of folder to be used for the simulation\n \"\"\"\n # stitch together name for simulation\n sim_name = telescope_file.split('/')[-1].split('.')[0] + '_' + mode + '_' + str(threshold)\n print('Simulation name: '+sim_name+', folder created')\n return sim_name+'_test'\n\n\ndef copy_database(sim_name):\n \"\"\"\n Create folder for new simulation and copy clean database into it, renaming as new simulation name\n :param sim_name: Name of simulation\n :return: Name of database file generated\n \"\"\"\n import shutil\n from os import mkdir\n database_name = sim_name+'.db' # add database suffix\n try:\n shutil.rmtree(sim_name, ignore_errors=True) # check for existing folder and remove\n mkdir(sim_name)\n shutil.copyfile('clean/clean.db', sim_name + '/' + database_name) # copy clean database and rename\n except FileExistsError:\n pass\n\n return database_name\n\n\ndef populate_telescopes(database):\n \"\"\"\n Obtain telescope data from csv file and store in database, and generate schedule table for each telescope\n :param database: Database object connected to database file\n \"\"\"\n import database_generator\n # generate telescope data table from csv file\n telescopes = database_generator.generate_sql_table_from_csv(database.telescope_file, 'TELESCOPES', database.cursor)\n # generate schedule table for each telescope\n for telescope in telescopes:\n database.cursor.execute('DROP TABLE IF EXISTS ' + telescope[0]) # delete existing table\n database.cursor.execute('CREATE TABLE IF NOT EXISTS ' + telescope[0] + '(Target VARCHAR(25), RA DECIMAL(16,8), '\n 'Dec DECIMAL(16,8), ObsCenter DATETIME, RunStart DATETIME, RunEnd DATETIME, RunDuration'\n ' TIME, Epoch REAL, UNIQUE(RunStart))') # create new table\n print(telescope[0])\n print('Network has '+str(len(telescopes))+' telescopes')\n database.db.commit()\n\n\ndef run_simulation(database):\n \"\"\"\n Run network simulation over duration of follow-up period\n :param database: Database object connected to database file\n :return counts: Array of the number of constrained targets at every forecasting period\n :return totals: Array of the total number of targets at every forecasting period\n :return dates: Array of the dates for every forecasting period\n \"\"\"\n from datetime import datetime, timedelta\n interval = timedelta(days=7) # set interval for scheduling interval\n database.sim_end = datetime(year=2030, month=6, day=12) # end of simulation after ARIEL launch\n database.initial_expiry_calculation()\n database.sim_start = datetime.today()\n database.transit_forecast(database.sim_start, database.sim_start + interval)\n #start_date = database.find_earliest_date() # start simulation at the date of the earliest transit in the database\n\n\n print('Running simulation from '+str(database.sim_start)+' until '+str(database.sim_end))\n\n # set counter and interval for forecasting period\n time_since_forecast = timedelta(days=0)\n limit = timedelta(days=28)\n\n current_date = database.sim_start # set start date\n\n # containers for result information\n totals = []\n counts = []\n dates = []\n\n while current_date < database.sim_end: # loop while date is within simulation\n\n database.increment_total_night(current_date, interval)\n database.make_schedules(current_date, interval, database.mode) # make schedules for the scheduling interval\n database.simulate_observations(current_date, interval) # simulate the observations\n time_since_forecast += interval # increment forecast counter\n #if time_since_forecast >= limit: # check forecast counter\n\n current_date += interval # increment date\n print('Forecasting on:', current_date)\n database.transit_forecast(current_date, current_date + limit)\n time_since_forecast = timedelta(days=0)\n\n\n # find constrained and total targets and store in arrays with date\n ####count, total = database.check_constrained(current_date)\n ###counts.append(count)\n ##totals.append(total)\n #dates.append(current_date.date())\n\n print('Simulation finished')\n\n\ndef write_count_results(counts, totals, dates, sim_name):\n \"\"\"\n Write running totals of constrained and total targets, with dates to a csv file\n :param counts: Array of the number of constrained targets at every forecasting period\n :param totals: Array of the total number of targets at every forecasting period\n :param dates: Array of the dates for every forecasting period\n :param sim_name: Name of simulation\n \"\"\"\n outfile = sim_name+'.csv' # generate filename for data\n # write results to file\n with open(outfile, 'w') as f:\n f.write('# Date\\tNoObserved\\tNoTargets')\n for i in range(0, len(totals)):\n f.write('\\n' + str(dates[i]) + '\\t' + str(counts[i]) + '\\t' + str(totals[i]))\n f.close()\n\n\ndef main():\n from os import chdir, getcwd\n import actions\n threshold, telescope_file, mode = parse_arguments() # collect arguments\n sim_name = create_simulation_name(telescope_file, threshold, mode) # generate simulation name\n database_name = copy_database(sim_name) # create new database file\n chdir(sim_name)\n\n # create Database object connected to database file\n database = actions.Database(database_name, telescope_file, mode, threshold)\n populate_telescopes(database)\n\n run_simulation(database)\n\n #write_count_results(counts, totals, dates, sim_name)\n\n database.propagate_final_errors()\n count, total = database.check_constrained()\n database.store_results(count, total)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run_sim.py","file_name":"run_sim.py","file_ext":"py","file_size_in_byte":8326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"591620753","text":"'''\r\nCreated on 2019年2月26日\r\n实现win下dir查看文件目录功能\r\n@author: Le\r\n'''\r\nimport os, time, sys\r\nfrom pprint import pprint\r\n\r\nclass ls:\r\n #输出格式设定\r\n def __init__(self, path='.'):\r\n self.path = path\r\n\r\n def output(self):\r\n localtime = time.localtime()\r\n Time = '/'.join([str(x) for x in localtime[0:3]])\r\n\r\n if os.name == 'nt':\r\n print('-' * 30)\r\n print(\"{: ^30}\".format(\"OS:Windows\"))\r\n print('-' * 30)\r\n print(\"{: <{}}{: >}\".format('Time',30-len(Time), Time))\r\n\r\n\r\n#实现ls-l\r\n\r\n#获取文件夹下文件个数,只取一层\r\n def numOfFile(self, path, num=1):\r\n try:\r\n if os.path.isdir(path):\r\n for x in os.listdir(path):\r\n num += 1\r\n except BaseException:\r\n pass\r\n finally:\r\n return num","sub_path":"test/dirachieve.py","file_name":"dirachieve.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"59094521","text":"\"\"\"Delete xth node from a singly linked list. Your task is to complete the method deleteNode() which takes two arguments: the address of the head of the linked list and an integer x. The function returns the head of the modified linked list.\n\nInput:\nThe first line of input contains an element T, denoting the number of test cases. Then T test cases follow. Each test case contains three lines. The first line of each test case contains an integer N denoting the number of elements of the linked list. Then in the next line are N space separated values of the linked list. The third line of each test case contains an integer x.\n\nOutput:\nThe output for each test case will be the space separated value of the returned linked list.\n\nUser Task:\nThe task is to complete the function deleteNode() which should delete the node at required position.\n\nConstraints:\n1 <= T <= 300\n2 <= N <= 100\n1 <= x <= N\n\nExample:\nInput:\n2\n3\n1 3 4\n3\n4\n1 5 2 9\n2\n\nOutput:\n1 3\n1 2 9\n\nExplanation:\nTestcase 1: After deleting the node at 3rd position (1-base indexing), the linked list is as 1-> 3.\nTestcase 2: After deleting the node at 2nd position (1-based indexing), the linked list is as 1-> 2-> 9.\"\"\"\ndef delNode(head, k):\n # import pdb; pdb.set_trace()\n cur=head\n if k == 1:\n return cur.next\n k -= 1\n while k > 1:\n cur = cur.next\n k -= 1\n cur.next = cur.next.next\n return head\n\n # temp = head\n #\n # while(temp is not None):\n # if temp.data == k:\n # head = temp.next\n # temp = None\n # return\n #\n # while(temp is not None):\n # if temp.data == k:\n # break\n # prev = temp\n # temp = temp.next\n #\n # if temp == None:\n # return\n #\n # prev.next = temp.next\n # temp=None\n #\n # return head\n #\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def append(self, data):\n new_node = Node(data)\n if self.head == None:\n self.head = new_node\n self.tail = new_node\n return\n else:\n self.tail.next = new_node\n self.tail = new_node\n\ndef print_list(head):\n temp = head\n while(temp):\n print(temp.data, end=\" \")\n temp= temp.next\n print(\" \")\n\n\n\nt = int(input())\nfor i in range(t):\n n = int(input())\n a = LinkedList()\n val = list(map(int, input().strip().split()))\n for i in val:\n a.append(i)\n k = int(input())\n\n new_head= delNode(a.head, k)\n print_list(new_head)","sub_path":"Linked_List/delete_node.py","file_name":"delete_node.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"144106227","text":"from scarce_learn.zero_shot import zsl_base\nimport attr\nimport numpy as np\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\n\n\n@attr.s\nclass ESZSLearner(zsl_base.ZeroShotClassifier):\n \"\"\"\n Embarassingly Simple Zero Shot Learning\n see http://proceedings.mlr.press/v37/romera-paredes15.pdf\n for the paper\n \"\"\"\n\n lmbda = attr.ib(default=1e-2)\n gamma = attr.ib(default=1e-2)\n\n def fit(self, X, y, class_attributes):\n le = LabelEncoder()\n ohe = OneHotEncoder()\n y_labels_encoded = le.fit_transform(y)\n\n y_labels_ohe = ohe.fit_transform(y_labels_encoded.reshape(-1, 1)).toarray()\n X_correlation_term_inv = np.linalg.pinv(\n X.T @ X + self.gamma * np.eye(X.shape[1])\n )\n attributes_correlation_term_inv = np.linalg.pinv(\n class_attributes.T @ class_attributes\n + self.lmbda * np.eye(class_attributes.shape[1])\n )\n X_times_ohe_times_attributes = X.T @ y_labels_ohe @ class_attributes\n self.attributes_to_attributes = (\n X_correlation_term_inv\n @ X_times_ohe_times_attributes\n @ attributes_correlation_term_inv\n )\n\n def predict(self, X, class_attributes, labels_to_attributes=None):\n if labels_to_attributes is None:\n labels_to_attributes = np.arange(class_attributes.shape[0])\n scores = X @ self.attributes_to_attributes @ class_attributes.T\n return labels_to_attributes[np.argmax(scores, axis=1)]\n\n def predict_raw(self, X):\n return X @ self.attributes_to_attributes\n\n fit.__doc__ = zsl_base.ZeroShotClassifier.fit.__doc__\n predict.__doc__ = zsl_base.ZeroShotClassifier.predict.__doc__\n","sub_path":"scarce_learn/zero_shot/eszsl.py","file_name":"eszsl.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"391927680","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nfrom subprocess import Popen, PIPE\n\ndef solve_it(input_data):\n\n # Writes the inputData to a temporay file\n\n tmp_file_name = 'tmp.data'\n tmp_file = open(tmp_file_name, 'w')\n tmp_file.write(input_data)\n tmp_file.close()\n\n # Runs the command: java Solver -file=tmp.data\n cmd = \"TSP\"\n\n output = Popen([cmd], stdout=PIPE).communicate()[0]\n \n\n # removes the temporay file\n #os.remove(tmp_file_name)\n with open('output.txt', 'r') as input_data_file:\n input_data = input_data_file.read()\n #os.remove('output.txt')\n\n return input_data\n\n\nimport sys\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n file_location = sys.argv[1].strip()\n with open(file_location, 'r') as input_data_file:\n input_data = input_data_file.read()\n s = solve_it(input_data)\n print(s)\n else:\n print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/ks_4_0)')\n\n","sub_path":"TSP/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"627579481","text":"\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2017 Zuzeng Lin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n\nimport feedback\nimport time\nimport numpy as np\n\nif __name__ == \"__main__\":\n _,feedback = feedback.create_loop()\n\n chn = feedback.acturator.chn\n init = feedback.acturator.default\n step = 10\n chn_max = feedback.acturator.max[0]\n chn_min = feedback.acturator.min[0]\n while True:\n for ch in range(0, chn):\n print(ch)\n # middle to max\n x = init.copy()\n for i in range(0, step):\n x[ch] = init[ch] + (chn_max - init[ch]) * (i / ((chn_max-chn_min) * step))\n #print(x)\n feedback.write(x)\n time.sleep(0.1)\n for i in range(0, step):\n x[ch] = chn_max + (chn_min - chn_max) * (i / ((chn_max-chn_min) * step))\n #print(x)\n feedback.write(x)\n time.sleep(0.1)\n for i in range(0, step):\n x[ch] = chn_min + (init[ch] - chn_min) * (i / ((chn_max-chn_min) * step))\n #print(x)\n feedback.write(x)\n time.sleep(0.1)\n","sub_path":"SWEEP.py","file_name":"SWEEP.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"328770492","text":"import pymssql\r\nimport boto3\r\n\r\n\r\nclass db():\r\n def __init__(self):\r\n self.dbTobus_URL = 'https://sqs.us-east-1.amazonaws.com/604291830461/Myqueue'\r\n self.busTodb_URL = 'https://sqs.us-east-1.amazonaws.com/604291830461/busTodb'\r\n self.client = boto3.client('sqs')\r\n\r\n def connect(self):\r\n \"\"\"\r\n 链接数据库\r\n :return: 游标\r\n \"\"\"\r\n self.conn = pymssql.connect(\r\n host='localhost',\r\n user='sa',\r\n password='123',\r\n database='SAW')\r\n cursor = self.conn.cursor()\r\n if not cursor:\r\n print('数据库连接失败')\r\n else:\r\n return cursor\r\n\r\n def send_message(self, message):\r\n \"\"\"\r\n 向业务逻辑层发送消息\r\n :param message: 发送的消息\r\n :return:\r\n \"\"\"\r\n print('send ', message)\r\n self.client.send_message(\r\n QueueUrl=self.dbTobus_URL, MessageBody=message)\r\n\r\n def recv_message(self):\r\n \"\"\"\r\n 接受业务逻辑层发来的消息\r\n :return: 有消息则返回消息 无消息返回None\r\n \"\"\"\r\n try:\r\n resp = self.client.receive_message(QueueUrl=self.busTodb_URL)\r\n self.client.delete_message(\r\n QueueUrl=self.busTodb_URL,\r\n ReceiptHandle=resp['Messages'][0]['ReceiptHandle'])\r\n print(resp['Messages'][0]['Body'])\r\n return resp['Messages'][0]['Body']\r\n except BaseException:\r\n return None\r\n\r\n def ExecQuery(self, sql):\r\n \"\"\"\r\n 执行数据库语句\r\n :param sql: sql语句\r\n :return: 操作结果\r\n \"\"\"\r\n cursor = self.connect()\r\n cursor.execute(sql)\r\n result = cursor.fetchall()\r\n self.conn.close()\r\n return result\r\n\r\n def send_format(self, result):\r\n \"\"\"\r\n 修改游标查询的信息格式\r\n :param result:\r\n :return:\r\n \"\"\"\r\n data = \"\"\r\n for i in range(len(result)):\r\n temp = \"(\"\r\n for j in range(len(result[i])):\r\n temp += str(result[i][j])\r\n if j < len(result[i]) - 1:\r\n temp += \",\"\r\n temp += \")\"\r\n data += temp\r\n return data\r\n\r\n\r\nif __name__ == '__main__':\r\n db = db()\r\n while True:\r\n print('waitting--------------------------')\r\n message = db.recv_message()\r\n if message:\r\n result = db.ExecQuery(message)\r\n data = db.send_format(result)\r\n db.send_message(str(data))\r\n","sub_path":"three/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"563156888","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\n\ndef line_fit_model():\n inputs = tf.keras.Input(shape=[1, ], name=\"inputs\")\n layer1 = layers.Dense(10, activation='relu', name='layer1')(inputs)\n layer2 = layers.Dense(15, activation='relu', name='layer2')(layer1)\n outputs = layers.Dense(5, activation='softmax', name='outputs')(layer2)\n model = tf.keras.Model(inputs=inputs, outputs=outputs)\n model.summary()\n keras.utils.plot_model(model, \"F:/tensorflow/images/line_fit_model.png\", show_shapes=True)\n return model\n\n\nif __name__ == \"__main__\":\n\n line_fit_model()\n","sub_path":"模型/keras_sample.py","file_name":"keras_sample.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"606531278","text":"#!/usr/bin/python\n\nfrom mininet.net import Mininet\nfrom mininet.cli import CLI\nfrom mininet.node import Node\nfrom mininet.link import Link\nfrom mininet.link import TCLink\nfrom mininet.log import setLogLevel, info\n\ndef run():\n\n\n\n\n\n\n\n net = Mininet ( )\n\n #Create hosts and routers. Also create a switch in case we would like to use\n #above method for sshd services\n info( \"Creating nodes\\n\" )\n #Create switch to use with sshd\n #s1 = net.addSwitch ( 's1' )\n r1 = net.addHost( 'r1' , ip='192.168.1.2/24', inNamespace=False )\n r2 = net.addHost( 'r2' , ip='192.168.2.3/24', inNamespace=False )\n r3 = net.addHost( 'r3' , ip='192.168.1.4/24', inNamespace=False )\n r4 = net.addHost( 'r4' , ip='192.168.1.5/24', inNamespace=False )\n r5 = net.addHost( 'r5' , ip='192.168.5.3/24', inNamespace=False )\n r6 = net.addHost( 'r6' , ip='192.168.3.3/24', inNamespace=False )\n \n h1 = net.addHost( 'h1' , ip='192.168.1.1/24', defaultRoute= 'via 192.168.1.3', inNamespace=False )\n h2 = net.addHost( 'h2' , ip='192.168.2.1/24', defaultRoute= 'via 192.168.2.2', inNamespace=False )\n h3 = net.addHost( 'h3' , ip='192.168.3.1/24', defaultRoute= 'via 192.168.3.2', inNamespace=False )\n h4 = net.addHost( 'h4' , ip='192.168.4.1/24', defaultRoute= 'via 192.168.4.2', inNamespace=False)\n #Establishing the links from hosts to routers\n info( \"Creating links\\n\" )\n net.addLink( r1, r2)\n net.addLink( r1, r3)\n net.addLink( r2, r4)\n net.addLink( r3, r5)\n net.addLink( r3, r4)\n net.addLink( r6, r5)\n \n\n #net.addLink( r1, r2)\n\n net.addLink( h1, r1, intfName2='r1-eth3', params2={'ip' : '192.168.1.3/24' } )\n net.addLink( h2, r4, intfName2='r4-eth3', params2={'ip' : '192.168.2.2/24' } )\n net.addLink( h3, r6, intfName2='r6-eth3', params2={'ip' : '192.168.3.2/24' } )\n net.addLink( h4, r6, intfName2='r6-eth4', params2={'ip' : '192.168.4.2/24' } )\n# net.addLink( r1, r2 )\n\n #Build the specified network\n info( \"Building network\\n\" )\n r1.cmd( 'sysctl net.ipv4.ip_forward=1' )\n r2.cmd( 'sysctl net.ipv4.ip_forward=1' )\n r3.cmd( 'sysctl net.ipv4.ip_forward=1' )\n r4.cmd( 'sysctl net.ipv4.ip_forward=1' )\n r5.cmd( 'sysctl net.ipv4.ip_forward=1' )\n r6.cmd( 'sysctl net.ipv4.ip_forward=1' )\n \n\n info( '*** Starting network\\n')\n net.start()\n\n info( '*** Running CLI\\n' )\n CLI( net )\n\n\n info( '*** Stopping network' )\n net.stop()\n\nif __name__ == '__main__':\n setLogLevel( 'info' )\n run()\n","sub_path":"Network_2/network_topo_2.py","file_name":"network_topo_2.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"182000865","text":"import json\nimport sys\nimport pandas as pd\nimport csv\n\nfinal_list = []\ntoken_list = []\ndef processTextItem(l,textItemID,tokenStr):\n #print(token_str)\n if(len(l) > 0):\n r = l[0]\n s = token_str\n final_list.append(str(textItemID)+\":\"+str(r))\n token_list.append(s)\n\n# with open('/Users/avneet/Desktop/CS249/Dataset/testing-annotated-text.json') as data_file:\n# test_ann_textItems = json.load(data_file)\n#\n# test_ann_textItems = pd.DataFrame(list(test_ann_textItems['TextItem'].items()))\n# test_ann_textItems.columns = ['id', 'text']\n\n#Processing test_ids file\ntest_ids = pd.read_csv('../Intermediate_files/mallet_test_ids',sep=' ',skip_blank_lines=False,header = None)\ntest_ids.columns = ['docid']\n\n\n##Processing output file generated by Mallet and Stanford NER\ntest_labels = pd.read_csv('../Intermediate_files/PyStructOutput.csv',sep=' ',skip_blank_lines=False,header = None)\ntest_labels.columns = ['token', 'label']\n\ntext_index = 0\nindex_str=\"\";\nseperator =\"-\"\nl = []\ntoken_str = \"\"\ni = 0\n#count = 0\nwhile(i < len(test_labels['label'])):\n label = str(test_labels['label'][i])\n token = str(test_labels['token'][i])\n #print(label+\":\"+str(i)+ \" \"+str(test_labels['token'][i])+\" \"+str(text_index))\n if(label == 'nan'):\n #processTextItem(l, test_ann_textItems['id'][count],token_str)\n text_index = 0\n #l.clear()\n l = []\n i = i+1\n token_str = \"\"\n #count+=1\n elif(label == 'prod'):\n print(\"Found product in: \",test_ids['docid'][i],\" at line = \",i, \" \",str(test_labels['token'][i]))\n start_index = text_index\n end_index = text_index\n while(label == 'prod'):\n token = str(test_labels['token'][i])\n token_str+=token + \" \"\n end_index+=1\n text_index+=1\n i = i+1\n label = str(test_labels['label'][i])\n #l.append(str(start_index)+seperator+str(end_index-1)) - Modifying logic to include word right after product mention\n #final_index = end_index-1\n # if(label !='nan'): #New logic of including prod+1 token\n # token = str(test_labels['token'][i])\n # token_str+=token\n # final_index = end_index\n\n l.append(str(start_index)+seperator+str(end_index))\n processTextItem(l, test_ids['docid'][i-1], token_str)\n #l.clear()\n l = []\n token_str=\"\"\n elif(label == 'O'):\n i+=1\n text_index += 1\n\n#processTextItem(l, test_ann_textItems['id'][count],token_str)\n\nwith open(\"../Intermediate_files/output_textids.csv\", \"w\") as output:\n writer = csv.writer(output, lineterminator='\\n')\n for val in final_list:\n writer.writerow([val])\n\nwith open(\"../Intermediate_files/output_query.csv\", \"w\") as output:\n writer = csv.writer(output, lineterminator='\\n')\n for val in token_list:\n writer.writerow([val])","sub_path":"Final-Project/Source/Generate_output_PyStruct.py","file_name":"Generate_output_PyStruct.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"291748718","text":"import ujson\nimport httptools\nfrom ujson import loads as json_loads\nfrom urllib.parse import parse_qs\n\nSTATUS_CODES = {\n 200: 'OK',\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 402: 'Payment Required',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 500: 'Internal Server Error',\n 501: 'Not Implemented',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n}\n\n\nclass HTTPResponse:\n __slots__ = ('body', 'status', 'content_type', 'headers')\n\n def __init__(self, body=None, status=200, headers=[], content_type='text/plain', body_bytes=b''):\n self.content_type = content_type\n\n if not body is None:\n self.body = body.encode('utf-8')\n else:\n self.body = body_bytes\n\n self.status = status\n self.headers = headers\n\n def output(self, version=\"1.1\", keep_alive=False, keep_alive_timeout=None):\n # This is all returned in a kind-of funky way\n # We tried to make this as fast as possible in pure python\n additional_headers = []\n if keep_alive and not keep_alive_timeout is None:\n additional_headers = [b'Keep-Alive: timeout=', str(keep_alive_timeout).encode(), b's\\r\\n']\n if self.headers:\n for name, value in self.headers.items():\n additional_headers.append('{}: {}\\r\\n'.format(name, value).encode('utf-8'))\n\n return b''.join([\n 'HTTP/{} {} {}\\r\\n'.format(version, self.status,\n STATUS_CODES.get(self.status, 'FAIL')).encode(),\n b'Content-Type: ', self.content_type.encode(), b'\\r\\n',\n b'Content-Length: ', str(len(self.body)).encode(), b'\\r\\n',\n b'Connection: ', ('keep-alive' if keep_alive else 'close').encode(), b'\\r\\n',\n ] + additional_headers + [\n b'\\r\\n',\n self.body,\n ])\n\n\ndef json(body, status=200, headers=None):\n return HTTPResponse(ujson.dumps(body), headers=headers, status=status,\n content_type=\"application/json; charset=utf-8\")\n\n\ndef text(body, status=200, headers=None):\n return HTTPResponse(body, status=status, headers=headers, content_type=\"text/plain; charset=utf-8\")\n\n\ndef html(body, status=200, headers=None):\n return HTTPResponse(body, status=status, headers=headers, content_type=\"text/html; charset=utf-8\")\n","sub_path":"sanic/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"552062944","text":"from bs4 import BeautifulSoup\nfrom pymongo import MongoClient\nimport datetime\nimport time\nimport requests as req\n\n\ndef main():\n\n scrape_eyd_html()\n\n return 0\n\n\ndef get_mongo_connection(database, collections):\n \"\"\"\n Connects to the local MongoDB.\n\n Parameters\n database: str\n The name of the MongoDB\n collections: list\n A list of strings naming the collections\n\n Returns\n -------\n client:\n The MongoDB client\n database:\n The MongoDB database\n collections: dict\n A dictionary with the passed strings as keys\n and the Mongo Collections as values\n \"\"\"\n\n client = MongoClient()\n db = client[database]\n col_dict = {name: db[name] for name in collections}\n\n return (client, db, col_dict)\n\n\ndef insert_html_to_mongo(url, soup, collection):\n \"\"\"\n Given a BeautifulSoup object and a MongoDB collection,\n inserts the html into the collection.\n\n Parameters\n ----------\n url: str\n The URL for the soup object\n soup: BeauitifulSoup\n The html to be inserted into the collection\n collection: MongoDB Collection\n The collection into which the soup is inserted\n\n Returns\n -------\n None\n \"\"\"\n collection.insert_one(\n {\n 'url': url,\n 'date_scraped': datetime.datetime.now(),\n 'html': soup.prettify()\n }\n )\n\n\ndef soupify(url):\n \"\"\"\n Given an url retreive the website and soupify the text.\n\n Parameters\n ----------\n url: str\n The full address of the website.\n logfile: str, default=None\n A file object for logging the attempt\n\n Returns\n -------\n soup: BeautifulSoup object\n Containins the html of the website.\n \"\"\"\n try:\n webpage = req.get(url)\n except Exception as e:\n print('Failed to retrieve {}.'.format(url),\n 'Error message: {}'.format(e))\n return None\n\n if webpage.status_code == 200:\n print('Retrieved {} at {}'\n .format(url, datetime.datetime.now()))\n else:\n print('Attempted to retreive {} at {}.'\n .format(url, datetime.datetime.now()),\n 'Status Code: {}'.format(webpage.status_code))\n\n return BeautifulSoup(webpage.text, 'html5lib')\n\n\ndef scrape_eyd_html():\n \"\"\"\n Scrapes the member pages of the form:\n https://eyd.yunguseng.com/season24/profile.php?id=564 from id=1 ... 850\n\n Parameters\n ---------\n None\n\n Return\n ------\n None\n \"\"\"\n # Connect to local MongoDB\n client, ayd_db, col_dict = get_mongo_connection('eyd', ['html'])\n html_col = col_dict['html']\n\n # Scrape each link\n for link in generate_eyd_urls():\n soup = soupify(link)\n insert_html_to_mongo(link, soup, html_col)\n time.sleep(2)\n\n return None\n\n\ndef generate_eyd_urls():\n \"\"\"\n Generates urls for scraping the EYD member pages.\n\n Parameters\n ----------\n None\n\n Yields\n ------\n eyd_url: string\n 'https://eyd.yunguseng.com/season24/profile.php?id=<1-850>'\n \"\"\"\n prepend_address = 'https://eyd.yunguseng.com/season24/profile.php?id='\n for id in range(1, 851):\n yield prepend_address + str(id)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"data_collection/scrape_profile_html.py","file_name":"scrape_profile_html.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"633916977","text":"import tkinter as tk\nfrom tkinter import ttk\nimport os\n\n###\n# This module defines several useful classes that create basic GUI components used\n# used throughout the PyHammer interface. Defined are are GUIs for opening an info\n# window to inform the user of information, a modal window for asking a yes/no\n# question, an option window for asking the user to pick a choice, and a tooltip\n# class to creating tooltips that are bound to widgets.\n#\n\n\nclass InfoWindow(object):\n \"\"\"\n Description:\n This brings up a new window derived from root\n that displays info and has a button to close\n the window when user is done. This optionally can\n display the multiple sets of text in multiple tabs\n so as to not have a huge, long window and to keep\n the information more organized.\n \n Input:\n args: This will be a set of arguments supplying what should be\n put into the info window. If the user wants a basic window\n with simple text, then just supply a string with that text.\n However, the user can also specify multiple arguments where\n each argument will be its own tab in a notebook on the window.\n Each argument in this case should be a tuple containing first\n the name that will appear on the tab, and second, the text to\n appear inside the tab.\n parent: The root window to potentially derive this one from. If\n nothing is provided, this will create a new window from scratch.\n title: The title to display on the window\n height: The height of the window, in lines. More height provides a\n taller window.\n width: The width of the window, in characters.\n pos: The physical position of this window with respect to the parent\n window, if one exists. Provide input as a tuple of pixels to shift\n the info window frame by, relative to the parent window's upper\n left corner. Default is tuple input of (0,0). Also accepts the\n command 'right' or 'below' to put new window to the right or below\n the parent window. Any other input defaults to tuple input of (0,0).\n fontFamily: A valid, specific font family to use, if desired.\n \n Example:\n This brings up a simple GUI with basic text in it. It derives from a\n top level root window named 'root'\n\n InfoWindow('This is an example\\ninfo window.', parent = root, title = 'A GUI title')\n \n This brings up a GUI with multiple tabs and different\n text in each tab. This is not derived from a root.\n \n InfoWindow(('Tab 1', 'Text in tab 1'), ('Tab 2', 'Some more text'), title = 'Title')\n \n \"\"\"\n\n def __init__(self, *args, parent = None, title = 'PyHammer', height = 6, width = 50, pos = (0,0), fontFamily = None):\n # Setup the window\n if parent is None:\n # If no top level was provided, define the window as the top level\n self.infoWindow = tk.Tk()\n else:\n # If a top level was provided, derive a new window from it\n self.infoWindow = tk.Toplevel(parent)\n self.infoWindow.grab_set() # Make the root window non-interactive\n if pos == 'right':\n self.infoWindow.geometry('+%i+%i' % (parent.winfo_rootx()+parent.winfo_width(), parent.winfo_rooty()))\n elif pos == 'below':\n self.infoWindow.geometry('+%i+%i' % (parent.winfo_rootx(), parent.winfo_rooty()+parent.winfo_height()))\n elif type(pos) is tuple:\n self.infoWindow.geometry('+%i+%i' % (parent.winfo_rootx()+pos[0], parent.winfo_rooty()+pos[1]))\n else:\n self.infoWindow.geometry('+%i+%i' % (parent.winfo_rootx(), parent.winfo_rooty()))\n self.infoWindow.title(title)\n if os.name == 'nt': self.infoWindow.iconbitmap(os.path.join(os.path.split(__file__)[0],'resources','sun.ico'))\n self.infoWindow.resizable(False, False)\n\n # Define the window contents\n if len(args) == 1:\n self.defineTab(self.infoWindow, args[0], height, width, fontFamily)\n else:\n notebook = ttk.Notebook(self.infoWindow)\n for a in args:\n tab = tk.Frame(notebook)\n notebook.add(tab, text = a[0])\n self.defineTab(tab, a[1], height, width, fontFamily)\n notebook.pack()\n if parent is None: self.infoWindow.mainloop()\n\n def defineTab(self, parent, text, height, width, fontFamily):\n # Create the Text widget which displays the text\n content = tk.Text(parent, height = height, width = width, background = parent.cget('background'),\n relief = tk.FLAT, wrap = tk.WORD, font = '-size 10')\n if fontFamily is not None: content.configure(font = '-family ' + fontFamily +' -size 10')\n content.grid(row = 0, column = 0, padx = 2, pady = 2)\n content.insert(tk.END, text)\n # Create the Scrollbar for the Text widget\n scrollbar = ttk.Scrollbar(parent, command = content.yview)\n scrollbar.grid(row = 0, column = 1, sticky = 'ns')\n # Link the Text widget to the Scrollbar\n content.config(state = tk.DISABLED, yscrollcommand = scrollbar.set)\n # Add the OK button at the bottom for quitting out\n but = ttk.Button(parent, text = 'OK', command = self.infoWindow.destroy)\n but.grid(row = 1, column = 0, columnspan = 2, sticky = 'nsew', padx = 2, pady = 5)\n parent.rowconfigure(1, minsize = 40)\n\n\nclass ModalWindow(object):\n \"\"\"\n Description:\n This brings up a new window, potentially derived\n from a top level root window that displays a question\n and asks the user to choose yes or no. At the termination\n of this window, one can look at the attribute choice\n to determine which button was pressed by the user. If the\n user X's out without choosing an option, then the choice\n will be equal to None.\n\n Input:\n text: The question to display to the user.\n parent: The root window to potentially derive this one from. If\n nothing is provided, this will create a new window from scratch.\n title: The title to display on the window. Default is \"PyHammer\".\n\n Output:\n choice: The user's choice is recorded in the object's choice variable.\n This variable will be set to either 'yes' if they chose the yes\n button, 'no' if they chose the no button, or None if they\n X'ed out.\n\n Example:\n To properly use this window, you must create a new object and\n assign it to a variable. This will bring up the window. You\n must then wait for the window to be closed before moving on in\n your code. This can be acheived in a manner similar to the following:\n\n modal = ModalWindow('Is the answer to this question no?', parent = self.root)\n self.root.wait_window(modal.modalWindow)\n\n After this, one can inspect modal.choice.\n\n If you are not deriving this window from a top level window, then\n you do not need the wait_window call and you can simply use:\n\n modal = ModalWindow('Is the answer to this question no?')\n \"\"\"\n\n def __init__(self, text, parent = None, title = 'PyHammer'):\n self.choice = None\n\n # Setup the window\n if parent is None:\n # If no top level was provided, define the window as the top level\n self.modalWindow = tk.Tk()\n else:\n # If a top level was provided, derive a new window from it\n self.modalWindow = tk.Toplevel(parent)\n self.modalWindow.grab_set() # Make the root window non-interactive\n self.modalWindow.geometry('+%i+%i' % (parent.winfo_rootx(), parent.winfo_rooty()))\n self.modalWindow.title(title)\n if os.name == 'nt': self.modalWindow.iconbitmap(os.path.join(os.path.split(__file__)[0],'resources','sun.ico'))\n self.modalWindow.resizable(False, False)\n\n # Setup the widgets in the window\n label = ttk.Label(self.modalWindow, text = text, font = '-size 10')\n label.grid(row = 0, column = 0, columnspan = 2, padx = 2, pady = 2)\n \n but = ttk.Button(self.modalWindow, text = 'Yes', command = self.choiceYes)\n but.grid(row = 1, column = 0, sticky = 'nsew', padx = 2, pady = 5)\n\n but = ttk.Button(self.modalWindow, text = 'No', command = self.choiceNo)\n but.grid(row = 1, column = 1, sticky = 'nsew', padx = 2, pady = 5)\n\n self.modalWindow.rowconfigure(1, minsize = 40)\n\n if parent is None: self.modalWindow.mainloop()\n\n def choiceYes(self):\n self.choice = 'yes'\n self.modalWindow.destroy()\n\n def choiceNo(self):\n self.choice = 'no'\n self.modalWindow.destroy()\n\n\nclass OptionWindow(object):\n \"\"\"\n Description:\n This brings up a window that allows the user to choose between\n a list of radio button choices, or else enter their own choice\n in an Entry field. Once their choice is made, they hit okay.\n\n Input:\n choices: A list of strings which contain choices that the user\n can pick from. These will appear as a selection of radio\n buttons.\n parent: A root tkinter frame to derive this frame from. If none\n is provided, then this will become a root frame itself.\n title: The title to display on the window.\n instruction: A label to place at the top of the GUI to instruct\n the user what to do.\n\n Output:\n name: This will be the object's variable which stores which name\n they chose from the list, including any name they entered\n into the Entry field. This will be equal to None if they\n X'ed out of the window.\n\n Example:\n To properly use this window, you must create a new object and\n assign it to a variable. This will bring up the window. You\n must then wait for the window to be closed before moving on in\n your code. This can be acheived in a manner similar to the following:\n\n option = OptionWindow(['Dog', 'Cat', 'Bird'], parent = self.root)\n self.root.wait_window(option.optionWindow)\n\n After this, one can inspect option.name.\n\n If you are not deriving this window from a top level window, then\n you do not need the wait_window call and you can simply use:\n\n option = OptionWindow(['Red', 'Blue', 'Purple'])\n \"\"\"\n\n def __init__(self, choices, parent = None, title = 'PyHammer', instruction = 'Pick a choice'):\n self.name = None\n self.choices = choices\n self.instruction = instruction\n\n # Setup the window\n if parent is None:\n # If no top level was provided, define the window as the top level\n self.optionWindow = tk.Tk()\n else:\n self.optionWindow = tk.Toplevel(parent)\n self.optionWindow.grab_set() # Make the root window non-interactive\n self.optionWindow.geometry('+%i+%i' % (parent.winfo_rootx(), parent.winfo_rooty()))\n self.optionWindow.title(title)\n if os.name == 'nt': self.optionWindow.iconbitmap(os.path.join(os.path.split(__file__)[0],'resources','sun.ico'))\n self.optionWindow.resizable(False, False)\n\n # Setup some GUI parameters\n self.radioChoice = tk.IntVar(value = 0)\n self.customName = tk.StringVar()\n self.label = tk.StringVar(value = instruction)\n\n # Setup the widgets in the window\n tk.Label(self.optionWindow, textvariable = self.label, justify = 'center').grid(row = 0, column = 0, columnspan = 2)\n \n # Create the radio buttons for the input choices\n for i, c in enumerate(choices):\n temp = ttk.Radiobutton(self.optionWindow, text = '', variable = self.radioChoice, value = i)\n temp.grid(row = i+1, column = 0, padx = (10,0), sticky = 'nesw')\n \n temp = ttk.Label(self.optionWindow, text = c)\n temp.grid(row = i+1, column = 1, sticky = 'w')\n\n # Create the radio button and entry field for the user's choice\n temp = ttk.Radiobutton(self.optionWindow, text = '', variable = self.radioChoice, value = i+1)\n temp.grid(row = i+2, column = 0, padx = (10,0), sticky = 'nesw')\n \n temp = ttk.Entry(self.optionWindow, textvariable = self.customName, width = 10)\n temp.grid(row = i+2, column = 1, sticky = 'w')\n\n # Define the button\n but = ttk.Button(self.optionWindow, text = 'OK', command = self._exit)\n but.grid(row = i+3, column = 0, columnspan = 2, sticky = 'nsew', padx = 2, pady = 5)\n\n # Configure grid sizes\n self.optionWindow.rowconfigure(i+3, minsize = 40)\n self.optionWindow.columnconfigure(1, minsize = 175)\n\n if parent is None: self.optionWindow.mainloop()\n\n def _exit(self):\n \"\"\"\n Description:\n This is called when the user X's out of the window or\n clicks the OK button in the window. It will check\n what choice they chose and set it as the name then\n destroy the window. It will make sure though, that the\n user has entered text into the Entry field if they\n pick that option.\n \"\"\"\n if self.radioChoice.get() < len(self.choices):\n self.name = self.choices[self.radioChoice.get()]\n else:\n if self.customName.get() == '':\n # Temporarily change label to inform user of the problem.\n self.label.set('Enter Text for Custom Name')\n self.optionWindow.bell() # Chime a bell to indicate a problem\n self.optionWindow.after(1500, lambda: self.label.set(self.instruction))\n return\n else:\n self.name = self.customName.get()\n self.optionWindow.destroy()\n\n\nclass ToolTip(object):\n \"\"\"\n Description:\n This class allows for defining a tool tip which will pop up\n and provide a helpful hint when the user's mouse hovers\n over a given widget.\n\n Input:\n widget: A tkinter widget such as tk.Button or tk.Entry to\n bind the tool tip to. This will work on ttk widgets as well.\n text: The text to display in the tool tip\n\n Example:\n button = tk.Button('Button!')\n ToolTip(button, 'Press this!')\n \"\"\"\n\n def __init__(self, widget, text, active = True):\n # Bind the widget mouse enter and leave callbacks\n # to the show and hide functions\n widget.bind('', lambda event: self.showtip())\n widget.bind('', lambda event: self.hidetip())\n\n # Create the derived Toplevel window and remove any\n # decorations or framing of that window\n self.tipWindow = tk.Toplevel(widget)\n self.tipWindow.wm_overrideredirect(1)\n try:\n # For Mac OS\n self.tipWindow.tk.call('::tk::unsupported::MacWindowStyle',\n 'style', self.tipWindow._w,\n 'help', 'noActivates')\n except tk.TclError:\n pass\n \n # Put a label into the window with the provided text\n # specify formatting\n tk.Label(self.tipWindow, text = text, justify = tk.LEFT, background='#FFFFFF',\n relief = tk.SOLID, borderwidth = 1, font=('tahoma', '8', 'normal')).pack(ipadx = 2)\n self.tipWindow.withdraw() # Hide the tooltip window initially\n\n self.widget = widget\n self.active = active\n\n def showtip(self):\n # Conditions to not show the tooltip\n if not self.active: return\n if str(self.widget.cget('state')) == 'disabled': return\n \n # Get widget position\n self.widget.update_idletasks()\n x = self.widget.winfo_rootx()\n y = self.widget.winfo_rooty()\n w = self.widget.winfo_width()\n h = self.widget.winfo_height()\n # If pointer is inside widget, define tipWindow position and display it\n if ( x <= self.widget.winfo_pointerx() <= x + w and\n y <= self.widget.winfo_pointery() <= y + h):\n\n self.tipWindow.wm_geometry('+{}+{}'.format(x+min(10,w/2),y+h))\n self.tipWindow.deiconify()\n\n def hidetip(self):\n self.tipWindow.withdraw()\n","sub_path":"gui_utils.py","file_name":"gui_utils.py","file_ext":"py","file_size_in_byte":16469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"2748679","text":"items = ['A', 'B', 'C', 'D', 'E']\nsupport_threshold = 2\nconfidence_threshold = 1.0\n\n\ndef support_count(item_set_param):\n s = 0\n for t in transactions:\n match = True\n for _item in item_set_param:\n if _item not in t:\n match = False\n break\n if match:\n s += 1\n return s\n\n\ndef hash_item_set(item_set_param):\n string = ''\n for _item in item_set_param:\n string += str(_item)\n return string\n\n\ndef confidence(rule_support, rule_cause_param):\n s = 0\n for t in transactions:\n match = True\n for _item in rule_cause_param:\n if _item not in t:\n match = False\n break\n if match:\n s += 1\n return rule_support/s\n\n\ndef generate_rules():\n confident_rules = dict()\n for k_set in frequent_item_sets:\n for frequent_item_set in k_set:\n if len(frequent_item_set) < 2:\n continue\n\n confident_rules[hash_item_set(frequent_item_set)] = dict()\n current_set_support = support_count(frequent_item_set)\n current_rules = list()\n current_rules_hash = set()\n # generate 1-item set in consequent\n current_rules.append(list())\n for idx in range(len(frequent_item_set)):\n item_set = frequent_item_set.copy()\n item_set.pop(idx)\n\n item_set_hash = hash_item_set(item_set)\n if item_set_hash not in current_rules_hash:\n if confidence(current_set_support, item_set) >= confidence_threshold:\n current_rules[0].append(item_set)\n current_rules_hash.add(item_set_hash)\n\n for k in range(1, len(frequent_item_set) - 1):\n current_rules.append(list())\n for k_minus_one in current_rules[k - 1]:\n for idx in range(len(k_minus_one)):\n item_set = k_minus_one.copy()\n item_set.pop(idx)\n\n item_set_hash = hash_item_set(item_set)\n if item_set_hash not in current_rules_hash:\n if confidence(current_set_support, item_set) >= confidence_threshold:\n current_rules[k].append(item_set)\n current_rules_hash.add(item_set_hash)\n if len(current_rules[k]) == 0:\n current_rules.pop()\n break\n\n confident_rules[hash_item_set(frequent_item_set)]['item set'] = frequent_item_set\n confident_rules[hash_item_set(frequent_item_set)]['rule list'] = current_rules\n return confident_rules\n\n\ndef list_diff(li1, li2):\n li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2]\n return li_dif\n\n\ntransactions = list()\n\ntransactions.append(['A', 'C', 'D'])\ntransactions.append(['B', 'C', 'E'])\ntransactions.append(['A', 'B', 'C', 'E'])\ntransactions.append(['B', 'E'])\n\nfrequent_item_sets = list()\nfrequent_item_sets_hash = set()\n# generate 1-frequent item set\nfrequent_item_sets.append(list())\nfor item in items:\n item_set = list()\n item_set.append(item)\n\n item_set_hash = hash_item_set(item_set)\n if item_set_hash not in frequent_item_sets_hash:\n if support_count(item_set) >= support_threshold:\n frequent_item_sets[0].append(item_set)\n frequent_item_sets_hash.add(item_set_hash)\n\n\nfor k in range(1, len(items)):\n frequent_item_sets.append(list())\n for k_minus_one in frequent_item_sets[k - 1]:\n for one_item_set in frequent_item_sets[0]:\n if one_item_set[0] in k_minus_one:\n continue\n k_item_set = k_minus_one.copy()\n k_item_set.append(one_item_set[0])\n k_item_set.sort()\n\n item_set_hash = hash_item_set(k_item_set)\n if item_set_hash not in frequent_item_sets_hash:\n if support_count(k_item_set) >= support_threshold:\n frequent_item_sets[k].append(k_item_set)\n frequent_item_sets_hash.add(item_set_hash)\n if len(frequent_item_sets[k]) == 0:\n frequent_item_sets.pop()\n break\n\n# output\noutput = open('.\\\\outputs\\\\q1\\\\section2_results.txt', 'w')\n# a\noutput.write('a.\\n')\nfor freq_set in frequent_item_sets:\n for freq in freq_set:\n output.write(str(freq) + '\\n')\noutput.write('---------------------------------\\n')\n# b\noutput.write('b.\\n')\n# rule generation\nconfidence_threshold = 0.65\nconfident_65 = generate_rules()\nnumber = 0\nfor key in confident_65:\n frequent_item = confident_65[key]['item set']\n for rule_set in confident_65[key]['rule list']:\n for rule_cause in rule_set:\n consequent = list_diff(frequent_item, rule_cause)\n output.write(str(rule_cause) + '=>' + str(consequent) + '\\n')\n number += 1\noutput.write('number of rules: ' + str(number) + '\\n')\noutput.write('---------------------------------\\n')\n# c\noutput.write('c.\\n')\n# rule generation\nconfidence_threshold = 0.8\nconfident_8 = generate_rules()\nfor key in confident_8:\n frequent_item = confident_8[key]['item set']\n for rule_set in confident_8[key]['rule list']:\n for rule_cause in rule_set:\n consequent = list_diff(frequent_item, rule_cause)\n output.write(str(rule_cause) + '=>' + str(consequent) + '\\n')\noutput.write('---------------------------------\\n')\n# d\noutput.write('d.\\n')\nnumerator = ['C', 'E']\ndenominator = ['E']\nresult = support_count(numerator) / support_count(denominator)\noutput.write(str(result) + '\\n')\noutput.write('---------------------------------\\n')\n# e\noutput.write('e.\\n')\nnumerator = ['B', 'C']\ndenominator = ['B']\nresult = support_count(numerator) / support_count(denominator)\noutput.write(str(result) + '\\n')\noutput.write('---------------------------------\\n')\n\n\n","sub_path":"data mining/hw3/a-priori-q2.py","file_name":"a-priori-q2.py","file_ext":"py","file_size_in_byte":5921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"536002504","text":"from random import randrange \r\n\r\n\r\npokracovani_hry = \"hra\"\r\n\r\nwhile pokracovani_hry == \"hra\":\r\n\r\n\thod_kostkou = randrange (0,3)\r\n\r\n\tif hod_kostkou == 0:\r\n\t\ttah_pocitace = \"kamen\"\r\n\telif hod_kostkou == 1:\r\n\t\ttah_pocitace = \"nuzky\"\r\n\telif hod_kostkou == 2:\r\n\t\ttah_pocitace = \"papir\"\r\n\r\n\ttah_hrace = input (\"zvol kamen, nuzky nebo papir \")\r\n\tprint (\"tah pocitace je:\", tah_pocitace)\r\n\r\n\tif tah_hrace == tah_pocitace:\r\n\t\tprint (\"plichta\")\r\n\telif tah_hrace == \"kamen\":\r\n\t\tif tah_pocitace == \"nuzky\":\r\n\t\t\tprint (\"vyhrál jsi\")\r\n\t\telif tah_pocitace == \"papir\":\r\n\t\t\tprint (\"prohrál jsi\")\r\n\telif tah_hrace == \"nuzky\":\r\n\t\tif tah_pocitace == \"papir\":\r\n\t\t\tprint (\"vyhrál jsi\")\r\n\t\telif tah_pocitace == \"kamen\":\r\n\t\t\tprint (\"prohrál jsi\")\r\n\telif tah_hrace == \"papir\":\r\n\t\tif tah_pocitace == \"nuzky\":\r\n\t\t\tprint (\"prohrál jis\")\r\n\t\telif tah_pocitace == \"kamen\":\r\n\t\t\tprint (\"vyhrál jsi\")\r\n\telse:\r\n\t\tprint(\"špatně zadaný tah hráče \")\r\n\r\n\tpokracovani_hry = input ( \"Pokud chcete hrát dál napište - hra, pokud nechcte dál hrát napište - konec \")\r\n\t\r\nprint (\"Tak si zahrajeme zase příště\")\r\n\t\r\n\r\n\r\n","sub_path":"ukol_4.py","file_name":"ukol_4.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"350822437","text":"from PIL import Image\nimport hcaptcha\nimport imagehash\nimport os\nimport glob\n\nclass Solver:\n max_retries = 3\n min_answers = 3\n\n def __init__(self, data_dir=None):\n data_dir = data_dir if data_dir is not None else \"./solver-data\"\n\n self.data_dir = data_dir\n self._confirmed = {}\n\n self._setup_data_dir()\n self._load_data()\n\n @staticmethod\n def hash_image(im):\n return str(imagehash.phash(im, 8))\n\n @staticmethod\n def hash_question(question):\n return question.split(\" \")[-1].lower().strip(\".,!?\")\n\n def get_token(self, sitekey, host, _retry=0, **kwargs):\n if _retry > self.max_retries:\n return\n \n ch = hcaptcha.Challenge(sitekey, host, **kwargs)\n q_hash = self.hash_question(ch.question)\n key_to_id = {}\n id_to_im = {}\n answers = []\n unused = []\n\n for key, im in ch.tasks(with_image=True):\n im_id = (q_hash, self.hash_image(im))\n key_to_id[key] = im_id\n id_to_im[im_id] = im\n if im_id in self._confirmed:\n answers.append(key)\n else:\n unused.append(key)\n \n while self.min_answers > len(answers):\n answers.append(unused.pop())\n \n token = ch.solve(answers)\n if token:\n for key in answers:\n im_id = key_to_id[key]\n if not im_id in self._confirmed:\n self._confirm(im_id, id_to_im[im_id])\n return token\n \n return self.get_token(sitekey, host, _retry+1, **kwargs)\n\n def _confirm(self, im_id, im):\n if im_id in self._confirmed:\n return\n self._confirmed[im_id] = True\n im_filepath = os.path.join(self.data_dir, \"confirmed\", \"_\".join(im_id) + \".png\")\n if not os.path.isfile(im_filepath):\n im.save(im_filepath)\n\n def _setup_data_dir(self):\n if not os.path.isdir(self.data_dir):\n os.mkdir(self.data_dir)\n\n for subdir in [\"confirmed\"]:\n if not os.path.isdir(os.path.join(self.data_dir, subdir)):\n os.mkdir(os.path.join(self.data_dir, subdir))\n \n def _load_data(self):\n for sample_filepath in glob.glob(self.data_dir + \"/confirmed/*.png\"):\n try:\n sample = Image.open(sample_filepath)\n q_hash = os.path.basename(sample_filepath).split(\"_\")[0]\n self._confirm((q_hash, self.hash_image(sample)), sample)\n except:\n pass\n","sub_path":"hcaptcha/solvers.py","file_name":"solvers.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"630445938","text":"import os\nimport time \nimport numpy as np\nfrom tqdm import tqdm\nimport scipy.stats\nimport pandas as pd\nimport matplotlib\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport argparse\nimport tensorflow as tf\nfrom tensorflow import keras\nimport model\nimport utils\nimport random\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--model\", help=\"model to train with, CNN, BLSTM or CNN-BLSTM\")\nparser.add_argument(\"--epoch\", type=int, default=100, help=\"number epochs\")\nparser.add_argument(\"--batch_size\", type=int, default=8, help=\"number batch_size\")\nparser.add_argument(\"--data\", help=\"data: VC, LA\")\nparser.add_argument(\"--feats\", help=\"feats: orig, DS-image, xvec_, or CNN\")\nparser.add_argument(\"--seed\", type=int, default=1984, help=\"specify a seed\")\nparser.add_argument(\"--alpha\", type=float, default=1.0, help=\"specify an alpha value\")\nargs = parser.parse_args()\n\n\nrandom.seed(args.seed)\n\nalpha = args.alpha\n\nif not args.model:\n raise ValueError('please specify model to train with, CNN, BLSTM or CNN-BLSTM')\n\nprint('training with model architecture: {}'.format(args.model)) \nprint('epochs: {}\\nbatch_size: {}'.format(args.epoch, args.batch_size))\nprint('training with data: {}'.format(args.data)) \nprint('training with features: {}'.format(args.feats)) \n\n# 0 = all messages are logged (default behavior)\n# 1 = INFO messages are not printed\n# 2 = INFO and WARNING messages are not printed\n# 3 = INFO, WARNING, and ERROR messages are not printed\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}\n\ntf.debugging.set_log_device_placement(False)\n# set memory growth\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n try:\n # Currently, memory growth needs to be the same across GPUs\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n \n logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n except RuntimeError as e:\n # Memory growth must be set before GPUs have been initialized\n print(e)\n\n \n# set dir\nDATA_DIR = './data_'+args.data\nBIN_DIR = os.path.join(DATA_DIR, args.feats)\nOUTPUT_DIR = './results_O_alpha/output_'+args.model+\"_\"+str(args.batch_size)+\"_\"+args.data+\"_\"+args.feats+\"_\"+str(alpha)\nresults_file = OUTPUT_DIR+\"/results.pkl\"\n\nEPOCHS = args.epoch\nBATCH_SIZE = args.batch_size\n\nif args.data == \"VC\":\n NUM_TRAIN = 13580\n NUM_TEST=4000\n NUM_VALID=3000\n mos_list = utils.read_list(os.path.join(DATA_DIR,'mos_list.txt'))\n random.shuffle(mos_list)\n train_list= mos_list[0:-(NUM_TEST+NUM_VALID)]\n random.shuffle(train_list)\n valid_list= mos_list[-(NUM_TEST+NUM_VALID):-NUM_TEST]\n test_list= mos_list[-NUM_TEST:]\nif args.data == \"LA\":\n train_list = utils.read_list(os.path.join(DATA_DIR,'train_list.txt'))\n valid_list = utils.read_list(os.path.join(DATA_DIR,'valid_list.txt'))\n test_list = utils.read_list(os.path.join(DATA_DIR,'test_list.txt'))\n random.shuffle(train_list)\n random.shuffle(valid_list)\n random.shuffle(test_list)\n NUM_TRAIN = len(train_list)\n NUM_TEST=len(valid_list)\n NUM_VALID=len(test_list)\n \n \n\nif not os.path.exists(OUTPUT_DIR):\n os.makedirs(OUTPUT_DIR)\n \n\nprint('{} for training; {} for valid; {} for testing'.format(NUM_TRAIN, NUM_TEST, NUM_VALID)) \n\n \n\n# init model\nif args.model == 'CNN':\n MOSNet = model.CNN()\nelif args.model == 'BLSTM':\n MOSNet = model.BLSTM()\nelif args.model == 'CNN-BLSTM':\n MOSNet = model.CNN_BLSTM()\nelse:\n raise ValueError('please specify model to train with, CNN, BLSTM or CNN-BLSTM')\n\nmodel = MOSNet.build()\n\nmodel.compile(\n optimizer=tf.keras.optimizers.Adam(1e-4),\n loss={'avg':'mse',\n 'frame':'mse'},\n loss_weights=[1,alpha],)\n \nCALLBACKS = [\n keras.callbacks.ModelCheckpoint(\n filepath=os.path.join(OUTPUT_DIR,'mosnet.h5'),\n save_best_only=True,\n monitor='val_loss',\n verbose=1),\n keras.callbacks.TensorBoard(\n log_dir=os.path.join(OUTPUT_DIR,'tensorboard.log'),\n update_freq='epoch'), \n keras.callbacks.EarlyStopping(\n monitor='val_loss',\n mode='min',\n min_delta=0,\n patience=5,\n verbose=1)\n]\n\n# data generator\nif args.feats == \"orig\":\n train_data = utils.data_generator(train_list, BIN_DIR, frame=True, batch_size=BATCH_SIZE)\n valid_data = utils.data_generator(valid_list, BIN_DIR, frame=True, batch_size=BATCH_SIZE)\nif args.feats == \"DS-image\":\n print(\"TODO: add a data generator for DS-image features\")\nelif args.feats[:-1] == \"xvec_\":\n print(\"TODO: add a data generator for xvec features\")\nelif args.feats == \"CNN\":\n print(\"TODO: add a data generator for CNN features\")\n\n \ntr_steps = int(NUM_TRAIN/BATCH_SIZE)\nval_steps = int(NUM_VALID/BATCH_SIZE)\n\n\n## start fitting model\nhist = model.fit_generator(train_data,\n steps_per_epoch=tr_steps,\n epochs=EPOCHS,\n callbacks=CALLBACKS,\n validation_data=valid_data,\n validation_steps=val_steps,\n verbose=1,)\n \n\n# plot testing result\nmodel.load_weights(os.path.join(OUTPUT_DIR,'mosnet.h5'),) # Load the best model \n\nprint('testing...')\nMOS_Predict=np.zeros([len(test_list),])\nMOS_true =np.zeros([len(test_list),])\ndf = pd.DataFrame(columns=['audio', 'true_mos', 'predict_mos', 'system_ID','speaker_ID'])\n\nfor i in tqdm(range(len(test_list))):\n\n if args.data == \"VC\":\n filepath=test_list[i].split(',')\n filename=filepath[0].split('.')[0]\n sysid = \"\"\n speakerid = \"\"\n mos=float(filepath[1])\n elif args.data == \"LA\":\n filepath=test_list[i].split(',')\n filename=filepath[2].split('.')[0]\n sysid = filepath[1]\n speakerid = filepath[0]\n mos=float(filepath[3])\n \n _feat = utils.read(os.path.join(BIN_DIR,filename+'.h5'))\n # this line is quite a bit redundant - just don't return a dictionary here.. \n _mag = _feat['mag_sgram'] \n \n \n [Average_score, Frame_score]=model.predict(_mag, verbose=0, batch_size=1)\n MOS_Predict[i]=Average_score\n MOS_true[i] =mos\n df = df.append({'audio': filepath[0], \n 'true_mos': MOS_true[i], \n 'predict_mos': MOS_Predict[i], \n 'system_ID': sysid, \n 'speaker_ID': speakerid}, \n ignore_index=True)\n \ndf.to_pickle(results_file)\n \n\nplt.style.use('seaborn-deep')\nx = df['true_mos']\ny = df['predict_mos']\nbins = np.linspace(1, 5, 40)\nplt.figure(2)\nplt.hist([x, y], bins, label=['true_mos', 'predict_mos'])\nplt.legend(loc='upper right')\nplt.xlabel('MOS')\nplt.ylabel('number') \nplt.show()\nplt.savefig('./'+OUTPUT_DIR+'/MOSNet_distribution.png', dpi=150)\n\nLCC=np.corrcoef(MOS_true, MOS_Predict)\nprint('[UTTERANCE] Linear correlation coefficient= %f' % LCC[0][1])\nSRCC=scipy.stats.spearmanr(MOS_true.T, MOS_Predict.T)\nprint('[UTTERANCE] Spearman rank correlation coefficient= %f' % SRCC[0]) \nMSE=np.mean((MOS_true-MOS_Predict)**2)\nprint('[UTTERANCE] Test error= %f' % MSE)\n \n\n\n# Plotting scatter plot\nM=np.max([np.max(MOS_Predict),5])\nplt.figure(3)\nplt.scatter(MOS_true, MOS_Predict, s =15, color='b', marker='o', edgecolors='b', alpha=.20)\nplt.xlim([0.5,M])\nplt.ylim([0.5,M])\nplt.xlabel('True MOS')\nplt.ylabel('Predicted MOS')\nplt.title('LCC= {:.4f}, SRCC= {:.4f}, MSE= {:.4f}'.format(LCC[0][1], SRCC[0], MSE))\nplt.show()\nplt.savefig('./'+OUTPUT_DIR+'/MOSNet_scatter_plot.png', dpi=150)\n\n\n\nif args.data == \"VC\":\n # load vcc2018_system\n sys_df = pd.read_csv(os.path.join(DATA_DIR,'vcc2018_system.csv'))\n df['system_ID'] = df['audio'].str.split('_').str[-1].str.split('.').str[0] + '_' + df['audio'].str.split('_').str[0]\nelif args.data == \"LA\":\n # load LA 2019 system\n sys_df = pd.read_csv(os.path.join(DATA_DIR,'LA_mos_system.csv'))\n \nsys_result_mean = df[['system_ID', 'predict_mos']].groupby(['system_ID']).mean()\nsys_mer_df = pd.merge(sys_result_mean, sys_df, on='system_ID') \nsys_true = sys_mer_df['mean']\nsys_predicted = sys_mer_df['predict_mos']\n\nprint(\"SYSTEM-LEVEL\")\nprint(sys_true)\nprint(sys_predicted)\nprint(sys_true.shape)\nprint(sys_predicted.shape)\n\nLCC=np.corrcoef(sys_true, sys_predicted)\nprint('[SYSTEM] Linear correlation coefficient= %f' % LCC[0][1])\nSRCC=scipy.stats.spearmanr(sys_true.T, sys_predicted.T)\nprint('[SYSTEM] Spearman rank correlation coefficient= %f' % SRCC[0])\nMSE=np.mean((sys_true-sys_predicted)**2)\nprint('[SYSTEM] Test error= %f' % MSE)\n\n\n# Plotting scatter plot\nM=np.max([np.max(sys_predicted),5])\n# m=np.max([np.min(sys_predicted)-1,0.5])\nplt.figure(4)\nplt.scatter(sys_true, sys_predicted, s =25, color='b', marker='o', edgecolors='b')\nplt.xlim([1,M])\nplt.ylim([1,M])\nplt.xlabel('True MOS')\nplt.ylabel('Predicted MOS')\nplt.title('LCC= {:.4f}, SRCC= {:.4f}, MSE= {:.4f}'.format(LCC[0][1], SRCC[0], MSE))\n\n# # add system id\n# for i in range(len(sys_mer_df)):\n# sys_ID = mer_df['system_ID'][i]\n# x = mer_df['mean'][i]\n# y = mer_df['predict_mos'][i]\n# plt.text(x-0.05, y+0.1, sys_ID, fontsize=8)\nplt.show()\nplt.savefig('./'+OUTPUT_DIR+'/MOSNet_system_scatter_plot.png', dpi=150)\n\n\n \nif args.data == \"LA\":\n spk_df = pd.read_csv(os.path.join(DATA_DIR,'LA_mos_speaker.csv'))\n spk_result_mean = df[['speaker_ID', 'predict_mos']].groupby(['speaker_ID']).mean()\n spk_mer_df = pd.merge(spk_result_mean, spk_df, on='speaker_ID') \n spk_true = spk_mer_df['mean']\n spk_predicted = spk_mer_df['predict_mos']\n\n\n print(\"SPEAKER-LEVEL\")\n print(spk_true)\n print(spk_predicted)\n print(spk_true.shape)\n print(spk_predicted.shape)\n\n \n LCC=np.corrcoef(spk_true, spk_predicted)\n print('[SPEAKER] Linear correlation coefficient= %f' % LCC[0][1])\n SRCC=scipy.stats.spearmanr(spk_true.T, spk_predicted.T)\n print('[SPEAKER] Spearman rank correlation coefficient= %f' % SRCC[0])\n MSE=np.mean((spk_true-spk_predicted)**2)\n print('[SPEAKER] Test error= %f' % MSE)\n\n\n \n # Plotting scatter plot\n M=np.max([np.max(spk_predicted),5])\n # m=np.max([np.min(spk_predicted)-1,0.5])\n plt.figure(4)\n plt.scatter(spk_true, spk_predicted, s =25, color='b', marker='o', edgecolors='b')\n plt.xlim([1,M])\n plt.ylim([1,M])\n plt.xlabel('True MOS')\n plt.ylabel('Predicted MOS')\n plt.title('LCC= {:.4f}, SRCC= {:.4f}, MSE= {:.4f}'.format(LCC[0][1], SRCC[0], MSE))\n\n # # add system id\n # for i in range(len(spk_mer_df)):\n # spk_ID = mer_df['speaker_ID'][i]\n # x = mer_df['mean'][i]\n # y = mer_df['predict_mos'][i]\n # plt.text(x-0.05, y+0.1, spk_ID, fontsize=8)\n plt.show()\n plt.savefig('./'+OUTPUT_DIR+'/MOSNet_speaker_scatter_plot.png', dpi=150)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"474174143","text":"import pytest\nimport os\nimport yaml\n\n\n@pytest.fixture\ndef swagger():\n dirname = os.path.dirname(__file__)\n filename = os.path.join(dirname, 'swagger/dr.yaml')\n\n with open(filename) as file:\n dr_swagger = yaml.load(file, Loader=yaml.FullLoader)\n\n # print(json.dumps(dr_swagger, indent=4))\n \n return dr_swagger","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"523872124","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 24 00:31:54 2020\n\n@author: kukurihime\n\"\"\"\nimport CRepetationalThread\nimport sys\nimport os\nimport time\nimport CTrainStatus\n\nclass CTrainCameraView(CRepetationalThread.CRepetationalThread):\n def __init__(self, ts, interval=0.5):\n super().__init__(interval)\n self.ts = ts\n self.update()\n \n def func(self):\n os.system('clear')\n self.update()\n print(self.apliInfo)\n print(self.separator)\n print(self.status)\n print(self.separator)\n print(self.commandView)\n print(self.command, '')\n \n def update(self):\n self.apliInfo = \"SystemStartTime:\\t\" + self.ts.getStartTime().strftime('%Y/%m/%d %H:%M:%S') +'\\n' \\\n + \"now:\\t\\t\\t\" + self.ts.getNow().strftime('%Y/%m/%d %H:%M:%S') + '\\n' \\\n + \"SystemMode:\" + self.ts.getSystemMode()\n \n self.separator = \"---------------------------------------------------\"\n self.status = \"MQTT Connected:\\t\" + str(self.ts.getMQTTConnected())+'\\n' \\\n + \"TrainSpeed:\\t\" + str(self.ts.getStatusAt(0)) + '\\n' \\\n + \"Command:\" + self.ts.getCommand() + \"\\tCommandID:\" + str(id(self.ts.getCommand()))\n \n self.commandView = \"q:quit\\n\" \\\n \"y:speedDown\\tu:speedup\"\n self.command =\"command:\"\n \n \nif __name__ == \"__main__\":\n tcv = CTrainCameraView(\"dummy\",0.5)\n tcv.start()\n time.sleep(5)\n tcv.join()\n \n \n ","sub_path":"CTrainCameraView.py","file_name":"CTrainCameraView.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"542985749","text":"\"\"\"\n创建线程示例 2\n\"\"\"\nfrom threading import Thread\nfrom time import sleep\n\n# 带有参数的线程函数\ndef func(sec,name):\n print(\"%s 线程开始执行\"%name)\n sleep(sec)\n print(\"%s 线程执行完喽\"%name)\n\n# 循环创建线程\nfor i in range(5):\n t = Thread(target=func,args=(2,),\n kwargs={\"name\":\"T-%d\"%i},\n daemon=True)\n t.start()","sub_path":"note/day14_all/day14/thread2.py","file_name":"thread2.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"587359861","text":"#\n# 给定一定数组和一个k 找到那个index 使得等于k的元素的个数等于右边不等于k的个数 index算在左边\n# 比如[ 1, 2,1, 4,5, 1], 1\n# 返回结果index 就是3,因为左边[1,2,1] 里面有2个1, 右边[4,5,1]里面有两个不等于1\n\n\n# 暴力解法就是扫描数组,对每一个点判断是否符合规则O(n^2)\n\n\n# time: O(n)\n# 先扫面数组,计算x的个数\n# 然后再扫描数组,对每一个点判断是否符合规则,但是这个只需要O(1)\nclass Solution:\n def findPartitonIndex(self, nums, x):\n count = 0\n for num in nums:\n if num == x:\n count += 1\n\n xLeft = 0\n xRight = count\n for i in range(len(nums)):\n # check if this index valid\n countRight = len(nums) - i # count how many numbers on the right part\n if xLeft == countRight - xRight:\n return i\n\n # update xLeft, xRight\n if nums[i] == x:\n xLeft += 1\n xRight -= 1\n\n return -1\n\n# follow up, 这样的index是否唯一\n# 如果我们能让index左移或者右移一位后,leftcount和rightcount同增同减或不变,就可以\n# 对于这个问题,答案是index唯一\n\nres = Solution().findPartitonIndex([1,2,1,4,5,1], 1)\nprint(res) # 3\n\nres = Solution().findPartitonIndex([1,1,1,2,2,2], 1)\nprint(res) # 3\n\nres = Solution().findPartitonIndex([1,1,2,1,2,2], 1)\nprint(res) # 3\n\n\n\n","sub_path":"pocket gems/数组/找到index平分array.py","file_name":"找到index平分array.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"626000360","text":"\"\"\"\nAuteur: Jean-Philippe Langelier \nÉtudiant à la maitrise \nUniversité Laval\n\"\"\"\n# Import module\nimport numpy as np\nimport pandas as pd\nimport clr, os, sys\nimport time\nfrom win32com.client import CastTo, constants\nimport matplotlib.pyplot as plt\nimport csv\nimport scipy.constants, scipy.optimize\n\n#Import other files\npathRaytraceDLL = 'C:\\Zemax Files\\ZOS-API\\Libraries\\Raytrace.DLL'\nsys.path.insert(1,os.path.dirname(os.path.realpath(pathRaytraceDLL)))\nimport PythonNET_ZRDLoaderFull as init_Zemax\nimport Vol_Raytrace\nimport matplotlib\nimport math\nimport random\nimport concurrent.futures\nimport tartes\n\nclass simulation:\n #Constants\n Usepol = True\n pice = 917\n NumModels = 1\n XY_half_width = 0.5\n Depth = 1.0\n max_segments = 4000\n posz_source = -0.0005\n NumArrayX = 3\n NumArrayY = 3\n NumArrayZ = 10\n \n path = os.path.join(os.sep, os.path.dirname(os.path.realpath(__file__)), '')\n \n def __init__(self,name,radius,delta,numrays,numrays_stereo,wlum,pol,Random_pol=False,diffuse_light=False):\n '''\n \\r name = Nom donné à la simulation \\r\n radius = Rayon des sphères \\r\n Delta = Distances entre les centres des sphères \\r\n Numrays = Nombre de rayons pour la simulation pour g et B (list array)\\r\n numrays_stereo = Nombre de rayons pour la simulation SSA et B (list array)\\r\n wlum = Nombre de rayons pour chaqune des simulations (list array)\\r\n pol = Polarization entrante pour chaqune des simulations (jx,jy,px,py)\n '''\n self.name = name\n self.radius = np.array(radius)\n self.source_radius = self.radius*10\n self.num_spheres = len(radius)\n self.numrays = numrays\n self.DeltaX = delta\n self.DeltaY = self.DeltaX\n self.DeltaZ = self.DeltaY\n self.numrays_stereo = numrays_stereo\n self.wlum = wlum\n self.jx,self.jy,self.phase_x,self.phase_y = np.array(pol)\n self.dist_min_spheres = delta/np.sqrt(2)\n self.pathZMX = os.path.join(self.path,'Simulations', self.name)\n self.Random_pol = Random_pol\n self.Depth = self.calculate_depth_guess()\n self.XY_half_width = self.Depth/2\n self.diffuse_light = diffuse_light\n self.ice_index,self.ice_complex = tartes.refice2016(self.wlum*1E-6)\n \n if self.diffuse_light == True:\n self.tartes_dir_frac = 0\n self.diffuse_str = 'diffuse'\n self.cosine = 1.0\n else:\n self.tartes_dir_frac = 1\n self.diffuse_str = 'not_diffuse'\n self.cosine = 100.0\n \n self.name_ZRD = '_'.join([name,str(radius),str(delta),str(pol),str(self.numrays),self.diffuse_str])+ \".ZRD\"\n self.name_stereo_ZRD = '_'.join([name,'stereo',str(radius),str(delta),str(self.numrays_stereo),self.diffuse_str])+ \".ZRD\"\n \n self.path_stereo_npy = os.path.join(self.pathZMX,'_'.join([name,'stereo',str(radius),str(delta),str(self.numrays_stereo),self.diffuse_str])+ \".npy\")\n self.path_npy = os.path.join(self.pathZMX,'_'.join([name,str(radius),str(delta),str(pol),str(self.numrays),self.diffuse_str])+ \".npy\")\n self.path_stereo_ZRD = os.path.join(self.pathZMX, self.name_stereo_ZRD)\n self.path_ZRD = os.path.join(self.pathZMX,self.name_ZRD)\n \n #Writing in the text file properties\n self.write_in_txt()\n self.write_in_txt(\"======================================================\")\n self.write_in_txt('Simulation :', name)\n self.write_in_txt('Radius :', radius)\n self.write_in_txt('Delta :', delta)\n self.write_in_txt('Numrays :', numrays)\n self.write_in_txt('Wavelength :', wlum)\n self.write_in_txt('Polarization :', pol)\n\n t = time.localtime()\n self.date = str(t.tm_year)+\"/\"+str(t.tm_mon)+\"/\"+str(t.tm_mday)\n self.ctime = str(t.tm_hour)+\":\"+str(t.tm_min)+\":\"+str(t.tm_sec)\n print('Date : ',self.date,', Time : ',self.ctime)\n self.write_in_txt('Time started', self.date + \" \" + self.ctime)\n self.write_in_txt()\n\n def create_folder(self):\n if not os.path.exists(self.pathZMX):\n os.makedirs(self.pathZMX)\n print(\"Le répertoire \" + str(self.name) + \" a été créé\")\n else:\n print(\"Le répertoire \" + str(self.name) + \" existe déjà\")\n \n def delete_null(self):\n self.list_null = []\n for i in range(1,self.TheNCE.NumberOfObjects+1):\n Object = self.TheNCE.GetObjectAt(i)\n ObjectType = Object.TypeName\n if ObjectType == 'Null Object':\n self.TheNCE.RemoveObjectAt(i)\n\n def find_ice_object(self):\n ice_obj = np.where(self.array_objects() == np.array(['MY_ICE.ZTG']))[0] + 1\n return ice_obj\n\n def find_source_object(self):\n Source_obj = np.where(self.array_objects() == np.array(['Source Ellipse']))[0] + 1\n return Source_obj\n \n def find_detector_object(self):\n Detector_obj = np.where(self.array_objects() == np.array(['Detector Rectangle']))[0] + 1\n return Detector_obj\n \n def array_objects(self):\n list_obj=[]\n for i in range(1,self.TheNCE.NumberOfObjects+1):\n Object = self.TheNCE.GetObjectAt(i)\n ObjectType = Object.TypeName\n ObjectMaterial = Object.Material \n list_obj += [[ObjectType,ObjectMaterial]]\n array_obj = np.array(list_obj)\n return array_obj\n \n def filter_ice_air(self,df):\n Sphere_ice_obj = self.find_ice_object()\n filt_inter_ice = (df['hitObj'] == Sphere_ice_obj[0]) & (df['insideOf'] == 0)\n filt_ice = (df['insideOf'] == Sphere_ice_obj[0])\n filt_air = (df['insideOf'] == 0) & (df['segmentLevel'] != 0)\n return filt_ice, filt_air, filt_inter_ice\n \n def Create_filter_raytracing(self):\n # #Create filter that only consider rays touching spheres\n # list_ice_filter = []\n # Sphere_ice_obj = self.find_ice_object()\n # detector_obj = np.where(self.array_objects() == np.array(['Detector Rectangle']))[0]+ 1\n # for i in Sphere_ice_obj:\n # list_ice_filter += [\"H\"+str(i)]\n self.filter_raytracing = \"\"#\"Z|((\"+\"|\".join(list_ice_filter)+\")&(\" + \"L\"+str(detector_obj[0]) + \"|\" + \"L\"+str(detector_obj[1]) + \"))\"\n \n def calculate_depth_guess(self):\n #Guess Ke so it can calculate depth required\n #Preselected depth\n depth = np.arange(0.00, self.Depth, 0.0001) # from 0 to 1m depth every 0.1mm\n wl = np.array([self.wlum*1E-06]) # in m\n \n #Calculate pre-theorical SSA, density, g and B\n #Density\n if np.sqrt(2)*self.radius[0] > self.DeltaX/2:\n DensityRatio=0\n else:\n volsphere=4*np.pi*self.radius[0]**3/3\n volcube=self.DeltaX*self.DeltaY*self.DeltaZ\n DensityRatio = volsphere*4/volcube\n density = DensityRatio*self.pice\n #B\n B=1.25\n #g\n g=0.89\n #SSA\n vol_sphere = 4*np.pi*self.radius[0]**3/3\n air_sphere = 4*np.pi*self.radius[0]**2\n SSA = air_sphere/(vol_sphere*self.pice)\n \n #Calculate ke with a fit on intensity curve of TARTES datas\n def linear_fit(depth,a,b):\n intensity = a*depth+b\n return intensity\n \n def ke_raytracing(depths_fit,intensity):\n [a,b],pcov=scipy.optimize.curve_fit(lambda x,a,b: a*x+b, depths_fit, np.log(intensity))\n I_rt_fit=a*depths_fit+b\n return depths_fit, I_rt_fit, -a\n \n down_irr_profile, up_irr_profile = tartes.irradiance_profiles(\n wl,depth,SSA,density,g0=g,B0=B,dir_frac=1,totflux=1)\n \n depths_fit, I_rt_fit, ke_guess = ke_raytracing(depth, down_irr_profile+up_irr_profile)\n ke_guess = ke_guess\n \n #To imitate semi-infinite we must lost at max 0.1% on the z axis in transmitance\n intensity_max = 0.01\n Init_intensity = 1\n depth_min = -np.log(intensity_max/Init_intensity)/ke_guess\n return depth_min\n \n def Initialize_Zemax(self):\n self.zosapi = init_Zemax.PythonStandaloneApplication()\n self.BatchRayTrace = self.zosapi.BatchRayTrace \n self.TheSystem = self.zosapi.TheSystem\n self.TheApplication = self.zosapi.TheApplication\n self.TheNCE = self.TheSystem.NCE\n \n self.ZOSAPI = self.zosapi.ZOSAPI\n self.ZOSAPI_NCE = self.ZOSAPI.Editors.NCE\n \n #Create File for non-sticky (ns)\n self.fileZMX = os.path.join(self.pathZMX, 'Vol_ns_' + str(self.radius) + '.zmx')\n \n def create_ZMX(self):\n self.TheSystem.New(False)\n self.TheSystem.SaveAs(self.fileZMX)\n self.TheSystem.MakeNonSequential()\n self.TheSystem.SystemData.Units.LensUnits = self.ZOSAPI.SystemData.ZemaxSystemUnits.Meters\n #Wavelength is changed in the function Shoot in Vol_Raytrace.py\n self.TheSystem.SystemData.Wavelengths.GetWavelength(1).Wavelength = self.wlum\n self.TheSystem.SystemData.NonSequentialData.MaximumIntersectionsPerRay = self.max_segments\n self.TheSystem.SystemData.NonSequentialData.MinimumRayIntensity = 1E-6\n self.TheSystem.SystemData.NonSequentialData.MaximumSegmentsPerRay = self.max_segments\n self.TheSystem.SystemData.NonSequentialData.MaximumNestedTouchingObjects = 8\n self.TheSystem.SystemData.NonSequentialData.SimpleRaySplitting = True\n self.TheSystem.SystemData.NonSequentialData.MaximumSourceFileRaysInMemory = 10000000\n self.TheSystem.SystemData.NonSequentialData.GlueDistanceInLensUnits = 1.0000E-10\n self.TheSystem.SaveAs(self.fileZMX)\n print('Fichier Créer')\n \n def Load_File(self):\n start = time.time()\n self.TheSystem.LoadFile(self.fileZMX,False)\n self.TheNCE = self.TheSystem.NCE\n \n #Change wl in um\n self.TheSystem.SystemData.Wavelengths.GetWavelength(1).Wavelength = self.wlum\n \n #Change Polarization\n Source_obj = self.find_source_object()[0]\n Source = self.TheNCE.GetObjectAt(Source_obj)\n Source.SourcesData.RandomPolarization = self.Random_pol\n Source.SourcesData.Jx = self.jx\n Source.SourcesData.Jy = self.jy\n Source.SourcesData.XPhase = self.phase_x\n Source.SourcesData.YPhase = self.phase_y\n Source = self.TheNCE.GetObjectAt(1)\n\n self.TheSystem.SaveAs(self.fileZMX)\n end = time.time()\n print('Fichier loader en ',end-start)\n self.write_in_txt('File Loaded')\n self.write_in_txt('')\n \n def create_source(self):\n #Créer la source avec un rectangle et 2 sphères\n self.TheNCE.InsertNewObjectAt(1)\n \n Source = self.TheNCE.GetObjectAt(1)\n \n # Type_Source = Source.GetObjectTypeSettings(self.ZOSAPI_NCE.ObjectType.SourceEllipse)\n # Source.ChangeType(Type_Source)\n Type_Source = Source.GetObjectTypeSettings(self.ZOSAPI_NCE.ObjectType.SourceEllipse)\n Source.ChangeType(Type_Source)\n \n Source.XPosition = self.XY_half_width\n Source.YPosition = self.XY_half_width\n Source.ZPosition = self.posz_source\n Source.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par1).IntegerValue = 100 #Layout Rays\n Source.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par6).DoubleValue = self.source_radius #X Half width\n Source.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par7).DoubleValue = self.source_radius #Y Half width\n Source.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par9).DoubleValue = self.cosine #cosine\n\n Source.SourcesData.RandomPolarization = self.Random_pol\n Source.SourcesData.Jx = self.jx\n Source.SourcesData.Jy = self.jy\n Source.SourcesData.XPhase = self.phase_x\n Source.SourcesData.YPhase = self.phase_y\n \n self.delete_null()\n self.TheSystem.SaveAs(self.fileZMX)\n pass\n \n def create_detectors(self):\n #Créer le détecteur pour la tansmission\n self.TheNCE.InsertNewObjectAt(1)\n Object = self.TheNCE.GetObjectAt(1)\n Type = Object.GetObjectTypeSettings(self.ZOSAPI_NCE.ObjectType.DetectorRectangle)\n Object.ChangeType(Type)\n Object.Material = 'ABSORB'\n \n Object.XPosition = self.XY_half_width\n Object.YPosition = self.XY_half_width\n #Derrière le dernier grains de neige\n depth_z = self.DeltaZ*self.NumArrayZ*math.ceil(self.Depth/(self.DeltaZ*self.NumArrayZ))-self.radius\n Object.ZPosition = depth_z\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par1).DoubleValue = self.XY_half_width\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par2).DoubleValue = self.XY_half_width\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par3).IntegerValue = 1\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par4).IntegerValue = 1\n \n #Créer le détecteur pour la réflexion\n self.TheNCE.InsertNewObjectAt(1)\n Object = self.TheNCE.GetObjectAt(1)\n Type = Object.GetObjectTypeSettings(self.ZOSAPI_NCE.ObjectType.DetectorRectangle)\n Object.ChangeType(Type)\n Object.Material = 'ABSORB'\n \n Object.XPosition = self.XY_half_width\n Object.YPosition = self.XY_half_width\n Object.ZPosition = -0.0006\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par1).DoubleValue = self.XY_half_width\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par2).DoubleValue = self.XY_half_width\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par3).IntegerValue = 1\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par4).IntegerValue = 1\n \n self.delete_null()\n self.TheSystem.SaveAs(self.fileZMX)\n pass\n \n def create_model_sphere(self):\n #Créer la forme\n sphere_ZPosition = -0.001\n sphere_XPosition = 0\n \n self.TheNCE.InsertNewObjectAt(1)\n Object = self.TheNCE.GetObjectAt(1)\n Type = Object.GetObjectTypeSettings(self.ZOSAPI_NCE.ObjectType.Sphere)\n Object.ChangeType(Type)\n Object.Material = 'MY_ICE.ZTG'\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par1).DoubleValue = self.radius\n Object.XPosition = sphere_XPosition\n Object.YPosition = 0\n Object.ZPosition = sphere_ZPosition\n Object.DrawData.DoNotDrawObject = True\n Object.TypeData.RaysIgnoreObject = self.ZOSAPI_NCE.RaysIgnoreObjectType.Always\n \n self.delete_null()\n self.TheSystem.SaveAs(self.fileZMX)\n pass\n \n def get_arrays_info(self):\n #Space between each element of the same Array\n DeltaArrayX=self.DeltaX*self.NumArrayX\n DeltaArrayY=self.DeltaY*self.NumArrayY\n DeltaArrayZ=self.DeltaZ*self.NumArrayZ\n DeltaArray = np.array([DeltaArrayX,DeltaArrayY,DeltaArrayZ])\n \n #Number of Object of the same Array\n NumObjectPerArrayX = math.ceil(2*self.XY_half_width/(DeltaArrayX))\n NumObjectPerArrayY = math.ceil(2*self.XY_half_width/(DeltaArrayY))\n NumObjectPerArrayZ = math.ceil(self.Depth/(DeltaArrayZ))\n # NumObjectPerArrayX = 1\n # NumObjectPerArrayY = 1\n # NumObjectPerArrayZ = 1\n NumObjectPerArray = np.array([NumObjectPerArrayX,NumObjectPerArrayY,NumObjectPerArrayZ])\n \n #For cross arrays\n #First coordinate for the first element of the Array\n PosArrayX = np.linspace(0,DeltaArrayX,self.NumArrayX+1)[:-1] #+ Random_x\n PosArrayY = np.linspace(0,DeltaArrayY,self.NumArrayY+1)[:-1] #+ Random_y\n PosArrayZ = np.linspace(0,DeltaArrayZ,self.NumArrayZ+1)[:-1]\n #Cross in plane zx\n PosArrayX_xz = np.linspace(0,DeltaArrayX,self.NumArrayX+1)[:-1] + self.DeltaX/2 #+ Random_x\n PosArrayY_xz = np.linspace(0,DeltaArrayY,self.NumArrayY+1)[:-1] #+ Random_y\n PosArrayZ_xz = np.linspace(0,DeltaArrayZ,self.NumArrayZ+1)[:-1] + self.DeltaZ/2\n #Cross in plane zy\n PosArrayX_xy = np.linspace(0,DeltaArrayX,self.NumArrayX+1)[:-1] + self.DeltaX/2 #+ Random_x\n PosArrayY_xy = np.linspace(0,DeltaArrayY,self.NumArrayY+1)[:-1] + self.DeltaZ/2 # + Random_y\n PosArrayZ_xy = np.linspace(0,DeltaArrayZ,self.NumArrayZ+1)[:-1]\n #Cross in plane zx and zy\n PosArrayX_yz = np.linspace(0,DeltaArrayX,self.NumArrayX+1)[:-1] #+ Random_x\n PosArrayY_yz = np.linspace(0,DeltaArrayY,self.NumArrayY+1)[:-1] + self.DeltaZ/2 #+ Random_y\n PosArrayZ_yz = np.linspace(0,DeltaArrayZ,self.NumArrayZ+1)[:-1] + self.DeltaZ/2\n \n Positions = np.array([[PosArrayX,PosArrayY,PosArrayZ],\n [PosArrayX_xz,PosArrayY_xz,PosArrayZ_xz],\n [PosArrayX_yz,PosArrayY_yz,PosArrayZ_yz],\n [PosArrayX_xy,PosArrayY_xy,PosArrayZ_xy]],dtype=object)\n \n #Randomize Positions\n Array_positions = self.randomize_positions(Positions,DeltaArray)\n \n #No Randomize\n # pos = np.array(np.meshgrid(PosArrayX,PosArrayY,PosArrayZ))\n # pos_xy = np.array(np.meshgrid(PosArrayX_xy,PosArrayY_xy,PosArrayZ_xy))\n # pos_xz = np.array(np.meshgrid(PosArrayX_xz,PosArrayY_xz,PosArrayZ_xz))\n # pos_yz = np.array(np.meshgrid(PosArrayX_yz,PosArrayY_yz,PosArrayZ_yz))\n # Array_positions = np.transpose(np.concatenate((pos,pos_xy,pos_xz,pos_yz),axis=1)).reshape(4*self.NumArrayY*self.NumArrayX*self.NumArrayZ,3)\n \n return Array_positions, NumObjectPerArray, DeltaArray\n \n def randomize_positions(self,Positions,DeltaArray):\n \n def Randomize(pos,pos_xy,pos_xz,pos_yz,filt,filt_xy,filt_xz,filt_yz):\n factor = (self.DeltaX/(2*np.sqrt(2))-self.radius)*2\n #Used DeltaX because DeltaX=DeltaY=DeltaZ\n pos_t = pos+filt*((np.random.rand(3,self.NumArrayY,self.NumArrayX,self.NumArrayZ)*factor)-factor/2)\n pos_xy_t = pos_xy+filt_xy*((np.random.rand(3,self.NumArrayY,self.NumArrayX,self.NumArrayZ)*factor)-factor/2)\n pos_xz_t = pos_xz+filt_xz*((np.random.rand(3,self.NumArrayY,self.NumArrayX,self.NumArrayZ)*factor)-factor/2)\n pos_yz_t = pos_yz+filt_yz*((np.random.rand(3,self.NumArrayY,self.NumArrayX,self.NumArrayZ)*factor)-factor/2)\n \n return pos_t,pos_xy_t,pos_xz_t,pos_yz_t\n \n def norm(pos1,pos2):\n posx1,posy1,posz1 = pos1\n posx2,posy2,posz2 = pos2\n norm = np.linalg.norm([posx1-posx2,posy1-posy2,posz1-posz2],axis=0)\n return norm\n \n def create_compare_array(pos,DeltaArray):\n posx,posy,posz = pos\n DeltaArrayX,DeltaArrayY,DeltaArrayZ = DeltaArray\n \n #Add line to posx in x axis\n posx_add_l = np.full((self.NumArrayY,self.NumArrayZ),posx[0,-1,0]-DeltaArrayX).reshape(self.NumArrayY,1,self.NumArrayZ)\n posx_add_r = np.full((self.NumArrayY,self.NumArrayZ),posx[0,0,0]+DeltaArrayX).reshape(self.NumArrayY,1,self.NumArrayZ)\n posx_c = np.append(posx_add_l,posx,axis=1)\n posx_c = np.append(posx_c,posx_add_r,axis=1)\n \n #Add line to posy in y axis\n posy_add_l = np.full((self.NumArrayX,self.NumArrayZ),posy[-1,0,0]-DeltaArrayY).reshape(1,self.NumArrayX,self.NumArrayZ)\n posy_add_r = np.full((self.NumArrayX,self.NumArrayZ),posy[0,0,0]+DeltaArrayY).reshape(1,self.NumArrayX,self.NumArrayZ)\n posy_c = np.append(posy_add_l,posy,axis=0)\n posy_c = np.append(posy_c,posy_add_r,axis=0)\n \n #Add line to posz in z axis\n posz_add_l = np.full((self.NumArrayX,self.NumArrayY),posz[0,0,-1]-DeltaArrayZ).reshape(self.NumArrayY,self.NumArrayX,1)\n posz_add_r = np.full((self.NumArrayX,self.NumArrayY),posz[0,0,0]+DeltaArrayZ).reshape(self.NumArrayY,self.NumArrayX,1)\n posz_c = np.append(posz_add_l,posz,axis=2)\n posz_c = np.append(posz_c,posz_add_r,axis=2)\n\n return posx_c,posy_c,posz_c\n \n def calculate_norm(pos1,pos_xy,pos_xz,pos_yz):\n #Function that calculate the norm with the pos1 vs pos xy,xz,yz\n #_ij indices indicate in which direction the shift will be\n #Shift Always occur in other plan than the plane of the two comparing spheres\n posx,posy,posz = pos1\n posx_xy,posy_xy,posz_xy = pos_xy\n posx_xz,posy_xz,posz_xz = pos_xz\n posx_yz,posy_yz,posz_yz = pos_yz\n\n #======Compare======\n #18 comparisons for normal array\n n = []\n #Creation of the compare_array\n posx_c,posy_c, posz_c = create_compare_array([posx,posy,posz],DeltaArray)\n #+y\n n += [norm([posx,posy,posz],[posx_c[:,2:,:],posy,posz])]\n #-y\n n += [norm([posx,posy,posz],[posx_c[:,:-2,:],posy,posz])]\n #+y\n n += [norm([posx,posy,posz],[posx,posy_c[2:,:,:],posz])]\n #-y\n n += [norm([posx,posy,posz],[posx,posy_c[:-2,:,:],posz])]\n #+z\n n += [norm([posx,posy,posz],[posx,posy,posz_c[:,:,:-2]])]\n #-z\n n += [norm([posx,posy,posz],[posx,posy,posz_c[:,:,2:]])]\n \n #====plan_xy=====\n posx_xy_c,posy_xy_c, posz_xy_c = create_compare_array([posx_xy,posy_xy,posz_xy],DeltaArray)\n if np.mean(posx) < np.mean(posx_xy): posx_xy_c = posx_xy_c[:,:-2,:]\n else: posx_xy_c = posx_xy_c[:,2:,:]\n if np.mean(posy) < np.mean(posy_xy): posy_xy_c = posy_xy_c[:-2,:,:]\n else: posy_xy_c = posy_xy_c[2:,:,:]\n \n #+x+y\n n += [norm([posx,posy,posz],[posx_xy,posy_xy,posz_xy])]\n #+x-y\n n += [norm([posx,posy,posz],[posx_xy,posy_xy_c,posz_xy])]\n #-x+y\n n += [norm([posx,posy,posz],[posx_xy_c,posy_xy,posz_xy])]\n #-x-y\n n += [norm([posx,posy,posz],[posx_xy_c,posy_xy_c,posz_xy])]\n \n #====plan_xz=====\n posx_xz_c,posy_xz_c, posz_xz_c = create_compare_array([posx_xz,posy_xz,posz_xz],DeltaArray)\n if np.mean(posx) < np.mean(posx_xz): posx_xz_c = posx_xz_c[:,:-2,:]\n else: posx_xz_c = posx_xz_c[:,2:,:]\n if np.mean(posz) < np.mean(posz_xz): posz_xz_c = posz_xz_c[:,:,:-2]\n else: posz_xz_c = posz_xz_c[:,:,2:]\n #+x+z\n n += [norm([posx,posy,posz],[posx_xz,posy_xz,posz_xz])]\n #+x-z\n n += [norm([posx,posy,posz],[posx_xz,posy_xz,posz_xz_c])]\n #-x+z\n n += [norm([posx,posy,posz],[posx_xz_c,posy_xz,posz_xz])]\n #-x-z\n n += [norm([posx,posy,posz],[posx_xz_c,posy_xz,posz_xz_c])]\n \n #====plan_yz=====\n posx_yz_c,posy_yz_c, posz_yz_c = create_compare_array([posx_yz,posy_yz,posz_yz],DeltaArray)\n if np.mean(posy) < np.mean(posy_yz): posy_yz_c = posy_yz_c[:-2,:,:]\n else: posy_yz_c = posy_yz_c[2:,:,:]\n if np.mean(posz) < np.mean(posz_yz): posz_yz_c = posz_yz_c[:,:,:-2]\n else: posz_yz_c = posz_yz_c[:,:,2:]\n #+y+z\n n += [norm([posx,posy,posz],[posx_yz,posy_yz,posz_yz])]\n #+y-z\n n += [norm([posx,posy,posz],[posx_yz,posy_yz,posz_yz_c])]\n #-y+z\n n += [norm([posx,posy,posz],[posx_yz,posy_yz_c,posz_yz])]\n #-y-z\n n += [norm([posx,posy,posz],[posx_yz,posy_yz_c,posz_yz_c])]\n\n return np.array(n)\n \n #Positions\n [[PosArrayX,PosArrayY,PosArrayZ],\n [PosArrayX_xz,PosArrayY_xz,PosArrayZ_xz],\n [PosArrayX_yz,PosArrayY_yz,PosArrayZ_yz],\n [PosArrayX_xy,PosArrayY_xy,PosArrayZ_xy]] = Positions\n \n #Initial positions\n pos_i = np.array(np.meshgrid(PosArrayX,PosArrayY,PosArrayZ))\n pos_xy_i = np.array(np.meshgrid(PosArrayX_xy,PosArrayY_xy,PosArrayZ_xy))\n pos_xz_i = np.array(np.meshgrid(PosArrayX_xz,PosArrayY_xz,PosArrayZ_xz))\n pos_yz_i = np.array(np.meshgrid(PosArrayX_yz,PosArrayY_yz,PosArrayZ_yz))\n filt_i=np.ones((3,self.NumArrayY,self.NumArrayX,self.NumArrayZ),dtype=bool)\n filt_xy_i=np.ones((3,self.NumArrayY,self.NumArrayX,self.NumArrayZ),dtype=bool)\n filt_xz_i=np.ones((3,self.NumArrayY,self.NumArrayX,self.NumArrayZ),dtype=bool)\n filt_yz_i=np.ones((3,self.NumArrayY,self.NumArrayX,self.NumArrayZ),dtype=bool)\n \n move = 10\n \n for move in range(1,move+1):\n if move == 1:\n #Position for the move\n pos_m,pos_xy_m,pos_xz_m,pos_yz_m = pos_i,pos_xy_i,pos_xz_i,pos_yz_i\n \n #Position trying to randomize\n pos,pos_xy,pos_xz,pos_yz = pos_m,pos_xy_m,pos_xz_m,pos_yz_m\n filt,filt_xy,filt_xz,filt_yz = filt_i,filt_xy_i,filt_xz_i,filt_yz_i \n \n #Checking if touches\n condition=False\n i=0\n j=0\n while condition != True:\n #Randomize position and associate it to a temporary variable\n pos_t,pos_xy_t,pos_xz_t,pos_yz_t = Randomize(pos, pos_xy, pos_xz, pos_yz, filt, filt_xy, filt_xz, filt_yz)\n # pos_t,pos_xy_t,pos_xz_t,pos_yz_t = pos,pos_xy,pos_xz,pos_yz\n \n #Calculate norm between each array\n norm_array = calculate_norm(pos_t,pos_xy_t,pos_xz_t,pos_yz_t)\n norm_array_xy = calculate_norm(pos_xy_t,pos_t,pos_yz_t,pos_xz_t)\n norm_array_xz = calculate_norm(pos_xz_t,pos_yz_t,pos_t,pos_xy_t)\n norm_array_yz = calculate_norm(pos_yz_t,pos_xz_t,pos_xy_t,pos_t)\n \n #Checking it touches and resize array\n filt_t = np.tile(np.any(norm_array < self.radius*2, axis=0),[3,1,1]).reshape(3,self.NumArrayY,self.NumArrayX,self.NumArrayZ)\n filt_xy_t = np.tile(np.any(norm_array_xy < self.radius*2, axis=0),[3,1,1]).reshape(3,self.NumArrayY,self.NumArrayX,self.NumArrayZ)\n filt_xz_t = np.tile(np.any(norm_array_xz < self.radius*2, axis=0),[3,1,1]).reshape(3,self.NumArrayY,self.NumArrayX,self.NumArrayZ)\n filt_yz_t = np.tile(np.any(norm_array_yz < self.radius*2, axis=0),[3,1,1]).reshape(3,self.NumArrayY,self.NumArrayX,self.NumArrayZ)\n \n #If it touches\n if filt_t.any()|filt_xy_t.any()|filt_xz_t.any()|filt_yz_t.any():\n #If array has improved\n count_t = sum(list(map(np.count_nonzero,(filt_t==True,filt_xy_t==True,filt_xz_t==True,filt_yz_t==True))))\n count = sum(list(map(np.count_nonzero,(filt==True,filt_xy==True,filt_xz==True,filt_yz==True))))\n if count_t=10: \n i=0\n j+=1\n pos,pos_xy,pos_xz,pos_yz = pos_m,pos_xy_m,pos_xz_m,pos_yz_m\n filt,filt_xy,filt_xz,filt_yz = filt_i,filt_xy_i,filt_xz_i,filt_yz_i\n if j>=25:\n print('Can\\'t randomize more, %d moves have been done' %move)\n # ax = plt.axes(projection='3d')\n # ax.scatter3D(pos_i[0],pos_i[1],pos_i[2], cmap='Greens')\n # ax.scatter3D(pos_xy_i[0],pos_xy_i[1],pos_xy_i[2], cmap='Greens')\n # ax.scatter3D(pos_xz_i[0],pos_xz_i[1],pos_xz_i[2], cmap='Greens')\n # ax.scatter3D(pos_yz_i[0],pos_yz_i[1],pos_yz_i[2], cmap='Greens')\n positions = np.transpose(np.concatenate((pos,pos_xy,pos_xz,pos_yz),axis=1)).reshape(4*self.NumArrayY*self.NumArrayX*self.NumArrayZ,3)\n return positions\n # print(len(pos[filt]),len(pos_xy[filt_xy]),len(pos_xz[filt_xz]),len(pos_yz[filt_yz]))\n #If Ok\n else:\n # Associate temporary position to real position\n pos_m,pos_xy_m,pos_xz_m,pos_yz_m = pos_t,pos_xy_t,pos_xz_t,pos_yz_t\n condition = True\n pos_i,pos_xy_i,pos_xz_i,pos_yz_i = pos_m,pos_xy_m,pos_xz_m,pos_yz_m\n # ax = plt.axes(projection='3d')\n # ax.scatter3D(pos_i[0],pos_i[1],pos_i[2], cmap='Greens')\n # ax.scatter3D(pos_xy_i[0],pos_xy_i[1],pos_xy_i[2], cmap='Greens')\n # ax.scatter3D(pos_xz_i[0],pos_xz_i[1],pos_xz_i[2], cmap='Greens')\n # ax.scatter3D(pos_yz_i[0],pos_yz_i[1],pos_yz_i[2], cmap='Greens')\n positions = np.transpose(np.concatenate((pos,pos_xy,pos_xz,pos_yz),axis=1)).reshape(4*self.NumArrayY*self.NumArrayX*self.NumArrayZ,3)\n return positions\n \n def create_snow(self):\n self.create_model_sphere()\n self.Array_positions, self.NumObjectPerArray,self.DeltaArray = self.get_arrays_info()\n self.create_array(self.Array_positions[0],self.NumObjectPerArray,self.DeltaArray)\n self.create_array_copies()\n self.TheSystem.SaveAs(self.fileZMX)\n \n def create_array(self,Pos,Num,Delta):\n #Add object + make it an array\n self.TheNCE.InsertNewObjectAt(2)\n Object = self.TheNCE.GetObjectAt(2)\n Type = Object.GetObjectTypeSettings(self.ZOSAPI_NCE.ObjectType.Array)\n Object.ChangeType(Type)\n \n #Positions\n Object.XPosition = Pos[0]\n Object.YPosition = Pos[1]\n Object.ZPosition = Pos[2]\n \n # parentObject = self.find_ice_object()[0]\n #Parent Object\n # Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par1).IntegerValue = parentObject\n #Number Object in X direction\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par2).IntegerValue = Num[0]\n #Number Object in Y direction\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par3).IntegerValue = Num[1]\n #Number Object in Z direction\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par4).IntegerValue = Num[2]\n #Delta between Object in X direction\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par5).DoubleValue = Delta[0]\n #Delta between Object in Y direction\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par6).DoubleValue = Delta[1]\n #Delta between Object in Z direction\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par7).DoubleValue = Delta[2]\n self.TheSystem.SaveAs(self.fileZMX)\n pass\n \n def create_array_copies(self):\n def change_parent_obj(i,obj):\n Object = self.TheNCE.GetObjectAt(i+2)\n Object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par1).IntegerValue = obj\n \n #Create a copie of the Array and change is position\n start = time.time()\n num_copies = len(self.Array_positions)\n for i in range(0,num_copies):\n self.TheNCE.CopyObjects(2,1,2)\n Object = self.TheNCE.GetObjectAt(3)\n Object.XPosition = self.Array_positions[i][0]\n Object.YPosition = self.Array_positions[i][1]\n Object.ZPosition = self.Array_positions[i][2]\n end = time.time()\n print(end-start)\n \n #Change the parent of the arrays using threading\n ice_obj = self.find_ice_object()[0]\n with concurrent.futures.ThreadPoolExecutor() as executor:\n for i in range(0,num_copies+1):\n executor.submit(change_parent_obj,i,ice_obj)\n\n end = time.time()\n print(end-start)\n \n #Remove initial array so it is not doubled\n self.TheNCE.RemoveObjectAt(2)\n \n def shoot_rays(self):\n self.Create_filter_raytracing()\n \n Source_obj = self.find_source_object()[0]\n Source_object = self.TheNCE.GetObjectAt(Source_obj)\n Source_object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par9).DoubleValue = self.cosine\n \n print('Raytrace')\n Vol_Raytrace.Shoot(self,self.filter_raytracing,self.numrays,self.path_npy,self.name_ZRD)\n pass\n \n def shoot_rays_stereo(self):\n #Créer un filtre pour la glace\n self.Create_filter_raytracing()\n \n #Change les grains de neige en air (pour que les rayons n'intéragissent pas)\n Sphere_ice_obj = self.find_ice_object()\n for i in Sphere_ice_obj:\n Object = self.TheNCE.GetObjectAt(i)\n Object.Material = ''\n \n self.TheSystem.SaveAs(self.fileZMX)\n \n #Change cosine object for stereo\n Source_obj = self.find_source_object()[0]\n Source_object = self.TheNCE.GetObjectAt(Source_obj)\n cosine = 0.0\n Source_object.GetObjectCell(self.ZOSAPI_NCE.ObjectColumn.Par9).DoubleValue = cosine\n \n #Calcul la stéréologie et retourne un fichier npy\n print('SSA Raytrace')\n Vol_Raytrace.Shoot(self,self.filter_raytracing,self.numrays_stereo,self.path_stereo_npy,self.name_stereo_ZRD)\n \n #Rechange les grains d'air en neige\n for i in Sphere_ice_obj:\n Object = self.TheNCE.GetObjectAt(i)\n Object.Material = 'MY_ICE.ZTG'\n \n self.TheSystem.SaveAs(self.fileZMX)\n \n def Load_npyfile(self):\n # Try loading the stereo file\n try: \n self.df_stereo = Vol_Raytrace.Load_npy(self.path_stereo_npy)\n except FileNotFoundError:\n print('The stereo npy file was not loaded')\n pass\n #Try loading the ray file\n try:\n #Filter les rayons avec plus de 4000 interactions\n self.df = Vol_Raytrace.Load_npy(self.path_npy)\n \n #Change intensity\n self.change_path_intensity()\n #Groupby for last segment of each ray\n df = self.df.groupby(self.df.index).agg({'hitObj':'last','segmentLevel':'last','intensity':'last'})\n #Transmitance\n filt_top_detector = df['hitObj'] == self.find_detector_object()[0]\n df_top = df[filt_top_detector]\n self.Reflectance = np.sum(df_top['intensity'])\n self.numrays_Reflectance = df_top.shape[0]\n #Reflectance\n filt_down_detector = df['hitObj'] == self.find_detector_object()[1]\n df_down = df[filt_down_detector]\n self.Transmitance = np.sum(df_down['intensity'])\n self.numrays_Transmitance = df_down.shape[0]\n #Error (max_segments)\n filt_error = df['segmentLevel'] == self.max_segments-1\n df_error = df[filt_error]\n self.Error = np.sum(df_error['intensity'])\n self.numrays_Error = df_error.shape[0]\n #Lost\n filt_Lost = (~filt_top_detector)&(~filt_down_detector)&(~filt_error)\n df_Lost = df[filt_Lost]\n self.Lost = np.sum(df_Lost['intensity'])\n self.numrays_Lost = df_Lost.shape[0]\n #Absorb (considering total intensity is 1)\n self.Absorb = 1-self.Reflectance-self.Transmitance-self.Error-self.Lost\n self.numrays_Absorb = self.numrays-self.numrays_Reflectance-self.numrays_Transmitance-self.numrays_Error-self.numrays_Lost\n except FileNotFoundError:\n print('The raytrace npy file was not loaded')\n pass\n \n def change_path_intensity(self):\n #Calculate the intensity for each segments\n filt_ice, filt_air, filt_inter_ice = self.filter_ice_air(self.df)\n\n #Calculate new intensity\n self.gamma = 4*np.pi*self.ice_complex/(self.wlum*1E-6)\n I_0 = 1./self.numrays\n #Ponderate pathlength for ice only (absorbing media)\n self.df.insert(15,'ponderation',0)\n self.df.loc[(filt_ice,'ponderation')] = 1\n pond_pL = self.df['ponderation']*self.df['pathLength']\n \n #Overwrite the intensity\n pathLength = pond_pL.groupby(pond_pL.index).cumsum()\n intensity = I_0*np.exp(-self.gamma*pathLength).values\n self.df['intensity'] = intensity\n \n self.df.drop(columns = ['ponderation'])\n pass\n\n def calculate_SSA(self):\n #====================SSA stéréologie====================\n #Shoot rays for SSA\n if not hasattr(self, 'df_stereo'):\n self.Load_npyfile()\n\n #Length\n filt_ice, filt_air, filt_inter_ice = self.filter_ice_air(self.df_stereo)\n numrays = self.df_stereo.index[-1]\n l_Ice_stereo = np.sum(self.df_stereo.loc[filt_ice, 'pathLength'])/numrays\n #Inter Air/Icef\n Num_ice_inter = self.df_stereo[filt_inter_ice].shape[0]/numrays\n lengthIce_per_seg = l_Ice_stereo/Num_ice_inter\n self.SSA_stereo = round(4/(self.pice*lengthIce_per_seg),6)\n self.write_in_txt('SSA stéréologie :', self.SSA_stereo)\n \n #====================SSA théorique====================\n vol_sphere = 4*np.pi*self.radius[0]**3/3\n air_sphere = 4*np.pi*self.radius[0]**2\n self.SSA_theo = air_sphere/(vol_sphere*self.pice)\n self.write_in_txt('SSA théorique:', self.SSA_theo)\n \n def calculate_density(self):\n #====================Densité physique théorique====================\n if np.sqrt(2)*self.radius[0] > self.DeltaX/2:\n DensityRatio=0\n else:\n volsphere=4*np.pi*self.radius[0]**3/3\n volcube=self.DeltaX*self.DeltaY*self.DeltaZ\n DensityRatio = volsphere*4/volcube\n self.density_theo = DensityRatio*self.pice\n self.write_in_txt('Densité théorique :', self.density_theo)\n \n \n #====================Densité physique stéréologie====================\n #Shoot rays for SSA if not already done\n if not hasattr(self, 'df_stereo'):\n self.Load_npyfile()\n \n filt_ice, filt_air, filt_inter_ice = self.filter_ice_air(self.df_stereo)\n #Remove first and last segment\n lengthIce = float(np.sum(self.df_stereo.loc[filt_ice, 'pathLength']))\n #Remove extra air segment du to source not beeing at origin\n lengthAir = float(np.sum(self.df_stereo.loc[filt_air, 'pathLength']))-np.abs(self.posz_source*self.numrays_stereo)\n self.density_stereo = round(lengthIce/(lengthAir+lengthIce),6)*self.pice\n self.write_in_txt('Densité stéreologique :', self.density_stereo)\n \n def calculate_porosity(self):\n #====================Porosité physique théorique====================\n if not hasattr(self, 'density_theo'): self.calculate_density()\n if not hasattr(self, 'B_stereo'): self.calculate_B()\n \n porosity = 1-self.density_theo/self.pice\n self.physical_porosity_theo = porosity\n \n #====================Porosité optique théorique====================\n self.optical_porosity_theo = porosity/(porosity+self.B_stereo*(1-porosity))\n \n #====================Porosité physique stéréologique====================\n #Shoot rays for SSA if not already done\n if not hasattr(self, 'df_stereo'):\n self.Load_npyfile()\n \n filt_ice_stereo, filt_air_stereo, filt_inter_ice_stereo = self.filter_ice_air(self.df_stereo)\n lengthIce = float(np.sum(self.df_stereo.loc[filt_ice_stereo, 'pathLength']))\n lengthAir = float(np.sum(self.df_stereo.loc[filt_air_stereo, 'pathLength']))\n self.physical_porosity_stereo = round(lengthAir/(lengthAir+lengthIce),6)\n \n #====================Porosité optique stéréologique====================\n self.optical_porosity_stereo = round(lengthAir/(lengthAir+self.B_stereo*lengthIce),6)\n \n self.write_in_txt('Porosité Physique théorique :', self.physical_porosity_theo)\n self.write_in_txt('Porosité Physique stéréologique :', self.physical_porosity_stereo)\n self.write_in_txt('Porosité Optique théorique :', self.optical_porosity_theo)\n self.write_in_txt('Porosité Optique stéréologique :', self.optical_porosity_stereo)\n \n def calculate_neff(self):\n df_filt = self.df[~((self.df['segmentLevel'] == 0)|(self.df['segmentLevel'] == 1))]\n #Calculate v mean\n self.neff_rt = sum(df_filt['pathLength']*df_filt['index'])/sum(df_filt['pathLength'])\n \n #Calculate neff stereo\n if not hasattr(self, 'B_stereo'): self.calculate_B()\n porosity = self.physical_porosity_stereo\n filt_ice, filt_air, filt_inter_ice = self.filter_ice_air(df_filt)\n n_ice = np.mean(df_filt['index'].loc[filt_ice])\n self.neff_stereo = (porosity + n_ice*self.B_stereo*(1-porosity))/(porosity + self.B_stereo*(1-porosity))\n pass\n \n def calculate_MOPL(self):\n #Shoot rays for SSA\n if not hasattr(self, 'df_stereo'):\n self.Load_npyfile()\n \n #Theorique\n if not hasattr(self, 'musp_stereo'): self.calculate_musp()\n if not hasattr(self, 'mua_rt'): self.calculate_mua()\n if not hasattr(self, 'neff_rt'): self.calculate_neff()\n \n #Approximation de Paterson\n # z_o = self.musp_stereo**(-1)\n # D = (3*(self.mua_stereo+self.musp_stereo))**(-1)\n # self.MOPL_stereo = self.neff_stereo*z_o/(2*np.sqrt(self.mua_stereo*D))\n \n #Raytracing\n filt_top_detector = self.df['hitObj'] == self.find_detector_object()[0]\n df_top = self.df[filt_top_detector]\n df_filt = self.df.loc[df_top.index]\n \n df_filt.insert(15,'OPL',np.nan)\n df_filt['OPL'] = df_filt['pathLength']*df_filt['index']\n df_OPL = df_filt.groupby(df_filt.index).agg({'pathLength':sum, 'OPL':sum, 'intensity':'last'})\n self.MOPL_rt = np.average(df_OPL['OPL'],weights=df_OPL['intensity'])\n \n #Stéréologique\n filt_ice_rt, filt_air_rt, filt_inter_ice_rt = self.filter_ice_air(self.df)\n n_ice = np.mean(self.df[filt_ice_rt]['index'])\n df_filt = self.df[filt_air_rt].groupby(self.df[filt_air_rt].index).agg({'pathLength':sum,'intensity':'last'})\n l_air_mean = np.average(df_filt['pathLength'],weights=df_filt['intensity'])\n self.MOPL_stereo = (n_ice*l_air_mean)/self.optical_porosity_stereo-(n_ice-1)*l_air_mean\n \n self.write_in_txt('MOPL raytracing:', self.MOPL_rt)\n self.write_in_txt('MOPL stéréologique:', self.MOPL_stereo)\n \n def calculate_g_theo(self):\n self.g_theo = 0.89\n self.gG_theo = self.g_theo*2-1\n self.write_in_txt('g théorique', self.g_theo)\n self.write_in_txt('gG théorique', self.gG_theo)\n \n def calculate_g_rt(self):\n if not hasattr(self, 'ke_rt'): self.calculate_ke_rt()\n if not hasattr(self, 'alpha_rt'): self.calculate_alpha()\n \n #g calculé avec ke et alpha raytracing\n #Équation Quentin Libois 3.3 thèse\n self.g_rt = 1+8*self.ke_rt/(3*self.density_stereo*np.log(self.alpha_rt)*self.SSA_stereo)\n self.gG_rt = self.g_rt*2-1\n \n self.write_in_txt('g raytracing', self.g_rt)\n self.write_in_txt('gG raytracing', self.gG_rt)\n \n def calculate_mus(self):\n if not hasattr(self, 'density_theo'): self.calculate_density()\n if not hasattr(self, 'SSA_theo'): self.calculate_SSA()\n self.mus_theo = self.density_theo*self.SSA_theo/2\n self.mus_stereo = self.density_stereo*self.SSA_stereo/2\n self.write_in_txt('mu_s stereo :', self.mus_stereo)\n self.write_in_txt('mu_s theo :', self.mus_theo)\n \n def calculate_musp(self):\n if not hasattr(self, 'mus_theo'): self.calculate_mus()\n if not hasattr(self, 'g_theo'): self.calculate_g_theo()\n self.musp_theo = self.mus_theo*(1-self.g_theo)\n self.musp_stereo = self.mus_stereo*(1-self.g_theo)\n self.write_in_txt('mu_s\\' stereo :', self.musp_stereo)\n self.write_in_txt('mu_s\\' theo :', self.musp_theo)\n \n def calculate_B(self):\n #Length of ice per rays\n filt_ice, filt_air, filt_inter_ice = self.filter_ice_air(self.df)\n num_inter = self.df[filt_inter_ice].shape[0]\n l_Ice_p = np.sum(self.df.loc[filt_ice]['pathLength'])/num_inter\n \n #Length of ice per rays for stereo\n filt_ice_stereo, filt_air_stereo, filt_inter_ice_stereo = self.filter_ice_air(self.df_stereo)\n num_inter_stereo = self.df_stereo[filt_inter_ice_stereo].shape[0]\n l_Ice_stereo = np.sum(self.df_stereo.loc[filt_ice_stereo, 'pathLength'])/num_inter_stereo\n \n #Calculate B stereological\n self.B_stereo = l_Ice_p/l_Ice_stereo\n\n #Calculate B raytracing\n if not hasattr(self, 'ke_theo'): self.calculate_ke_theo()\n if not hasattr(self, 'alpha_rt'): self.calculate_alpha()\n if not hasattr(self, 'optical_porosity_stereo'): self.calculate_porosity()\n\n self.B_theo = -self.ke_theo*np.log(self.alpha_theo)/(4*(1-self.physical_porosity_theo)*self.gamma)\n\n self.write_in_txt('B stéréologique :',round(self.B_stereo,4))\n self.write_in_txt('B stéréologique :',round(self.B_theo,4))\n pass\n\n def ke_raytracing(self,depths_fit,intensity):\n [a,b], pcov=scipy.optimize.curve_fit(lambda x,a,b: a*x+b, depths_fit, np.log(intensity))\n return -a, b\n \n def calculate_ke_rt(self):\n #ke raytracing\n def linear_fit(depth,a,b):\n intensity = a*depth+b\n return intensity\n \n def I_ke_raytracing(depth):\n df = self.up_irradiance_at_depth(depth)\n irradiance_down = sum(df['intensity']*np.abs(df['n']))\n \n df = self.down_irradiance_at_depth(depth)\n irradiance_up = sum(df['intensity']*np.abs(df['n']))\n # print(irradiance_down+irradiance_up)\n return irradiance_down+irradiance_up\n \n if not hasattr(self, 'musp_stereo'): self.calculate_musp()\n \n depths_fit = np.linspace(1/self.musp_theo,10/self.musp_theo,10)\n # with concurrent.futures.ThreadPoolExecutor() as executor:\n # for intensity_rt in executor.map(I_ke_raytracing, depths_fit):\n # print(intensity_rt)\n intensity_rt = list(map(I_ke_raytracing,depths_fit))\n self.ke_rt, self.b_rt = self.ke_raytracing(depths_fit,intensity_rt)\n self.write_in_txt('ke raytrace:',round(self.ke_rt,4))\n \n def calculate_ke_theo(self):\n if not hasattr(self, 'density_theo'): self.calculate_density()\n if not hasattr(self, 'g_theo'): self.calculate_g_theo()\n if not hasattr(self, 'B_stereo'): self.calculate_B()\n if not hasattr(self, 'SSA_theo'): self.calculate_SSA()\n if not hasattr(self, 'musp_stereo'): self.calculate_musp()\n \n depths_fit = np.linspace(1/self.musp_theo,10/self.musp_theo,10)\n #ke TARTES\n down_irr_profile, up_irr_profile = tartes.irradiance_profiles(\n self.wlum*1E-6,depths_fit,self.SSA_theo,self.density_theo,g0=self.g_theo,B0=self.B_stereo,dir_frac=self.tartes_dir_frac)\n # plt.plot(depths_fit,np.exp(-self.ke_rt*depths_fit + b),label='fit raytracing')\n self.ke_tartes, self.b_tartes = self.ke_raytracing(depths_fit, down_irr_profile+up_irr_profile)\n\n #ke stéréologique\n #Imaginay part of the indice of refraction\n self.gamma = 4*np.pi*self.ice_complex/(self.wlum*1E-6)\n self.ke_stereo = self.density_stereo*np.sqrt(3*self.B_stereo*self.gamma/(4*self.pice)*self.SSA_theo*(1-self.gG_theo))\n \n #ke théorique\n self.ke_theo = self.density_theo*np.sqrt(3*self.B_stereo*self.gamma/(4*self.pice)*self.SSA_theo*(1-self.gG_theo))\n \n # plt.plot(depths_fit,np.exp(-self.ke_tartes*depths_fit + b),label='fit TARTES')\n # plt.legend()\n self.write_in_txt('ke TARTES:',round(self.ke_tartes,4))\n self.write_in_txt('ke théorique:',round(self.ke_theo,4))\n self.write_in_txt('ke stéréologique:',round(self.ke_stereo,4))\n pass\n \n def calculate_alpha(self):\n if not hasattr(self, 'density_theo'): self.calculate_density()\n if not hasattr(self, 'g_theo'): self.calculate_g_theo()\n if not hasattr(self, 'SSA_theo'): self.calculate_SSA()\n if not hasattr(self, 'B_stereo'): self.calculate_B()\n \n #alpha raytracing\n #Intensity top detector\n filt_top = (self.df['hitObj'] == self.find_detector_object()[0])\n I_top_detector = np.sum(self.df[filt_top]['intensity'])\n \n #Rajoute l'intensité contenu dans les erreurs à alpha\n # filt_error = self.df['segmentLevel'] == self.max_segments-1\n # df_error = self.df[filt_error]\n # I_error = np.sum(df_error['intensity']*np.exp(-df_error['z']*self.ke_rt)/2)\n \n #Intensité total\n self.alpha_rt = I_top_detector #+ I_error\n \n #alpha TARTES\n self.alpha_tartes = float(tartes.albedo(self.wlum*1E-6,self.SSA_stereo,self.density_theo,g0=self.g_theo,B0=self.B_stereo,dir_frac=self.tartes_dir_frac))\n \n #alpha stéréologique\n self.gamma = 4*np.pi*self.ice_complex/(self.wlum*1E-6)\n self.alpha_stereo = np.exp(-4*np.sqrt(2*self.B_stereo*self.gamma/(3*self.pice*self.SSA_stereo*(1-self.g_theo))))\n\n #alpha théorique\n self.alpha_theo = np.exp(-4*np.sqrt(2*self.B_stereo*self.gamma/(3*self.pice*self.SSA_theo*(1-self.g_theo))))\n\n self.write_in_txt('alpha raytracing:',round(self.alpha_rt,4))\n self.write_in_txt('alpha TARTES:',round(self.alpha_tartes,4))\n self.write_in_txt('alpha stéréologique:',round(self.alpha_stereo,4))\n self.write_in_txt('alpha théorique:',round(self.alpha_theo,4))\n pass\n \n def calculate_mua(self):\n if not hasattr(self, 'B_stereo'): self.calculate_B()\n if not hasattr(self, 'optical_porosity_stereo'): self.calculate_porosity()\n if not hasattr(self, 'ke_rt'): self.calculate_ke_rt()\n if not hasattr(self, 'alpha_rt'): self.calculate_alpha()\n if not hasattr(self, 'musp_stereo'): self.calculate_musp()\n \n #Calculate mua theorique\n self.gamma = 4*np.pi*self.ice_complex/(self.wlum*1E-6)\n self.mua_stereo = self.B_stereo*self.gamma*(1-self.physical_porosity_stereo)\n \n #Calculate mua with raytracing\n #Using alpha_theo because depend if direct illumination or diffuse\n self.mua_rt = -self.ke_rt*np.log(self.alpha_rt)/4\n \n #Calculate mua with Tartes\n self.mua_tartes = -self.ke_tartes*np.log(self.alpha_tartes)/4\n \n self.write_in_txt('mua théorique:',round(self.mua_stereo,4))\n self.write_in_txt('mua raytracing:',round(self.mua_rt,4))\n self.write_in_txt('mua raytracing:',round(self.mua_tartes,4))\n\n def up_irradiance_at_depth(self,depth):\n filt_detector = self.df['z'] <= depth\n df = self.df.loc[filt_detector]\n filt = ((df['segmentLevel'].diff() != 1.0)\n & (df['segmentLevel'] != 0))\n df_filtered = df[filt]\n return df_filtered\n \n def down_irradiance_at_depth(self,depth):\n filt_detector = self.df['z'] >= depth\n df = self.df.loc[filt_detector]\n filt = df['segmentLevel'].diff() != 1.0 \n df_filtered = df.loc[filt]\n return df_filtered\n \n def transmitance_at_depth(self,depth):\n filt_detector = self.df['z'] >= depth\n df_filtered = self.df[filt_detector][~self.df[filt_detector].index.duplicated(keep='first')]\n return df_filtered\n \n def calculate_DOP_vs_depth(self,depth):\n df = self.transmitance_at_depth(depth)\n [I,Q,U,V] = self.calculate_Stokes_of_rays(df)\n \n I=np.mean(I)\n Q=np.mean(Q)\n U=np.mean(U)\n V=np.mean(V)\n \n DOP=np.sqrt(Q**2+U**2+V**2)/I\n DOPLT=np.sqrt(Q**2+U**2)/I\n DOPL=np.sqrt(Q**2)/I\n DOP45=np.sqrt(U**2)/I\n DOPC=np.sqrt(V**2)/I\n \n return np.array([DOP, DOPLT, DOPL, DOP45, DOPC])\n \n def calculate_DOP_vs_radius(self,df):\n [I,Q,U,V] = self.calculate_Stokes_of_rays(df)\n \n #Calculate radius from source\n r = np.sqrt((df['x']-self.XY_half_width)**2+(df['y']-self.XY_half_width)**2)\n df.insert(15,'radius',r)\n \n #Calculate Stokes vs Radius\n bins = np.linspace(0,self.XY_half_width,100)\n \n #Histogram of time vs intensity\n I, radius = np.histogram(df['radius'], weights=I, bins=bins)\n Q, radius = np.histogram(df['radius'], weights=Q, bins=bins)\n U, radius = np.histogram(df['radius'], weights=U, bins=bins)\n V, radius = np.histogram(df['radius'], weights=V, bins=bins)\n\n #Create Dataframe for the DOPs\n df_DOP = pd.DataFrame(data=np.transpose([I]),columns = ['intensity'])\n\n #Remove division by 0 by filter NaNs (Q,U and V are 0 anyway)\n I_df = df_DOP['intensity'] #Remove divide by zero exception with using df instead of array\n\n #Calculate DOPs\n DOP=np.sqrt(Q**2+U**2+V**2)/I_df\n DOPLT=np.sqrt(Q**2+U**2)/I_df\n DOPL=np.sqrt(Q**2)/I_df\n DOP45=np.sqrt(U**2)/I_df\n DOPC=np.sqrt(V**2)/I_df\n \n df_DOP.insert(len(df_DOP.columns),'DOP',DOP)\n df_DOP.insert(len(df_DOP.columns),'DOPLT',DOPLT)\n df_DOP.insert(len(df_DOP.columns),'DOPL',DOPL)\n df_DOP.insert(len(df_DOP.columns),'DOP45',DOP45)\n df_DOP.insert(len(df_DOP.columns),'DOPC',DOPC)\n df_DOP[df_DOP.isna()] = 0\n\n df_DOP.insert(len(df_DOP.columns),'radius',radius[:-1])\n return df_DOP\n \n def calculate_Stokes_xy(self,df):\n [I,Q,U,V] = self.calculate_Stokes_of_rays(df)\n \n #Calculate Stokes vs Radius\n bins = (np.linspace(0,self.XY_half_width*2,200),np.linspace(0,self.XY_half_width*2,200))\n \n #Histogram of time vs intensity\n I, x_bins, y_bins = np.histogram2d(df['x'], df['y'], weights=I, bins=bins)\n Q, x_bins, y_bins = np.histogram2d(df['x'], df['y'], weights=Q, bins=bins)\n U, x_bins, y_bins = np.histogram2d(df['x'], df['y'], weights=U, bins=bins)\n V, x_bins, y_bins = np.histogram2d(df['x'], df['y'], weights=V, bins=bins)\n \n return np.array([I,Q,U,V]), x_bins, y_bins\n \n def calculate_DOP_vs_xy(self,df):\n [I,Q,U,V], x_bins, y_bins = self.calculate_Stokes_xy(df)\n \n #Calculate DOPs\n #With handling division by zero\n # DOP=np.true_divide(np.sqrt(Q**2+U**2+V**2), I, out=np.zeros_like(np.sqrt(Q**2+U**2+V**2)), where=I!=0)\n # DOPLT=np.true_divide(np.sqrt(Q**2+U**2), I, out=np.zeros_like(np.sqrt(Q**2+U**2)), where=I!=0)\n DOPL=np.true_divide(np.sqrt(Q**2), I, out=np.zeros_like(np.sqrt(Q**2)), where=I!=0)\n DOP45=np.true_divide(np.sqrt(U**2), I, out=np.zeros_like(np.sqrt(U**2)), where=I!=0)\n DOPC=np.true_divide(np.sqrt(V**2), I, out=np.zeros_like(np.sqrt(V**2)), where=I!=0)\n \n return np.array([I,DOPL,DOP45,DOPC]),x_bins,y_bins\n \n def calculate_Stokes_of_rays(self,df):\n if df.empty:\n #Return empty sequence\n return np.zeros(5)\n \n #Vecteur de polarization dans le plan othogonaux\n Ex = np.array(df['exr']+complex(0,1)*df['exi'])\n Ey = np.array(df['eyr']+complex(0,1)*df['eyi'])\n \n #Polariseur horizontale\n Efx=(1*Ex+0*Ey)\n Efy=(0*Ex+0*Ey)\n Iv=(Efx*Efx.conjugate()+Efy*Efy.conjugate()).real\n \n #Polariseur verticale\n Efx=(0*Ex+0*Ey)\n Efy=(0*Ex+1*Ey)\n Ih=(Efx*Efx.conjugate()+Efy*Efy.conjugate()).real\n\n #Polariseur à 45\n Efx=1/2*(Ex+Ey)\n Efy=1/2*(Ex+Ey)\n I45=(Efx*Efx.conjugate()+Efy*Efy.conjugate()).real\n \n #Polariseur à -45\n Efx=1/2*(Ex-Ey)\n Efy=1/2*(-Ex+Ey)\n Im45=(Efx*Efx.conjugate()+Efy*Efy.conjugate()).real\n\n #Polariseur Circulaire droit\n Efx=1/2*(Ex-complex(0,1)*Ey)\n Efy=1/2*(complex(0,1)*Ex+Ey)\n Icd=(Efx*Efx.conjugate()+Efy*Efy.conjugate()).real\n \n #Polariseur Circulaire gauche\n Efx=1/2*(Ex+complex(0,1)*Ey)\n Efy=1/2*(-complex(0,1)*Ex+Ey)\n Icg=(Efx*Efx.conjugate()+Efy*Efy.conjugate()).real\n \n I=Ih+Iv\n Q=Ih-Iv\n U=I45-Im45\n V=Icd-Icg\n return np.array([I,Q,U,V])\n \n def plot_DOP_transmitance(self):\n #Plot datas\n fig, ax = plt.subplots(nrows=2,ncols=2)\n depth = np.linspace(0,self.Depth,100)\n DOPs = np.array(list(map(self.calculate_DOP_vs_depth,depth))) \n ax[0,0].plot(depth,DOPs[:,0]) #DOP\n ax[0,1].plot(depth,DOPs[:,2]) #DOPL\n ax[1,0].plot(depth,DOPs[:,3]) #DOP45\n ax[1,1].plot(depth,DOPs[:,4]) #DOPC\n \n #Set limits\n ax[0,0].set_ylim(0,1.0)\n ax[0,1].set_ylim(0,1.0)\n ax[1,0].set_ylim(0,1.0)\n ax[1,1].set_ylim(0,1.0)\n \n #Set titles\n ax[0,0].set_title('DOP')\n ax[0,1].set_title('DOPL')\n ax[1,0].set_title('DOP45')\n ax[1,1].set_title('DOPC')\n fig.suptitle('DOPs vs Depth')\n \n def plot_DOP_radius_top_detector(self):\n filt_top_detector = self.df['hitObj'] == self.find_detector_object()[0]\n df = self.df[filt_top_detector]\n \n #Plot datas\n fig, ax = plt.subplots(nrows=2,ncols=2)\n #return dataframe with dops colummns\n df_DOP = self.calculate_DOP_vs_radius(df)\n ax[0,0].plot(df_DOP['radius'],df_DOP['intensity']) #Intensity\n ax[0,1].plot(df_DOP['radius'],df_DOP['DOPL']) #DOPL\n ax[1,0].plot(df_DOP['radius'],df_DOP['DOP45']) #DOP45\n ax[1,1].plot(df_DOP['radius'],df_DOP['DOPC']) #DOPC\n \n #Set limits\n ax[0,1].set_ylim(0,1.0)\n ax[1,0].set_ylim(0,1.0)\n ax[1,1].set_ylim(0,1.0)\n \n #Set titles\n ax[0,0].set_title('Intensity')\n ax[0,1].set_title('DOPL')\n ax[1,0].set_title('DOP45')\n ax[1,1].set_title('DOPC')\n fig.suptitle('DOP map')\n pass\n \n def map_stokes_reflectance(self):\n filt_top_detector = self.df['hitObj'] == self.find_detector_object()[0]\n df = self.df[filt_top_detector]\n \n #Plot datas\n fig, ax = plt.subplots(nrows=2,ncols=2)\n #return dataframe with dops colummns\n array_Stokes, x_bins, y_bins = self.calculate_Stokes_xy(df)\n x, y = np.meshgrid(x_bins, y_bins)\n intensity = ax[0,0].pcolormesh(x, y, array_Stokes[0])\n DOPL = ax[0,1].pcolormesh(x, y, array_Stokes[1]) #DOPL\n DOP45 = ax[1,0].pcolormesh(x, y, array_Stokes[2]) #DOP45\n DOPC = ax[1,1].pcolormesh(x, y, array_Stokes[3]) #DOPC\n \n #plot colormap\n fig.colorbar(intensity,ax=ax[0,0])\n fig.colorbar(DOPL,ax=ax[0,1])\n fig.colorbar(DOP45,ax=ax[1,0])\n fig.colorbar(DOPC,ax=ax[1,1])\n \n #Set titles\n ax[0,0].set_title('Intensity')\n ax[0,1].set_title('DOPL')\n ax[1,0].set_title('DOP45')\n ax[1,1].set_title('DOPC')\n fig.suptitle('DOPs vs Depth')\n pass\n \n def map_DOP_reflectance(self):\n filt_top_detector = self.df['hitObj'] == self.find_detector_object()[0]\n df = self.df[filt_top_detector]\n \n #Plot datas\n fig, ax = plt.subplots(nrows=2,ncols=2)\n #return dataframe with dops colummns\n array_DOPs, x_bins, y_bins = self.calculate_DOP_vs_xy(df)\n x, y = np.meshgrid(x_bins, y_bins)\n intensity = ax[0,0].pcolormesh(x, y, array_DOPs[0],cmap='PuBu')\n DOPL = ax[0,1].pcolormesh(x, y, array_DOPs[1],cmap='PuBu') #DOPL\n DOP45 = ax[1,0].pcolormesh(x, y, array_DOPs[2],cmap='PuBu') #DOP45\n DOPC = ax[1,1].pcolormesh(x, y, array_DOPs[3],cmap='PuBu') #DOPC\n \n #plot colormap\n fig.colorbar(intensity,ax=ax[0,0])\n fig.colorbar(DOPL,ax=ax[0,1])\n fig.colorbar(DOP45,ax=ax[1,0])\n fig.colorbar(DOPC,ax=ax[1,1])\n \n #Set titles\n ax[0,0].set_title('Intensity')\n ax[0,1].set_title('DOPL')\n ax[1,0].set_title('DOP45')\n ax[1,1].set_title('DOPC')\n fig.suptitle('DOPs vs Depth')\n pass\n \n def plot_time_reflectance(self):\n if not hasattr(self, 'musp_stereo'): self.calculate_musp()\n if not hasattr(self, 'mua_rt'): self.calculate_mua()\n if not hasattr(self, 'neff_rt'): self.calculate_neff()\n \n #Raytracing\n #Add a line of time for each segment\n self.df.insert(15,'time',np.nan)\n v_medium = scipy.constants.c/self.df['index']\n self.df['time'] = self.df['pathLength']/v_medium\n \n #Time for each ray\n df = self.df.groupby(self.df.index).agg({'time':sum,'intensity':'last','hitObj':'last'})\n \n #Filt only reflectance rays\n filt_top_detector = df['hitObj'] == self.find_detector_object()[0]\n df_top = df[filt_top_detector]\n \n #Histogram of time vs intensity\n R_rt, bins = np.histogram(df_top['time'], weights=df_top['intensity'], bins=1000)\n t_rt = bins[:-1]\n \n #Théorique\n z_o = self.musp_stereo**(-1)\n D = (3*(self.mua_stereo+self.musp_stereo))**(-1)\n t_theo = np.linspace(1E-12,t_rt[-1],100000)\n c = scipy.constants.c/self.neff_stereo\n R_theo = (4*np.pi*D*c)**(-1/2)*z_o*t_theo**(-3/2)*np.exp(-self.mua_stereo*c*t_theo)*np.exp(-z_o**2/(4*D*c*t_theo))\n \n #Normalize\n R_rt = R_rt/max(R_rt)\n R_theo = R_theo/max(R_theo)\n \n #Change the offset on time theo so the 2 curves overlap (theo and rt)\n t_rt_offset = t_rt[(list(R_rt)).index(max(R_rt))]\n t_theo_offset = t_theo[(list(R_theo)).index(max(R_theo))]\n t_diff = t_rt_offset-t_theo_offset\n t_theo = t_theo+t_diff\n \n # np.average(t_theo*scipy.constants.c/self.neff_stereo,weights=R_theo)\n #Plot reflectance vs time\n plt.figure()\n plt.plot(bins[:-1],R_rt)\n plt.plot(t_theo,R_theo)\n plt.xlim(1E-12,max(t_rt)/2)\n pass\n \n \n \n def map_top_detector(self):\n filt_top_detector = self.df['hitObj'] == self.find_detector_object()[0]\n df_top_detector = self.df[filt_top_detector]\n df_top_detector.plot(x='x',y='y',kind='scatter')\n print('Numrays top detector',df_top_detector.shape[0])\n pass\n \n def map_down_detector(self):\n filt_down_detector = self.df['hitObj'] == self.find_detector_object()[1]\n df_down_detector = self.df[filt_down_detector]\n df_down_detector.plot(x='x',y='y',kind='scatter')\n print('Numrays down detector',df_down_detector.shape[0])\n pass\n \n def map_detector(self,depth):\n df = self.transmitance_at_depth(self.df,depth)\n df.plot(x='x', y='y', kind='scatter')\n print('Numrays on detector',df.shape[0])\n pass\n \n def plot_irradiances(self):\n #Irradiance raytracing\n def Irradiance_down(depth):\n df = self.down_irradiance_at_depth(depth)\n irradiance_down = sum(df['intensity']*np.abs(df['n']))\n return irradiance_down\n \n def Irradiance_up(depth):\n df = self.up_irradiance_at_depth(depth)\n irradiance_up = sum(df['intensity']*np.abs(df['n']))\n return irradiance_up\n \n depth = np.linspace(-0.001,25/self.musp_theo,200)\n irradiance_down_rt = np.array(list(map(Irradiance_down,depth)))\n irradiance_up_rt = np.array(list(map(Irradiance_up,depth)))\n \n #Irradiance TARTES\n if not hasattr(self, 'density_stereo'): self.calculate_density()\n if not hasattr(self, 'g_theo'): self.calculate_g_theo()\n if not hasattr(self, 'SSA_stereo'): self.calculate_SSA()\n irradiance_down_tartes, irradiance_up_tartes = tartes.irradiance_profiles(\n self.wlum*1E-6, depth, self.SSA_stereo, density=self.density_stereo,\n g0=self.g_theo,B0=self.B_stereo,dir_frac=self.tartes_dir_frac,totflux=1)\n \n #Plot irradiance down\n plt.figure()\n plt.semilogy(depth,np.exp(-self.ke_rt*depth + self.b_rt),label='fit total irradiance raytracing')\n plt.semilogy(depth,np.exp(-self.ke_tartes*depth + self.b_tartes),label='fit TARTES')\n plt.semilogy(depth,irradiance_down_tartes+irradiance_up_tartes, label='irradiance TARTES')\n plt.semilogy(depth,irradiance_down_rt, label='downwelling irradiance raytracing')\n plt.semilogy(depth,irradiance_up_rt, label='upwelling irradiance raytracing')\n plt.semilogy(depth,irradiance_down_rt+irradiance_up_rt, label='total irradiance raytracing')\n plt.xlabel('depth (m)')\n plt.ylabel('irradiance (W/m^2)')\n plt.legend()\n plt.title(self.name + '_numrays_' + str(self.numrays) + '_wlum_' + str(self.wlum) + '_alpha_' + str(round(self.alpha_rt,4)) + '_' + str(round(self.alpha_tartes,4)))\n plt.savefig(os.path.join(self.pathZMX,self.name + '_wlum_' + str(self.numrays) + '_wlum_' + str(self.wlum) + '_alpha_ ' + str(round(self.alpha_rt,4))+'_' + str(round(self.alpha_tartes,4))+'.png'),format='png')\n \n def write_in_txt(self,properties='',value=''):\n with open('Properties_Simulations_SSP.txt','a') as f:\n f.write(properties +' '+ str(value)+'\\n')\n \n def time(self,text=''):\n t = time.localtime()\n self.date = str(t.tm_year)+\"/\"+str(t.tm_mon)+\"/\"+str(t.tm_mday)\n self.ctime = str(t.tm_hour)+\":\"+str(t.tm_min)+\":\"+str(t.tm_sec)\n print('Date : ',self.date,', Time : ',self.ctime,' ',text)\n \n def properties(self):\n print('\\n----------------------------------------------------\\n')\n if hasattr(self, 'path_npy'): print('Simulation path npy file: ', self.path_npy)\n if hasattr(self, 'path_stereo_npy'): print('Simulation path npy file: ', self.path_stereo_npy)\n if hasattr(self, 'fileZMX'): print('Simulation path ZMX files: ', self.fileZMX)\n if hasattr(self, 'B_stereo'): print('Le B stéréologique: ' + str(round(self.B_stereo,4)))\n if hasattr(self, 'B_theo'): print('Le B théorique: ' + str(round(self.B_theo,4)))\n if hasattr(self, 'g_theo'): print('Le g théorique: ' + str(round(self.g_theo,4)))\n if hasattr(self, 'gG_theo'): print('Le gG théorique: ' + str(round(self.gG_theo,4)))\n if hasattr(self, 'g_rt'): print('Le g raytracing: ' + str(round(self.g_rt,4)))\n if hasattr(self, 'gG_rt'): print('Le gG raytracing: ' + str(round(self.gG_rt,4)))\n if hasattr(self, 'SSA_stereo'): print('La SSA stéréologie: ' + str(round(self.SSA_stereo,4)))\n if hasattr(self, 'SSA_theo'): print('La SSA théorique: ' + str(round(self.SSA_theo,4)))\n if hasattr(self, 'density_theo'): print('La densité théorique: ' + str(round(self.density_theo,4)))\n if hasattr(self, 'density_stereo'): print('La densité stéréologique: ' + str(round(self.density_stereo,4)))\n if hasattr(self, 'physical_porosity_theo'): print('La porosité physique théorique: ' + str(round(self.physical_porosity_theo,5)))\n if hasattr(self, 'physical_porosity_stereo'): print('La porosité physique stéréologique: ' + str(round(self.physical_porosity_stereo,5)))\n if hasattr(self, 'optical_porosity_theo'): print('La porosité optique théorique: ' + str(round(self.optical_porosity_theo,5)))\n if hasattr(self, 'optical_porosity_stereo'): print('La porosité optique stéréologique: ' + str(round(self.optical_porosity_stereo,5)))\n if hasattr(self, 'mus_theo'): print('La mus théorique: ' + str(round(self.mus_theo,4)))\n if hasattr(self, 'mus_stereo'): print('La mus stéréologie: ' + str(round(self.mus_stereo,4)))\n if hasattr(self, 'musp_theo'): print('La musp théorique: ' + str(round(self.musp_theo,4)))\n if hasattr(self, 'musp_stereo'): print('La musp stéréologie: ' + str(round(self.musp_stereo,4)))\n if hasattr(self, 'mua_stereo'): print('mua stéréologique: ' + str(round(self.mua_stereo,6)))\n if hasattr(self, 'mua_rt'): print('mua raytracing: ' + str(round(self.mua_rt,6)))\n if hasattr(self, 'mua_tartes'): print('mua tartes: ' + str(round(self.mua_tartes,6)))\n if hasattr(self, 'alpha_theo'): print('alpha théorique: ' + str(round(self.alpha_theo,6)))\n if hasattr(self, 'alpha_stereo'): print('alpha stéréologique: ' + str(round(self.alpha_stereo,6)))\n if hasattr(self, 'alpha_rt'): print('alpha raytracing: ' + str(round(self.alpha_rt,6)))\n if hasattr(self, 'alpha_tartes'): print('alpha TARTES: ' + str(round(self.alpha_tartes,6)))\n if hasattr(self, 'ke_stereo'): print('ke stéréologique: ' + str(round(self.ke_stereo,6)))\n if hasattr(self, 'ke_theo'): print('ke théorique: ' + str(round(self.ke_theo,6)))\n if hasattr(self, 'ke_rt'): print('ke raytracing: ' + str(round(self.ke_rt,6)))\n if hasattr(self, 'ke_tartes'): print('ke TARTES: ' + str(round(self.ke_tartes,6)))\n if hasattr(self, 'MOPL_stereo'): print('La MOPL stéréologique: ' + str(round(self.MOPL_stereo,6)))\n if hasattr(self, 'MOPL_rt'): print('La MOPL raytracing: ' + str(round(self.MOPL_rt,6)))\n if hasattr(self, 'neff_stereo'): print('Le neff stéréologique: ' + str(round(self.neff_stereo,6)))\n if hasattr(self, 'neff_rt'): print('Le neff raytracing: ' + str(round(self.neff_rt,6)))\n if hasattr(self, 'Reflectance'): print('Reflectance raytracing: ' + str(round(self.Reflectance,6)) + ', NumRays: ' +str(self.numrays_Reflectance))\n if hasattr(self, 'Transmitance'): print('Transmitance raytracing: ' + str(round(self.Transmitance,6)) + ', NumRays: ' +str(self.numrays_Transmitance))\n if hasattr(self, 'Error'): print('Error raytracing: ' + str(round(self.Error,6)) + ', NumRays: ' +str(self.numrays_Error))\n if hasattr(self, 'Lost'): print('Lost raytracing: ' + str(round(self.Lost,6)) + ', NumRays: ' +str(self.numrays_Lost))\n if hasattr(self, 'Absorb'): print('Absorb raytracing: ' + str(round(self.Absorb,6)) + ', NumRays: ' +str(self.numrays_Absorb))\n \n def __del__(self):\n try:\n self.TheSystem.SaveAs(self.fileZMX)\n del self.zosapi\n self.zosapi = None\n except Exception:\n pass\n\nplt.close('all')\n# simulation(name, radius, delta, numrays, numrays_stereo, wlum, pol)\nproperties=[]\nfor wlum in [1.0]:\n # sim = simulation('test1', [65E-6], 287E-6, 1000, 100, wlum, [1,1,0,0], diffuse_light=False)\n sim = simulation('test2', [66E-6], 287E-6, 10000, 1000, wlum, [1,1,0,90], diffuse_light=False)\n # sim = simulation('test1', [36.32E-6], 220E-6, 1000, 1000, 1.0, [1,1,0,90], diffuse_light=True)\n sim.create_folder()\n sim.Initialize_Zemax()\n sim.Load_File()\n # sim.create_ZMX()\n # sim.create_source()\n # sim.create_detectors()\n # sim.create_snow()\n # sim.shoot_rays_stereo()\n # sim.shoot_rays()\n sim.Load_npyfile()\n # sim.calculate_g_theo()\n # sim.calculate_g_rt()\n # sim.calculate_B()\n # sim.calculate_SSA()\n # sim.calculate_density()\n # sim.calculate_mus()\n # sim.calculate_mua()\n # sim.calculate_musp()\n # sim.calculate_MOPL()\n # sim.calculate_neff()\n # sim.calculate_porosity()\n # sim.calculate_alpha()\n # sim.calculate_ke_theo()\n # sim.calculate_ke_rt()\n # sim.reflectance_transmitance()\n # sim.map_top_detector()\n # sim.map_down_detector()\n # sim.plot_DOP_radius_top_detector()\n # sim.plot_irradiances()\n # sim.map_DOP_reflectance()\n sim.map_stokes_reflectance()\n # sim.plot_time_reflectance()\n sim.properties()\n # properties += [[sim.mua_stereo,sim.alpha_rt,sim.alpha_stereo,sim.MOPL_stereo,sim.MOPL_rt,sim.Error]]\n # del sim","sub_path":"Sphere/Volume/Vol_Simulation.py","file_name":"Vol_Simulation.py","file_ext":"py","file_size_in_byte":72649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"340703807","text":"from State import State\nactions=['Right','Left','Up','Down']\nepsilon=0.00001\ndiscount=0.99\nlivingreward=-2\nfirereward=-1\ndiamondreward=1\nv=[]\nv_=[[],[],[]]\n\ndef printfinalpolicy(Policy):\n for i in range(len(Policy)):\n for j in range(len(Policy[i])):\n if Policy[i][j]=='Right':\n print('%-4s'%'>',end='')\n elif Policy[i][j]=='Left':\n print('%-4s'%'<',end='')\n elif Policy[i][j]=='Up':\n print('%-4s'%'^',end='')\n elif Policy[i][j]=='Down':\n print('%-4s'%'v',end='')\n elif Policy[i][j]=='Block':\n print('%-4s'%'|',end='')\n else:\n print('%-4s'%Policy[i][j][0],end='')\n print()\n\ndef predictnext(rowindex,columnindex,direction):\n if direction=='Right' and (columnindex==3 or (rowindex==1 and columnindex==0)) :\n return (rowindex,columnindex)\n elif direction=='Left' and (columnindex==0 or (rowindex==1 and columnindex==2)):\n return (rowindex,columnindex)\n elif direction=='Up' and (rowindex==0 or (rowindex==2 and columnindex==1)):\n return (rowindex,columnindex)\n elif direction=='Down' and (rowindex==2 or (rowindex==0 and columnindex==1)):\n return (rowindex,columnindex)\n elif direction=='Right':\n return (rowindex,columnindex+1)\n elif direction=='Left':\n return (rowindex,columnindex-1)\n elif direction=='Up':\n return (rowindex-1,columnindex)\n elif direction=='Down':\n return (rowindex+1,columnindex)\n\ndef calculatemax(state,v):\n P=[0.8,0.1,0.1]\n actionsu=[0 for i in actions]\n for i in range(len(actions)):\n if actions[i]=='Right' or actions[i]=='Left':\n actionscan=[actions[i],'Down','Up']\n elif actions[i]=='Up' or actions[i]=='Down':\n actionscan=[actions[i],'Right','Left']\n for j in range(len(actionscan)):\n nextstate=predictnext(state.rowindex,state.columnindex,actionscan[j])\n if nextstate[0]==0 and nextstate[1]==3:\n actionsu[i]+=P[j]*(diamondreward+(discount*v[nextstate[0]][nextstate[1]]))\n elif nextstate[0]==1 and nextstate[1]==3:\n actionsu[i]+=P[j]*(firereward+(discount*v[nextstate[0]][nextstate[1]]))\n else:\n actionsu[i]+=P[j]*(livingreward+(discount*v[nextstate[0]][nextstate[1]]))\n maxindex=0\n maxvalue=actionsu[0]\n for j in range(1,len(actions)):\n if actionsu[j]>maxvalue:\n maxvalue=actionsu[j]\n maxindex=j\n return (maxvalue,actions[maxindex])\n\nfor i in range(3): ## making states\n for j in range(4):\n if i==0 and j==3:\n v_[i].append(State(i,j,diamondreward,'Diamond'))\n elif i==1 and j==1:\n v_[i].append(State(i,j,livingreward,'Block'))\n elif i==1 and j==3:\n v_[i].append(State(i,j,firereward,'Fire'))\n else:\n v_[i].append(State(i,j,livingreward))\nv=[[i.V for i in v_[0]],[i.V for i in v_[1]],[i.V for i in v_[2]]]\n\nPolicy=[['none' for i in range(4)] for i in range(3)] # For Save Action Policy for each state.\niterations=0 # Counting iteration of while loop\nwhile True:\n iterations+=1\n delta=0\n v=[[i.V for i in v_[0]],[i.V for i in v_[1]],[i.V for i in v_[2]]]\n for i in range(3):\n for j in range(4):\n if not ((i==0 and j==3) or (i==1 and j==3) or (i==1 and j==1)): \n temp=calculatemax(v_[i][j],v)\n v_[i][j].V=temp[0]\n Policy[i][j]=temp[1]\n if abs(v_[i][j].V -v[i][j])>delta:\n delta = abs(v_[i][j].V-v[i][j])\n Policy[0][3]='Diamond'\n Policy[1][3]='Fire'\n Policy[1][1]='Block'\n if delta < (epsilon*(1-discount))/discount:\n break\nprintfinalpolicy(Policy)\ninput()","sub_path":"CLI_Version/GridWorld.py","file_name":"GridWorld.py","file_ext":"py","file_size_in_byte":3819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"398455379","text":"import sys\nsys.path.append(\"/Users/Shared/Autodesk/maya/2014/plug-ins/\")\n\nimport maya.OpenMayaAnim as OpenMayaAnim\nimport maya.OpenMaya as OpenMaya\nimport maya.cmds as cmds\n\nimport Maya.Reaper as MR\nimport Maya.Utils as MU\n\ndef frameRange():\n minF = OpenMayaAnim.MAnimControl.minTime().value() - 1\n maxF = OpenMayaAnim.MAnimControl.maxTime().value()\n return (minF, maxF)\n\n# ---------------------------------------------------------------------------- #\n\ndef resetGlobals():\n global SQST_MANAGER, SQST_MESH, SQST_PARTICLE, INSTANCE_COUNT, SIGMA, REAPED_DATA, SLIDER_CB_ID\n SQST_MANAGER = \"\"\n SQST_MESH = \"\"\n SQST_PARTICLE = \"\"\n INSTANCE_COUNT = 0\n SIGMA = 3\n REAPED_DATA = {}\n SLIDER_CB_ID = 0\nresetGlobals()\n\ndef setManager():\n global SQST_MANAGER, INSTANCE_COUNT, SIGMA\n transform = cmds.ls(selection = True)[0]\n SQST_MANAGER = cmds.listRelatives(transform)[0]\n INSTANCE_COUNT = cmds.getAttr(\"%s.iTrainingCount\" % SQST_MANAGER)\n SIGMA = cmds.getAttr(\"%s.iSigma\" % SQST_MANAGER)\n \ndef setMesh():\n global SQST_MESH\n SQST_MESH = cmds.ls(selection = True)[0]\n \n # cmds.duplicate(SQST_MESH, name = SQST_MESH + \"_other\")\n if SQST_MANAGER:\n orgMesh = MU.flatMeshArr(SQST_MESH)\n cmds.setAttr(\"%s.iOriginalMeshData\" % SQST_MANAGER, orgMesh, type=\"doubleArray\")\n\ndef setParticle():\n global SQST_PARTICLE\n SQST_PARTICLE = cmds.ls(selection = True)[0]\n\n# ---------------------------------------------------------------------------- #\n\ndef setSigma(val):\n global SIGMA\n SIGMA = float(cmds.textField(val, q = True, text = True))\n cmds.setAttr(\"%s.iSigma\" % SQST_MANAGER, SIGMA)\n\ndef setSqStMesh():\n ghost = cmds.duplicate(SQST_MESH, name = (SQST_MESH + \"_ghost\"))[0]\n cmds.toggle(ghost, template = True)\n # cmds.connectAttr(\"%s.tx\" % SQST_MESH, \"%s.tx\" % ghost)\n # cmds.connectAttr(\"%s.ty\" % SQST_MESH, \"%s.ty\" % ghost)\n # cmds.connectAttr(\"%s.tz\" % SQST_MESH, \"%s.tz\" % ghost)\n # cmds.connectAttr(\"%s.sx\" % SQST_MESH, \"%s.sx\" % ghost)\n # cmds.connectAttr(\"%s.sy\" % SQST_MESH, \"%s.sy\" % ghost)\n # cmds.connectAttr(\"%s.sz\" % SQST_MESH, \"%s.sz\" % ghost)\n cmds.select(SQST_MESH)\n \ndef initManager():\n global SQST_MANAGER\n SQST_MANAGER = cmds.createNode(\"VmSqStManager\")\n cmds.connectAttr(\"%s_ghost.outMesh\" % SQST_MESH, \"%s.iMesh\" % SQST_MANAGER, f = True)\n\n# ---------------------------------------------------------------------------- #\n\ndef createInstance(x, y, z, name):\n sqstInstance = cmds.createNode(\"VmSqStInstance\")\n cmds.move(x, y, z, sqstInstance)\n cmds.setAttr(\"%s.iFrame\" % sqstInstance, cmds.currentTime(q = True))\n cmds.setAttr(\"%s.iName\" % sqstInstance, name, type = \"string\")\n\n orgMesh = MU.flatMeshArr(SQST_MESH)\n #print \"neshst\", orgMesh\n cmds.setAttr(\"%s.iOriginalMeshData\" % sqstInstance, orgMesh, type=\"doubleArray\")\n\n return sqstInstance\n \ndef createGhost(x, y, z, name):\n ghost = cmds.duplicate(name, name = name + \"_ghost\")[0]\n # cmds.toggle(ghost, template = True)\n # cmds.move(x, y, z, ghost)\n return ghost\n \ndef createEditable(x, y, z, name):\n editable = cmds.duplicate(name, name = name + \"_editable\")[0]\n cmds.toggle(editable)\n cmds.move(x, y, z, editable)\n return editable\n\ndef createSqstInstance(name):\n global INSTANCE_COUNT\n \n x = cmds.getAttr(\"%s.tx\" % SQST_MESH)\n y = cmds.getAttr(\"%s.ty\" % SQST_MESH)\n z = cmds.getAttr(\"%s.tz\" % SQST_MESH)\n \n sqstInstance = createInstance(x, y, z, SQST_PARTICLE)\n # ghost = createGhost(x, y, z, name)\n editable = createEditable(x, y, z, name)\n \n cmds.connectAttr(\"%s.outMesh\" % editable, \"%s.iMesh\" % sqstInstance, f = True)\n # cmds.connectAttr(\"%s.oMesh\" % sqstInstance, \"%s.inMesh\" % ghost, f = True)\n\n tForm = cmds.listRelatives(sqstInstance, allParents = True)[0]\n\n # cmds.connectAttr(\"%s.tx\" % tForm, \"%s.tx\" % ghost)\n # cmds.connectAttr(\"%s.ty\" % tForm, \"%s.ty\" % ghost)\n # cmds.connectAttr(\"%s.tz\" % tForm, \"%s.tz\" % ghost)\n cmds.connectAttr(\"%s.tx\" % tForm, \"%s.tx\" % editable)\n cmds.connectAttr(\"%s.ty\" % tForm, \"%s.ty\" % editable)\n cmds.connectAttr(\"%s.tz\" % tForm, \"%s.tz\" % editable)\n \n cmds.setAttr(\"%s.iInstanceNames[%d]\" % (SQST_MANAGER, INSTANCE_COUNT), sqstInstance, type = \"string\")\n INSTANCE_COUNT += 1\n \n cmds.select(name)\n\n# ---------------------------------------------------------------------------- #\n\ndef compileActiveInputs(inD):\n useIns = [\n cmds.getAttr(\"%s.iUsePosX\" % SQST_MANAGER),\n cmds.getAttr(\"%s.iUsePosY\" % SQST_MANAGER),\n cmds.getAttr(\"%s.iUsePosZ\" % SQST_MANAGER),\n cmds.getAttr(\"%s.iUseHeadingX\" % SQST_MANAGER),\n cmds.getAttr(\"%s.iUseHeadingY\" % SQST_MANAGER),\n cmds.getAttr(\"%s.iUseHeadingZ\" % SQST_MANAGER),\n cmds.getAttr(\"%s.iUseVel\" % SQST_MANAGER),\n cmds.getAttr(\"%s.iUseAcc\" % SQST_MANAGER)\n ]\n #print useIns\n activeIns = []\n if useIns[0]: activeIns += [inD[\"pos\"][0]]\n if useIns[1]: activeIns += [inD[\"pos\"][1]]\n if useIns[2]: activeIns += [inD[\"pos\"][2]]\n if useIns[3]: activeIns += [inD[\"dir\"][0]]\n if useIns[4]: activeIns += [inD[\"dir\"][1]]\n if useIns[5]: activeIns += [inD[\"dir\"][2]]\n if useIns[6]: activeIns += [inD[\"vel\"]]\n if useIns[7]: activeIns += [inD[\"acc\"]]\n #print \"returning\", activeIns\n return activeIns\n\ndef poolInstances():\n instances = []\n for i in range(INSTANCE_COUNT):\n inst = cmds.getAttr(\"%s.iInstanceNames[%s]\" % (SQST_MANAGER, i), asString = True)\n instances += [inst]\n return instances\n\ndef updateInstance(inst, inD, t):\n x = cmds.getAttr(\"%s.tx\" % SQST_PARTICLE, time = t)\n y = cmds.getAttr(\"%s.ty\" % SQST_PARTICLE, time = t)\n z = cmds.getAttr(\"%s.tz\" % SQST_PARTICLE, time = t)\n # cmds.move(x, y, z, inst)\n\n cmds.setAttr(\"%s.oHeading\" % inst, inD[\"dir\"][0], inD[\"dir\"][1], inD[\"dir\"][2], type=\"double3\")\n cmds.setAttr(\"%s.oVelocity\" % inst, inD[\"vel\"])\n cmds.setAttr(\"%s.oAccel\" % inst, inD[\"acc\"])\n \ndef getInputs(instances):\n inputs = []\n for inst in instances:\n frame = cmds.getAttr(\"%s.iFrame\" % inst)\n inD = REAPED_DATA[str(int(frame))]\n updateInstance(inst, inD, frame)\n\n # Remeber this should be a 1D array!\n inputs += compileActiveInputs(inD)\n return inputs\n\ndef getOutputs(instances):\n outputs = []\n for inst in instances:\n meshData = cmds.getAttr(\"%s.oMeshData\" % inst)\n outputs += meshData\n #print meshData\n return outputs \n\ndef updateManager():\n instances = poolInstances()\n inputs = getInputs(instances)\n outputs = getOutputs(instances)\n cmds.setAttr(\"%s.iInputValues\" % SQST_MANAGER, inputs, type=\"doubleArray\")\n cmds.setAttr(\"%s.iOutputValues\" % SQST_MANAGER, outputs, type=\"doubleArray\")\n cmds.setAttr(\"%s.iTrainingCount\" % SQST_MANAGER, len(instances))\n cmds.setAttr(\"%s.iReset\" % SQST_MANAGER, 0)\n cmds.setAttr(\"%s.iReset\" % SQST_MANAGER, 1)\n \ndef cacheInputs():\n global REAPED_DATA\n REAPED_DATA = {}\n \n l, h = frameRange()\n posArr = MR.positions(SQST_PARTICLE, int(l + 1), int(h))\n dirArr = MR.headings(posArr)\n velArr = MR.velocities(posArr)\n accArr = MR.accelerations(velArr)\n \n for i in range(int(h)):\n frame = i + l + 1\n REAPED_DATA[str(int(frame))] = {\n \"pos\" : [posArr[i].x, posArr[i].y, posArr[i].z],\n \"dir\" : [dirArr[i].x, dirArr[i].y, dirArr[i].z],\n \"vel\" : velArr[i],\n \"acc\" : accArr[i]\n }\n\n# ---------------------------------------------------------------------------- #\n\ndef timeSliderCB(newTime, clientData):\n frame = int(cmds.currentTime(q = True))\n inputArr = compileActiveInputs(REAPED_DATA[str(int(frame))])\n orgMesh = MU.flatMeshArr(SQST_MESH)\n cmds.setAttr(\"%s.iOriginalMeshData\" % SQST_MANAGER, orgMesh, type=\"doubleArray\")\n cmds.setAttr(\"%s.iCurrentInput\" % SQST_MANAGER, inputArr, type=\"doubleArray\")\n cmds.setAttr(\"%s.iSigma\" % SQST_MANAGER, SIGMA)\n cmds.setAttr(\"%s.iSigma\" % SQST_MANAGER, SIGMA + 0.0001)\n \ndef removeSliderCallback():\n OpenMaya.MMessage.removeCallback(SLIDER_CB_ID)\n cmds.disconnectAttr(\"%s.oMesh\" % SQST_MANAGER, \"%s_ghost.inMesh\" % (SQST_MESH))\n \ndef addTimeSliderCallback():\n global SLIDER_CB_ID\n cmds.connectAttr(\"%s.oMesh\" % SQST_MANAGER, \"%s_ghost.inMesh\" % (SQST_MESH), f = True)\n SLIDER_CB_ID = OpenMaya.MDGMessage.addTimeChangeCallback(timeSliderCB)\n\n# ---------------------------------------------------------------------------- #","sub_path":"Plugins/Shelf/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":8607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"315160146","text":"import os\nimport sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.layers import Input,Dense, GlobalMaxPooling1D\nfrom keras.layers import Conv1D, MaxPooling1D, Embedding\nfrom keras.models import Model\nfrom sklearn.metrics import roc_auc_score\n\nDATA_PATH = './data/toxic-comment'\nEMBEDDING_VECTOR_PATH = \"glove.6B/glove.6B.{}d.txt\"\n\nMAX_SEQUENCE_LENGTH = 100\nMAX_VOCAB_SIZE = 20000\nEMBEDDING_DIM = 100\nVALIDATION_SPLIT = .2\nBATCH_SIZE = 128\nEPOCHS = 10\n\n\n\n\nprint('Loading word vectors')\nword2vec = {}\nwith open(EMBEDDING_VECTOR_PATH.format(EMBEDDING_DIM),'r') as f:\n for line in f:\n values = line.split()\n word = values[0]\n vector = np.asarray(values[1:],dtype = 'float32')\n word2vec[word] = vector\nprint('Word Vectors loaded.')\n\n\n\ntrain = pd.read_csv(os.path.join(DATA_PATH, \"train.csv\"))\nsentences = train['comment_text'].fillna('DUMMY_VALUES').values\npossible_labels = ['toxic','severe_toxic','obscene','threat','insult','identity_hate']\ntargets = train[possible_labels].values\n\nprint('Max sequence length:', max(len(seq) for seq in sentences))\nprint('Min sequence length:', min(len(seq) for seq in sentences))\ns = sorted((len(s) for s in sentences))\nprint('Medium sequence length:',s[int(len(s))// 2])\n\n\nprint('Sentence tokenization...')\ntokenizer = Tokenizer(num_words = MAX_VOCAB_SIZE)\n\n# fit_on_texts documentation, here we use list of list of strings.\n# argument: can be a list of strings,\n# a generator of strings (for memory-efficiency),\n# or a list of list of strings.\ntokenizer.fit_on_texts(sentences)\nsequences = tokenizer.texts_to_sequences(sentences)\n\nword2index = tokenizer.word_index\nindex2word = {v:k for k,v in word2index.items()}\n\nsequences = pad_sequences(sequences,maxlen = MAX_SEQUENCE_LENGTH)\nprint('Found {} unique index'.format(len(word2index)))\n\n\nprint('Building embedding matrix and embedding layer')\nnum_words = max(MAX_VOCAB_SIZE, len(word2index) + 1)\nembedding_matrix = np.zeros((num_words, EMBEDDING_DIM))\nfor word, ind in word2index.items():\n if ind < MAX_VOCAB_SIZE:\n embedding_vector = word2vec.get(word)\n if embedding_vector is not None:\n embedding_matrix[ind] = embedding_vector\n\nembedding_layer = Embedding(num_words,\n EMBEDDING_DIM,\n weights = [embedding_matrix],\n input_length = MAX_SEQUENCE_LENGTH,\n trainable = False)\nprint('Preprocessing done.')\n\n\n# shapes\n# sequence: N * T\n# targets: N * 6 (six possible binary labels)\n# embedding: V * D (num_words, embedding_dimension)\n\ninput_ = Input(shape = (MAX_SEQUENCE_LENGTH,))\nx = embedding_layer(input_)\nx = Conv1D(128,3,activation = 'relu')(x)\nx = MaxPooling1D(3)(x)\nx = Conv1D(128,3,activation = 'relu')(x)\nx = MaxPooling1D(3)(x)\nx = Conv1D(128,3,activation = 'relu')(x)\nx = MaxPooling1D(3)(x)\nx = GlobalMaxPooling1D()(x)\nx = Dense(128,activation = 'relu')(x)\nx = Dense(len(possible_labels), activation = 'sigmoid')(x)\nmodel = Model(inputs = input_,outputs = x)\nmodel.compile(optimizer = 'adam',\n loss = 'binary_crossentropy',\n metrics = ['accuracy'])\nprint(model.summary())\n\nhistory = model.fit(x = sequences,\n y = targets,\n batch_size = BATCH_SIZE,\n epochs = 5,\n validation_split =VALIDATION_SPLIT)\n\nplt.plot(history.history['loss'], label = 'Loss')\nplt.plot(history.history['val_loss'], label = 'Val-loss')\nplt.legend()\nplt.show()\n\nplt.plot(history.history['accuracy'], label = 'Accuracy')\nplt.plot(history.history['val_accuracy'], label = 'Val-Accuracy')\nplt.legend()\nplt.show()\n","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"398782186","text":"from backports import configparser\n\nfrom Model.Button import Button\nfrom Model.Constants import Constants\n\n\nclass MappingManager:\n @staticmethod\n def map():\n print(\"detecting mapping...\")\n\n buttons = []\n\n for player_idx in range(1, 3):\n config = configparser.RawConfigParser()\n print(\"\\nMapping player [\"+str(player_idx)+\"]\")\n ini_str =\\\n '[' + Constants.default_conf_section + ']\\n' \\\n + open(Constants.config_gpio_base_path+str(player_idx)+\".cfg\", 'r').read()\n\n config.read_string(ini_str.decode('utf8'))\n\n for direction in Constants.directions:\n btn = MappingManager.__map_input(\"input_\" + direction + \"_axis\", config, player_idx)\n buttons.append(btn)\n for button_key in Constants.buttons_keys:\n btn = MappingManager.__map_input(\"input_\" + button_key + \"_btn\", config, player_idx)\n if btn is not None:\n buttons.append(btn)\n\n return buttons\n\n @staticmethod\n def __map_input(conf_key, config, player_idx):\n if config.has_option(Constants.default_conf_section, conf_key):\n key = config.get(Constants.default_conf_section, conf_key)[1:-1]\n bcm_code = Constants.keys_map[player_idx - 1][key]\n print(\"[\" + conf_key + \"] [\" + key + \"] -> [\" + str(bcm_code) + \"]\")\n return Button(conf_key, bcm_code, player_idx)\n else:\n print(\"[\" + conf_key + \"] -> [ NOT MAPPED ]\")\n return None\n","sub_path":"Core/MappingManager.py","file_name":"MappingManager.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"628146622","text":"import sys\nimport os\nimport numpy as np\nimport numpy.random as npr\nimport pandas as pd\nimport random\nfrom sklearn.model_selection import train_test_split\n\n# Module file with functions that you fill in so that they can be\n# called by the notebook. This file should be in the same\n# directory/folder as the notebook when you test with the notebook.\n\n# You can modify anything here, add \"helper\" functions, more imports,\n# and so on, as long as the notebook runs and produces a meaningful\n# result (though not necessarily a good classifier). Document your\n# code with reasonable comments.\n\n# Function for Part 1\ndef preprocess(inputfile):\n return inputfile.readlines()\n\n# Code for part 2\nclass Instance:\n def __init__(self, neclass, features):\n self.neclass = neclass\n self.features = features\n\n def __str__(self):\n return \"Class: {} Features: {}\".format(self.neclass, self.features)\n\n def __repr__(self):\n return str(self)\n\ndef create_instances(data, pos_include = False, split_pos_vs_words = False):\n \"\"\"\n Will use start tokens (,,,,) and end tokens (,,,,).\n These will encode the distance from the start and end of sentence. \n We will also include and go past other named entities (NEs). I have decided that the actual\n names of other neighbouring entities themselves aren't relevant, so will have a generic tag for these. \n The tag can represent a named entity spanning more than one token. \n \"\"\"\n #need to append extra rows to data in order to avoid out-of-index errors. \n data_len = len(data)\n for i in range(1,6):\n data.insert(0,[-i,0,f'','NONE','O'])\n data.append([data[len(data)-1][0]+1,data[data_len-1][1]+1,f'','NONE','O'])\n\n #we iterate over the data not including the fake ones we just added (5 at beginning and end of list)\n instances = list()\n if split_pos_vs_words:\n instances_pos = list()\n \n for index in range(5, len(data)-5):\n entity_type = data[index][4]\n if entity_type == 'O':#dont do anything if the word isnt a NE\n continue\n if entity_type.split('-')[0] == 'I':\n continue\n #we only do the next bit for a word if it its the head (or B- tag) of a NE\n \n features_list = list()\n if split_pos_vs_words:\n features_list_pos_only = list()\n \n sent_num = data[index][1]\n crawl_count = 1 \n #the following generates the features list for before the target word\n while True:\n compared_entity_type = data[index - crawl_count][4]\n if sent_num == data[index - crawl_count][1]: #if word in the same sentence\n if pos_include == True:\n if split_pos_vs_words:\n features_list_pos_only.insert(0,data[index - crawl_count][3])#insert pos for neighbouring word\n else:\n features_list.insert(0,data[index - crawl_count][3])#insert pos for neighbouring word\n if compared_entity_type == 'O':\n features_list.insert(0,data[index - crawl_count][2])#insert neighbouring word (to feature)\n elif compared_entity_type.split('-')[0] == 'B':\n features_list.insert(0,'')#insert NE tag, the specific NE isn't relevant imo\n else:\n for i in range(1, 7 - crawl_count):\n features_list.insert(0,f'')\n break\n \n if crawl_count==5:\n break\n else:\n crawl_count+=1\n \n crawl_count = 1 \n while True:\n compared_entity_type = data[index - crawl_count][4]\n if sent_num == data[index + crawl_count][1]: #if word in the same sentence\n if pos_include == True:\n if split_pos_vs_words:\n features_list_pos_only.append(data[index - crawl_count][3])#insert pos for neighbouring word\n else:\n features_list.append(data[index - crawl_count][3])#insert pos for neighbouring word\n if compared_entity_type == 'O':\n features_list.append(data[index + crawl_count][2])\n elif compared_entity_type.split('-')[0] == 'B':\n features_list.append('')\n else:\n for i in range(1, 7 - crawl_count):\n features_list.append(f'')\n break\n \n if crawl_count==5:\n break\n else:\n crawl_count+=1\n \n \n instances.append(Instance(entity_type.split('-')[1], features_list))\n if split_pos_vs_words:\n instances_pos.append(Instance(entity_type.split('-')[1], features_list_pos_only))\n \n \n if split_pos_vs_words:\n return instances, instances_pos\n else:\n return instances\n\n# Code for part 3\ndef create_table(instances, top_freq=3000):\n \n #get most frequent words by iterating over all the documents\n #each word is an key/index; each value is the count itself\n all_words_count = dict()\n for instance in instances:\n for word in instance.features:\n all_words_count[word] = all_words_count.get(word, 0) + 1\n \n #following is an ordered list of the most frequent words in all texts:\n top_freq_words = [word_freq[0] for word_freq in sorted(all_words_count.items(), key=lambda x: x[1], reverse=True)][0:top_freq]\n \n #we can now generate the matrix row by row (doc by doc)\n #each row will be a list() in all_data\n all_data = list()\n for instance in instances:\n word_counts = np.zeros(len(top_freq_words)) #scaffold the row\n for word in instance.features:\n try:\n #for each word in the doc, we try to increment the count of each word in word_counts\n #using top_freq_words as an index, will pass if a word isn't in the top 3000 words\n word_counts[top_freq_words.index(word)] += 1\n except:\n pass\n #throw the whole row in all_data once finished with the sentence, adding the filename in the first column\n all_data.append( [instance.neclass] + list(word_counts) )\n #we is done, yeeee\n return pd.DataFrame(all_data, columns= ['class'] + top_freq_words )\n\ndef ttsplit(bigdf):\n df_train, df_test = train_test_split(bigdf, test_size=0.2)\n \n return df_train.drop('class', axis=1).to_numpy(), df_train['class'], df_test.drop('class', axis=1).to_numpy(), df_test['class']\n\n# Code for part 5\n\ndef confusion_matrix(truth, predictions):\n truth = list(truth)\n predictions = list(predictions)\n \n classes_list = list()\n for i in range(len(truth)):\n if truth[i] not in classes_list:\n classes_list.append(truth[i])\n if predictions[i] not in classes_list:\n classes_list.append(predictions[i])\n \n classes_nested_dict = dict()\n for i in classes_list:\n classes_nested_dict[i] = dict()\n for j in classes_list:\n classes_nested_dict[i][j] = 0\n \n for i in range(len(truth)):\n classes_nested_dict[truth[i]][predictions[i]] += 1\n \n truth_list = list()\n for key_truth, value_truth in classes_nested_dict.items():\n pred_list = list()\n for key_pred, value_pred in value_truth.items():\n pred_list.append(value_pred)\n truth_list.append(pred_list)\n \n df_confusion = pd.DataFrame(np.array(truth_list),columns=classes_list,index=classes_list)\n \n return df_confusion\n\ndef info_associated_w_cf(truth, predictions):\n truth = list(truth)\n predictions = list(predictions)\n confusion_dict = dict()\n for i in range(len(truth)):\n if truth[i] not in confusion_dict:\n confusion_dict[truth[i]] = { 'tp':0, 'tn':0, 'fn':0, 'fp':0 }\n if predictions[i] not in confusion_dict:\n confusion_dict[predictions[i]] = { 'tp':0, 'tn':0, 'fn':0, 'fp':0 }\n \n for key in confusion_dict.keys():\n for i in range(len(truth)):\n if (key == truth[i]) and (key == predictions[i]):\n confusion_dict[key]['tp'] += 1\n elif (key == truth[i]):\n confusion_dict[key]['fn'] += 1\n elif (key == predictions[i]):\n confusion_dict[key]['fp'] += 1\n else:\n confusion_dict[key]['tn'] += 1\n \n for key in confusion_dict.keys():\n correct_sum = confusion_dict[key]['tp'] + confusion_dict[key]['tn']\n wrong_sum = confusion_dict[key]['fp'] + confusion_dict[key]['fn']\n confusion_dict[key]['correct_percentage'] = correct_sum/(correct_sum+wrong_sum)\n confusion_dict[key]['wrong_percentage'] = wrong_sum/(correct_sum+wrong_sum)\n \n return confusion_dict\n\n# Code for bonus part B\ndef bonusb(filename):\n pass\n","sub_path":"a2.py","file_name":"a2.py","file_ext":"py","file_size_in_byte":9034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"365773415","text":"from indexer.info import Info\nfrom indexer.body import Body\nfrom pathlib import Path\nfrom bs4 import BeautifulSoup\nimport json\nimport getopt\nimport sys\nimport logging\n\n\nlogging.basicConfig(level=logging.INFO)\ninput_directory = output_file = None\n\ndef usage():\n print(f\"usage: {sys.argv[0]} -i case_directory -o output.json\")\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], 'i:o:')\nexcept getopt.GetoptError:\n usage()\n sys.exit(2)\n\nfor opt, arg in opts:\n if opt == '-i':\n input_directory = arg\n elif opt == '-o':\n output_file = arg\n else:\n assert False, \"unknown option\"\n\nif input_directory is None or output_file is None:\n usage()\n sys.exit(2)\n\npath = Path(input_directory)\ndata = []\n\nfor i, in_file in enumerate(sorted(path.glob('*.htm*'))):\n with open(in_file, 'r') as read_file:\n logging.info(f'Processing: \"{in_file}\"')\n soup = BeautifulSoup(read_file, 'lxml')\n case = Info.index(soup)\n case['paragraphs'] = Body.index(soup)\n data.append(case)\n\nwith open(output_file, 'w') as w:\n logging.info(f'Writing JSON to {output_file}')\n json.dump(data, w, indent=2)\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"444478034","text":"from geodata import *\n\npath = r'\\\\172.21.195.2\\thematic\\!projects\\Rucode\\images_fin\\composits\\8_ch'\nout = r'e:\\rks\\source\\kanopus_test\\Rucode\\composite\\test\\8_bands'\nnames = folder_paths(path,1,'tif')\nsource = r'e:\\rks\\source\\kanopus_test\\Rucode\\source'\noutxls = r'e:\\rks\\source\\kanopus_test\\Rucode\\reproject\\komposit_list.xls'\n\ndef GetRasterDataParams(path):\n raster = gdal.Open(path)\n if raster:\n params = [raster.RasterXSize, raster.RasterYSize]\n for num in range(1, raster.RasterCount+1):\n band = raster.GetRasterBand(num)\n params.append(flist(band.GetStatistics(1,1), round))\n return params\n\ndef RasterMatchCheck(files):\n matches = []\n data_params = flist(files, GetRasterDataParams)\n scroll(data_params)\n for i, param1 in enumerate(data_params):\n if param1 is not None:\n for j, param2 in enumerate(data_params):\n if param2 is not None:\n if i!=j:\n if param1==param2:\n matches.append((files[i],files[j]))\n return matches\n\nscroll(RasterMatchCheck(folder_paths(r'\\\\172.21.195.2\\exchanger\\fetsival',1,'tif')))\n\n\nsys.exit()\nxls = xls_to_dict(r'\\\\172.21.195.2\\thematic\\!SPRAVKA\\S3\\report_KV_fall.xls')\nout = r'e:\\rks\\source\\kv_fall'\nres = []\nfor jpg in xls:\n if int(xls[jpg]['mark'])==1:\n f,n,e = split3(jpg)\n res.append(n)\nwith open(r'C:\\Users\\admin\\Desktop\\list5.txt', 'w') as txt:\n txt.write('\\n'.join(res))\n\n\nfor file in names:\n name = split3(file)[1]\n basics = name.split('.L2')\n old = basics[0] + '.L2'\n new = basics[1] + '.L2'\n if 'RRG' in basics[2]:\n continue\n channels = [1,2,3,4,1,2,3,4]\n line = OrderedDict()\n for file in source_files:\n if old in file:\n line['old'] = old\n elif new in file:\n line['new'] = new\n if line.get('old') and line.get('new'):\n line['composit'] = name\n line['channels'] = '1,2,3,4,1,2,3,4'\n report[name] = line\n else:\n print('Wrong name: %s' % name)\n\ndict_to_xls(outxls,report)\n","sub_path":"__temp.py","file_name":"__temp.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"418752641","text":"import sys\nimport random\nimport string\n\nprint(\"ape [alpha 1]\\n\")\n\n\ninputFile = open(sys.argv[1])\ninputFileCode = inputFile.read().split(\"\\n\")\n\ndef processString(str):\n if str[0] == \"\\\"\" and str[-1] == \"\\\"\":\n return {\"type\": \"string\", \"value\": str[1:-1]}\n else:\n return {\"type\": \"var\", \"value\": str}\n\nsectionStart = []\nvariables = {}\nsections = []\n\ninlineParentInstruction = None\n\nfor line in inputFileCode:\n lineSplit = line.split(\" \")\n\n if lineSplit[0] == \"}\":\n if inlineParentInstruction is None:\n print(\"YOU'RE ENDING AN INLINE YOU NEVER STARTED DUMBASS!\")\n sys.exit()\n sectionStart.append(inlineParentInstruction)\n inlineParentInstruction = None\n\n if lineSplit[0] == \"var\":\n if lineSplit[2] == \"=\":\n processedString = processString(\" \".join(lineSplit[3:]))\n if processedString.get(\"type\") == \"string\":\n variables[lineSplit[1]] = processedString[\"value\"]\n if lineSplit[0] == \"if\":\n if inlineParentInstruction is not None:\n print(\"YOU CAN'T USE INLINE CODE INSIDE OF INLINE CODE!\")\n sys.exit()\n comparisonX = lineSplit[1]\n comparisonY = lineSplit[3]\n if lineSplit[2] == \"==\" and lineSplit[4] == \"{\":\n if comparisonX in variables and comparisonY in variables:\n inlineParentInstruction = [\"if\", [comparisonX, comparisonY], []]\n else:\n print(\"Invalid variables used in statement\") \n else:\n # check if function\n functionSplit = line.split(\"(\")\n if len(functionSplit) > 1:\n arguments = functionSplit[1].split(\")\")[0]\n arguments = arguments.split(\",\")\n if functionSplit[0] == \"print\":\n processedString = processString(arguments[0])\n if processedString.get(\"type\") == \"string\":\n randomStr = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n newVar = \"unnamed_var_\" + randomStr\n variables[newVar] = processedString[\"value\"]\n\n instruction = [\"print\", newVar]\n if inlineParentInstruction is None:\n sectionStart.append(instruction)\n else:\n inlineParentInstruction[2].append(instruction)\n elif processedString.get(\"type\") == \"var\":\n if processedString.get(\"value\") in variables:\n instrucion = [\"print\", processedString.get(\"value\")]\n if inlineParentInstruction is None:\n sectionStart.append(instruction)\n else:\n inlineParentInstruction[2].append(instruction)\n else:\n print(\"error: \" + processedString.get(\"value\") + \" is not a variable!!!\")\n\nprint(variables)\nprint(sectionStart)\n\ndef parseInstructions(instructions):\n parsedLines = []\n for instruction in instructions:\n print(\"3\")\n if instruction[0] == \"print\":\n parsedLines.append(\"\\tmov rax,1\")\n parsedLines.append(\"\\tmov rdi,1\")\n parsedLines.append(\"\\tmov rsi,\" + instruction[1])\n parsedLines.append(\"\\tmov rdx,\" + instruction[1] + \"_SYSTEM_LEN\")\n parsedLines.append(\"\\tsyscall\")\n elif instruction[0] == \"if\":\n parsedLines.append(\"\\tmov eax,[\" + instruction[1][0] + \"]\")\n parsedLines.append(\"\\tmov ebx,[\" + instruction[1][1] + \"]\")\n parsedLines.append(\"\\tcmp eax,ebx\")\n randomName = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n successJump = \".SUCCESS_\" + randomName\n parsedLines.append(\"\\tje \" + successJump)\n \n sections.append([successJump, instruction[2]])\n return parsedLines\n\nfinalFileLines = []\nfinalFileLines.append(\"global _start\")\nfinalFileLines.append(\"section .data\")\nfor var in variables:\n finalFileLines.append(\"\\t\" + var + \": db '\" + variables[var] + \"',\" + str(len(variables[var])))\n finalFileLines.append(\"\\t\" + var + \"_SYSTEM_LEN: equ $-\" + var)\n\nfinalFileLines.append(\"section .text\")\n\nfinalFileLines.append(\"_start:\")\nfor line in parseInstructions(sectionStart):\n finalFileLines.append(line)\nfinalFileLines.append(\"\\tjmp .end\")\n\nfor section in sections:\n finalFileLines.append(section[0] + \":\")\n for instructions in parseInstructions(section[1]):\n finalFileLines.append(instructions)\n finalFileLines.append(\"\\tjmp .end\")\n\nfinalFileLines.append(\".end:\")\nfinalFileLines.append(\"\\tmov rax,60\")\nfinalFileLines.append(\"\\txor rdi,rdi\")\nfinalFileLines.append(\"\\tsyscall\")\n\nfinalFile = \"\\n\".join(finalFileLines)\n\noutputFile = open(\"output.asm\", \"w\")\noutputFile.write(finalFile)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"46106008","text":"from torchvision import datasets\nfrom torchvision.transforms import ToTensor\nfrom Dpex import dataloader\nfrom torch.utils.data.distributed import DistributedSampler\nimport torch.nn as nn\nimport torch\nimport matplotlib.pyplot as plt\nimport time\nfrom torch.autograd import Variable\n\ntorch.distributed.init_process_group(backend=\"nccl\")\n# 2) 配置每个进程的gpu\nlocal_rank = torch.distributed.get_rank()\ntorch.cuda.set_device(local_rank)\ndevice = torch.device(\"cuda\", local_rank)\n\nclass FashionCNN(nn.Module):\n\n def __init__(self):\n super(FashionCNN, self).__init__()\n\n self.layer1 = nn.Sequential(\n nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, padding=1),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2)\n )\n\n self.layer2 = nn.Sequential(\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.MaxPool2d(2)\n )\n\n self.fc1 = nn.Linear(in_features=64 * 6 * 6, out_features=600)\n self.drop = nn.Dropout2d(0.25)\n self.fc2 = nn.Linear(in_features=600, out_features=120)\n self.fc3 = nn.Linear(in_features=120, out_features=10)\n\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = out.view(out.size(0), -1)\n out = self.fc1(out)\n out = self.drop(out)\n out = self.fc2(out)\n out = self.fc3(out)\n\n return out\n\n\ntraining_data = datasets.FashionMNIST(\n root=\"data\",\n train=True,\n download=True,\n transform=ToTensor()\n)\ntest_data = datasets.FashionMNIST(\n root=\"data\",\n train=False,\n download=True,\n transform=ToTensor()\n)\n\nmodel = FashionCNN()\n\nerror = nn.CrossEntropyLoss()\n\nlearning_rate = 0.001\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\ntrain_loader = dataloader.DpexDataLoader(training_data, sampler=DistributedSampler(training_data), distribute_mode=True, num_workers=4, batch_size=100)\ntest_loader = dataloader.DpexDataLoader(test_data, sampler=DistributedSampler(test_data), distribute_mode=True, num_workers=1, batch_size=100)\n\nnum_epochs = 1\ncount = 0\n# Lists for visualization of loss and accuracy\nloss_list = []\niteration_list = []\naccuracy_list = []\n\n# Lists for knowing classwise accuracy\npredictions_list = []\nlabels_list = []\n\nif torch.cuda.is_available():\n model.cuda()\n\nif torch.cuda.device_count() > 1:\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n # 5) 封装\n model = torch.nn.parallel.DistributedDataParallel(model,\n device_ids=[local_rank],\n output_device=local_rank)\n\nfor epoch in range(num_epochs):\n for images, labels in train_loader:\n # Transfering images and labels to GPU if available\n images, labels = images.to(device), labels.to(device)\n\n train = Variable(images.view(100, 1, 28, 28))\n labels = Variable(labels)\n\n # Forward pass\n outputs = model(train)\n loss = error(outputs, labels)\n\n # Initializing a gradient as 0 so there is no mixing of gradient among the batches\n optimizer.zero_grad()\n\n # Propagating the error backward\n loss.backward()\n\n # Optimizing the parameters\n optimizer.step()\n\n count += 1\n\n # Testing the model\n if not (count % 50): # It's same as \"if count % 50 == 0\"\n total = 0\n correct = 0\n print(f\"iteration count is {count}\")\n\n for images, labels in test_loader:\n images, labels = images.to(device), labels.to(device)\n labels_list.append(labels)\n\n test = Variable(images.view(100, 1, 28, 28))\n\n outputs = model(test)\n\n predictions = torch.max(outputs, 1)[1].to(device)\n predictions_list.append(predictions)\n correct += (predictions == labels).sum()\n\n total += len(labels)\n\n accuracy = correct * 100 / total\n loss_list.append(loss.data)\n iteration_list.append(count)\n accuracy_list.append(accuracy)\n\n print(\"Iteration: {}, Loss: {}, Accuracy: {}%\".format(count, loss.data, accuracy))\n\n\nplt.plot(iteration_list, loss_list)\nplt.xlabel(\"No. of Iteration\")\nplt.ylabel(\"Loss\")\nplt.title(\"Iterations vs Loss\")\nplt.show()\n\n\n","sub_path":"tests/fashion_mnist_train_test_ddp.py","file_name":"fashion_mnist_train_test_ddp.py","file_ext":"py","file_size_in_byte":4482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"70392336","text":"from rest_framework.authentication import BaseAuthentication\nfrom rest_framework import exceptions\nfrom apiapp.models import User\n\n\nclass MyAuth(BaseAuthentication):\n\n def authenticate(self, request):\n\n auth = request.META.get('HTTP_AUTHORIZATION', None)\n print(auth)\n if auth is None:\n return None\n auth_list = auth.split()\n if not (len(auth_list) == 2 and auth_list[0].lower() == 'auth'):\n raise exceptions.APIException('认证信息格式有误')\n if auth_list[1] != 'william.abc.123':\n raise exceptions.APIException('校验失败')\n user = User.objects.filter(username='du-web').first()\n if not user:\n raise exceptions.APIException('用户不存在')\n return (user, None)\n\n\n","sub_path":"apiapp/authenticator.py","file_name":"authenticator.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"407228257","text":"from PyQt5.QtCore import QTimer\nfrom PyQt5.QtGui import QCloseEvent\n\nfrom src.config import Config\nfrom src.controller import Controller\nfrom src.data_processing.consumer_factory import ConsumerFactory\nfrom src.domain_error import DomainError\nfrom src.message_type import MessageType\nfrom src.realtime.serial_data_producer import SerialDataProducer, NoConnectedDeviceException\nfrom src.save import SaveManager, SaveStatus\nfrom src.ui.real_time_widget import RealTimeWidget\nfrom src.ui.motor_widget import MotorWidget\n\n\nclass RealTimeController(Controller):\n def __init__(self, real_time_widget: RealTimeWidget, motor_widget: MotorWidget, serial_data_producer: SerialDataProducer,\n consumer_factory: ConsumerFactory, save_manager: SaveManager, config: Config, timer: QTimer):\n super().__init__(real_time_widget, motor_widget, serial_data_producer, consumer_factory, config, timer)\n self.save_manager = save_manager\n\n self.data_widget.set_target_altitude(self.target_altitude)\n self.data_widget.set_button_callback(self.real_time_button_callback)\n\n def update_ui(self):\n super().update_ui()\n self.update_timer()\n\n def update_timer(self):\n self.data_widget.set_time(self.consumer[\"time_stamp\"][-1])\n\n def real_time_button_callback(self):\n if not self.is_running:\n try:\n if self.data_producer.has_unsaved_data():\n save_status = self.save_manager.save()\n\n if save_status == SaveStatus.CANCELLED:\n return\n\n self.data_producer.clear_rocket_packets()\n self.data_widget.reset()\n self.create_new_consumer(self.current_config.rocket_packet_config.version)\n\n self.start_updates()\n except (DomainError, NoConnectedDeviceException) as error:\n self.is_running = False\n self.notify_all_message_listeners(str(error), MessageType.ERROR)\n else:\n self.stop_updates()\n\n self.data_widget.update_button_text(self.is_running)\n\n def on_close(self, event: QCloseEvent):\n if self.data_producer.has_unsaved_data():\n save_status = self.save_manager.save()\n\n if save_status == SaveStatus.CANCELLED:\n event.ignore()\n return\n\n if self.is_running:\n self.stop_updates()\n\n event.accept()\n\n def activate(self, _):\n self.data_widget.update_button_text(self.is_running)\n\n def deactivate(self) -> bool:\n if self.data_producer.has_unsaved_data():\n save_status = self.save_manager.save()\n\n if save_status == SaveStatus.CANCELLED:\n return False\n\n if self.is_running:\n self.stop_updates()\n\n self.data_producer.clear_rocket_packets()\n self.data_widget.reset()\n\n return True\n","sub_path":"BaseStation/src/real_time_controller.py","file_name":"real_time_controller.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"406211469","text":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, LSTM\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.utils import np_utils\n\n# loading the dataset\nfilename='input.txt'\nraw_text = open(filename).read()\n\n# Preprocessing\nnew_raw_text = \"\"\nfor i in raw_text:\n if ('a'<= i <= 'z') or ('A'<= i <= 'Z') or (i == ' '):\n new_raw_text += i\n else:\n new_raw_text += ' '\n\nraw_text = new_raw_text\n\n# Create mapping of unique chars to integers\nchars = sorted(list(set(raw_text)))\nchar_to_int = dict((c, i) for i, c in enumerate(chars))\n\n# sumarize\nn_chars = len(raw_text)\nn_vocab = len(chars)\n\n# prepare the dataset of input to output pairs encoded as integers\nseq_length = 100\ndataX = []\ndataY = []\n\nfor i in range(0, n_chars - seq_length, 1):\n seq_in = raw_text[i: i + seq_length]\n seq_out = raw_text[i + seq_length]\n dataX.append([char_to_int[char] for char in seq_in])\n dataY.append(char_to_int[seq_out])\n\n# total number of pattens\nn_patterns = len(dataX)\n\n# reshape X to be [samples, time steps, features]\nX = np.reshape(dataX, (n_patterns, seq_length, 1))\n\n# normalize\nX = X / float(n_vocab)\n\n# one hot encode the output variable\ny = np_utils.to_categorical(dataY)\n\n\n# Defining the model\nmodel = Sequential()\nmodel.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True)) \nmodel.add(Dropout(0.2))\nmodel.add(LSTM(256))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(y.shape[1], activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam')\n\n\n# define the checkpoint\nfilepath=\"models/weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')\ncallbacks_list = [checkpoint]\n# fit the model\nmodel.fit(X, y, epochs=1000, batch_size=40, callbacks=callbacks_list)\n\n\n\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"150615896","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport MySQLdb\nimport datetime\nimport math as m\nimport warnings as w\n\nclass DB():\n\n def __init__(self, host='localhost', user='root', password='', database='', debugfile=None, cursor=None):\n self.__host = host\n self.__user = user\n self.__password = password\n self.__database = database\n self.debugfile = debugfile\n self.maxnumrows = float(5000)\n self.__openSession()\n # self.__setCursor(cursor)\n self.useDictCursor()\n w.filterwarnings('error', category=MySQLdb.Warning) # MySQL-Warnings werden hierdurch in Exceptions verwandelt. \n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.__closeSession()\n\n def __openSession(self):\n try:\n self.cnx = MySQLdb.connect(host = self.__host, user = self.__user, passwd = self.__password, db = self.__database, charset='utf8')\n self.__log(\"Verbindung zu {0} ersellt.\".format(self.__host))\n except MySQLdb.Error as e:\n self.__log(\"Error {}: {}\".format(e.args[0],e.args[1]))\n\n def __setCursor(self, cursor = None):\n if cursor:\n self.cur = self.cnx.cursor(cursor)\n else:\n self.cur = self.cnx.cursor()\n self.__log(\"Cursor {0} eingerichtet.\".format(cursor))\n\n def useSSCursor(self):\n self.__setCursor(MySQLdb.cursors.SSCursor)\n\n def useDictCursor(self):\n self.__setCursor(MySQLdb.cursors.DictCursor)\n\n\n def __execQuery(self, query):\n self.__log(query)\n try:\n self.cur.execute(query)\n except MySQLdb.Error as e:\n self.__log(\"Error {}: {}\".format(e.args[0],e.args[1]))\n\n\n def __closeSession(self):\n self.cur.close()\n self.cnx.close()\n self.__log(\"Verbindung erfolgreich getrennt.\")\n\n\n def __log(self, text):\n output = \"{}: {}\\n\".format(datetime.datetime.now(), text)\n if self.debugfile:\n with open(self.debugfile, 'a') as f:\n f.write(output)\n else:\n print(output)\n\n\n def __getDataTypes(self, table, columns):\n query = \"\"\"select a.COLUMN_NAME, a.DATA_TYPE\n from information_schema.`COLUMNS` as a\n where a.TABLE_NAME = '{0}' and a.TABLE_SCHEMA = '{1}'\n order by a.ORDINAL_POSITION\"\"\".format(table, self.__database)\n result = self.queryToArray(query)\n datatypes = {}\n for row in result:\n if row[\"COLUMN_NAME\"] in columns:\n datatypes[row[\"COLUMN_NAME\"]] = row[\"DATA_TYPE\"]\n return datatypes\n \n\n def __formatRow(self, row, datatypes):\n formattedvals = []\n if len(row) != len(datatypes):\n self.__log(\"row und datatypes unterschiedlich lang! \\n row: {} \\n dat: {}\".format(row, datatypes))\n raise\n for colName in row:\n colValue = row[colName]\n colDatatype = datatypes[colName]\n if colValue == None:\n formattedvals.append('Null')\n elif colValue == '' and colDatatype not in ['enum', 'set', 'timestamp', 'year', 'date', 'datetime', 'time', 'binary', 'varbinary', 'tinyblob', 'mediumblob', 'longblob', 'blob', 'char', 'varchar', 'tinytext', 'text', 'mediumtext', 'longtext']:\n formattedvals.append('Null') \n elif colDatatype in ['enum', 'set', 'timestamp', 'year', 'date', 'datetime', 'time', 'binary', 'varbinary', 'tinyblob', 'mediumblob', 'longblob', 'blob', 'char', 'varchar', 'tinytext', 'text', 'mediumtext', 'longtext']:\n sval = str(colValue)\n seval = sval.replace(\"'\", \"''\"); # MySQL: A “'” inside a string quoted with “'” may be written as “''”\n formattedvals.append(\"'\"+seval+\"'\")\n else:\n formattedvals.append(str(colValue))\n return formattedvals\n\n\n def __insertRowsBatch(self, table, datatypes, rows):\n if not rows:\n return\n cols = rows[0].keys()\n query = \"insert into {0} ({1}) values \\n\".format(table, \",\".join(cols))\n for row in rows:\n formattedvals = self.__formatRow(row, datatypes)\n query += \"( {} ),\\n\".format(\",\".join(formattedvals))\n query = query[:-2]\n self.__execQuery(query)\n\n\n def insertRows(self, table, rows):\n if not rows:\n return\n cols = rows[0].keys()\n datatypes = self.__getDataTypes(table, cols)\n batches = int(m.ceil(len(rows)/self.maxnumrows))\n for n in range(batches):\n start = int(n*self.maxnumrows)\n end = int(min((n+1)*self.maxnumrows, len(rows)))\n self.__insertRowsBatch(table, datatypes, rows[start:end])\n\n\n def queryToArray(self, query):\n result = []\n self.__execQuery(query)\n for row in self.cur:\n result.append(row)\n return result\n\n def querySingleToArray(self, query):\n result = self.queryToArray(query)\n sr = [r[0] for r in result]\n return sr\n\n def queryToDicts(self, query):\n self.useDictCursor()\n result = self.queryToArray(query)\n return result\n\n def fetchColNames(self, table):\n cols = []\n query = \"\"\"select a.COLUMN_NAME from information_schema.`COLUMNS` as a \n where a.TABLE_NAME = '{0}' and a.TABLE_SCHEMA = '{1}'\n order by a.ORDINAL_POSITION\"\"\".format(table, self.__database)\n self.__execQuery(query)\n for col in self.cur:\n cols.append(col[0])\n return cols\n\n def execRawQuery(self, query):\n self.__execQuery(query)\n \n\nif __name__ == \"__main__\":\n \"\"\" By using 'with', the metods __enter__ and __exit__ are called.\n We use this to only start and close a session once. \"\"\"\n with DB(host, user, password, database, debugfile, cursor) as db:\n result = db.queryToArray(\"select * from tableA\")\n\n","sub_path":"DB.py","file_name":"DB.py","file_ext":"py","file_size_in_byte":6005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"649438082","text":"#!/usr/bin/python3\n\ndef main():\n try:\n fh = open('lines.txt')\n except IOError as e:\n print('Could not open file, Come back with the file Please.', e)\n else:\n for line in fh: print(line.strip())\nif __name__ == \"__main__\": main()\n","sub_path":"exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"181520193","text":"import math\r\n\r\nimport torch.nn.functional as F\r\nfrom torch import nn\r\n\r\n\r\n\r\n\r\n\r\nclass Discriminator(nn.Module):\r\n def __init__(self):\r\n super(Discriminator, self).__init__()\r\n self.net = nn.Sequential(\r\n nn.Conv2d(3, 64, kernel_size=3, padding=1),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1),\r\n nn.BatchNorm2d(64),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(64, 128, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(128),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(128, 128, kernel_size=3, stride=2, padding=1),\r\n nn.BatchNorm2d(128),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(128, 256, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(256),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(256, 256, kernel_size=3, stride=2, padding=1),\r\n nn.BatchNorm2d(256),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(256, 512, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(512),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.Conv2d(512, 512, kernel_size=3, stride=2, padding=1),\r\n nn.BatchNorm2d(512),\r\n nn.LeakyReLU(0.2),\r\n\r\n nn.AdaptiveAvgPool2d(1),\r\n nn.Conv2d(512, 1024, kernel_size=1),\r\n nn.LeakyReLU(0.2),\r\n nn.Conv2d(1024, 1, kernel_size=1)\r\n )\r\n\r\n def forward(self, x):\r\n batch_size = x.size(0)\r\n return F.sigmoid(self.net(x).view(batch_size))\r\n \r\n #def set_multiple_gpus(self):\r\n # here uses multi gpu\r\n #elf.net = nn.DataParallel(self.net).cuda()\r\n #self.sigmoid = nn.DataParallel(self.sigmoid).cuda()\r\n\r\n\r\nclass ResidualBlock(nn.Module):\r\n def __init__(self, channels):\r\n super(ResidualBlock, self).__init__()\r\n self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)\r\n self.bn1 = nn.BatchNorm2d(channels)\r\n self.prelu = nn.PReLU()\r\n self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)\r\n self.bn2 = nn.BatchNorm2d(channels)\r\n\r\n def forward(self, x):\r\n residual = self.conv1(x)\r\n residual = self.bn1(residual)\r\n residual = self.prelu(residual)\r\n residual = self.conv2(residual)\r\n residual = self.bn2(residual)\r\n\r\n return x + residual\r\n\r\n\r\nclass UpsampleBLock(nn.Module):\r\n def __init__(self, in_channels, up_scale):\r\n super(UpsampleBLock, self).__init__()\r\n self.conv = nn.Conv2d(in_channels, in_channels * up_scale ** 2, kernel_size=3, padding=1)\r\n self.pixel_shuffle = nn.PixelShuffle(up_scale)\r\n self.prelu = nn.PReLU()\r\n\r\n def forward(self, x):\r\n x = self.conv(x)\r\n x = self.pixel_shuffle(x)\r\n x = self.prelu(x)\r\n return x","sub_path":"ours/super_resolution/SRResNet/scripts_retrain/srgan/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"120139776","text":"\"\"\"\nA python program sends 'Hello World' to the WSL with port 8888.\n\"\"\"\nimport socket\nfrom subprocess import run, PIPE\nimport re\n\nPORT = 8888\nMESSAGE = 'Hello World'\n\nwsl2_ip = re.search('\\sinet ((?:\\d+\\.){3}\\d+)/', run('wsl -e ip -4 addr show dev eth0'.split(), stdout=PIPE, encoding='utf8', check=True).stdout)[1]\nprint('sending ' + MESSAGE + ' to ' + wsl2_ip)\nwith socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n s.connect((wsl2_ip, PORT))\n print(s.send(MESSAGE))\n","sub_path":"WSL/udp_to_wsl.py","file_name":"udp_to_wsl.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"396091183","text":"import json\nimport jieba\n\nfrom hanziconv import HanziConv\n\ndef load_jieba_dic(dic_path):\n jieba.load_userdict(dic_path)\n\ndef load_dic(dic_path):\n json_str = ''\n with open(dic_path,'r',encoding='utf-8') as op:\n for text in op:\n json_str += text.strip()\n dictionary=json.loads(json_str)\n simple_to_traditional_dict = dict()\n traditional_to_simple_dict = dict()\n for index in range(0,len(dictionary['dic']),2):\n simple_to_traditional_dict[dictionary['dic'][index]] = dictionary['dic'][index+1]\n traditional_to_simple_dict[dictionary['dic'][index+1]] = dictionary['dic'][index]\n return simple_to_traditional_dict,traditional_to_simple_dict\n\n\ndef to_simple(sentence):\n trans_sentence = ''\n for word in jieba.cut(sentence):\n print(word)\n\n if word in traditiona_to_simple_dict.keys():\n trans_sentence += traditiona_to_simple_dict[word]\n else:\n trans_sentence += word\n return trans_sentence\n\ndef to_traditional(sentence):\n trans_sentence = ''\n for word in jieba.cut(sentence):\n if word in simple_to_traditional_dict.keys():\n trans_sentence += simple_to_traditional_dict[word]\n else:\n trans_sentence += word\n return trans_sentence\n\nsimple_to_traditional_dict, traditiona_to_simple_dict = load_dic('NLP_TOOL/tr_sim_dic.txt')\nload_jieba_dic('NLP_TOOL/Taiwan_Jieba_dic.txt')\nif __name__ == '__main__':\n sen = '我很喜歡吃飯糰'\n print(to_simple(sen))\n print(HanziConv.toSimplified(sen))","sub_path":"ZH_Simple_Traditional.py","file_name":"ZH_Simple_Traditional.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"209175496","text":"def get_children(tri, m, n):\n # Creates an empty list to store the children of the element\n # (The two elements directly below and adjacent to it)\n children = []\n #Tthe returned list contains the two elements directly\n # above and adjacent to the element in the triangle grid\n for i in range(2):\n children.append(tri[m + 1][n + i])\n return children\n\n\ndef get_parents(tri, m, n):\n # Creates an empty list to store the parent(s) of the element\n # (The two element(s) directly above and adjacent to it)\n parents = []\n # If the element is the first in the list, then it has only\n # one parent\n if n + 1 >= len(tri[m - 1]):\n return [tri[m - 1][n - 1]]\n # Otherwise, the returned list contains the two elements\n # directly above and adjacent to the element in the triangle grid\n for i in range(2):\n parents.append(tri[m - 1][n + i])\n return parents\n\n# Dynamic method to calculate the maximum sum of a path of elements\n# in a triangle grid\n\n\ndef get_max_path(tri):\n\n # Starts with the line just before the last line in the\n # triangle grid and continues until all lines have been\n # checked and replaced by their optimized pairings\n\n while len(tri) > 1:\n # Gets the current line in the grid whose values are to be checked\n currentLine = tri[-2]\n\n # Creates a variable to store the value of the new line\n # which will be replaced by its optimized values\n newLine = []\n\n # Goes through each value in the current line\n # and determines the value's largest child. Then,\n # the sum of the element and its largest child is\n # added to newLine as one of the optimized values\n for j in range(len(currentLine)):\n currentNum = currentLine[j]\n currentChildren = get_children(tri, -2, j)\n newLine.append(currentNum + max(currentChildren))\n # print(currentNum + max(currentChildren))\n\n # After determining all the optimized values for the current line,\n # the last line of the triangle is deleted and the line that was just\n # before it (which was the line that was just being checked) is\n # replaced by the newLine, which is the optimized pairings of these\n # two previous lines. newLine has a length of one less than that of\n # the last line in the triangle, which was just deleted.\n # Ultimately, the most optimized line will be all that's left,\n # and it will have a length of 1\n del tri[-1]\n tri[-1] = newLine\n\n return tri[0][0]\n\n while len(tri) > 1:\n currentLine = tri[-2]\n numWithBiggestChild = currentLine[0]\n biggestChild = get_children(tri, -2, 0)[0]\n\n newLine = []\n for j in range(len(currentLine)):\n currentNum = currentLine[j]\n currentChildren = get_children(tri, -2, j)\n # print(currentNum + max(currentChildren))\n newLine.append(currentNum + max(currentChildren))\n del tri[-1]\n tri[-1] = newLine\n\n return tri[0][0]\n\ntriangle = []\n\ntriangleFile = open(\"67.txt\", \"r\")\n\nfor s in triangleFile.readlines():\n triangle.append(list(map(int, s.split())))\n\ntriangleFile.close()\n\nprint(get_max_path(triangle))\n","sub_path":"67.py","file_name":"67.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"277923560","text":"from Data import Data\nfrom LogBoxSD import LogBoxSD\n\n\nclass Monitor:\n # Class provides methods to query for data in the SDCard of LogBoxSD\n def __init__(self, connection):\n self.logBoxSD = LogBoxSD(connection)\n\n # get_data: Datetime -> Array\n # Return all registers for the date\n def get_data(self, date):\n self.logBoxSD.service_mode_state()\n self.logBoxSD.sd_mode()\n file_number = self.__get_file_number(date)\n return self.__parse_data(self.logBoxSD.get_file_data(file_number))\n\n def __get_file_number(self, date):\n for file_name in self.logBoxSD.list_files():\n if date == self.__get_date_of_file_name(file_name):\n return self.__get_file_number_of_file_name(file_name)\n return -1\n\n def __parse_data(self, registers):\n parsed_registers = []\n for register in registers:\n parsed_registers.append(self.__parse_register(register))\n return parsed_registers\n\n @staticmethod\n def __get_date_of_file_name(file_name):\n if \"SD card size:\" in file_name:\n return -1\n split = file_name.split(\" \")\n return split[3]\n\n @staticmethod\n def __get_file_number_of_file_name(file_name):\n return int(file_name.split(\" \")[0][4:-4])\n\n @staticmethod\n def __parse_register(split):\n data = Data(\n date=split[0],\n time=split[1],\n data1=split[3],\n data2=split[6],\n data3=split[9]\n )\n\n return data\n","sub_path":"Monitor.py","file_name":"Monitor.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"429772562","text":"def longest_substring_different_characters(s: str) -> int:\n if len(s.strip()) == 0:\n return 0\n substring = \"\"\n longest_substring = 0\n first_char, second_char = \"\", \"\"\n for character in s:\n if character in substring:\n substring += character\n else:\n if first_char == \"\" or second_char == \"\":\n substring += character\n if first_char == \"\":\n first_char = character\n else:\n second_char = character\n else:\n new_starting_position = min(substring.rfind(first_char), substring.rfind(second_char)) + 1\n first_char = substring[new_starting_position]\n second_char = character\n substring = substring[new_starting_position: ] + character\n longest_substring = max(longest_substring, len(substring))\n return longest_substring\n\n","sub_path":"Year One/longest_substring_different_characters.py","file_name":"longest_substring_different_characters.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"301033553","text":"from setuptools import setup\nfrom setuptools.command.build_ext import build_ext as _build_ext\n\ninstall_requires = [\n 'cython',\n 'numpy',\n 'pysam',\n 'h5py',\n 'pandas>=0.23.0',\n 'slugid',\n 'numpy',\n 'scipy==1.0.1',\n 'cooler',\n 'pybbi==0.1.3',\n]\n\nsetup(\n name='hgtiles',\n version='0.2.14',\n description='Tile loading for higlass-server',\n author='Peter Kerpedjiev',\n author_email='pkerpedjiev@gmail.com',\n url='',\n install_requires=install_requires,\n setup_requires=['numpy'],\n packages=['hgtiles']\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"607363153","text":"from .base import FunctionalTest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n\nclass NewVisitorTest(FunctionalTest):\n def test_can_start_a_list_and_retrieve_it_later(self):\n\n #Edyta dowiedziala sie o nowej wspanialej aplikacji i postanowila ja wyprobowac\n self.browser.get(self.server_url)\n #Zwrocila uwage, ze tytul strony i naglowek zawieraja slowo Lista\n self.assertIn('Lista', self.browser.title)\n headerText = self.browser.find_element_by_tag_name('h1').text\n self.assertIn('liste', headerText)\n\n\n #Od razu zostaje zachecona aby wpisac rzecz do zrobienia\n inputbox = self.get_item_input_box()\n self.assertEqual(inputbox.get_attribute('placeholder'), 'Wpisz rzecz do zrobienia')\n\n #W polu tekstowym wpisala \"Kupić pawie pióra\"\n inputbox.send_keys('Kupic pawie piora')\n #Po naciśnięciu klawisza enter strona została uaktualniona i wyświetla \"1: kupić pawie pióra\" jako element listy\n inputbox.send_keys(Keys.ENTER)\n\n edith_list_url = self.browser.current_url\n self.assertRegex(edith_list_url, '/lists/.+')\n\n self.check_for_row_in_list_table('1. Kupic pawie piora')\n #Na stronie nadal znajduje sie pole zachecajace do podania kolejnej pozycji\n inputbox = self.get_item_input_box()\n inputbox.send_keys(\"Uzyc pawich pior do zrobienia przynety\")\n inputbox.send_keys(Keys.ENTER)\n\n self.check_for_row_in_list_table('1. Kupic pawie piora')\n self.check_for_row_in_list_table('2. Uzyc pawich pior do zrobienia przynety')\n\n self.browser.quit()\n\n self.browser = webdriver.Firefox()\n self.browser.get(self.server_url)\n\n page_text = self.browser.find_element_by_tag_name('body').text\n\n self.assertNotIn('Kupic pawie piora', page_text)\n self.assertNotIn('Uzyc pawich pior do zrobienia przynety', page_text)\n\n inputbox = self.get_item_input_box()\n inputbox.send_keys('Kupic mleko')\n inputbox.send_keys(Keys.ENTER)\n\n francis_list_url = self.browser.current_url\n self.assertRegex(francis_list_url, '/lists/.+')\n self.assertNotEqual(francis_list_url,edith_list_url)\n\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertNotIn('Kupic pawie piora', page_text)\n self.assertIn('Kupic mleko', page_text)\n\n\n","sub_path":"functional_tests/test_simple_list_creation.py","file_name":"test_simple_list_creation.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"4934953","text":"\"\"\"\nThe sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\n\nFind the sum of all the primes below two million.\n\"\"\"\n\n\ndef is_prime(num):\n d = 2\n while d * d <= num and num % d != 0:\n d += 1\n return d * d > num\n\n\nnum, sum = 2, 0\nwhile num < 2000000:\n if is_prime(num):\n sum += num\n # print(sum, num)\n num += 1\nprint(sum)\n","sub_path":"10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"220921986","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 13:32:16 2019\n\n@author: jungangzou\n\"\"\"\n\nfrom Neighbors import Neighbors\n\ndef Frequent_Words_With_Mismatches_Problem(Text, k, d):\n #k means the length of frequent words with k-mers\n #d means the maximun number of mismatches\n Neighbor_Dictionary = {}\n Frequent_Set = set()\n Frequent_Dictionary = {}\n Frequent_Count = 0\n for i in range(len(Text) - k + 1):\n pattern = Text[i:i+k]\n if pattern not in Neighbor_Dictionary:\n pattern_neighbor = set(Neighbors(pattern, d))\n Neighbor_Dictionary[pattern] = pattern_neighbor\n else:\n pattern_neighbor = Neighbor_Dictionary[pattern]\n pattern_neighbor.add(pattern)\n #print(i,pattern_neighbor)\n for neighbor in pattern_neighbor:\n Frequent_Dictionary[neighbor] = Frequent_Dictionary.get(neighbor,0) + 1\n #pattern_count += Frequent_Dictionary[neighbor]\n #print(i,Frequent_Dictionary) \n \n# =============================================================================\n# if pattern_count > Frequent_Count:\n# Frequent_Count = pattern_count\n# Frequent_Set = set()\n# Frequent_Set.add(pattern)\n# elif pattern_count == Frequent_Count:\n# Frequent_Set.add(pattern)\n# =============================================================================\n \n for i in Frequent_Dictionary:\n #print(Frequent_Dictionary[i], Frequent_Count)\n if Frequent_Dictionary[i] > Frequent_Count:\n Frequent_Count = Frequent_Dictionary[i]\n #print(Frequent_Set)\n Frequent_Set = set()\n Frequent_Set.add(i)\n elif Frequent_Dictionary[i] == Frequent_Count:\n Frequent_Set.add(i)\n return sorted(Frequent_Set)\n\nif __name__ == \"__main__\":\n with open(\"dataset_9_7.txt\",'r') as f:\n string = f.readlines()\n\n Text = string[0][:-1]\n number = string[1][:-1].split()\n k,d = int(number[0]),int(number[1])\n result = Frequent_Words_With_Mismatches_Problem(Text, k, d)\n print(result)\n\n \n \n ","sub_path":"UCSD/Finding Hidden Messages in DNA (Bioinformatics I)/Week 2/Frequent_Words_With_Mismatches_Problem.py","file_name":"Frequent_Words_With_Mismatches_Problem.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"83204773","text":"# Problem Statement: https://leetcode.com/problems/find-common-characters/\n\nclass Solution:\n def commonChars(self, A):\n if not A:\n return []\n\n common = {}\n for i in A[0]:\n common[i] = common[i] + 1 if i in common else 1\n\n for i in range(1, len(A)):\n temp_common = {}\n for i in A[i]:\n temp_common[i] = temp_common[i] + 1 if i in temp_common else 1\n for i in list(temp_common):\n if i in common:\n temp_common[i] = min(common[i], temp_common[i])\n else:\n temp_common.pop(i)\n common = temp_common\n\n result = []\n for i in common:\n count = common[i]\n while count > 0:\n result.append(i)\n count -= 1\n return result\n\n\n\nsol = Solution()\nresult = sol.commonChars([\"bella\",\"label\",\"roller\"])\nprint(result)\nresult = sol.commonChars([\"cool\",\"lock\",\"cook\"])\nprint(result)","sub_path":"CommonChars.py","file_name":"CommonChars.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"138793328","text":"# -*- coding: utf-8 -*-\n\n#%%\n# import various libraries necessery to run your Python code\nimport time # time related library\nimport sys # system related library\nok_loc = 'C:\\\\Program Files\\\\Opal Kelly\\\\FrontPanelUSB\\\\API\\\\Python\\\\3.6\\\\x64'\nsys.path.append(ok_loc) # add the path of the OK library\nimport ok # OpalKelly library\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport threading\nimport cv2\n\n#%% \n# Define FrontPanel device variable, open USB communication and\n# load the bit file in the FPGA\ndev = ok.okCFrontPanel() # define a device for FrontPanel communication\nSerialStatus=dev.OpenBySerial(\"\") # open USB communicaiton with the OK board\nConfigStatus=dev.ConfigureFPGA(\"BTPipeExample.bit\"); # Configure the FPGA with this bit file\n\n# Check if FrontPanel is initialized correctly and if the bit file is loaded.\n# Otherwise terminate the program\nprint(\"----------------------------------------------------\")\nif SerialStatus == 0:\n print (\"FrontPanel host interface was successfully initialized.\")\nelse: \n print (\"FrontPanel host interface not detected. The error code number is:\" + str(int(SerialStatus)))\n print(\"Exiting the program.\")\n sys.exit ()\n\nif ConfigStatus == 0:\n print (\"Your bit file is successfully loaded in the FPGA.\")\nelse:\n print (\"Your bit file did not load. The error code number is:\" + str(int(ConfigStatus)))\n print (\"Exiting the progam.\")\n sys.exit ()\nprint(\"----------------------------------------------------\")\nprint(\"----------------------------------------------------\")\n\n#%% \n# Define the two variables that will send data to the FPGA\n# We will use WireIn instructions to send data to the FPGA\ndev.UpdateWireOuts()\nregaddress = [1,2,3,4,39,42,43,44,57,58,59,60,68,69,80,83,97,98,100,101,102,103,106,107,108,109,110,117]\nregvalues = [232,1,0,0,1,232,1,0,3,44,240,10,2,9,2,187,240,10,112,98,34,64,94,110,91,82,80,91]\nR_W = -1\nFLAG = 0\nADDRS = -1\nREG_Val = -1\nSTART_BIT = -1\n\ndev.SetWireInValue(0x06, 0)\n\nwhile(dev.GetWireOutValue(0x24) != 1):\n dev.UpdateWireOuts()\n continue\nprint(\"Setting register values to required\")\nfor i in range(len(regaddress)):\n R_W = -1\n FLAG = 0\n ADDRS = -1\n REG_Val = -1\n START_BIT = -1\n dev.UpdateWireIns()\n START_BIT = 0\n dev.SetWireInValue(0x03, START_BIT)\n dev.UpdateWireIns()\n time.sleep(.1)\n START_BIT = 1\n REG_ADDR = regaddress[i]\n dev.SetWireInValue(0x00, REG_ADDR) #Input data for Variable 1 using mamoery spacee 0x00\n dev.SetWireInValue(0x01, 1) #Input data for Variable 2 using mamoery spacee 0x01\n REG_VAL = regvalues[i]\n dev.SetWireInValue(0x02, REG_VAL)\n dev.UpdateWireIns() # Update the WireIns\n time.sleep(.1)\n dev.SetWireInValue(0x03, START_BIT)\n dev.UpdateWireIns() # Update the WireIns\n time.sleep(.1)\n dev.UpdateWireOuts()\n while(dev.GetWireOutValue(0x21)!=1):\n continue\n\nprint('Configuring required registers completed')\n \ndef writeToReg(add, val):\n R_W = -1\n FLAG = 0\n START_BIT = -1\n dev.UpdateWireIns()\n START_BIT = 0\n dev.SetWireInValue(0x03, START_BIT)\n dev.UpdateWireIns()\n time.sleep(.1)\n START_BIT = 1\n dev.SetWireInValue(0x00, add) #Input data for Variable 1 using mamoery spacee 0x00\n dev.SetWireInValue(0x01, 1) #Input data for Variable 2 using mamoery spacee 0x01\n dev.SetWireInValue(0x02, val)\n dev.UpdateWireIns() # Update the WireIns\n time.sleep(.1)\n dev.SetWireInValue(0x03, START_BIT)\n dev.UpdateWireIns() # Update the WireIns\n time.sleep(.1)\n dev.UpdateWireOuts()\n while(dev.GetWireOutValue(0x21)!=1):\n continue\n\ndef readFromReg(add):\n START_BIT = -1\n dev.UpdateWireIns()\n START_BIT = 0\n dev.SetWireInValue(0x03, START_BIT)\n dev.UpdateWireIns()\n time.sleep(.1)\n START_BIT = 1\n dev.SetWireInValue(0x00, add) #Input data for Variable 1 using mamoery spacee 0x00\n dev.SetWireInValue(0x01, 0) #Input data for Variable 2 using mamoery spacee 0x01\n dev.UpdateWireIns() # Update the WireIns\n time.sleep(.1)\n dev.SetWireInValue(0x03, START_BIT)\n dev.UpdateWireIns() # Update the WireIns\n time.sleep(.1)\n dev.UpdateWireOuts()\ndev.SetWireInValue(0x05, 1); #Reset FIFOs and counter\ndev.UpdateWireIns(); # Update the WireIns\n\ntime.sleep(.01)\n\ndev.SetWireInValue(0x05, 0); #Release reset signal\ndev.UpdateWireIns(); # Update the WireIns\n\nbuf = np.arange(315392).astype('uint8')\nbuf12 = np.arange(648*486).astype('uint8')\n\nwhile(dev.GetWireOutValue(0x24) != 1):\n dev.UpdateWireOuts()\n continue\n\nprint(\"start\")\nprint(\"done: \"+str(dev.ReadFromBlockPipeOut(0xa0, 1024, buf)))\n\nprint(\"done\")\nbuf12 = buf[0:314928]\n \n \nbuf12 = buf12.reshape(648*486)\n\n#reading temp:\nglobal count,average\ncount = 0\nprint(dev.SetWireInValue(0x07,1))\ndev.UpdateWireIns()\ntime.sleep(.01)\ndef readTemp():\n global count,average\n dev.UpdateWireOuts()\n Final_Temp = dev.GetWireOutValue(0x25)\n if((float(Final_Temp)/128.0) == 0.0):\n return\n elif(count == 0):\n average = (float(Final_Temp)/16.0)\n count = count + 1;\n else:\n print(\"The Temperature is: \"+str((average+(float(Final_Temp)/16.0))/2));\n\nglobal abc\ndef updateImage():\n global abc,pixels\n dev.SetWireInValue(0x06, 1) \n dev.UpdateWireIns()\n dev.SetWireInValue(0x06, 0)\n dev.UpdateWireIns()\n print(\"done: \"+str(dev.ReadFromBlockPipeOut(0xa0, 1024, buf)))\n buf12 = buf[0:314928]\n \n readTemp()\n readTemp()\n readTemp()\n readTemp()\n readTemp()\n readTemp()\n readTemp()\n readTemp()\n return buf12.reshape(486,648)\n\nframecount = 0\nprint(time.time())\nwhile True:\n array = updateImage()\n framecount += 1\n# if(framecount == 20):\n# print(time.time())\n# break\n cv2.imshow('test',array)\n cv2.waitKey(1)\n\ndev.Close\n \n#%%","sub_path":"Final Project/python/8bittest/lab2_example_python_DEMO_FILE.py","file_name":"lab2_example_python_DEMO_FILE.py","file_ext":"py","file_size_in_byte":5894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"584075057","text":"import json\r\nimport traceback\r\nfrom os import urandom\r\nfrom sys import version_info\r\nfrom typing import List, Tuple\r\n\r\nfrom Crypto.PublicKey import RSA as old_RSA\r\nfrom Cryptodome.Cipher import AES\r\nfrom Cryptodome.PublicKey import RSA\r\n\r\nfrom config.settings import STORE_DECRYPTION_KEY_ERRORS, STORE_DECRYPTION_LINE_ERRORS\r\nfrom constants.security_constants import ASYMMETRIC_KEY_LENGTH, URLSAFE_BASE64_CHARACTERS\r\nfrom database.profiling_models import (DecryptionKeyError, EncryptionErrorMetadata,\r\n LineEncryptionError)\r\nfrom database.study_models import Study\r\nfrom database.user_models import Participant\r\nfrom libs.security import Base64LengthException, decode_base64, encode_base64, PaddingException\r\n\r\n\r\n# TODO: there is a circular import due to the database imports in this file and this file being\r\n# imported in s3, forcing local s3 imports in various files. Refactor and fix\r\n\r\n# Pycrypto (not pycryptodome) uses an old function inside the std lib time library that was\r\n# deprecated because the name is misleading. The exact replacement is the process_time function,\r\n# so we patch it to keep it working.\r\n# TODO: We only use the old pycrypto because we are using a not-best-practice of the direct RSA\r\n# encryption instead of a something like PKCS1_OAEP (OAEP is a padding mechanism). I have been\r\n# unable to replicate the old code (and have zero incentive to do so) using of either the\r\n# pycryptodome library (which explicitly disallows it) or the `rsa` library.\r\nif version_info.minor > 7:\r\n import time\r\n time.clock = time.process_time\r\n\r\n\r\nclass DecryptionKeyInvalidError(Exception): pass\r\nclass HandledError(Exception): pass\r\n# class UnHandledError(Exception): pass # for debugging\r\nclass InvalidIV(Exception): pass\r\nclass InvalidData(Exception): pass\r\nclass DefinitelyInvalidFile(Exception): pass\r\n\r\n################################################################################\r\n################################# RSA ##########################################\r\n################################################################################\r\n\r\n# The private keys are stored server-side (S3), and the public key is sent to the device.\r\n\r\ndef generate_key_pairing() -> Tuple[bytes, bytes]:\r\n \"\"\"Generates a public-private key pairing, returns tuple (public, private)\"\"\"\r\n private_key = RSA.generate(ASYMMETRIC_KEY_LENGTH)\r\n public_key = private_key.publickey()\r\n return public_key.exportKey(), private_key.exportKey()\r\n\r\n\r\ndef prepare_X509_key_for_java(exported_key) -> bytes:\r\n # This may actually be a PKCS8 Key specification.\r\n \"\"\" Removes all extraneous config (new lines and labels from a formatted key string,\r\n because this is how Java likes its key files to be formatted.\r\n (Y'know, not in accordance with the specification. Because Java.) \"\"\"\r\n return b\"\".join(exported_key.split(b'\\n')[1:-1])\r\n\r\n\r\ndef get_RSA_cipher(key: bytes) -> old_RSA._RSAobj:\r\n return old_RSA.importKey(key)\r\n\r\n\r\n# pycryptodome: the following is correct for PKCS1_OAEP.\r\n # RSA_key = RSA.importKey(key)\r\n # cipher = PKCS1_OAEP.new(RSA_key)\r\n # return cipher\r\n\r\n# This function is only for use in debugging.\r\n# def encrypt_rsa(blob, private_key):\r\n# return private_key.encrypt(\"blob of text\", \"literally anything\")\r\n# \"\"\" 'blob of text' can be either a long or a string, we will use strings.\r\n# The second parameter must be entered... but it is ignored. Really.\"\"\"\r\n\r\n\r\n################################################################################\r\n################################# AES ##########################################\r\n################################################################################\r\n\r\n\r\ndef encrypt_for_server(input_string: bytes, study_object_id: str) -> bytes:\r\n \"\"\"\r\n Encrypts config using the ENCRYPTION_KEY, prepends the generated initialization vector.\r\n Use this function on an entire file (as a string).\r\n \"\"\"\r\n if not isinstance(study_object_id, str):\r\n raise Exception(f\"received non-string object {study_object_id}\")\r\n encryption_key = Study.objects.get(object_id=study_object_id).encryption_key.encode() # bytes\r\n iv = urandom(16) # bytes\r\n return iv + AES.new(encryption_key, AES.MODE_CFB, segment_size=8, IV=iv).encrypt(input_string)\r\n\r\n\r\ndef decrypt_server(data: bytes, study_object_id: str) -> bytes:\r\n \"\"\" Decrypts config encrypted by the encrypt_for_server function. \"\"\"\r\n if not isinstance(study_object_id, str):\r\n raise TypeError(f\"received non-string object {study_object_id}\")\r\n \r\n encryption_key = Study.objects.filter(\r\n object_id=study_object_id\r\n ).values_list('encryption_key', flat=True).get().encode()\r\n iv = data[:16]\r\n data = data[16:] # gr arg, memcopy operation...\r\n return AES.new(encryption_key, AES.MODE_CFB, segment_size=8, IV=iv).decrypt(data)\r\n\r\n\r\n########################### User/Device Decryption #############################\r\n\r\n\r\ndef decrypt_device_file(file_name: str, original_data: bytes, participant: Participant) -> bytes:\r\n \"\"\" Runs the line-by-line decryption of a file encrypted by a device. \"\"\"\r\n \r\n def create_line_error_db_entry(error_type):\r\n # declaring this inside decrypt device file to access its function-global variables\r\n if STORE_DECRYPTION_LINE_ERRORS:\r\n LineEncryptionError.objects.create(\r\n type=error_type,\r\n base64_decryption_key=encode_base64(aes_decryption_key),\r\n line=encode_base64(line),\r\n prev_line=encode_base64(file_data[i - 1] if i > 0 else ''),\r\n next_line=encode_base64(file_data[i + 1] if i < len(file_data) - 1 else ''),\r\n participant=participant,\r\n )\r\n \r\n bad_lines = []\r\n error_types = []\r\n error_count = 0\r\n good_lines = []\r\n \r\n # don't refactor to pop the decryption key line out of the file_data list, this list\r\n # can be thousands of lines. Also, this line is a 2x memcopy with N new bytes objects.\r\n file_data = [line for line in original_data.split(b'\\n') if line != b\"\"]\r\n \r\n if not file_data:\r\n raise HandledError(\"The file had no data in it. Return 200 to delete file from device.\")\r\n \r\n private_key_cipher = participant.get_private_key()\r\n aes_decryption_key = extract_aes_key(\r\n file_name, file_data, participant, private_key_cipher, original_data\r\n )\r\n \r\n for i, line in enumerate(file_data):\r\n # we need to skip the first line (the decryption key), but need real index values in i\r\n if i == 0:\r\n continue\r\n \r\n if line is None:\r\n # this case causes weird behavior inside decrypt_device_line, so we test for it instead.\r\n error_count += 1\r\n create_line_error_db_entry(LineEncryptionError.LINE_IS_NONE)\r\n error_types.append(LineEncryptionError.LINE_IS_NONE)\r\n bad_lines.append(line)\r\n print(\"encountered empty line of data, ignoring.\")\r\n continue\r\n \r\n try:\r\n good_lines.append(decrypt_device_line(participant.patient_id, aes_decryption_key, line))\r\n except Exception as error_orig:\r\n error_string = str(error_orig)\r\n error_count += 1\r\n \r\n error_message = \"There was an error in user decryption: \"\r\n if isinstance(error_orig, (Base64LengthException, PaddingException)):\r\n # this case used to also catch IndexError, this probably changed after python3 upgrade\r\n error_message += \"Something is wrong with data padding:\\n\\tline: %s\" % line\r\n create_line_error_db_entry(LineEncryptionError.PADDING_ERROR)\r\n error_types.append(LineEncryptionError.PADDING_ERROR)\r\n bad_lines.append(line)\r\n continue\r\n \r\n # case not reachable, decryption key has validation logic.\r\n # if isinstance(error_orig, TypeError) and aes_decryption_key is None:\r\n # error_message += \"The key was empty:\\n\\tline: %s\" % line\r\n # create_line_error_db_entry(LineEncryptionError.EMPTY_KEY)\r\n # error_types.append(LineEncryptionError.EMPTY_KEY)\r\n # bad_lines.append(line)\r\n # continue\r\n \r\n # untested, error should be caught as a decryption key error\r\n # if isinstance(error_orig, ValueError) and \"Key cannot be the null string\" in error_string:\r\n # error_message += \"The key was the null string:\\n\\tline: %s\" % line\r\n # create_line_error_db_entry(LineEncryptionError.EMPTY_KEY)\r\n # error_types.append(LineEncryptionError.EMPTY_KEY)\r\n # bad_lines.append(line)\r\n # continue\r\n \r\n ################### skip these errors ##############################\r\n if \"unpack\" in error_string:\r\n error_message += \"malformed line of config, dropping it and continuing.\"\r\n create_line_error_db_entry(LineEncryptionError.MALFORMED_CONFIG)\r\n error_types.append(LineEncryptionError.MALFORMED_CONFIG)\r\n bad_lines.append(line)\r\n # the config is not colon separated correctly, this is a single\r\n # line error, we can just drop it.\r\n # implies an interrupted write operation (or read)\r\n continue\r\n \r\n # This error had a new error string, solution is now tested, we pad and then trunate.\r\n # if \"Input strings must be a multiple of 16 in length\" in error_string:\r\n # error_message += \"Line was of incorrect length, dropping it and continuing.\"\r\n # create_line_error_db_entry(LineEncryptionError.INVALID_LENGTH)\r\n # error_types.append(LineEncryptionError.INVALID_LENGTH)\r\n # bad_lines.append(line)\r\n # continue\r\n \r\n if isinstance(error_orig, InvalidData):\r\n error_message += \"Line contained no data, skipping: \" + str(line)\r\n create_line_error_db_entry(LineEncryptionError.LINE_EMPTY)\r\n error_types.append(LineEncryptionError.LINE_EMPTY)\r\n bad_lines.append(line)\r\n continue\r\n \r\n if isinstance(error_orig, InvalidIV):\r\n error_message += \"Line contained no iv, skipping: \" + str(line)\r\n create_line_error_db_entry(LineEncryptionError.IV_MISSING)\r\n error_types.append(LineEncryptionError.IV_MISSING)\r\n bad_lines.append(line)\r\n continue\r\n \r\n elif \"Incorrect IV length\" in error_string or 'IV must be' in error_string:\r\n # shifted this to an okay-to-proceed line error March 2021\r\n # Jan 2022: encountered pycryptodome form: \"Incorrect IV length\"\r\n error_message += \"iv has bad length.\"\r\n create_line_error_db_entry(LineEncryptionError.IV_BAD_LENGTH)\r\n error_types.append(LineEncryptionError.IV_BAD_LENGTH)\r\n bad_lines.append(line)\r\n continue\r\n \r\n # Give up on these errors:\r\n # should be handled in decryption key validation.\r\n # if 'AES key' in error_string:\r\n # error_message += \"AES key has bad length.\"\r\n # create_line_error_db_entry(LineEncryptionError.AES_KEY_BAD_LENGTH)\r\n # error_types.append(LineEncryptionError.AES_KEY_BAD_LENGTH)\r\n # bad_lines.append(line)\r\n # raise HandledError(error_message)\r\n \r\n elif 'Incorrect padding' in error_string:\r\n error_message += \"base64 padding error, config is truncated.\"\r\n create_line_error_db_entry(LineEncryptionError.MP4_PADDING)\r\n error_types.append(LineEncryptionError.MP4_PADDING)\r\n bad_lines.append(line)\r\n # this is only seen in mp4 files. possibilities:\r\n # upload during write operation.\r\n # broken base64 conversion in the app\r\n # some unanticipated error in the file upload\r\n raise HandledError(error_message)\r\n else:\r\n # If none of the above errors happened, raise the error raw\r\n raise\r\n \r\n if error_count:\r\n EncryptionErrorMetadata.objects.create(\r\n file_name=file_name,\r\n total_lines=len(file_data),\r\n number_errors=error_count,\r\n # generator comprehension:\r\n error_lines=json.dumps( (str(line for line in bad_lines)) ),\r\n error_types=json.dumps(error_types),\r\n participant=participant,\r\n )\r\n \r\n # join should be rather well optimized and not cause O(n^2) total memory copies\r\n return b\"\\n\".join(good_lines)\r\n\r\n\r\ndef extract_aes_key(\r\n file_name: str, file_data: List[bytes], participant: Participant, private_key_cipher, original_data: bytes\r\n) -> bytes:\r\n # The following code is ... strange because of an unfortunate design design decision made\r\n # quite some time ago: the decryption key is encoded as base64 twice, once wrapping the\r\n # output of the RSA encryption, and once wrapping the AES decryption key. This happened\r\n # because I was not an experienced developer at the time, python2's unified string-bytes\r\n # class didn't exactly help, and java io is... java io.\r\n \r\n def create_decryption_key_error(an_traceback):\r\n # helper function with local variable access.\r\n # do not refactor to include raising the error in this function, that obfuscates the source.\r\n if STORE_DECRYPTION_KEY_ERRORS:\r\n DecryptionKeyError.do_create(\r\n file_path=file_name,\r\n contents=original_data,\r\n traceback=an_traceback,\r\n participant=participant,\r\n )\r\n \r\n try:\r\n key_base64_raw: bytes = file_data[0]\r\n # print(f\"key_base64_raw: {key_base64_raw}\")\r\n except IndexError:\r\n # probably not reachable due to test for emptiness prior in code; keep just in case...\r\n create_decryption_key_error(traceback.format_exc())\r\n raise DecryptionKeyInvalidError(\"There was no decryption key.\")\r\n \r\n # Test that every \"character\" (they are 8 bit bytes) in the byte-string of the raw key is\r\n # a valid url-safe base64 character, this will cut out certain junk files too.\r\n for c in key_base64_raw:\r\n if c not in URLSAFE_BASE64_CHARACTERS:\r\n # need a stack trace....\r\n try:\r\n raise DecryptionKeyInvalidError(f\"Decryption key not base64 encoded: {key_base64_raw}\")\r\n except DecryptionKeyInvalidError:\r\n create_decryption_key_error(traceback.format_exc())\r\n raise\r\n \r\n # handle the various cases that can occur when extracting from base64.\r\n try:\r\n decoded_key: bytes = decode_base64(key_base64_raw)\r\n # print(f\"decoded_key: {decoded_key}\")\r\n except (TypeError, PaddingException, Base64LengthException) as decode_error:\r\n create_decryption_key_error(traceback.format_exc())\r\n raise DecryptionKeyInvalidError(f\"Invalid decryption key: {decode_error}\")\r\n \r\n try:\r\n base64_key = private_key_cipher.decrypt(decoded_key)\r\n # print(f\"base64_key: {len(base64_key)} {base64_key}\")\r\n decrypted_key = decode_base64(base64_key)\r\n # print(f\"decrypted_key: {len(decrypted_key)} {decrypted_key}\")\r\n if not decrypted_key:\r\n raise TypeError(f\"decoded key was '{decrypted_key}'\")\r\n except (TypeError, IndexError, PaddingException, Base64LengthException) as decr_error:\r\n create_decryption_key_error(traceback.format_exc())\r\n raise DecryptionKeyInvalidError(f\"Invalid decryption key: {decr_error}\")\r\n \r\n # If the decoded bits of the key is not exactly 128 bits (16 bytes) that probably means that\r\n # the RSA encryption failed - this occurs when the first byte of the encrypted blob is all\r\n # zeros. Apps require an update to solve this (in a future rewrite we should use a padding\r\n # algorithm).\r\n if len(decrypted_key) != 16:\r\n # print(len(decrypted_key))\r\n # need a stack trace....\r\n try:\r\n raise DecryptionKeyInvalidError(f\"Decryption key not 128 bits: {decrypted_key}\")\r\n except DecryptionKeyInvalidError:\r\n create_decryption_key_error(traceback.format_exc())\r\n raise\r\n \r\n return decrypted_key\r\n\r\n\r\ndef decrypt_device_line(patient_id, key, data: bytes) -> bytes:\r\n \"\"\" Config is expected to be 3 colon separated values.\r\n value 1 is the symmetric key, encrypted with the patient's public key.\r\n value 2 is the initialization vector for the AES CBC cipher.\r\n value 3 is the config, encrypted using AES CBC, with the provided key and iv. \"\"\"\r\n # orig_data = data\r\n iv, data = data.split(b\":\")\r\n iv = decode_base64(iv)\r\n data = decode_base64(data)\r\n \r\n # handle cases of no data, and less than 16 bytes of data, which is an equivalent scenario.\r\n if not data or len(data) < 16:\r\n raise InvalidData()\r\n if not iv or len(iv) < 16:\r\n raise InvalidIV()\r\n \r\n # CBC data encryption requires alignment to a 16 bytes, we lose any data that overflows that length.\r\n overflow_bytes = len(data) % 16\r\n \r\n if overflow_bytes:\r\n print(\"\\n\\nFOUND OVERFLOWED DATA\\n\\n\")\r\n print(\"device os:\", Participant.objects.get(patient_id=patient_id).os_type)\r\n print(\"\\n\\n\")\r\n data = data[:-overflow_bytes]\r\n \r\n try:\r\n decipherer = AES.new(key, mode=AES.MODE_CBC, IV=iv)\r\n decrypted = decipherer.decrypt(data)\r\n except Exception:\r\n if iv is None:\r\n len_iv = \"None\"\r\n else:\r\n len_iv = len(iv)\r\n if data is None:\r\n len_data = \"None\"\r\n else:\r\n len_data = len(data)\r\n if key is None:\r\n len_key = \"None\"\r\n else:\r\n len_key = len(key)\r\n # these print statements cause problems in getting encryption errors because the print\r\n # statement will print to an ascii formatted log file on the server, which causes\r\n # ascii encoding error. Enable them for debugging only. (leave uncommented for Sentry.)\r\n # print(\"length iv: %s, length data: %s, length key: %s\" % (len_iv, len_data, len_key))\r\n # print('%s %s %s' % (patient_id, key, orig_data))\r\n raise\r\n \r\n # PKCS5 Padding: The last byte of the byte-string contains the number of bytes at the end of the\r\n # bytestring that are padding. As string slicing in python are a copy operation we will\r\n # detect the fast-path case of no change so that we can skip it\r\n num_padding_bytes = decrypted[-1]\r\n if num_padding_bytes:\r\n decrypted = decrypted[0: -num_padding_bytes]\r\n \r\n return decrypted\r\n","sub_path":"libs/encryption.py","file_name":"encryption.py","file_ext":"py","file_size_in_byte":19134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"412100108","text":"import subprocess\nfrom PKD_tools import libCrypto\nfrom PKD_tools import libFile\n\nimport pymel.core as pm\nimport getpass\n\n\nclass MusterAPI(object):\n def __init__(self):\n # Initialise the muster class\n\n # Set the app path\n self.appPath = r\"C:\\apps\\muster\\8.6.0\\Mrtool\".strip()\n\n # Login details\n self.ip = \"10.0.0.21\"\n self.port = \"9781\"\n self.username = \"admin\"\n self.encyptedPwd = \"w9rl6MrqnaY=\"\n self._pwd_ = ''\n # Cmd line\n self._cmdline_ = \"\"\n # Defaults settings\n # By frame\n self._byframe_ = 1\n # Set the pool\n self._pool_ = \"BOAD - Vray\"\n # Set the images folder\n self._images_folder_ = r\"\\\\productions\\boad\\Pipeline\\tools\\maya\\rendering\\Images\"\n # Start frame\n self._startframe_ = None\n # End Frame\n self._endframe_ = None\n # Set the project foldeer\n self._project_folder_ = r\"\\\\productions\\boad\\Pipeline\\tools\\maya\\rendering\"\n # #Set the project\n # does not work\n # self.cmdline = \"-project ABC\"\n # Set the Name\n self._jobname_ = \"TestingSubmitMaya_ABC\"\n # Set the Packet Size\n self._packetsize_ = 4\n # Set the max instances\n self._instances_ = 20\n # Set the priority\n self._priority_ = 1\n\n # Set the priority\n self._file_name_ = 20\n\n def initialise_muster(self, mode=\"-b\"):\n # Initialise the Muster tool\n self._cmdline_ = self.appPath.strip()\n self.cmdline = mode\n self.cmdline = \"-s \" + self.ip\n self.cmdline = \"-port \" + self.port\n self.cmdline = '-u %s' % self.username\n self.cmdline = \"-p %s\" % self.pwd\n\n def get_pools(self):\n self.initialise_muster(mode=\"-q p\")\n # Build the query command for the pools\n self.cmdline = \"-H 0 -S 0 -pf parent\"\n\n pools = self.execute_cmd()\n\n for i in range(len(pools)):\n if not len(pools[i]):\n pools[i] = \"Entire Farm\"\n pools[i] = pools[i].strip()\n\n return pools\n\n def get_engines(self):\n self.initialise_muster(mode=\"-q t\")\n # Build the query command for the pools\n self.cmdline = \"-H 0 -S 0 -pf parent\"\n\n pools = self.execute_cmd()\n\n for i in range(len(pools)):\n pools[i] = pools[i].strip()\n\n return pools\n\n def execute_cmd(self):\n p = subprocess.Popen(self.cmdline, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n output = []\n for line in p.stdout.readlines():\n line = line.replace(\"\\r\\n\", \"\")\n if line not in output:\n output.append(line)\n retval = p.wait()\n # print self.cmdline\n return output\n\n def send_to_farm(self):\n # Render Globals\n # Get the folder\n self.initialise_muster()\n\n # Set the start frame\n self.cmdline = self.startframe\n\n # Set the end frame\n self.cmdline = self.endframe\n\n # By frame\n self.cmdline = self.byframe\n\n # Maya defeals\n self.cmdline = \"-attr MAYADIGITS 4 0 -se 1 -st 1\"\n\n # Set the Vray engine\n self.cmdline = '-e 37'\n\n # Set the pool\n self.cmdline = self.pool\n\n # Set the priority\n self.cmdline = self.priority\n\n # Set the Packet Size\n self.cmdline = self.packetsize\n\n # Set the max instances\n self.cmdline = self.instances\n\n # Set the Name\n\n self.cmdline = self.jobname\n\n # Set the Department name\n self.cmdline = self.department\n\n\n # Set the scene name\n self.cmdline = self.filename\n\n # Set the images foldeer\n self.cmdline = self.project_folder\n\n # Set the images foldeer\n self.cmdline = self.images_folder\n\n # #Set the project\n # self.cmdline = \"-project ABC\"\n\n\n # Set the batch submit\n output = self.execute_cmd()\n return output\n\n @property\n def pwd(self):\n # Set the password\n if not self._pwd_:\n if self.username == \"admin\":\n self._pwd_ = libCrypto.decode(\"muster\", self.encyptedPwd)\n else:\n raise Exception(\"Password not defined\")\n return self._pwd_\n\n @pwd.setter\n def pwd(self, pwd):\n # Set the password\n self._pwd_ = pwd\n\n @property\n def cmdline(self):\n return self._cmdline_\n\n @cmdline.setter\n def cmdline(self, newdata):\n # Add to command line\n self._cmdline_ = \" %s %s\" % (self._cmdline_, newdata)\n\n @property\n def startframe(self):\n if self._startframe_ is None:\n self._startframe_ = pm.playbackOptions(q=1, ast=1)\n return \"-sf %i\" % self._startframe_\n\n @startframe.setter\n def startframe(self, newdata):\n self._startframe_ = int(newdata)\n\n @property\n def endframe(self):\n if self._endframe_ is None:\n self._endframe_ = pm.playbackOptions(q=1, aet=1)\n return \"-ef %i\" % self._endframe_\n\n @endframe.setter\n def endframe(self, newdata):\n self._endframe_ = int(newdata)\n\n @property\n def byframe(self):\n return \"-bf %i\" % self._byframe_\n\n @byframe.setter\n def byframe(self, newdata):\n self._byframe_ = int(newdata)\n\n @property\n def packetsize(self):\n return \"-pk %i\" % self._packetsize_\n\n @packetsize.setter\n def packetsize(self, newdata):\n self._packetsize_ = int(newdata)\n\n @property\n def priority(self):\n return \"-pr %i\" % self._priority_\n\n @priority.setter\n def priority(self, newdata):\n self._priority_ = int(newdata)\n\n @property\n def instances(self):\n return \"-max %i\" % self._instances_\n\n @instances.setter\n def instances(self, newdata):\n self._instances_ = int(newdata)\n\n @property\n def pool(self):\n return '-pool \"%s\"' % self._pool_\n\n @pool.setter\n def pool(self, newdata):\n self._pool_ = newdata\n\n @property\n def images_folder(self):\n return '-dest \"%s\"' % self._images_folder_\n\n @images_folder.setter\n def images_folder(self, newdata):\n self._images_folder_ = libFile.windows_path(newdata)\n\n @property\n def project_folder(self):\n # Set the project foldeer\n return '-proj \"%s\"' % self._project_folder_\n\n @project_folder.setter\n def project_folder(self, newdata):\n self._project_folder_ = libFile.windows_path(newdata)\n\n @property\n def filename(self):\n if not self._file_name_:\n self._file_name_ = libFile.windows_path(pm.sceneName())\n return '-f \"%s\"' % self._file_name_\n\n @filename.setter\n def filename(self, filename):\n\n self._file_name_ = filename\n\n @property\n def jobname(self):\n # '-n TestingSubmitMaya_ABC'\n return '-n \"%s\"' % self._jobname_\n\n @jobname.setter\n def jobname(self, newdata):\n self._jobname_ = newdata\n\n @property\n def department(self):\n username = getpass.getuser()\n return '-department \"%s\"' % username\n\n# api = MusterAPI()\n# api.username = \"BAD15023\"\n# api.pwd = \"BAD15023\"\n# #api.test_submit_render()\n# print api.get_pools()\n# print api.get_engines()\n\n\n# for stuff in api.get_engines():\n# print stuff\n","sub_path":"maya/PKD_tools/libMuster.py","file_name":"libMuster.py","file_ext":"py","file_size_in_byte":7389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"608502050","text":"import datetime\nimport re\nimport json\nimport pytz\nfrom django.contrib.auth import login\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import EmailMessage\nfrom django.http import HttpResponse, request\nfrom django.shortcuts import render, redirect\nfrom django.template.loader import render_to_string\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\n\nfrom foodscan.middleware.login_exempt import login_exempt\nfrom foodshow.forms import CustomUserCreationForm, CustomFoodsForm, CustomFridgeFoodsForm\nfrom foodshow.models import Fridge, FoodData, CustomUser\nfrom foodshow.ocr_core import ocr_core\nfrom foodshow.tokens import account_activation_token\nimport cv2\nfrom pyzbar import pyzbar\n\nUPLOAD_FOLDER = '/static/uploads/'\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\n\n@login_exempt\ndef landing(request):\n return render(request, 'landing.html')\n\n\n\n\n@login_exempt\ndef signup(request):\n if request.method == 'POST':\n form = CustomUserCreationForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n print(user)\n # passwrd check here.... how is the page rendering password areas if its not in the form..\n user.is_patient = True\n user.is_active = False\n user.save()\n '''hashing process here to give link'''\n current_site = get_current_site(request)\n mail_subject = 'Activate your account.'\n message = render_to_string('acc_active_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'token': account_activation_token.make_token(user),\n })\n to_email = form.cleaned_data.get('email')\n email = EmailMessage(\n mail_subject, message, to=[to_email]\n )\n email.send()\n\n return HttpResponse(\n 'Please confirm your email address to complete the registration') # should redirect to dead end page until user confirms email\n form = CustomUserCreationForm()\n return render(request, 'signup.html', {'form': form})\n\n\n@login_exempt\ndef activate(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = CustomUser.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n login(request, user)\n # flash message saying thanks\n return redirect('foodshow:index')\n else:\n return HttpResponse('Activation link is invalid!')\n# the list will come in from the cam module...\n\ndef fridge_filler(response, extracted_text):\n # however it splits assuming perfect spacing.... more work needed here to clean real data...\n print(extracted_text)\n shopping_list = re.sub(\"[^\\w]\", \" \", extracted_text.lower()).split()\n print(shopping_list)\n food_id_list = []\n for food_name in shopping_list:\n database_food = FoodData.objects.filter(food_name=food_name).first()\n # its a set of one and so we need to go inside the query set\n if database_food is not None:\n food_id_list.append(database_food.id)\n print(food_id_list)\n # still this function is adding it the list two times ...\n for i in food_id_list:\n food = Fridge(used=False, fooddata_id=i)\n food.save()\n\n return redirect('foodshow:index')\n\n\n\n\ndef index(request):\n fridge_foods = Fridge.objects.all()\n food_list = []\n if request.method == 'POST':\n eaten_food = request.POST.get('submit')\n get_eaten_food_from_fridge = Fridge.objects.get(id=eaten_food)\n get_eaten_food_from_fridge.used = True\n get_eaten_food_from_fridge.save()\n\n for one_food in fridge_foods:\n if one_food.used == False:\n get_food_id = int(one_food.fooddata_id)\n this_food = FoodData.objects.get(id=get_food_id)\n good_for = this_food.days_good_for\n foodname = FoodData.objects.get(id=get_food_id).food_name\n food_image = FoodData.objects.get(id=get_food_id).image_of_food\n scanneddate = one_food.date_scanned\n end_date = scanneddate + datetime.timedelta(days=good_for)\n utc = pytz.UTC\n now = utc.localize(datetime.datetime.now())\n time_left = end_date - now\n days_left = time_left.days\n\n if days_left < 0:\n one_food.delete()\n # small cleaner code for any over due food to not clog up fridge database... this info may want to be kept for data analysis later down the line..\n if days_left == 0:\n days_left = \"Today\"\n elif days_left == 1:\n days_left = \"Tomorrow\"\n fridge_food_id = one_food.id\n\n food_list.append({\"foodname\": foodname, \"scanneddate\": scanneddate, \"days_left\": days_left,\n \"fridge_food_id\": fridge_food_id, \"food_image\": food_image})\n\n day_list = [\"Today\", \"Tomorrow\", 2, 3, 4, 5, 6, 7, 8, \"over 8 days\"]\n return render(request, \"index.html\", {\"food_list\": food_list, \"day_list\": day_list})\n\n\ndef sort_by_catagory(request):\n fridge_foods = Fridge.objects.all()\n food_list = []\n if request.method == 'POST':\n eaten_food = request.POST.get('submit')\n get_eaten_food_from_fridge = Fridge.objects.get(id=eaten_food)\n get_eaten_food_from_fridge.used = True\n get_eaten_food_from_fridge.save()\n for one_food in fridge_foods:\n if one_food.used == False:\n get_food_id = int(one_food.fooddata_id)\n this_food = FoodData.objects.get(id=get_food_id)\n good_for = this_food.days_good_for\n foodname = FoodData.objects.get(id=get_food_id).food_name\n food_image = FoodData.objects.get(id=get_food_id).image_of_food\n scanneddate = one_food.date_scanned\n end_date = scanneddate + datetime.timedelta(days=good_for)\n utc = pytz.UTC\n now = utc.localize(datetime.datetime.now())\n time_left = end_date - now\n days_left = time_left.days\n fridge_food_id = one_food.id\n food_catagory = FoodData.objects.get(id=get_food_id).food_category\n food_list.append({\"foodname\": foodname, \"scanneddate\": scanneddate, \"days_left\": days_left,\n \"fridge_food_id\": fridge_food_id, \"food_image\": food_image , \"food_catagory\":food_catagory})\n# chagne logic here or sorting!\n\n food_catagory_list = [\"dairy\", \"fruit\", \"vegetable\", \"meat\", \"fish\", \"grain\", \"other\"]\n return render(request, \"index_by__food_catagory.html\", {\"food_list\": food_list, \"food_catagory_list\": food_catagory_list})\n\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\ndef upload_page(request):\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.FILES:\n msg = 'No file selected'\n return render(request, 'upload.html', {\"msg\":msg})\n file = request.FILES['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.name == '':\n msg = 'No file selected'\n return render(request, 'upload.html', {\"msg\":msg})\n\n if file and allowed_file(file.name):\n # default_storage.save(os.path.join(os.getcwd() + UPLOAD_FOLDER, file.name), file)\n\n # call the OCR function on it\n extracted_text = ocr_core(file)\n\n print(str(extracted_text))\n print(\"here is the food!\")\n # extract the text and display it\n # then make user say yes or no.../correct the text...?\n # text correction/edits could take place here\n # before redirect show the message...\n trial_output = str(extracted_text)\n return render(request ,\"upload.html\", {\"trial_output\":trial_output})\n\n elif request.method == 'GET':\n\n return render(request, 'upload.html')\n\n\ndef eaten(request):\n if request.method == 'POST':\n if 'submit' in request.POST:\n non_eaten_food_id = request.POST.get('submit')\n get_eaten_food_from_fridge = Fridge.objects.get(id=non_eaten_food_id)\n get_eaten_food_from_fridge.used = False\n get_eaten_food_from_fridge.save()\n\n elif 'delete_foods' in request.POST:\n Fridge.objects.filter(used=True).delete()\n\n fridge_foods = Fridge.objects.all()\n eaten_foods = []\n for one_food in fridge_foods:\n get_food_id = int(one_food.fooddata_id)\n foodname = FoodData.objects.get(id=get_food_id).food_name\n fridge_food_id = one_food.id\n food_image = FoodData.objects.get(id=get_food_id).image_of_food\n if one_food.used == True:\n eaten_foods.append({\"foodname\": foodname, \"fridge_food_id\": fridge_food_id, \"food_image\": food_image})\n\n return render(request, 'eaten.html', {\"eaten_foods\": eaten_foods})\n\n\nclass VideoCamera(object):\n def __init__(self):\n # Using OpenCV to capture from device 0. If you have trouble capturing\n # from a webcam, comment the line below out and use a video file\n # instead.\n self.video = cv2.VideoCapture(0)\n # If you decide to use video.mp4, you must have this file in the folder\n # as the main.py.\n # self.video = cv2.VideoCapture('video.mp4')\n\n def __del__(self):\n self.video.release()\n\n def get_frame(self):\n success, image = self.video.read()\n # We are using Motion JPEG, but OpenCV defaults to capture raw images,\n # so we must encode it into JPEG in order to correctly display the\n # video stream.\n\n # _, frame = cap.read()\n decodedObjects = pyzbar.decode(image)\n thedata = None\n for obj in decodedObjects:\n print(\"Data\", obj.data)\n # this is the print...\n thedata = obj.data\n ret, jpeg = cv2.imencode('.jpg', image)\n\n return jpeg.tobytes(), thedata\n\n\ndef gen(camera):\n while True:\n frame = camera.get_frame()[0]\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n if camera.get_frame()[1] is not None:\n break\n\n return shopping()\n\n\ndef shopping(request):\n return render(request, 'shopping.html')\n\n\ndef custom_foods(request):\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = CustomFoodsForm(request.POST)\n if form.is_valid():\n for foodobj in FoodData.objects.all():\n if form.cleaned_data[\"food_name\"] == foodobj.food_name:\n error = \"This is not a custom food, add it from our data base of foods!\"\n return render(request, \"custom_foods.html\", {\"error\": error})\n break\n form.save()\n print(\"saved\")\n return render(request, \"custom_foods.html\")\n else:\n form = CustomFoodsForm()\n # payment_to = scanner.camera()\n return render(request, \"custom_foods.html\", {\"form\": form})\n\n\ndef fridge_manager(request):\n # only problem is that it resets when you pass through each time...\n if request.method == 'POST':\n if \"clear-custom-foods-added\" in request.POST:\n data = {\"food_added_list\":[]}\n with open('customfoods.txt', 'w') as outfile:\n json.dump(data, outfile)\n return redirect(\"foodshow:index\")\n # create a form instance and populate it with data from the request:\n form = CustomFridgeFoodsForm(request.POST)\n with open('customfoods.txt') as json_file:\n context = json.load(json_file)\n food_added_list = context[\"food_added_list\"]\n if form.is_valid():\n x = form.save()\n foodid =x.fooddata_id\n thisfood = FoodData.objects.get(id=foodid).food_name\n food_added_list.append(thisfood)\n data = {\"food_added_list\":food_added_list}\n print(data)\n with open('customfoods.txt', 'w') as outfile:\n json.dump(data, outfile)\n return redirect(\"foodshow:fridge_manager\")\n else:\n with open('customfoods.txt') as json_file:\n context = json.load(json_file)\n passinlist = context[\"food_added_list\"]\n form = CustomFridgeFoodsForm()\n\n return render(request, \"fridge_manager.html\", {\"form\": form, \"passinlist\":passinlist})\n\n\n\ndef fullfoodshow(request):\n get_all_foods = FoodData.objects.all()\n food_data_list = []\n for foodobj in get_all_foods:\n if foodobj.image_of_food != \"general.svg\":\n food_icon = foodobj.image_of_food\n food_id = foodobj.id\n food_category = foodobj.food_category\n food_data_list.append({\"food_icon\":food_icon,\"food_id\":food_id, \"food_category\":food_category })\n return render(request, \"fullfoodshow.html\" ,{\"food_data\":food_data_list})\n","sub_path":"foodshow/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367120933","text":"from django.conf.urls import (\n include,\n url,\n)\n\nfrom rest_framework import routers\n\nfrom .viewsets import (\n BeerViewSet,\n BeerTypeViewSet,\n FridgeShelfViewSet,\n)\n\nrouter_v1 = routers.DefaultRouter()\n\nrouter_v1.register(\n r'beers',\n BeerViewSet,\n base_name='beers',\n)\nrouter_v1.register(\n r'beer_types',\n BeerTypeViewSet,\n base_name='beer_types',\n)\nrouter_v1.register(\n r'fridge_shelves',\n FridgeShelfViewSet,\n base_name='fridge_shelves',\n)\n\nurlpatterns = (\n url(\n r'^v1/',\n include(\n router_v1.urls,\n namespace='v1_beers',\n ),\n ),\n)\n","sub_path":"beers/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"10841333","text":"# -*- coding: utf-8 -*-\nimport os\nfrom socket import *\nfrom multiprocessing import Pool\n\n\ndef talk(conn):\n while 1: # 循环通讯\n try:\n from_client_msg = conn.recv(1024)\n if not from_client_msg:break\n print(\"进程(%s)来自客户端的消息:%s\" %(os.getpid(), from_client_msg))\n conn.send(from_client_msg.upper())\n except:\n break\n conn.close()\n\n\nif __name__ == '__main__':\n server = socket()\n ip_port = (\"127.0.0.1\", 8001)\n server.bind(ip_port)\n server.listen(5)\n pool = Pool(4) # 创建进程池,进程池内,最多可运行4个进程\n while 1: # 循环连接\n conn, addr = server.accept()\n pool.apply_async(talk, args=(conn,)) # 异步执行\n pool.close() # 进程池不再接收新任务\n pool.join() # 进程池内的进程都执行完了\n server.close()\n\n","sub_path":"学习系列/socket多并发(线程池).py","file_name":"socket多并发(线程池).py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"278611804","text":"\nimport sys, os\n#packages which define __version__:\npackages = ['numpy','matplotlib','scipy','processing','wx',\n 'paramiko','Crypto','setuptools']\n\nif os.name == 'nt':\n packages.append('mpl_toolkits.basemap')\n\n#some packages do not define __version__:\nspecial_packages = [('serial','VERSION'),\n ('bbfreeze','version'),\n ('Image','VERSION')]\n\n\nif os.name=='nt':\n special_packages.append(('elementtree.ElementTree','VERSION'))\nelse:\n special_packages.append(('xml.etree.ElementTree','VERSION'))\n\ndef save_version_numbers(filename):\n \"\"\"\n Save version number of packages to filename\n \"\"\"\n\n fid = open(filename,'w')\n fid.write('Python %s' % sys.version)\n fid.write('\\n\\n%-15s: %s\\n\\n'% ('Package name','version'))\n for package in packages:\n module = __import__(package, fromlist=['__version__'])\n fid.write('%-15s: %-15s\\n' %(package,module.__version__))\n\n\n for package,version in special_packages:\n module = __import__(package, fromlist=[version])\n fid.write('%-15s: %-15s\\n' %(package,eval('module.%s'%version)))\n\n fid.close()\n\nif __name__ == '__main__':\n save_version_numbers('../../../documentation/package_versions.txt')","sub_path":"utilities/version_control.py","file_name":"version_control.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"20962923","text":"import numpy as np\nimport datetime\nimport time\nimport copy\nimport os\nimport subprocess\nimport yaml\nimport traceback\nimport sys\nimport threading\n\nimport mts_util\nimport symbol_map\nimport tpmon\n\n\"\"\"\nA Reference Parameter from Camid2, other strategies\ncould take similar forms\n\nparam = { \\\n 'spread_list':\\\n [ \\\n { \\\n 'symbol':'Brent_N1-Brent_N6', \\\n 'bar_file': '',\\\n 'state': { \\\n 'prev_px':[], \\\n 'bar_array':np.zeros(5), \\\n 'last_utc': 0,\\\n 'cur_sig': 0\\\n } \\\n } \\\n ], \\\n 'trade_symbol': 'Brent_N1',\\\n 'strat_code': 'TSC-7000-1', \\\n 'strat_weight': 1.0, \\\n 'barsec':300, \\\n 'smooth_n':5, \\\n 'smooth_method':'median',\\\n 'bar_trade':900 ,\\\n 'alpha':0.00361663652802893297, \\\n 'scale':4000, \\\n 'thres':0, \\\n 'buffer':0.1, \\\n 'ceil':5, \\\n 'pos_mul':27.35293614,\\\n 'time_from': '0800', \\\n 'time_to': '1430', \\\n 'start_utc': 0, \\\n 'end_utc': 0, \\\n 'prev_end_utc':0, \\\n 'trade_day': '20220215', \\\n 'last_ewma_time':'2022-02-14 1800',\\\n }\n\"\"\"\n\n#####################\n# Market Data Utils #\n#####################\ndef get_bar(barfile, barcnt):\n try:\n lines = subprocess.check_output(['tail', '-n', str(barcnt), barfile]).decode().split('\\n')[:-1]\n # bar line in the format of\n # bar_utc, open, high, low, close, vol, last_px, last_micro, vbs\n bars = []\n utc_col = 0\n close_px_col = 4\n for line in lines:\n v=line.split(',')\n bars.append([int(v[utc_col]), float(v[close_px_col])])\n return np.array(bars)\n except :\n traceback.print_exc()\n return None\n\ndef get_bar_utc(barfile, utc_array, max_search_cnt = 3600*24*2):\n utc_array = np.array(utc_array).astype(int)\n bars = get_bar(barfile, max_search_cnt)\n if bars is None:\n raise RuntimeError('Failed to get bar from %s'%(barfile))\n bcnt = len(bars)\n ix = np.clip(np.searchsorted(bars[:,0].astype(int),utc_array),0,bcnt-1)\n ixnz = np.nonzero(bars[ix,0].astype(int) != utc_array)[0]\n if len(ixnz) > 0:\n ix[ixnz] = np.clip(ix[ixnz]-1,0,bcnt-1)\n return bars[ix,1]\n\ndef get_latest_bar(barfile, last_utc):\n lbar = get_bar(barfile, 1)\n if lbar is None or lbar[0,0]<=last_utc:\n return None\n return lbar[0,:]\n\n\n##################################\n# get bar with column seletion ##\n##################################\ndef get_bar_cols(barfile, barcnt, cols=[0,1,2,3,4]):\n \"\"\"\n bar columns from live bar file:\n bar_utc, open, high, low, close, vol, last_px, last_micro, vbs\n\n same as get_bar(), with column selection\n input:\n cols: the index into the above list\n \"\"\"\n try:\n lines = subprocess.check_output(['tail', '-n', str(barcnt), barfile]).decode().split('\\n')[:-1]\n # bar line in the format of\n # bar_utc, open, high, low, close, vol, last_px, last_micro, vbs\n bars = []\n for line in lines:\n v=line.split(',')\n b = []\n for c in cols:\n if c == 0:\n b.append(int(v[c]))\n else :\n b.append(float(v[c]))\n bars.append(b)\n return np.array(bars)\n except :\n traceback.print_exc()\n return None\n\ndef get_bar_file(symbol, trade_day, barsec, symbol_spread_dict={}):\n # could throw if not a trading day\n smap = symbol_map.SymbolMap()\n tinfo = smap.get_tinfo(symbol, trade_day, True, symbol_spread_dict = symbol_spread_dict)\n fn = tpmon.get_bar_file(tinfo['tradable'], tinfo['venue'], int(barsec))\n return fn\n\ndef get_symbol_day_detail(symbol, trade_day, barsec, symbol_spread_dict={}, smap=None):\n # could throw if not a trading day\n if smap is None:\n smap = symbol_map.SymbolMap()\n tinfo = smap.get_tinfo(symbol, trade_day, True, symbol_spread_dict = symbol_spread_dict)\n live_bar_file = tpmon.get_bar_file(tinfo['tradable'], tinfo['venue'], int(barsec))\n contract = tinfo['contract_month']\n contract_size = int(float(tinfo['point_value']))\n tick_size = tinfo['tick_size']\n start_time = tinfo['start_time']\n end_time = tinfo['end_time']\n return live_bar_file, contract, float(contract_size), float(tick_size), start_time, end_time\n\n##############################\n# Smooth => EWMA => Position #\n##############################\ndef get_smooth(param, bar_array) :\n assert param['smooth_method'] == 'median'\n smooth_n = param['smooth_n']\n return np.median(bar_array[-smooth_n:])\n\ndef rolling_window(x, roll_period, roll_func, initial_val=None) :\n \"\"\"\n getting a rolling value of input 'x' using roll_func. \n input:\n x: 1d array\n roll_period: int, i.e. 14\n roll_func: expect to be able to run with roll_func(xv, axis=1),\n i.e. np.min/max/mean/std/sum/cumsum, etc\n initial_val: the value to use before roll_period can be obtained, \n i.e. the initial roll_period-1 \n if None, then uses the x[0]\n return:\n y: same length of x\n \"\"\"\n from scipy.linalg import hankel\n nd = len(x)\n if roll_period == 1:\n return roll_func(x.reshape((nd,1)),axis=1)\n\n assert roll_period <= nd, \"roll_period must not be more than data length\"\n x0 = initial_val\n if x0 is None:\n x0 = x[0]\n x0=np.array([x0]*(roll_period-1))\n xv=hankel(np.r_[x0, x[:-roll_period+1]],x[-roll_period:])\n return roll_func(xv,axis=1)\n\n##########################\n# State init from config #\n##########################\ndef get_strategy_weight(strategy_key, strat_weight_file):\n try :\n with open(strat_weight_file, 'r') as f:\n sw = yaml.safe_load(f)\n return float(sw[strategy_key])\n except :\n raise ValueError(\"failed to get weight for %s from %s!\"%(strategy_key,strat_weight_file))\n\n# submodels instead of spread_list\ndef init_symbol_config(param, logger, trade_day=None, symbol_spread_dict={}):\n sym_info = {}\n sym_list = []\n if trade_day is None:\n tdu = mts_util.TradingDayUtil()\n trade_day = tdu.get_trading_day(\n yyyymmdd_hh_mm_ss=trade_day,snap_forward=True)\n assert trade_day == param['trade_day'], \\\n \"current trading day (%s) mismatch with config (%s)\"%(trade_day, param['trade_day'])\n\n # getting the bar files for spreads\n smap = symbol_map.SymbolMap()\n barsec = param['barsec']\n for slist in param['submodels']:\n sym = slist['spread_symbol']\n tinfo = smap.get_tinfo(sym, trade_day, True, symbol_spread_dict = symbol_spread_dict)\n fn = tpmon.get_bar_file(tinfo['tradable'], tinfo['venue'], 1)\n slist['bar_file'] = fn\n\n # getting the start/stop times\n utc0 = int(datetime.datetime.strptime(trade_day, '%Y%m%d').strftime('%s'))\n ssutc = []\n for tstr in [tinfo['start_time'], tinfo['end_time']]:\n ts = tstr.split(':')\n ssutc.append(int(ts[0])*3600+int(ts[1])*60+int(ts[2]))\n if ssutc[0] >= ssutc[1]:\n ssutc[0]-=3600*24\n param['start_utc'] = utc0+ssutc[0]+barsec\n param['end_utc'] = utc0+ssutc[1]\n param['bar_utc'] = np.arange(param['start_utc'],\n param['end_utc']+barsec,barsec).astype(int)\n\n # getting the trade from/to\n ssutc = []\n for tstr in [param['time_from'], param['time_to']]:\n t=int(tstr[:2])*3600+int(tstr[2:4])*60+utc0\n if t>param['end_utc']:\n t-=(3600*24)\n ssutc.append(t)\n assert ssutc[0] <= ssutc[1], 'time_from not before time_to'\n param['trade_start_utc'] = ssutc[0]\n param['trade_end_utc'] = ssutc[1]\n\n # getting previous end time\n tdi = mts_util.TradingDayIterator(trade_day)\n tdi.begin()\n try :\n prev_trade_day = tdi.prev()\n tinfo = smap.get_tinfo(sym, prev_trade_day, True)\n logger.logInfo('got previous trading day of '+ prev_trade_day)\n except :\n logger.logInfo('problem getting previous trading day, try earlier day')\n prev_trade_day = tdi.prev()\n ts=tinfo['end_time'].split(':')\n utc0 = int(datetime.datetime.strptime(prev_trade_day, '%Y%m%d').strftime('%s'))\n param['prev_end_utc'] = utc0 + int(ts[0])*3600+int(ts[1])*60+int(ts[2])\n\n# Previous end of day signal is in the LiveHO\ndef init_state(param):\n \"\"\"\n [ \\\n { \\\n 'spread_symbol':'Brent_N1-Brent_N2', \\\n 'bar_file': '',\\\n 'state': { \\\n 'prev_px':[], \\\n 'bar_array':np.zeros(5), \\\n 'last_utc': 0,\\\n 'cur_ma':0 \\\n } \\\n } \\\n ], \\\n \"\"\"\n barcnt = param['smooth_n']\n barsec = param['barsec']\n utc_array = param['prev_end_utc']-np.arange(barcnt).astype(int)[::-1]*barsec\n\n for sdict in param['submodels']:\n fn = sdict['bar_file']\n prev_sig = sdict['sigprev']\n prev_bar = get_bar_utc(fn, utc_array)\n prev_px = get_smooth(param, prev_bar)\n state = { \\\n 'prev_px':[prev_px], \\\n 'bar_array':prev_bar, \\\n 'last_utc': utc_array[-1],\\\n 'cur_sig':prev_sig,\n }\n sdict['state']=copy.deepcopy(state)\n\ndef update_signal(param, sdict, lbar=None, update_state_signal=True):\n if lbar is None:\n # get the latest\n barfile = sdict['bar_file']\n barsec = param['barsec']\n last_utc = sdict['state']['last_utc']\n # normalize last_utc w.r.t barsec\n last_utc = int(np.round(float(last_utc)/barsec)*barsec)\n lbar = get_latest_bar(barfile, last_utc)\n if lbar is None:\n print('lbar is None ' + barfile + str(last_utc))\n return None\n if lbar[0] < last_utc+barsec:\n print('lbar[0] < last_utc+barsec: %d %d %d %s'%(lbar[0], last_utc, barsec, \\\n str(datetime.datetime.now())))\n return None\n\n state_sym = sdict['state']\n last_utc, lpx = lbar\n state_sym['last_utc']=last_utc\n state_sym['bar_array']=np.r_[state_sym['bar_array'][1:],lpx]\n smooth_px = get_smooth(param, state_sym['bar_array'])\n sig = None\n if update_state_signal:\n # Signal is Z-score of daily ret - standardized\n # Get current return\n cur_ret = smooth_px - sdict['pxprev']\n # Calc 'z-score'\n zeta = (cur_ret - sdict['sig_m']) / sdict['sig_s']\n # Apply scale factor\n zsc = zeta * sdict['sig_sf']\n # Apply buffer to get raw signal\n buf = sdict['buffer']\n raw = int(abs(zsc)/buf)*buf * np.sign(zsc)\n # Get previous binary signal\n prev_sig = state_sym['cur_sig']\n # Get new binary signal\n # No position -> Check entry threshold\n if prev_sig == 0 and abs(raw) >= sdict['entry']:\n sig = np.sign(raw)\n # Position on -> Check exit threshold\n elif prev_sig > 0 and raw <= sdict['exit']:\n sig = 0\n elif prev_sig < 0 and raw >= -sdict['exit']:\n sig = 0\n # Keep previous position\n else: \n sig = prev_sig\n\n # Update state\n sig = np.sign(sig)\n state_sym['cur_sig'] = sig\n\n state_sym['prev_px'].append(smooth_px) # not used in current version\n return sig\n\ndef get_pos(ret_ma, param):\n pos_mul = param['pos_mul']\n sig = ret_ma\n sigs = np.sign(sig)\n sig*=sigs\n pos = int(sig*pos_mul+0.5)*sigs\n return pos\n\ndef dump_state(sdict):\n # dump format \n # spread_symbol, ma, last_px, smoothed_px, last_utc\n return '%s, %.7f, %.7f, %.7f, %d'%\\\n (sdict['spread_symbol'], \\\n sdict['state']['cur_sig'], \\\n sdict['state']['bar_array'][-1],\\\n sdict['state']['prev_px'][-1], \\\n sdict['state']['last_utc'])\n\ndef pnl_from_p0(p00, p0, lpx, tcost, fee = 2.0, contract_size=1000, lr0=0) :\n \"\"\"\n p00: scalar, the starting position\n p0: len(n) integer vector, target position at bar k, k=0,1,2,...,n-1.\n p0[k] is the target position at close of bar k. bar 0 is the first\n bar from 6:00 to 6:05pm\n lpx: len(n) vector, price at close of each bar\n tcost: scalar, usually half of spread plus a slippage, in price\n fee: scalar, fee per transaction, regardless of size\n lr0: the first log return at 6:05, used to apply p00 for initial pnl\n\n return:\n pnl, pnl_cost - \n length n+1 vector, pnl[k] is the value of cash+asset at close of bar k.\n the last pnl is the ending value.\n \"\"\"\n p0d = p0-np.r_[p00,p0[:-1]]\n trd_cst = np.abs(p0d)*tcost*contract_size+np.abs(np.sign(p0d))*fee\n lpx0 = np.r_[lpx[0]/np.exp(lr0),lpx]\n pnl = (lpx0[1:]-lpx0[:-1])*np.r_[p00,p0[:-1]]* contract_size\n #pnl = np.r_[0,(lpx[1:]-lpx[:-1])*p0[:-1]]* contract_size\n pnl_cst = pnl-trd_cst\n return pnl, pnl_cst\n\n##################\n# MTS Floor Util #\n##################\ndef set_target_position(strat, symbol, qty, logger, twap_minutes = 15, trader_type='T'):\n # set position for symbol with target position to be qty\n run_str = ['/home/mts/run/bin/flr', 'X', strat + ', ' + symbol + ', ' + str(qty) + ', %s%dm'%(trader_type,twap_minutes)]\n try :\n ret = subprocess.check_output(run_str)\n except subprocess.CalledProcessError as e:\n if logger is not None:\n logger.logError(\"Failed to run command \" + str(run_str) + \", return code: \" + str(e.returncode) + \", return output: \" + str(e.output))\n\ndef get_mts_position(strat, symbol, logger=None, verbose=False):\n run_str = ['/home/mts/run/bin/flr', 'P', ',']\n symbol_str = symbol.split('_')[0]\n try:\n ret = subprocess.check_output(run_str)\n lines = ret.decode().split('\\n')[:-1]\n pos = []\n for line in lines:\n line = ' '.join(line.split())\n if strat in line and symbol_str in line:\n pos.append(int(line.split(' ')[2]))\n if len(pos) == 0:\n if verbose:\n if logger is not None:\n logger.logInfo('position not found for strategy %s, symbol %s'%(strat, symbol_str))\n if len(pos) > 1:\n if logger is not None:\n logger.logInfo('%d positions found for strategy %s, symbol %s: %s'%(len(pos), strat, symbol_str, str(pos)))\n return np.sum(pos)\n except subprocess.CalledProcessError as e:\n if logger is not None:\n logger.logError(\"Failed to run command \" + str(run_str) + \", return code: \" + str(e.returncode) + \", return output: \" + str(e.output))\n except Exception as e:\n if logger is not None:\n logger.logError(\"Failed to run command \" + str(run_str) + \", return code: \" + str(e))\n return None\n","sub_path":"mts/python/strat_utils.py","file_name":"strat_utils.py","file_ext":"py","file_size_in_byte":14867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"301937614","text":"import argparse\nimport yaml\nimport os\nimport time\nfrom src.result.model_output_generation import make_evaluation \n\nwith open(\"cnfg.yml\", 'r') as stream:\n try:\n config = yaml.safe_load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n\t\t\n# Create the parser and add arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('-c', '--num_class', type=int, help=\"The number of classes for test or validation\", nargs = '?', const = 1, default = 3)\nparser.add_argument('-i', '--input_source', type=int, help=\"Input foom flat file or DB, 1 for DB\", nargs = '?', const = 1, default = 0)\nparser.add_argument('-t', '--is_train', type=int, help=\"use for train or test, 1 for train\", nargs = '?', const = 1, default = 0)\nparser.add_argument('-f', '--input_file_name', type=str, help=\"get file name if flat file source is defined\", nargs = '?', const = 1, default = 'input_data.csv')\nparser.add_argument('-d', '--device', type=str, help=\"select device (cpu, cuda) for model run\", nargs = '?', choices = ['cpu', 'cuda'], default = 'cpu') \nargs = parser.parse_args()\nprint(args)\n\nconfig['file_input']['use_DB'] = args.input_source\nconfig['model_input']['num_class'] = args.num_class\nconfig['model_input']['is_train'] = args.is_train\nconfig['file_input']['input_file_name'] = args.input_file_name\nconfig['model_input']['device'] = args.device\nprint('Model is running for {0} classes on {1}...'.format(config['model_input']['num_class'], config['model_input']['device']))\n \nif __name__ == '__main__':\n start = time.time()\n df = make_evaluation(config)\n if config['model_input']['num_class'] > 2:\n save_name = os.path.join(os.getcwd(), config['file_output']['output_dir'], config['file_output']['file_name'][1])\n else:\n save_name = os.path.join(os.getcwd(), config['file_output']['output_dir'], config['file_output']['file_name'][0])\n df.to_csv(save_name, index = False)\n done = time.time()\n elapsed = done - start\n print('time taken to complete the module is {:.2f} seconds'.format(round(elapsed, 2)))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"302953402","text":"#!/usr/bin/python\n\nimport aerospike\nfrom aerospike.exception import TimeoutError, ClientError\nimport itertools\nimport re\nimport pprint\n\nimport collectd\n\nclass Data(object):\n pass\n\nclass AerospikePlugin(object):\n def __init__(self):\n self.plugin_name = \"aerospike\"\n self.prefix = None\n self.host_name = None\n self.aerospike = Data()\n self.aerospike.host = \"127.0.0.1\"\n self.aerospike.port = 3000\n self.aerospike.user = None\n self.aerospike.password = None\n self.node_id = None\n self.timeout = 2000\n\n def submit(self, value_type, instance, value, context, use_node_id=True):\n plugin_instance = []\n if self.prefix:\n plugin_instance.append(self.prefix)\n\n if use_node_id:\n plugin_instance.append(self.node_id)\n plugin_instance.append(context)\n\n plugin_instance = \".\".join(plugin_instance)\n data = pprint.saferepr((value_type,plugin_instance,instance\n ,value,context))\n collectd.debug(\"Dispatching: %s\"%(data))\n\n val = collectd.Values()\n if self.host_name:\n val.host = self.host_name\n val.plugin = self.plugin_name\n val.plugin_instance = plugin_instance\n val.type = value_type\n val.type_instance = instance.lower().replace('-', '_')\n # HACK with this dummy dict in place JSON parsing works\n # https://github.com/collectd/collectd/issues/716\n val.meta = {'0': True}\n val.values = [value, ]\n val.dispatch()\n\n def process_statistics(self, meta_stats, statistics, context, counters=None\n , counts=None, storage=None, booleans=None\n , percents=None, operations=None, config=None):\n if counters is None:\n counters = set()\n if counts is None:\n counts = set()\n if storage is None:\n storage = set()\n if booleans is None:\n booleans = set()\n if percents is None:\n percents = set()\n if operations is None:\n operations = set()\n if config is None:\n config = set()\n for key, value in statistics.iteritems():\n if key in counters:\n value_type = \"count\"\n elif key in counts:\n value_type = \"count\"\n elif key in booleans:\n value_type = \"boolean\"\n value = value.lower()\n if value == \"false\" or value == \"no\" or value == \"0\" or value == \"CLUSTER_DOWN\":\n value = 0\n else:\n value = 1\n elif key in percents:\n value_type = \"percent\"\n elif key in storage:\n value_type = \"bytes\"\n elif key in operations:\n value_type = \"count\"\n elif key in config:\n continue\n else:\n try:\n float(value)\n except ValueError:\n pass\n else:\n # Log numeric values that aren't emitted\n stat_name = \"%s.%s\"%(context, key)\n\n collectd.info(\"Unused numeric stat: %s has value %s\"%(\n stat_name, value))\n meta_stats[\"unknown_metrics\"] += 1\n continue\n\n self.submit(value_type, key, value, context)\n\n def do_service_statistics(self, meta_stats, client, hosts):\n counters = set([\"uptime\",])\n\n counts = set([\n \"batch_queue\"\n , \"batch_tree_count\"\n , \"client_connections\"\n , \"cluster_size\"\n , \"delete_queue\"\n , \"info_queue\"\n , \"migrate_progress_recv\"\n , \"migrate_progress_send\"\n , \"migrate_rx_objs\"\n , \"migrate_tx_objs\"\n , \"objects\"\n , \"ongoing_write_reqs\"\n , \"partition_absent\"\n , \"partition_actual\"\n , \"partition_desync\"\n , \"partition_object_count\"\n , \"partition_ref_count\"\n , \"partition_replica\"\n , \"proxy_in_progress\"\n , \"queue\"\n , \"record_locks\"\n , \"record_refs\"\n , \"stat_evicted_objects_time\"\n , \"sub-records\"\n , \"tree_count\"\n , \"waiting_transactions\"\n , \"query_long_queue_size\"\n , \"query_short_queue_size\"\n ])\n\n booleans = set([\n \"cluster_integrity\"\n , \"system_swapping\"\n ])\n\n percents = set([\n \"free-pct-disk\"\n , \"free-pct-memory\"\n , \"system_free_mem_pct\"\n ])\n\n storage = set([\n \"data-used-bytes-memory\"\n , \"index-used-bytes-memory\"\n , \"sindex-used-bytes-memory\"\n , \"total-bytes-disk\"\n , \"total-bytes-memory\"\n , \"used-bytes-disk\"\n , \"used-bytes-memory\"\n ])\n\n operations = set([\n \"aggr_scans_succeeded\"\n , \"aggr_scans_failed\"\n , \"basic_scans_failed\"\n , \"basic_scans_succeeded\"\n , \"batch_errors\"\n , \"batch_index_initiate\"\n , \"batch_index_complete\"\n , \"batch_index_timeout\"\n , \"batch_index_errors\"\n , \"batch_index_unused_buffers\"\n , \"batch_index_huge_buffers\"\n , \"batch_index_created_buffers\"\n , \"batch_index_destroyed_buffers\"\n , \"batch_initiate\"\n , \"batch_timeout\"\n , \"err_duplicate_proxy_request\"\n , \"err_out_of_space\"\n , \"err_replica_non_null_node\"\n , \"err_replica_null_node\"\n , \"err_rw_cant_put_unique\"\n , \"err_rw_pending_limit\"\n , \"err_rw_request_not_found\"\n , \"err_storage_queue_full\"\n , \"err_sync_copy_null_master\"\n , \"err_sync_copy_null_node\"\n , \"err_tsvc_requests\"\n , \"err_tsvc_requests_timeout\"\n , \"err_write_fail_bin_exists\"\n , \"err_write_fail_bin_name\"\n , \"err_write_fail_bin_not_found\"\n , \"err_write_fail_forbidden\"\n , \"err_write_fail_generation\"\n , \"err_write_fail_generation_xdr\"\n , \"err_write_fail_incompatible_type\"\n , \"err_write_fail_key_exists\"\n , \"err_write_fail_key_mismatch\"\n , \"err_write_fail_not_found\"\n , \"err_write_fail_noxdr\"\n , \"err_write_fail_parameter\"\n , \"err_write_fail_prole_delete\"\n , \"err_write_fail_prole_generation\"\n , \"err_write_fail_prole_unknown\"\n , \"err_write_fail_record_too_big\"\n , \"err_write_fail_unknown\"\n , \"fabric_msgs_rcvd\"\n , \"fabric_msgs_sent\"\n , \"heartbeat_received_foreign\"\n , \"heartbeat_received_self\"\n , \"migrate_msgs_recv\"\n , \"migrate_msgs_sent\"\n , \"migrate_num_incoming_accepted\"\n , \"migrate_num_incoming_refused\"\n , \"proxy_action\"\n , \"proxy_initiate\"\n , \"proxy_retry\"\n , \"proxy_retry_new_dest\"\n , \"proxy_retry_q_full\"\n , \"proxy_retry_same_dest\"\n , \"proxy_unproxy\"\n , \"query_abort\"\n , \"query_agg\"\n , \"query_agg_abort\"\n , \"query_agg_avg_rec_count\"\n , \"query_agg_err\"\n , \"query_agg_success\"\n , \"query_avg_rec_count\"\n , \"query_fail\"\n , \"query_long_queue_full\"\n , \"query_long_reqs\"\n , \"query_long_running\"\n , \"query_lookup_abort\"\n , \"query_lookup_avg_rec_count\"\n , \"query_lookup_err\"\n , \"query_lookups\"\n , \"query_lookup_success\"\n , \"query_reqs\"\n , \"query_short_queue_full\"\n , \"query_short_reqs\"\n , \"query_short_running\"\n , \"query_success\"\n , \"query_tracked\"\n , \"read_dup_prole\"\n , \"reaped_fds\"\n , \"rw_err_ack_badnode\"\n , \"rw_err_ack_internal\"\n , \"rw_err_ack_nomatch\"\n , \"rw_err_dup_cluster_key\"\n , \"rw_err_dup_internal\"\n , \"rw_err_dup_send\"\n , \"rw_err_write_cluster_key\"\n , \"rw_err_write_internal\"\n , \"rw_err_write_send\"\n , \"scans_active\"\n , \"sindex_gc_activity_dur\"\n , \"sindex_gc_garbage_cleaned\"\n , \"sindex_gc_garbage_found\"\n , \"sindex_gc_inactivity_dur\"\n , \"sindex_gc_list_creation_time\"\n , \"sindex_gc_list_deletion_time\"\n , \"sindex_gc_locktimedout\"\n , \"sindex_gc_objects_validated\"\n , \"sindex_ucgarbage_found\"\n , \"stat_cluster_key_err_ack_dup_trans_reenqueue\"\n , \"stat_cluster_key_err_ack_rw_trans_reenqueue\"\n , \"stat_cluster_key_partition_transaction_queue_count\"\n , \"stat_cluster_key_prole_retry\"\n , \"stat_cluster_key_regular_processed\"\n , \"stat_cluster_key_transaction_reenqueue\"\n , \"stat_cluster_key_trans_to_proxy_retry\"\n , \"stat_deleted_set_objects\"\n , \"stat_delete_success\"\n , \"stat_duplicate_operation\"\n , \"stat_evicted_objects\"\n , \"stat_expired_objects\"\n , \"stat_ldt_proxy\"\n , \"stat_nsup_deletes_not_shipped\"\n , \"stat_evicted_set_objects\"\n , \"stat_proxy_errs\"\n , \"stat_proxy_reqs\"\n , \"stat_proxy_reqs_xdr\"\n , \"stat_proxy_success\"\n , \"stat_read_errs_notfound\"\n , \"stat_read_errs_other\"\n , \"stat_read_reqs\"\n , \"stat_read_reqs_xdr\"\n , \"stat_read_success\"\n , \"stat_rw_timeout\"\n , \"stat_slow_trans_queue_batch_pop\"\n , \"stat_slow_trans_queue_pop\"\n , \"stat_slow_trans_queue_push\"\n , \"stat_write_errs\"\n , \"stat_write_errs_notfound\"\n , \"stat_write_errs_other\"\n , \"stat_write_reqs\"\n , \"stat_write_reqs_xdr\"\n , \"stat_write_success\"\n , \"stat_xdr_pipe_miss\"\n , \"stat_xdr_pipe_writes\"\n , \"stat_zero_bin_records\"\n , \"storage_defrag_corrupt_record\"\n , \"transactions\"\n , \"tscan_aborted\"\n , \"tscan_initiate\"\n , \"tscan_pending\"\n , \"tscan_succeeded\"\n , \"udf_bg_scans_succeeded\"\n , \"udf_bg_scans_failed\"\n , \"udf_delete_err_others\"\n , \"udf_delete_reqs\"\n , \"udf_delete_success\"\n , \"udf_lua_errs\"\n , \"udf_query_rec_reqs\"\n , \"udf_read_errs_other\"\n , \"udf_read_reqs\"\n , \"udf_read_success\"\n , \"udf_replica_writes\"\n , \"udf_scan_rec_reqs\"\n , \"udf_write_err_others\"\n , \"udf_write_reqs\"\n , \"udf_write_success\"\n , \"write_master\"\n , \"write_prole\"\n ])\n\n try:\n _, (_, statistics) = client.info(\"statistics\", hosts=hosts).items()[0]\n except (TimeoutError, ClientError):\n collectd.warning('WARNING: TimeoutError executing info(\"statistics\")')\n meta_stats[\"timeouts\"] += 1\n else:\n statistics = info_to_dict(statistics)\n self.process_statistics(meta_stats\n , statistics\n , \"service\"\n , counters=counters\n , counts=counts\n , storage=storage\n , booleans=booleans\n , percents=percents\n , operations=operations)\n\n def do_namespace_statistics(self, meta_stats, client, hosts, namespaces):\n counters = set([\n \"available-bin-names\"\n , \"current-time\"\n , \"max-evicted-ttl\"\n , \"max-void-time\"\n , \"obj-size-hist-max\"\n ])\n\n counts = set([\n \"master-objects\"\n , \"master-sub-objects\"\n , \"non-expirable-objects\"\n , \"nsup-cycle-duration\"\n , \"objects\"\n , \"prole-objects\"\n , \"prole-sub-objects\"\n , \"repl-factor\"\n , \"sub-objects\"\n ])\n\n storage = set([\n \"data-used-bytes-memory\"\n , \"index-used-bytes-memory\"\n , \"sindex-used-bytes-memory\"\n , \"total-bytes-disk\"\n , \"total-bytes-memory\"\n , \"used-bytes-disk\"\n , \"used-bytes-memory\"\n ])\n\n booleans = set([\n \"hwm-breached\"\n , \"stop-writes\"\n ])\n\n percents = set([\n \"available_pct\"\n , \"cache-read-pct\"\n , \"free-pct-disk\"\n , \"free-pct-memory\"\n , \"nsup-cycle-sleep-pct\"\n ])\n\n operations = set([\n \"evicted-objects\"\n , \"expired-objects\"\n , \"ldt_deletes\"\n , \"ldt_delete_success\"\n , \"ldt_errors\"\n , \"ldt_reads\"\n , \"ldt_read_success\"\n , \"ldt_updates\"\n , \"ldt_writes\"\n , \"ldt_write_success\"\n , \"set-deleted-objects\"\n , \"set-evicted-objects\"\n ])\n\n config = set([\n \"max-write-cache\"\n , \"defrag-startup-minimum\"\n , \"ldt-page-size\"\n , \"high-water-memory-pct\"\n , \"memory-size\"\n , \"max-ttl\"\n , \"filesize\"\n , \"min-avail-pct\"\n , \"fsync-max-sec\"\n , \"default-ttl\"\n , \"cold-start-evict-ttl\"\n , \"defrag-sleep\"\n , \"write-smoothing-period\"\n , \"stop-writes-pct\"\n , \"defrag-queue-min\"\n , \"post-write-queue\"\n , \"high-water-disk-pct\"\n , \"writethreads\"\n , \"writecache\"\n , \"evict-tenths-pct\"\n , \"defrag-lwm-pct\"\n , \"flush-max-ms\"\n ])\n\n for namespace in namespaces:\n command = \"namespace/%s\"%(namespace)\n try:\n _, (_, statistics) = client.info(command\n , hosts=hosts).items()[0]\n except (TimeoutError, ClientError):\n collectd.warning('WARNING: TimeoutError executing info(\"%s\")'%(command))\n meta_stats[\"timeouts\"] += 1\n continue\n\n statistics = info_to_dict(statistics)\n\n self.process_statistics(meta_stats\n , statistics\n , \"namespace.%s\"%(namespace)\n , counters=counters\n , counts=counts\n , storage=storage\n , booleans=booleans\n , percents=percents\n , operations=operations\n , config=config)\n\n def do_dc_statistics(self, meta_stats, client, hosts, datacenters):\n counters = set([\n \"xdr_dc_delete_ship_attempts\"\n , \"xdr_dc_rec_ship_attempts\"\n , \"xdr_dc_remote_ship_ok\"\n ])\n counts = set([\n \"xdr_dc_size\"\n , \"open_conn\"\n , \"xdr_dc_recs_shipping\"\n , \"xdr_dc_timelag\"\n , \"latency_avg_ship_ema\"\n , \"pool_conn\"\n ])\n percents = set([\n \"est_ship_compression_pct\"\n ])\n booleans = set([\n \"xdr_dc_state\"\n ])\n storage = set([\n \"esmt_byes_put_compressed\"\n ])\n for dc in datacenters:\n command = \"dc/%s\"%(dc)\n try:\n _, (_, statistics) = client.info(command\n , hosts=hosts).items()[0]\n except (TimeoutError, ClientError):\n collectd.warning('WARNING: TimeoutError executing info(\"%s\")'%(command))\n meta_stats[\"timeouts\"] += 1\n continue\n\n statistics = info_to_dict(statistics)\n\n self.process_statistics(meta_stats\n , statistics\n , \"namespace.%s\"%(namespace)\n , counters=counters\n , counts=counts\n , storage=storage\n , booleans=booleans\n , percents=percents)\n\n def do_latency_statistics(self, meta_stats, client, hosts):\n try:\n _, (_, tdata) = client.info(\"latency:\", hosts=hosts).items()[0]\n except (TimeoutError, ClientError):\n collectd.warning('WARNING: TimeoutError executing info(\"latency:\")')\n meta_stats[\"timeouts\"] += 1\n return\n\n tdata = tdata.split(';')[:-1]\n while tdata != []:\n columns = tdata.pop(0)\n row = tdata.pop(0)\n\n hist_name, columns = columns.split(':', 1)\n columns = columns.split(',')\n row = row.split(',')\n\n # Get rid of duration data\n columns.pop(0)\n row.pop(0)\n row = [float(r) for r in row]\n\n # Don't need TPS column name\n columns.pop(0)\n tps_name = \"%s_tps\"%(hist_name)\n tps_value = row.pop(0)\n\n self.submit(\"count\", tps_name, tps_value, \"latency\")\n\n while columns:\n name = \"%s_pct%s\"%(hist_name, columns.pop(0))\n name = name.replace(\">\", \"_gt_\")\n value = row.pop(0)\n self.submit(\"percent\", name, value, \"latency\")\n\n def do_cluster_statistics(self, meta_stats, client, hosts):\n try:\n _, (_, tservices) = client.info(\"services\", hosts=hosts).items()[0]\n except (TimeoutError, ClientError):\n collectd.warning('WARNING: TimeoutError executing info(\"services\")')\n meta_stats[\"timeouts\"] += 1\n\n try:\n _, (_, talumni) = client.info(\"services-alumni\", hosts=hosts).items()[0]\n except (TimeoutError, ClientError):\n collectd.warning('WARNING: TimeoutError executing info(\"services-alumni\")')\n meta_stats[\"timeouts\"] += 1\n\n if tservices and talumni:\n services = tservices.split(\";\")\n alumni = talumni.split(\";\")\n\n self.submit(\"count\", \"services\", len(services), \"cluster\")\n self.submit(\"count\", \"services-alumni\", len(alumni), \"cluster\")\n\n def do_meta_statistics(self, meta_stats, context=\"meta\"):\n for key, value in meta_stats.iteritems():\n name = \"%s\"%(key)\n if isinstance(value, dict):\n self.do_meta_statistics(value, context=\"%s.%s\"%(context, name))\n else:\n self.submit(\"count\", name, value, context)\n\n def get_all_statistics(self):\n collectd.debug(\"AEROSPIKE PLUGIN COLLECTING STATS\")\n hosts = [(self.aerospike.host, self.aerospike.port)]\n policy = {\"timeout\": self.timeout}\n config = {\"hosts\":hosts, \"policy\":policy}\n\n meta_stats = {\"timeouts\": 0\n , \"unknown_metrics\": 0}\n\n client = aerospike.client(config)\n try:\n if self.aerospike.user:\n client.connect(self.aerospike.user, self.aerospike.password)\n else:\n client.connect()\n except (TimeoutError, ClientError):\n collectd.warning('WARNING: ClientError unable to connect to Aerospike Node')\n self.submit(\"count\", \"connection_failure\", 1, \"meta\", use_node_id=False)\n return\n else:\n self.submit(\"count\", \"connection_failure\", 0, \"meta\", use_node_id=False)\n # Get this Nodes ID\n try:\n _, (_, node_id) = client.info(\"node\", hosts=hosts).items()[0]\n except (TimeoutError, ClientError):\n collectd.warning('WARNING: TimeoutError executing info(\"node\")')\n meta_stats[\"timeouts\"] += 1\n else:\n self.node_id = node_id.strip()\n self.do_service_statistics(meta_stats, client, hosts)\n\n # Get list of namespaces\n try:\n _, (_, namespaces) = client.info(\"namespaces\"\n , hosts=hosts).items()[0]\n except (TimeoutError, ClientError):\n collectd.warning('WARNING: TimeoutError executing info(\"namespaces\")')\n meta_stats[\"timeouts\"] += 1\n else:\n namespaces = info_to_list(namespaces)\n self.do_namespace_statistics(meta_stats, client\n , hosts, namespaces)\n # Get list of XDR targets\n try:\n _, (_, dc_info) = client.info(\"get-dc-config\"\n , hosts=hosts).items()[0]\n except (TimeoutError, ClientError): \n collectd.warning('WARNING: TimeoutError executing info(\"get-dc-config\")')\n meta_stats[\"timeouts\"] += 1\n else:\n if dc_info:\n dcs = info_to_list(dc_info)\n self.do_dc_statistics(meta_stats, client\n , hosts, dcs)\n\n self.do_latency_statistics(meta_stats, client, hosts)\n\n self.do_cluster_statistics(meta_stats, client, hosts)\n finally:\n client.close()\n\n self.do_meta_statistics(meta_stats)\n\n def config(self, obj):\n for node in obj.children:\n if node.key == \"Host\":\n self.aerospike.host = node.values[0]\n elif node.key == \"Port\":\n self.aerospike.port = int(node.values[0])\n elif node.key == \"User\":\n self.aerospike.user = node.values[0]\n elif node.key == \"Password\":\n self.aerospike.password = node.values[0]\n elif node.key == \"Timeout\":\n self.timeout = int(node.values[0])\n elif node.key == \"Prefix\":\n self.prefix = node.values[0]\n elif node.key == \"HostNameOverride\":\n self.host_name = node.values[0]\n else:\n collectd.warning(\"%s: Unknown configuration key %s\"%(\n self.plugin_name\n , node.key))\n\ndef info_to_dict(value, delimiter=';'):\n \"\"\"\n Simple function to convert string to dict\n \"\"\"\n\n stat_dict = {}\n stat_param = itertools.imap(lambda sp: info_to_tuple(sp, \"=\"),\n info_to_list(value, delimiter))\n for g in itertools.groupby(stat_param, lambda x: x[0]):\n try:\n value = [v[1] for v in g[1]]\n value = \",\".join(sorted(value))\n stat_dict[g[0]] = value\n except:\n collectd.warning(\"WARNING: info_to_dict had problems parsing %s\"%(\n value))\n return stat_dict\n\ndef info_colon_to_dict(value):\n \"\"\"\n Simple function to convert colon separated string to dict\n \"\"\"\n return info_to_dict(value, ':')\n\ndef info_to_list(value, delimiter=\";\"):\n return [s.strip() for s in re.split(delimiter, value)]\n\ndef info_to_tuple(value, delimiter=\":\"):\n return tuple(info_to_list(value, delimiter))\n\ndef info_to_dc_names(value):\n v = value.strip().split(';')\n return [ s.split(':')[0].split('=')[1] for s in v ]\n\n\nas_plugin = AerospikePlugin()\ncollectd.register_read(as_plugin.get_all_statistics)\ncollectd.register_config(as_plugin.config)\n","sub_path":"aerospike_plugin.py","file_name":"aerospike_plugin.py","file_ext":"py","file_size_in_byte":24050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"254647683","text":"# -*- coding: utf-8 -*-\ndef max_deg(k):\n deg_k = []\n for i in range(0, len(k)-1):\n deg_k.append(abs(k[i]-k[i+1]))\n return max(deg_k)\n############ - PROGRAMA PRINCIPAL - ############\nn = int(input(\"Digite a quantidade de termos da lista: \"))\nk = []\nfor i in range(1, n+1):\n k.append(int(input(\"Digite o %dº elemento: \"%i)))\nprint(max_deg(k))","sub_path":"moodledata/vpl_data/334/usersdata/292/94150/submittedfiles/listas.py","file_name":"listas.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"290404168","text":"import json\n\nfrom tornado.ioloop import IOLoop\nfrom tornado.websocket import WebSocketHandler\nfrom tornado.web import Application, RequestHandler\nimport jwt\n\nfrom lib.logger import Logger\nfrom lib.controller import UserController\nfrom lib.conf import settings\n\nlogger_instance = Logger(**{\n 'file_name': 'error.log',\n 'stream_handler': True,\n 'file_handler': True\n})\nlogger_instance_info = Logger(**{\n 'file_name': 'tornado_server.log',\n 'stream_handler': True,\n 'file_handler': False\n})\n\n\nactive_clients = []\n\n\nclass SocketOutputHandler(WebSocketHandler):\n\n def check_origin(self, origin):\n return True\n\n def open(self):\n try:\n token = self.request.headers.get('Authorization')\n payload = jwt.decode(token, verify=False)\n\n if 'email' not in payload:\n self.close()\n\n if self not in active_clients:\n active_clients.append(self)\n except jwt.exceptions.DecodeError as error:\n self.close()\n\n except Exception as error:\n logger_instance.logger.error(\n 'SocketOutputHandler::open:{}'.format(\n error.message\n ))\n\n def on_message(self, message):\n try:\n logger_instance_info.logger.info('client message::{}'.format(\n message))\n except Exception as error:\n logger_instance.logger.error(\n 'SocketOutputHandler::on_message:{}'.format(error.message))\n\n def on_close(self):\n try:\n logger_instance_info.logger.info(\n 'disconnecting client...')\n except Exception as error:\n logger_instance.logger.error(\n 'SocketOutputHandler::on_close:{}'.format(error.message))\n\n def authenticate_client(self):\n try:\n pass\n except Exception as error:\n logger_instance\n\n\nclass ClientAuthentication(RequestHandler):\n\n def post(self, *args, **kwargs):\n try:\n post_param = json.loads(self.request.body)\n if 'email' not in post_param or 'password' not in post_param:\n raise KeyError\n\n if UserController.authenticate(post_param['email'],\n post_param['password']):\n payload = {\n 'email': post_param['email'],\n 'password': post_param['password']\n }\n response_json = {'token': jwt.encode(\n payload, settings.JWT_SECRET, algorithm='HS512')}\n self.write(json.dumps(response_json))\n else:\n self.clear()\n self.set_status(403)\n self.write('invalid credentials')\n\n except Exception as error:\n logger_instance.logger.error(\n 'ClientAuthentication::post:{}'.format(error.message))\n\n\nclass MainApplication(Application):\n\n def __init__(self):\n handlers = [\n (r'/sock_server/', SocketOutputHandler),\n (r'/get_token/', ClientAuthentication),\n ]\n\n Application.__init__(self, handlers)\n\n\ndef main():\n app_instance = MainApplication()\n print('[*] started socket server at 8001')\n app_instance.listen(8001, address='0.0.0.0')\n IOLoop.instance().start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"components/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"186951746","text":"load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\", \"http_file\")\nload(\"@bazel_tools//tools/build_defs/repo:java.bzl\", \"java_import_external\")\nload(\"@bazel_tools//tools/build_defs/repo:jvm.bzl\", \"jvm_maven_import_external\")\nload(\"//3rdparty:maven.bzl\", \"list_dependencies\")\n\n_SRC_FILEGROUP_BUILD_FILE_CONTENT = \"\"\"\nfilegroup(\n name = \"src\",\n srcs = glob([\"**/*.scala\", \"**/*.java\"]),\n visibility = [\"//visibility:public\"]\n)\"\"\"\n\ndef scala_repositories():\n for dep in list_dependencies():\n java_import_external(**dep[\"import_args\"])\n\n BAZEL_JAVA_LAUNCHER_VERSION = \"0.11.1\"\n java_stub_template_url = (\n \"raw.githubusercontent.com/bazelbuild/bazel/\" +\n BAZEL_JAVA_LAUNCHER_VERSION +\n \"/src/main/java/com/google/devtools/build/lib/bazel/rules/java/\" +\n \"java_stub_template.txt\"\n )\n\n http_file(\n name = \"anx_java_stub_template\",\n sha256 = \"2cbba7c512e400df0e7d4376e667724a38d1155db5baaa81b72ad785c6d761d1\",\n urls = [\n \"https://mirror.bazel.build/%s\" % java_stub_template_url,\n \"https://%s\" % java_stub_template_url,\n ],\n )\n\n http_archive(\n name = \"compiler_bridge_2_11\",\n build_file_content = _SRC_FILEGROUP_BUILD_FILE_CONTENT,\n sha256 = \"355abdd13ee514a239ed48b6bf8846f2a1d9d78bca8df836028d0156002ea08a\",\n url = \"http://central.maven.org/maven2/org/scala-sbt/compiler-bridge_2.11/1.2.1/compiler-bridge_2.11-1.2.1-sources.jar\",\n )\n\n http_archive(\n name = \"compiler_bridge_2_12\",\n build_file_content = _SRC_FILEGROUP_BUILD_FILE_CONTENT,\n sha256 = \"d7a5dbc384c2c86479b30539cef911c256b7b3861ced68699b116e05b9357c9b\",\n url = \"http://central.maven.org/maven2/org/scala-sbt/compiler-bridge_2.12/1.2.1/compiler-bridge_2.12-1.2.1-sources.jar\",\n )\n\n jvm_maven_import_external(\n name = \"scala_compiler_2_12_8\",\n artifact = \"org.scala-lang:scala-compiler:2.12.8\",\n licenses = [\"notice\"],\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n jvm_maven_import_external(\n name = \"scala_library_2_12_8\",\n artifact = \"org.scala-lang:scala-library:2.12.8\",\n licenses = [\"notice\"],\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n jvm_maven_import_external(\n name = \"scala_reflect_2_12_8\",\n artifact = \"org.scala-lang:scala-reflect:2.12.8\",\n licenses = [\"notice\"],\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef scala_register_toolchains():\n # reserved for future use\n return ()\n","sub_path":"rules/scala/workspace.bzl","file_name":"workspace.bzl","file_ext":"bzl","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"403055223","text":"from PIL import Image\r\n\r\n# Add commands to import modules here.\r\n# Define your load_img() function here.\r\n# Parameters: The name of the file to be opened (string)\r\n# Returns: The image object with the opened file.\r\ndef load_img(filename):\r\n img = Image.open(filename)\r\n show_img(filename,img)\r\n return img\r\n\r\n# Define your show_img() function here.\r\n# Parameters: The image object to display.\r\n# Returns: nothing.\r\ndef show_img(filename,img):\r\n img.show()\r\n save_img(filename,img)\r\n\r\n# Define your save_img() function here.\r\n# Parameters: The image object to save, the name to save the file as (string)\r\n# Returns: nothing.\r\ndef save_img(filename,img):\r\n img.save(filename, \"jpeg\")\r\n\r\n# Define your obamicon() function here.\r\n# Parameters: The image object to apply the filter to.\r\n# Returns: A New Image object with the filter applied.\r\ndef obamicon(img,filename):\r\n pixels = img.getdata()\r\n newpixels = []\r\n darkblue = (0,51,76)\r\n red = (217,26,33)\r\n lightblue = (112,150,158)\r\n yellow = (252,227,166)\r\n for p in pixels:\r\n intensity = p[0]+p[1]+p[2]\r\n if intensity < 182:\r\n newpixels.append(darkblue)\r\n elif intensity >= 182 and intensity < 364:\r\n newpixels.append(red)\r\n elif intensity >= 364 and intensity < 546:\r\n newpixels.append(lightblue)\r\n elif intensity >=546:\r\n newpixels.append(yellow)\r\n newim = Image.new(\"RGB\", img.size)\r\n newim.putdata(newpixels)\r\n show_img(filename,newim)\r\n return newim\r\n","sub_path":"filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"439015283","text":"'''\nRespond to mentions on twitter.\nThe bot will follow the user who mentioned it and\nfavorite the post in which the mention was made.\n'''\n\nchatbot = ChatBot(\"ChatterBot\",\n storage_adapter=\"chatterbot.adapters.storage.JsonDatabaseAdapter\",\n logic_adapter=\"chatterbot.adapters.logic.ClosestMatchAdapter\",\n io_adapter=\"chatterbot.adapters.io.TwitterAdapter\",\n database=\"../database.db\")\n\nfor mention in chatbot.get_mentions():\n\n '''\n Check to see if the post has been favorited\n We will use this as a check for whether or not to respond to it.\n Only respond to unfavorited mentions.\n '''\n\n if not mention[\"favorited\"]:\n screen_name = mention[\"user\"][\"screen_name\"]\n text = mention[\"text\"]\n response = chatbot.get_response(text)\n\n print(text)\n print(response)\n\n chatbot.follow(screen_name)\n chatbot.favorite(mention[\"id\"])\n chatbot.reply(mention[\"id\"], response)\n\n","sub_path":"examples/twitter_example.py","file_name":"twitter_example.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"386454928","text":"import sys\r\n\r\n\r\n# Function to calculate single exponential smoothing\r\ndef exponential_smoothing(data, alpha):\r\n result = [data[0]]\r\n for i in range(1, len(data)):\r\n result.append(alpha * data[i] + (1 - alpha) * result[i - 1])\r\n result.append(alpha * data[-1] + (1 - alpha) * result[-1]) # prediction\r\n return result\r\n\r\n\r\n# Function to calculate double exponential smoothing\r\ndef double_exponential_smoothing(data, alpha, beta):\r\n result = [data[0]]\r\n for i in range(1, len(data) + 2):\r\n if i == 1:\r\n level, trend = data[0], data[1] - data[0]\r\n if i >= len(data):\r\n value = result[-1] # prediction\r\n else:\r\n value = data[i]\r\n last_level = level\r\n level = alpha * value + (1 - alpha) * (level + trend)\r\n trend = beta * (level - last_level) + (1 - beta) * trend\r\n result.append(level + trend)\r\n return result\r\n\r\n\r\n# Function to calculate sse\r\ndef sse(values, predictions):\r\n try:\r\n s = 0\r\n for n, r in zip(values, predictions):\r\n s = s + (n - r) ** 2\r\n return s\r\n except OverflowError:\r\n return sys.float_info.max\r\n","sub_path":"2021/GuzziDangiolillo/smoothing.py","file_name":"smoothing.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"373458942","text":"import torch\nimport torchvision\nfrom _utils_torch import reset_gradients, save_sample_images\nfrom torch import nn\n\nfrom networks_munit import Generator, Discriminator\nfrom utils import get_config, get_scheduler, weights_init\n\n\nclass Trainer(nn.Module):\n def __init__(self, config, device):\n super(Trainer, self).__init__()\n \n self.config = config\n self.device = device\n lr = config['lr'] # 0.0001 # initial learning rate\n beta1 = config['beta1'] # 0.5 # Adam parameter\n beta2 = config['beta2'] # 0.999 # Adam parameter\n weight_decay = config['weight_decay'] # 0.0001 # weight decay\n\n self.generator_a = Generator(config['input_dim_a'], config['gen'])\n self.generator_b = Generator(config['input_dim_a'], config['gen'])\n self.discriminator_a = Discriminator(config['input_dim_b'], config['dis'])\n self.discriminator_b = Discriminator(config['input_dim_b'], config['dis'])\n\n params_d = list(self.discriminator_a.parameters()) + list(self.discriminator_b.parameters())\n params_g = list(self.generator_a.parameters()) + list(self.generator_b.parameters())\n self.optimizer_d = torch.optim.Adam(params_d, lr, (beta1, beta2), weight_decay=weight_decay)\n self.optimizer_g = torch.optim.Adam(params_g, lr, (beta1, beta2), weight_decay=weight_decay)\n\n self.scheduler_d = get_scheduler(self.optimizer_d, config)\n self.scheduler_g = get_scheduler(self.optimizer_g, config)\n\n self.apply(weights_init(config['init']))\n self.discriminator_a.apply(weights_init('gaussian'))\n self.discriminator_b.apply(weights_init('gaussian'))\n\n self.criterion_l1 = nn.L1Loss()\n self.criterion_l2 = nn.MSELoss()\n \n self.to(device)\n\n def update_scheduler(self):\n if self.scheduler_d and self.scheduler_g:\n self.scheduler_d.step()\n self.scheduler_g.step()\n\n def get_variables_within_domain(self, real_a, real_b):\n style_a, content_a = self.generator_a.encode(real_a)\n style_b, content_b = self.generator_b.encode(real_b)\n\n recon_a = self.generator_a.decode(style_a, content_a)\n recon_b = self.generator_b.decode(style_b, content_b)\n return style_a, content_a, style_b, content_b, recon_a, recon_b\n\n def get_variables_cross_domain(self, content_a, content_b):\n batch_size = self.config['batch_size']\n style_dim = self.config['gen']['style_dim']\n\n style_random_a = torch.rand(batch_size, style_dim).to(self.device)\n style_random_b = torch.rand(batch_size, style_dim).to(self.device)\n\n fake_a = self.generator_a.decode(style_random_a, content_b)\n fake_b = self.generator_b.decode(style_random_b, content_a)\n\n style_recon_a, content_recon_b = self.generator_a.encode(fake_a)\n style_recon_b, content_recon_a = self.generator_b.encode(fake_b)\n\n return style_random_a, style_random_b, fake_a, fake_b, style_recon_a, content_recon_b, style_recon_b, content_recon_a\n\n def update_g(self, real_a, real_b):\n reset_gradients([self.optimizer_d, self.optimizer_g])\n\n gan_w = self.config['gan_w'] # 1\n recon_x_w = self.config['recon_x_w'] # 10\n recon_s_w = self.config['recon_s_w'] # 1\n recon_c_w = self.config['recon_c_w'] # 1\n\n style_a, content_a, style_b, content_b, recon_a, recon_b = self.get_variables_within_domain(real_a, real_b)\n style_random_a, style_random_b, fake_a, fake_b, style_recon_a, content_recon_b, style_recon_b, content_recon_a = \\\n self.get_variables_cross_domain(content_a, content_b)\n\n # Logits\n logit_fake_a = self.discriminator_a(fake_a)\n logit_fake_b = self.discriminator_b(fake_b)\n\n image_recon_loss = self.criterion_l1(recon_a, real_a) + self.criterion_l1(recon_b, real_b)\n style_recon_loss = self.criterion_l1(style_recon_a, style_random_a) + self.criterion_l1(style_recon_b, style_random_b)\n content_recon_loss = self.criterion_l1(content_recon_a, content_a) + self.criterion_l1(content_recon_b, content_b)\n\n gan_loss_g = 0\n for logit in logit_fake_a + logit_fake_b:\n gan_loss_g += self.criterion_l2(logit, torch.ones_like(logit))\n\n weight_repo_g = [recon_x_w, recon_s_w, recon_c_w, gan_w]\n loss_repo_g = [image_recon_loss, style_recon_loss, content_recon_loss, gan_loss_g]\n loss_total_g = sum([weight * loss for weight, loss in zip(weight_repo_g, loss_repo_g)])\n loss_total_g.backward()\n\n self.optimizer_g.step()\n return gan_loss_g, image_recon_loss, style_recon_loss, content_recon_loss\n\n def update_d(self, real_a, real_b):\n reset_gradients([self.optimizer_d, self.optimizer_g])\n\n gan_w = self.config['gan_w'] # 1\n\n _, content_a, _, content_b, _, _ = self.get_variables_within_domain(real_a, real_b)\n _, _, fake_a, fake_b, _, _, _, _ = self.get_variables_cross_domain(content_a, content_b)\n\n logit_real_a = self.discriminator_a(real_a)\n logit_real_b = self.discriminator_b(real_b)\n\n logit_fake_a = self.discriminator_a(fake_a)\n logit_fake_b = self.discriminator_b(fake_b)\n\n loss_total_d = 0\n for logit in logit_real_a + logit_real_b:\n loss_total_d += self.criterion_l2(logit, torch.ones_like(logit))\n\n for logit in logit_fake_a + logit_fake_b:\n loss_total_d += self.criterion_l2(logit, torch.zeros_like(logit))\n loss_total_d *= gan_w\n\n loss_total_d.backward()\n\n self.optimizer_d.step()\n return loss_total_d\n\n def eval_mode_all(self):\n self.generator_a.eval()\n self.generator_b.eval()\n self.discriminator_a.eval()\n self.discriminator_b.eval()\n\n def test_samples(self, test_a, test_b, n_test_style, epoch, *a, **k):\n self.eval_mode_all()\n with torch.no_grad():\n repo = []\n style_random = torch.rand(n_test_style, self.config['gen']['style_dim']).to(self.device)\n for i in range(test_a.size(0)):\n test_a_i = test_a[i].unsqueeze_(0)\n test_b_i = test_b[i].unsqueeze_(0)\n\n style_a, content_a = self.generator_a.encode(test_a_i)\n style_b, content_b = self.generator_b.encode(test_b_i)\n\n content_a_tile = content_a.repeat(n_test_style, 1, 1, 1)\n content_b_tile = content_b.repeat(n_test_style, 1, 1, 1)\n\n fake_a = self.generator_a.decode(style_random, content_a_tile)\n recon_a = self.generator_a.decode(style_a, content_a)\n\n fake_b = self.generator_b.decode(style_random, content_b_tile)\n recon_b = self.generator_b.decode(style_b, content_b)\n\n repo.append(torch.cat([test_a_i, fake_a, recon_a, test_b_i, fake_b, recon_b]))\n\n return save_sample_images(torch.cat(repo, 2), save_name='{}.png'.format(epoch), *a, **k)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"120435255","text":"import urllib.request # for getting the page from the internet\nimport re # for using regex \n\n# This FancyURLopener helps get around websites that attempt to block python requests\nclass AppURLopener(urllib.request.FancyURLopener):\n version = \"Mozilla/5.0\"\nopener = AppURLopener()\n\n# url to retrieve\nurl = \"http://www.bettycrocker.com/recipes/easy-chocolate-banana-snack-cake/32f5b7ba-3226-4c35-bf63-bc42951f8f8a\"\n# url = \"https://www.hersheys.com/celebrate/valentines/recipedetail.aspx?id=4780&name=Celebration-Tarts\"\n# url = \"http://www.thewickednoodle.com/turkey-tetrazzini/#_a5y_p=5810571\"\n# url = \"http://allrecipes.com/recipe/222085/healthier-delicious-ham-and-potato-soup/?internalSource=staff%20pick&referringId=1552&referringContentType=recipe%20hub&clickId=cardslot%205\"\n# url = \"http://simply-delicious-food.com/steak-mushroom-pot-pies/\"\n\n\n\n# file to save to\n# fileName = 'recipe.txt'\nfileName = 'Recipe Texts/bettycrocker.txt' # url = \"http://www.bettycrocker.com/recipes/easy-chocolate-banana-snack-cake/32f5b7ba-3226-4c35-bf63-bc42951f8f8a\"\n# fileName = 'Recipe Texts/hersheys.txt' # url = \"https://www.hersheys.com/celebrate/valentines/recipedetail.aspx?id=4780&name=Celebration-Tarts\"\n# fileName = 'Recipe Texts/thewickednoodle.txt' # url = \"http://www.thewickednoodle.com/turkey-tetrazzini/#_a5y_p=5810571\"\n# fileName = 'Recipe Texts/AllRecipes.txt' # url = \"http://allrecipes.com/recipe/222085/healthier-delicious-ham-and-potato-soup/?internalSource=staff%20pick&referringId=1552&referringContentType=recipe%20hub&clickId=cardslot%205\"\n# fileName = 'Recipe Texts/SimplyDelicious.txt' # url = \"http://simply-delicious-food.com/steak-mushroom-pot-pies/\"\n\ningredient = \"eggs\"\n\nprint(\"Retrieving webpage...\")\n\n# # Get the webpage and save it to a file\n# req = opener.open(url)\n# page_content = req.read()\n# with open(fileName, 'wb') as fid: \n # fid.write(page_content) \n \n\n \nprint(\"Opening file...\")\n\ntry: #Try to open the file normally\n with open(fileName, 'r') as inf:\n filetext = inf.read() \n\nexcept UnicodeDecodeError: #If there is an encoding error, open the file in a different format\n with open(fileName, encoding='utf-8') as inf:\n filetext = inf.read()\n \n \n \n \n \nprint(\"Finding recipe title...\")\n\n#search for the title. It will probably be the first thing that is found between tags\npattern = re.compile(\"(?<=\\)(.*?)(?=\\<\\/title\\>)\",re.DOTALL)\nmatch = re.search(pattern, filetext)\n\n# clean up the found title by removing junk\ncleanup = re.sub(r'[^\\x00-\\x7F]+',' ', match.group(0)) #remove non-ASCII characters by replacing them with white space\ntitle = re.sub(r'[\\t\\n\\r\\f\\v]','', cleanup) #remove most \"blank\" characters that aren't spaces\n\n\nprint(title)\n\n#find a specific ingredient\n\n\n\n# possibly default to anything with a tag where itemprop*=\"ing\"\n\n#find all html list items that include that ingredient\ningpattern1 = re.compile(\"[()(.*?)(?=[(<)(\\n)])\") # pattern that finds everything between '>' and '<' (can also end with a new line)\n ingmatch[ndx] = re.search(ingpattern2,ingmatch[ndx]).group(0) # sets the element in ingmatch to the version with html stripped out\n print(\"\\n\\n\")\n\nprint(ingmatch)\n\n# remove the blank elements from ingmatch\ningmatch = [x for x in ingmatch if x != '']\n\nprint(ingmatch)\n\n#guess that the shortest string is the one that lists an ingredient amount\n\n\n\nAmtGuess = min(ingmatch, key=len)\n\nprint(AmtGuess)\n\n\n\n\n\n\n\n\n#find all html list items that include that ingredient\n# ingpattern1 = re.compile(\"[()(\\n))(.*?)(?=[<\\n])\") # pattern that finds everything between '>' and '<' (can also end with a new line)\n # ingmatch[ndx] = re.search(ingpattern2,ingmatch[ndx]).group(0) # sets the element in ingmatch to the version with html stripped out\n \n \n \n \n \n \n \n \n#find all html list items that include that ingredient\n# ingpattern1 = re.compile(\")(.*?)(?=[<\\n])\") # pattern that finds everything between '>' and '<' (can also end with a new line)\n # ingmatch[ndx] = re.search(ingpattern2,ingmatch[ndx]).group(0) # sets the element in ingmatch to the version with html stripped out","sub_path":"Archive/recipe_reader_orig.py","file_name":"recipe_reader_orig.py","file_ext":"py","file_size_in_byte":4948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"77586114","text":"from django import forms\nfrom django.forms.models import inlineformset_factory\n\nfrom us_ignite.common import output\nfrom us_ignite.apps.models import Feature\nfrom us_ignite.hubs.models import Hub, HubRequest, HubURL\n\n\nclass HubRequestForm(forms.ModelForm):\n\n class Meta:\n model = HubRequest\n fields = ('name', 'website', 'summary', 'description')\n\n\nclass HubForm(forms.ModelForm):\n features = forms.ModelMultipleChoiceField(\n queryset=Feature.objects.all(), required=False,\n widget=forms.CheckboxSelectMultiple)\n\n def clean_tags(self):\n if 'tags' in self.cleaned_data:\n return output.prepare_tags(self.cleaned_data['tags'])\n\n class Meta:\n model = Hub\n fields = ('name', 'website', 'summary', 'description', 'image',\n 'features', 'tags')\n\n\nHubURLFormSet = inlineformset_factory(\n Hub, HubURL, max_num=3, extra=3, can_delete=False)\n\n\nclass HubAppMembershipForm(forms.Form):\n hubs = forms.ModelMultipleChoiceField(\n label=u'Communities',\n queryset=Hub.objects.filter(status=Hub.PUBLISHED),\n required=False, widget=forms.CheckboxSelectMultiple,\n help_text=u'Is the Application Connected to a US Ignite '\n 'Community or Partner? (e.g. Funding, Development, Piloting, '\n 'Testing, etc.)')\n\n\nclass HubActionClusterMembershipForm(forms.Form):\n hubs = forms.ModelMultipleChoiceField(\n label=u'Communities',\n queryset=Hub.objects.filter(status=Hub.PUBLISHED),\n required=False, widget=forms.CheckboxSelectMultiple,\n help_text=u'Is the Action Cluster Connected to a US Ignite '\n 'Community or Partner? (e.g. Funding, Development, Piloting, '\n 'Testing, etc.)')\n\n\nclass HubApprovalRequestForm(forms.ModelForm):\n\n class Meta:\n model = HubRequest\n fields = ('status', 'notes')\n","sub_path":"us_ignite/hubs/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"331750045","text":"import numpy as np\nfrom coastlib.models.linear_wave_theory import solve_dispersion_relation\nfrom coastlib.coreutils.design_tools import dAngremond, Seabrook\nimport scipy.constants\nimport math\nimport matplotlib.pyplot as plt\nimport warnings\n\n\n#####################\n# Design parameters #\n#####################\n\nstorm_tide = 12.9 # ft\nSLR = 30 / 12 # ft\nstorm_tide_SLR = storm_tide + SLR # ft\nwave_height = 5.3 # ft\nwave_period = 5.8 # sec\n\nseabed = -11 # ft, this is the Breakwater type\nlength = 600 # ft\nbreakwaters = 2\nbtype = 'C'\npath = r'C:\\Users\\GRBH.COWI.001\\Desktop\\desktop projects\\1 Living breakwaters\\1 Crest width\\1 Analysis results\\No SLR'\n\nwater_depth = storm_tide - seabed # ft\nwater_depth_SLR = storm_tide_SLR - seabed # ft\ncrest_elevations = np.arange(0, 20.1, 0.1) # ft\ncrest_widths = np.arange(10, 40.1, 0.1) # ft\nD50 = 40 / 12 # ft\n\n\n##############\n# Conversion #\n##############\n\nwater_depth_m = water_depth * 0.3048 # m\nlength_m = length * 0.3048 # m\nwater_depth_SLR_m = water_depth_SLR * 0.3048 # m\ncrest_elevations_m = crest_elevations * 0.3048 # m\ncrest_widths_m = crest_widths * 0.3048 # m\nwave_height_m = wave_height * 0.3048 # m\nstorm_tide_m = storm_tide * 0.3048 # m\nstorm_tide_SLR_m = storm_tide_SLR * 0.3048 # m\nD50_m = D50 * 0.3048 # m\nseabed_m = seabed * 0.3048 # m\n\nwave_length_m = solve_dispersion_relation(wave_period, water_depth_m) # m\nwave_length_SLR_m = solve_dispersion_relation(wave_period, water_depth_SLR_m) # m\n\n\n#################################\n# Wave transmission calculation #\n#################################\ndef bwvol(crel, crew, tana, seabed, length, breakwaters, mhw, mlw):\n \"\"\"\n Breakwater total volume calculation. Returns the total volume of a\n breakwater section (no reef streets).\n\n :param tana: seaward breakwater slope\n :param crel: crest elevation [ft]\n :param crew: crest width [ft NAVD88]\n :param seabed: seabed elevation [ft NAVD88]\n :param length: breakwater length [ft]\n :param breakwaters: number of breakwaters of type\n :param mhw: mean high water [ft NAVD88]\n :param mlw: mean low water [ft NAVD88]\n :return: total breakwater volume [ft^3], no reef streets\n \"\"\"\n\n # Cross section per-linear-foot (plf) volume\n if crel > mhw:\n volume_plf_above_mhw = (crew + (crew + 2 * ((crel - mhw) / tana))) * (crel - mhw) / 2\n else:\n volume_plf_above_mhw = 0\n\n if crel > mlw and crel >= mhw:\n volume_plf_intertidal = ((crew + 2 * ((crel - mhw) / tana)) * 2 + 2 * (mhw - mlw) / tana) * \\\n (mhw - mlw) / 2\n elif crel > mlw and crel < mhw:\n volume_plf_intertidal = (crew + (crew + 2 * ((crel - mlw) / tana))) * (crel - mlw) / 2\n else:\n volume_plf_intertidal = 0\n\n volume_plf_below_mlw = ((crew + 2 * (crel - mlw) / tana) * 2 + 2 * (mlw - seabed) / tana) *\\\n (mlw - seabed) / 2\n\n if seabed == -11:\n volume_plf_below_mlw += 44.33 + 10.21\n elif seabed == -8:\n volume_plf_intertidal += 2\n volume_plf_below_mlw += 44.33 + 10.21 - 2\n elif seabed == -6:\n volume_plf_intertidal += 12.96 + 3.32\n volume_plf_below_mlw += 44.33 + 10.21 - (12.96 + 3.32)\n else:\n raise ValueError('Add a calculation case for the seabed elevation {} ft'.format(seabed))\n\n volume_plf_below_mhw = volume_plf_below_mlw + volume_plf_intertidal\n\n # End treatments volume (found as volumes of cones - 2 ends make a full cone)\n if crel > mhw:\n volume_ends_above_mhw = math.pi * ((crel - mhw) / tana) ** 2 * (crel - mhw) / 3\n volume_ends_below_mhw = (1 / 3) * math.pi * (\n ((crel - mhw) / tana) ** 2 +\n ((crel - mhw) / tana) * ((crel - seabed) / tana) +\n ((crel - seabed) / tana) ** 2\n ) * (mhw - seabed)\n else:\n volume_ends_above_mhw = 0\n volume_ends_below_mhw = math.pi * ((crel - seabed) / tana) ** 2 * (crel - seabed) / 3\n\n volume_ends_below_mhw += ((44.33 + 10.21) / 2) * (2 * math.pi * (crel - seabed) / tana) * 1.04 # ends approximation\n\n # Total volume calculation\n if crel > 0:\n length_at_crest = (length - 2 * crel / tana) * breakwaters\n else:\n length_at_crest = length\n # length_at_base = (length_at_crest + 2 * (crel - seabed) / tana) * breakwaters\n volume_above_mhw = length_at_crest * volume_plf_above_mhw + volume_ends_above_mhw * breakwaters\n volume_below_mhw = length_at_crest * volume_plf_below_mhw + volume_ends_below_mhw * breakwaters\n return volume_below_mhw + volume_above_mhw\n\nbwvol(\n crel=12,\n crew=15,\n tana=0.5,\n seabed=-11,\n length=300,\n breakwaters=6,\n mhw=2.08,\n mlw=-2.62\n) / 27 # for testing volume function\n\nKt = np.zeros((len(crest_widths), len(crest_elevations)))\nVolume = np.zeros((len(crest_widths), len(crest_elevations)))\nfor i, crew in enumerate(crest_widths_m):\n for j, crel in enumerate(crest_elevations_m):\n Rc = crel - storm_tide_SLR_m # freeboard [m] (with SLR)\n\n if Rc > 0:\n Kt[i][j] = dAngremond(Rc=Rc, Hm0=wave_height_m, B=crew, Tp=wave_period, tana=0.5)\n elif Rc < 0:\n Kt[i][j] = Seabrook(Hm0=wave_height_m, ds=-Rc, B=crew, L=wave_length_SLR_m, D50=D50_m)\n else:\n Kt[i][j] = (dAngremond(Rc=Rc, Hm0=wave_height_m, B=crew, Tp=wave_period, tana=0.5) +\n Seabrook(Hm0=wave_height_m, ds=-Rc, B=crew, L=wave_length_SLR_m, D50=D50_m)) / 2\n\n if Kt[i][j] * wave_height >= 3 or np.isnan(Kt[i][j]):\n Volume[i][j] = np.inf\n else:\n Volume[i][j] = bwvol(\n tana=0.5,\n crel=crest_elevations[j],\n crew=crest_widths[i],\n seabed=seabed,\n length=length,\n breakwaters=breakwaters,\n mhw=2.08,\n mlw=-2.62\n )\n\n\ntransmitted_waves = Kt * wave_height # ft\nVolume /= 3 ** 3 # To yd^3\nVolume /= 1000 # To 10^3 yd^3\n\ni, j = np.unravel_index(Volume.argmin(), dims=Volume.shape)\ntext = \"\"\"Breakwater {0} optimal dimensions:\ncrest width: {1} ft\ncrest elevation: {2} ft\ntotal volume: {3} yd^3\n\"\"\".format(\n btype,\n round(crest_widths[i], 1),\n round(crest_elevations[j], 1),\n round(Volume.min() * 1000, 0)\n)\nprint(text)\nwith open(path + r'\\{} summary.txt'.format(btype), 'w') as f:\n f.write(text)\n\n\n########################################\n# Plot wave height and volume heatmaps #\n########################################\n# Plot a heatmap of transmitted wave heights\nfig = plt.figure()\nfig.patch.set_facecolor('white')\nplt.imshow(\n transmitted_waves,\n interpolation='nearest',\n cmap=plt.cm.viridis,\n origin='lower'\n)\ncbar = plt.colorbar()\ncbar.ax.set_ylabel('Transmitted wave height [$ft$]', labelpad=10)\nplt.xticks(np.arange(0, 250, 50), np.arange(0, 25, 5))\nplt.xlabel('Crest elevation [$ft$]')\nplt.xlim(0, 200)\nplt.yticks(np.arange(0, 350, 50), np.arange(10, 45, 5))\nplt.ylabel('Crest width [$ft$]')\nplt.ylim(0, 300)\nplt.title('Breakwater {}. Transmitted wave heights'.format(btype), y=1.04)\ncontour = plt.contour(transmitted_waves, colors='white', linewidths=1, levels=np.arange(1, 8, 1))\nplt.clabel(contour, fmt='%1.1f', manual=[(166, 155), (152, 250), (134, 150), (105, 150), (61, 150), (18, 25)])\nplt.grid(True, which='major', color='lightgray', linestyle='--', linewidth=0.5)\nplt.savefig(path + r'\\{} TWH.png'.format(btype), dpi=300, bbox_inches='tight')\n\n# Plot a heatmap of volumes\nfig = plt.figure()\nfig.patch.set_facecolor('white')\nplt.imshow(\n Volume,\n interpolation='nearest',\n cmap=plt.cm.viridis,\n origin='lower'\n)\ncbar = plt.colorbar()\ncbar.ax.set_ylabel(r'Breakwater volume [$10^3\\cdot yd^3$]', labelpad=10)\nplt.xticks(np.arange(0, 250, 50), np.arange(0, 25, 5))\nplt.xlabel('Crest elevation [$ft$]')\nplt.xlim(0, 200)\nplt.yticks(np.arange(0, 350, 50), np.arange(10, 45, 5))\nplt.ylabel('Crest width [$ft$]')\nplt.ylim(0, 300)\nplt.title('Breakwater {}. Total breakwater volume'.format(btype), y=1.04)\ncontour = plt.contour(Volume, colors='white', linewidths=1)\nplt.clabel(contour, fmt='%1.1f')\nplt.grid(True, which='major', color='lightgray', linestyle='--', linewidth=0.5)\nplt.savefig(path + r'\\{} Vol.png'.format(btype), dpi=300, bbox_inches='tight')\n\n# Presentation graphics\npg_path = r'C:\\Users\\GRBH.COWI.001\\Desktop\\desktop projects\\1 Living breakwaters\\1 Crest width\\3 Presentation graphics'\n\nfig = plt.figure(figsize=(16, 12))\nfig.patch.set_facecolor('white')\nplt.subplot(1, 2, 1)\nplt.imshow(\n transmitted_waves,\n interpolation='nearest',\n cmap=plt.cm.viridis,\n origin='lower'\n)\ncbar = plt.colorbar()\ncbar.ax.set_ylabel('Transmitted wave height [$ft$]', labelpad=10)\nplt.scatter(120, 50, marker='h', s=100, edgecolors='k', facecolor='#F04E23', label='Optimized breakwater')\nplt.scatter(140, 30, marker='h', s=100, edgecolors='k', facecolor='#009cde', label='Currently used breakwater')\nplt.xticks(np.arange(0, 250, 50), np.arange(0, 25, 5))\nplt.xlabel('Crest elevation [$ft$]')\nplt.xlim(0, 200)\nplt.yticks(np.arange(0, 350, 50), np.arange(10, 45, 5))\nplt.ylabel('Crest width [$ft$]')\nplt.ylim(0, 300)\nplt.title('Breakwater {}. Transmitted wave heights'.format(btype), y=1.04)\ncontour = plt.contour(transmitted_waves, colors='white', linewidths=1, levels=np.arange(1, 8, 1))\nplt.clabel(contour, fmt='%1.1f', manual=[(166, 155), (152, 250), (134, 150), (105, 150), (61, 150), (18, 25)])\nplt.grid(True, which='major', color='lightgray', linestyle='--', linewidth=0.5)\nplt.legend()\n\nplt.subplot(1, 2, 2)\nplt.imshow(\n Volume,\n interpolation='nearest',\n cmap=plt.cm.viridis,\n origin='lower'\n)\ncbar = plt.colorbar()\ncbar.ax.set_ylabel(r'Breakwater volume [$10^3\\cdot yd^3$]', labelpad=10)\nplt.scatter(120, 50, marker='h', s=100, edgecolors='k', facecolor='#F04E23',\n label='Optimized breakwater (64,332 $yd^3$)')\nplt.scatter(140, 30, marker='h', s=100, edgecolors='k', facecolor='#009cde',\n label='Currently used breakwater (71,173 $yd^3$)')\nplt.xticks(np.arange(0, 250, 50), np.arange(0, 25, 5))\nplt.xlabel('Crest elevation [$ft$]')\nplt.xlim(0, 200)\nplt.yticks(np.arange(0, 350, 50), np.arange(10, 45, 5))\nplt.ylabel('Crest width [$ft$]')\nplt.ylim(0, 300)\nplt.title('Breakwater {}. Total breakwater volume'.format(btype), y=1.04)\ncontour = plt.contour(Volume, colors='white', linewidths=1)\nplt.clabel(contour, fmt='%1.1f')\nplt.grid(True, which='major', color='lightgray', linestyle='--', linewidth=0.5)\nplt.legend()\nplt.savefig(pg_path + r'\\Breakwater type {} Optimization.png'.format(btype), dpi=300, bbox_inches='tight')\n","sub_path":"Archive/Living breakwaters wave transmission/transmission analysis.py","file_name":"transmission analysis.py","file_ext":"py","file_size_in_byte":10574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"573090509","text":"from flask import Flask, render_template, url_for, redirect, flash\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import current_user, LoginManager, UserMixin, login_user,logout_user\nfrom requests.utils import quote\nfrom oauth import OAuthSignIn\n\napp = Flask(__name__)\n\napp.config['SECRET_KEY'] = 'Sha Qian'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'\n# Replace with your base(tenant) URI\napp.config['BASE_URI'] = 'https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'\n# Replace with your callback URI\napp.config['CALLBACK_URI'] = 'http://127.0.0.1:5000/index'\n# Replace with your APP ID and secret in Azure AD\napp.config['OAUTH_CREDENTIALS'] = {\n 'microsoft': {\n 'id': 'yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy',\n 'secret': 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz='\n }\n}\n\ndb = SQLAlchemy(app)\nlm = LoginManager(app)\nlm.login_view = 'index'\n\nclass User(UserMixin, db.Model):\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n unique_name = db.Column(db.String(64), nullable=False, unique=True)\n nickname = db.Column(db.String(64), nullable=False)\n\n@lm.user_loader\ndef load_user(id):\n return User.query.get(int(id))\n\n@app.route('/', methods=['POST', 'GET'])\n@app.route('/index', methods=['POST', 'GET'])\ndef index():\n return render_template('index.html')\n\n@app.route('/authorize/')\ndef oauth_authorize(provider):\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n oauth = OAuthSignIn.get_provider(provider)\n return oauth.authorize()\n\n@app.route('/callback/')\ndef oauth_callback(provider):\n if not current_user.is_anonymous:\n return redirect(url_for('index'))\n oauth = OAuthSignIn.get_provider(provider)\n name, unique_name = oauth.callback()\n if unique_name is None:\n flash('Authentication failed.')\n return redirect(url_for('index'))\n user = User.query.filter_by(unique_name=unique_name).first()\n if not user:\n user = User(unique_name=unique_name, nickname=name)\n db.session.add(user)\n db.session.commit()\n login_user(user, True)\n return redirect(url_for('index'))\n\n@app.route('/logout')\ndef logout():\n logout_user()\n logout_url = app.config['BASE_URI'] + '/oauth2/logout?post_logout_redirect_uri=' + quote(app.config['CALLBACK_URI'], safe='')\n return redirect(logout_url)\n\nif __name__ == '__main__':\n db.create_all()\n app.run(debug=True)","sub_path":"oauth/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"231242357","text":"import requests\nimport time\n\n\ndef requester(page_url, index):\n headers = {\n 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}\n while True:\n page_content = \"\"\n for page in page_url:\n try:\n page_content = requests.get(page, headers=headers, timeout=10)\n try:\n page_content.raise_for_status()\n except Exception as error:\n print('There was a problem getting web data: %s' % error)\n if page_content.status_code != 200:\n print('There was a problem getting web data: %s' % error)\n break\n except requests.ConnectionError as e:\n print(\n \"OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\\n\")\n print(str(e))\n time.sleep(5) # wait 5 seconds before we make the next request\n break\n except requests.Timeout as e:\n print(\"OOPS!! Timeout Error\")\n print(str(e))\n time.sleep(5) # wait 5 seconds before we make the next request\n break\n except requests.RequestException as e:\n print(\"OOPS!! General Error\")\n print(str(e))\n time.sleep(5) # wait 5 seconds before we make the next request\n break\n except KeyboardInterrupt:\n print(\"Someone closed the program\")\n # print(\"Page %d done!!!. Proceeding to the next trial\" % index)\n if page_content != \"\":\n break\n return page_content\n","sub_path":"home/fetcher.py","file_name":"fetcher.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"373231413","text":"from tkinter import *\nfrom math import sqrt, sin, cos\nimport threading\n#Global variables\nbounds = 500\nrefresh_time = 40\ndefault_vec = [0, 0, 0, 50, 0]\nclass ship:\n\tdef __init__(self, bullets_list, x=0, y=0, gun_direction=0, health=50, refresh_clock=0):\n\t\tself.bullets_list = bullets_list\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.size = 15\n\t\tself.gun_direction = gun_direction\n\t\tself.health = health\n\t\tself.refresh_clock = refresh_clock\n\n\tdef truncate_to_bounds(self):\n\t\tif(self.x < 0):\n\t\t\tself.x = 0\n\t\telif(self.x > bounds):\n\t\t\tself.x = bounds\n\t\tif(self.y < 0):\n\t\t\tself.y = 0\n\t\telif(self.y > bounds):\n\t\t\tself.y = bounds\n\n\tdef action(self, input):\n\t\t#Move on the screen\n\t\tlength = sqrt(input[0]**2+input[1]**2)\n\t\tvx = 0\n\t\tvy = 0\n\t\tif(length > 0):\n\t\t\tvx = input[0]/length\n\t\t\tvy = input[1]/length\n\t\tself.truncate_to_bounds()\n\t\tif(vx+self.x < bounds and vx + self.x > 0):\n\t\t\tself.x += vx\n\t\tif(vy+self.y < bounds and vy + self.y > 0):\n\t\t\tself.y += vy\n\t\t#Rotate the gun to determined position\n\t\tself.gun_direction += 0.1*input[2]/abs(input[2])\n\t\t#Shoot\n\t\tif(input[3] > 0 and self.refresh_clock <= 0):\n\t\t\tvx = 5*cos(self.gun_direction)\n\t\t\tvy = 5*sin(self.gun_direction)\n\t\t\tself.bullets_list.append(bullet(self.x + vx + 25*cos(self.gun_direction), self.y + vy + 25*sin(self.gun_direction), vx, vy))\n\t\t\tself.refresh_clock = refresh_time\n\t\tself.refresh_clock -= 1\n\tdef to_vec(self):\n\t\treturn [self.x, self.y, self.gun_direction, self.health, self.refresh_clock]\n\nclass bullet:\n\tdef __init__(self, x=0, y=0, vx=0, vy=0):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.vx = vx\n\t\tself.vy = vy\n\t\tself.size = 8\n\tdef action(self):\n\t\tself.x += self.vx\n\t\tself.y += self.vy\n\tdef in_bounds(self):\n\t\treturn (self.x > 0 and self.x < bounds and self.y > 0 and self.y < bounds)\n\n\tdef to_vec(self):\n\t\treturn [self.x, self.y, self.vx, self.vy]\n\nclass game:\n\tdef __init__(self, state_vec):\n\t\tself.bullets_list = []\n\t\ts = state_vec[0 : 5]\n\t\tself.ship_0 = ship(self.bullets_list, s[0], s[1], s[2], s[3], s[4])\n\t\t#print(\"ship_0 health:\", self.ship_0.health)\n\t\ts = state_vec[5 : 10]\n\t\tself.ship_1 = ship(self.bullets_list, s[0], s[1], s[2], s[3], s[4])\n\t\t#print(\"ship_1 health:\", self.ship_1.health)\n\t\tplace = 10\n\t\twhile(place < 70):\n\t\t\ts = state_vec[place: place + 4]\n\t\t\tself.bullets_list.append(bullet(s[0], s[1], s[2], s[3]))\n\t\t\tplace += 4\n\n\tdef dist(self, a, b):\n\t\treturn sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)\n\n\tdef is_collision(self, a, b):\n\t\ta_vec = [a.x, a.y]\n\t\tb_vec = [b.x, b.y]\n\t\tdist = self.dist(a_vec, b_vec)\n\t\t#if((dist < (a.size + b.size))):\n\t\t#\tprint(\"collision\", dist, a_vec, b_vec)\n\t\treturn (dist < (a.size + b.size))\n\n\tdef action(self, input_0, input_1):\n\t\t#Have ships and bullets move\n\t\tself.ship_0.action(input_0)\n\t\tself.ship_1.action(input_1)\n\t\tfor b in self.bullets_list:\n\t\t\tb.action()\n\t\t#Delete bullets that go out of bounds or hit ships\n\t\t#Lower ship health if it's in collision\n\t\ti = 0\n\t\twhile (i < len(self.bullets_list)):\n\t\t\tb = self.bullets_list[i]\n\t\t\t#print(i, b.x, b.y)\n\t\t\tif(self.is_collision(self.ship_0, self.bullets_list[i])):\n\t\t\t\tself.ship_0.health -= 1\n\t\t\t\tdel self.bullets_list[i]\n\t\t\telif(self.is_collision(self.ship_1, b)):\n\t\t\t\tself.ship_1.health -= 1\n\t\t\t\tdel self.bullets_list[i]\n\t\t\telif(not self.bullets_list[i].in_bounds()):\n\t\t\t\tdel self.bullets_list[i]\n\t\t\telse:\n\t\t\t\ti += 1\n\t\t#Get reward for ship_0\n\t\tif(self.ship_0.health <= 0):\n\t\t\tprint(\"Game Lost\")\n\t\t\treturn -1\n\t\telif(self.ship_1.health <= 0):\n\t\t\tprint(\"Game Won\")\n\t\t\treturn 1\n\t\telse:\n\t\t\treturn 0\n\n\tdef to_vec(self):\n\t\tret = self.ship_0.to_vec() + self.ship_1.to_vec()\n\t\tfor b in self.bullets_list:\n\t\t\tret = ret + b.to_vec()\n\t\tpadding = []\n\t\tif(len(self.bullets_list) < 15):\n\t\t\tpadding = [0, 0, 0, 0]*(15 - len(self.bullets_list))\n\t\treturn ret + padding\n\n\ndef start_game():\n\tstate_vec = [-1]*70\n\t# state_vec[0] = state_vec[1] = 100\n\tstate_vec[3] = 1\n\t# state_vec[5] = state_vec[6] = 400\n\tstate_vec[0] = state_vec[1] = 400\n\tstate_vec[5] = state_vec[6] = 100\n\tstate_vec[8] = 1\n\treturn game(state_vec)\n\ndef change_state(state_vec, action_0, action_1, w):\n\tnew_game = game(state_vec)\n\treward = new_game.action(action_0, action_1)\n\treturn reward, new_game.to_vec(), new_game\n\ndef tkinter_test():\n\troot = tk.Tk()\n\tw = tk.Label(root, text=\"Hello, world!\")\n\tw.pack()\n\troot.mainloop()\n\ndef print_game(w, game):\n\tw.delete(\"all\")\n\tw.create_rectangle(50, 50, 550, 550, fill=\"blue\")\n\tprint_entity(game.ship_0, w)\n\tprint_entity(game.ship_1, w)\n\tfor b in game.bullets_list:\n\t\tprint_entity(b, w)\n\t#mainloop()\n\ndef run_game(curr_game):\n\tmaster = Tk()\n\tw = Canvas(master, width=600, height=600)\n\tw.pack()\n\tframe(w, curr_game, master)\n\ndef frame(w, curr_game, master):\n\tw.delete(\"all\")\n\tw.create_rectangle(50, 50, 550, 550, fill=\"blue\")\n\tprint_entity(curr_game.ship_0, w)\n\tprint_entity(curr_game.ship_1, w)\n\tfor b in curr_game.bullets_list:\n\t\tprint_entity(b, w)\n\n\tacts = [0, 1, 3.14159/4, 1]\n\tcurr_game.action(acts, acts)\n\tmaster.after(40, (lambda : frame(w, curr_game, master)))\n\ndef print_entity(entity, c):\n\tx = entity.x+50\n\ty = entity.y+50\n\ts = entity.size\n\tc.create_oval(x-s/2, y-s/2, x+s/2,y+s/2, fill=\"red\")\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"day3/AllIsCircle.py","file_name":"AllIsCircle.py","file_ext":"py","file_size_in_byte":5054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"467156668","text":"# | Copyright 2007-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# Generic base class for authentication proxies GCSCF:\n\nimport os, time, logging\nfrom grid_control import utils\nfrom grid_control.gc_exceptions import UserError\nfrom grid_control.gc_plugin import NamedPlugin\nfrom grid_control.utils.parsing import parseTime, strTime\nfrom grid_control.utils.process_base import LocalProcess\nfrom hpfwk import AbstractError, NestedException\nfrom python_compat import identity, imap, lmap, rsplit\n\nclass AccessTokenError(NestedException):\n\tpass\n\nclass AccessToken(NamedPlugin):\n\tconfigSections = NamedPlugin.configSections + ['proxy', 'access']\n\ttagName = 'access'\n\n\tdef getUsername(self):\n\t\traise AbstractError\n\n\tdef getFQUsername(self):\n\t\treturn self.getUsername()\n\n\tdef getGroup(self):\n\t\traise AbstractError\n\n\tdef getAuthFiles(self):\n\t\traise AbstractError\n\n\tdef canSubmit(self, neededTime, canCurrentlySubmit):\n\t\traise AbstractError\n\n\nclass MultiAccessToken(AccessToken):\n\tdef __init__(self, config, name, tokenList):\n\t\tAccessToken.__init__(self, config, name)\n\t\tself._subtokenList = tokenList\n\n\tdef getUsername(self):\n\t\treturn self._subtokenList[0].getUsername()\n\n\tdef getFQUsername(self):\n\t\treturn self._subtokenList[0].getFQUsername()\n\n\tdef getGroup(self):\n\t\treturn self._subtokenList[0].getGroup()\n\n\tdef getAuthFiles(self):\n\t\treturn self._subtokenList[0].getAuthFiles()\n\n\tdef canSubmit(self, neededTime, canCurrentlySubmit):\n\t\tfor subtoken in self._subtokenList:\n\t\t\tcanCurrentlySubmit = canCurrentlySubmit and subtoken.canSubmit(neededTime, canCurrentlySubmit)\n\t\treturn canCurrentlySubmit\n\n\nclass TrivialAccessToken(AccessToken):\n\talias = ['TrivialProxy']\n\n\tdef getUsername(self):\n\t\tfor var in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):\n\t\t\tresult = os.environ.get(var)\n\t\t\tif result:\n\t\t\t\treturn result\n\t\traise AccessTokenError('Unable to determine username!')\n\n\tdef getGroup(self):\n\t\treturn os.environ.get('GROUP', 'None')\n\n\tdef getAuthFiles(self):\n\t\treturn []\n\n\tdef canSubmit(self, neededTime, canCurrentlySubmit):\n\t\treturn True\n\n\nclass TimedAccessToken(AccessToken):\n\tdef __init__(self, config, name):\n\t\tAccessToken.__init__(self, config, name)\n\t\tself._lowerLimit = config.getTime('min lifetime', 300, onChange = None)\n\t\tself._maxQueryTime = config.getTime('max query time', 5 * 60, onChange = None)\n\t\tself._minQueryTime = config.getTime('min query time', 30 * 60, onChange = None)\n\t\tself._ignoreTime = config.getBool('ignore walltime', False, onChange = None)\n\t\tself._lastUpdate = 0\n\t\tself._logUser = logging.getLogger('user.time')\n\n\tdef canSubmit(self, neededTime, canCurrentlySubmit):\n\t\tif not self._checkTimeleft(self._lowerLimit):\n\t\t\traise UserError('Your access token (%s) only has %d seconds left! (Required are %s)' %\n\t\t\t\t(self.getObjectName(), self._getTimeleft(cached = True), strTime(self._lowerLimit)))\n\t\tif self._ignoreTime:\n\t\t\treturn True\n\t\tif not self._checkTimeleft(self._lowerLimit + neededTime) and canCurrentlySubmit:\n\t\t\tself._logUser.warning('Access token (%s) lifetime (%s) does not meet the access and walltime (%s) requirements!',\n\t\t\t\tself.getObjectName(), strTime(self._getTimeleft(cached = False)), strTime(self._lowerLimit + neededTime))\n\t\t\tself._logUser.warning('Disabling job submission')\n\t\t\treturn False\n\t\treturn True\n\n\tdef _getTimeleft(self, cached):\n\t\traise AbstractError\n\n\tdef _checkTimeleft(self, neededTime): # check for time left\n\t\tdelta = time.time() - self._lastUpdate\n\t\ttimeleft = max(0, self._getTimeleft(cached = True) - delta)\n\t\t# recheck token => after > 30min have passed or when time is running out (max every 5 minutes)\n\t\tif (delta > self._minQueryTime) or (timeleft < neededTime and delta > self._maxQueryTime):\n\t\t\tself._lastUpdate = time.time()\n\t\t\ttimeleft = self._getTimeleft(cached = False)\n\t\t\tself._logUser.info('Time left for access token \"%s\": %s', self.getObjectName(), strTime(timeleft))\n\t\treturn timeleft >= neededTime\n\n\nclass VomsProxy(TimedAccessToken):\n\tdef __init__(self, config, name):\n\t\tTimedAccessToken.__init__(self, config, name)\n\t\tself._infoExec = utils.resolveInstallPath('voms-proxy-info')\n\t\tself._proxyPath = config.get('proxy path', '')\n\t\tself._ignoreWarning = config.getBool('ignore warnings', False, onChange = None)\n\t\tself._cache = None\n\n\tdef getUsername(self):\n\t\treturn self._getProxyInfo('identity').split('CN=')[1].strip()\n\n\tdef getFQUsername(self):\n\t\treturn self._getProxyInfo('identity')\n\n\tdef getGroup(self):\n\t\treturn self._getProxyInfo('vo')\n\n\tdef getAuthFiles(self):\n\t\treturn [self._getProxyInfo('path')]\n\n\tdef _getTimeleft(self, cached):\n\t\treturn self._getProxyInfo('timeleft', parseTime, cached)\n\n\tdef _parseProxy(self, cached = True):\n\t\t# Return cached results if requested\n\t\tif cached and self._cache:\n\t\t\treturn self._cache\n\t\t# Call voms-proxy-info and parse results\n\t\targs = ['--all']\n\t\tif self._proxyPath:\n\t\t\targs.extend(['--file', self._proxyPath])\n\t\tproc = LocalProcess(self._infoExec, *args)\n\t\t(retCode, stdout, stderr) = proc.finish(timeout = 10)\n\t\tif (retCode != 0) and not self._ignoreWarning:\n\t\t\tmsg = ('voms-proxy-info output:\\n%s\\n%s\\n' % (stdout, stderr)).replace('\\n\\n', '\\n')\n\t\t\tmsg += 'If job submission is still possible, you can set [access] ignore warnings = True\\n'\n\t\t\traise AccessTokenError(msg + 'voms-proxy-info failed with return code %d' % retCode)\n\t\tself._cache = utils.DictFormat(':').parse(stdout)\n\t\treturn self._cache\n\n\tdef _getProxyInfo(self, key, parse = identity, cached = True):\n\t\tinfo = self._parseProxy(cached)\n\t\ttry:\n\t\t\treturn parse(info[key])\n\t\texcept Exception:\n\t\t\traise AccessTokenError(\"Can't access %s in proxy information:\\n%s\" % (key, info))\n\n\nclass RefreshableAccessToken(TimedAccessToken):\n\tdef __init__(self, config, name):\n\t\tTimedAccessToken.__init__(self, config, name)\n\t\tself._refresh = config.getTime('access refresh', 60*60, onChange = None)\n\n\tdef _refreshAccessToken(self):\n\t\traise AbstractError\n\n\tdef _checkTimeleft(self, neededTime): # check for time left\n\t\tif self._getTimeleft(True) < self._refresh:\n\t\t\tself._refreshAccessToken()\n\t\t\tself._getTimeleft(False)\n\t\treturn TimedAccessToken._checkTimeleft(self, neededTime)\n\n\nclass AFSAccessToken(RefreshableAccessToken):\n\talias = ['AFSProxy']\n\n\tdef __init__(self, config, name):\n\t\tRefreshableAccessToken.__init__(self, config, name)\n\t\tself._kinitExec = utils.resolveInstallPath('kinit')\n\t\tself._klistExec = utils.resolveInstallPath('klist')\n\t\tself._cache = None\n\t\tself._authFiles = dict(imap(lambda name: (name, config.getWorkPath('proxy.%s' % name)), ['KRB5CCNAME', 'KRBTKFILE']))\n\t\tself._backupTickets(config)\n\t\tself._tickets = config.getList('tickets', [], onChange = None)\n\n\tdef _backupTickets(self, config):\n\t\timport stat, shutil\n\t\tfor name in self._authFiles: # store kerberos files in work directory for persistency\n\t\t\tif name in os.environ:\n\t\t\t\tfn = os.environ[name].replace('FILE:', '')\n\t\t\t\tif fn != self._authFiles[name]:\n\t\t\t\t\tshutil.copyfile(fn, self._authFiles[name])\n\t\t\t\tos.chmod(self._authFiles[name], stat.S_IRUSR | stat.S_IWUSR)\n\t\t\t\tos.environ[name] = self._authFiles[name]\n\n\tdef _refreshAccessToken(self):\n\t\treturn LocalProcess(self._kinitExec, '-R').finish(timeout = 10)\n\n\tdef _parseTickets(self, cached = True):\n\t\t# Return cached results if requested\n\t\tif cached and self._cache:\n\t\t\treturn self._cache\n\t\t# Call klist and parse results\n\t\tproc = LocalProcess(self._klistExec)\n\t\tself._cache = {}\n\t\ttry:\n\t\t\tfor line in proc.stdout.iter(timeout = 10):\n\t\t\t\tif line.count('@') and (line.count(':') > 1):\n\t\t\t\t\tissued_expires, principal = rsplit(line, ' ', 1)\n\t\t\t\t\tissued_expires = issued_expires.replace('/', ' ').split()\n\t\t\t\t\tassert(len(issued_expires) % 2 == 0)\n\t\t\t\t\tissued_str = str.join(' ', issued_expires[:int(len(issued_expires) / 2)])\n\t\t\t\t\texpires_str = str.join(' ', issued_expires[int(len(issued_expires) / 2):])\n\t\t\t\t\tparseDate = lambda value, format: time.mktime(time.strptime(value, format))\n\t\t\t\t\tif expires_str.count(' ') == 3:\n\t\t\t\t\t\tif len(expires_str.split()[2]) == 2:\n\t\t\t\t\t\t\texpires = parseDate(expires_str, '%m %d %y %H:%M:%S')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\texpires = parseDate(expires_str, '%m %d %Y %H:%M:%S')\n\t\t\t\t\telif expires_str.count(' ') == 2: # year information is missing\n\t\t\t\t\t\tcurrentYear = int(time.strftime('%Y'))\n\t\t\t\t\t\texpires = parseDate(expires_str + ' %d' % currentYear, '%b %d %H:%M:%S %Y')\n\t\t\t\t\t\tissued = parseDate(issued_str + ' %d' % currentYear, '%b %d %H:%M:%S %Y')\n\t\t\t\t\t\tif expires < issued: # wraparound at new year\n\t\t\t\t\t\t\texpires = parseDate(expires_str + ' %d' % (currentYear + 1), '%b %d %H:%M:%S %Y')\n\t\t\t\t\tself._cache.setdefault('tickets', {})[principal] = expires\n\t\t\t\telif line.count(':') == 1:\n\t\t\t\t\tkey, value = lmap(str.strip, line.split(':', 1))\n\t\t\t\t\tself._cache[key.lower()] = value\n\t\texcept Exception:\n\t\t\traise AccessTokenError('Unable to parse kerberos ticket information!')\n\t\tproc.status_raise(timeout = 0)\n\t\treturn self._cache\n\n\tdef _getTimeleft(self, cached):\n\t\tinfo = self._parseTickets(cached)['tickets']\n\t\ttime_current = time.time()\n\t\ttime_end = time_current\n\t\tfor ticket in info:\n\t\t\tif (self._tickets and (ticket not in self._tickets)) or not ticket:\n\t\t\t\tcontinue\n\t\t\ttime_end = max(info[ticket], time_end)\n\t\treturn time_end - time_current\n\n\tdef _getPrincipal(self):\n\t\tinfo = self._parseTickets()\n\t\treturn info.get('default principal', info.get('principal'))\n\n\tdef getUsername(self):\n\t\treturn self._getPrincipal().split('@')[0]\n\n\tdef getFQUsername(self):\n\t\treturn self._getPrincipal()\n\n\tdef getGroup(self):\n\t\treturn self._getPrincipal().split('@')[1]\n\n\tdef getAuthFiles(self):\n\t\treturn self._authFiles.values()\n","sub_path":"packages/grid_control/backends/access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":10020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"192726684","text":"import pandas as pd\nimport numpy as np\n\nimport ijson\nimport os\nimport sys\n\nfrom tkinter import *\nfrom tkinter import filedialog, messagebox, simpledialog\nfrom pandastable import Table, TableModel\n\n\nbasepath = os.path.dirname(__file__)\n\ndef ProjectLangs():\n f = open(basepath+'\\\\ProjectLangs.json','r')\n objects = ijson.items(f,'datasets.item')\n \n\n\n projectlangsDF = pd.DataFrame( list(objects) ) \n projectlangsDF = projectlangsDF.set_index('languageName')\n\n projectlangsDF['code'] = projectlangsDF['languageCode'] + projectlangsDF['countryCode']\n\n print(projectlangsDF[ ['languageId','isSourceLanguage']])\n print()\n print(projectlangsDF[ ['languageId','isSourceLanguage']].sort_values(by='languageName')) \n\n ValidLangList = ['English','SimpChinese','French']\n\n validDF = projectlangsDF[ projectlangsDF.index.isin(ValidLangList) ]\n\n print()\n print(validDF)\n print()\n print(projectlangsDF[ projectlangsDF.index.isin(ValidLangList) ][['languageId','isSourceLanguage']].sort_values(by='languageName'))\n\ndef StringResults():\n\n ResultList2DF = []\n\n with open(basepath+'\\\\StringResult.json','r') as f:\n\n # Used the json parser to run throught file and print the parsertuples and see structure of JSON\n parser = ijson.parse(f)\n for parsertuple in parser:\n print(parsertuple)\n print()\n\n # set file back to beginning\n f.seek(0)\n\n # From structure, saw that result that I want is under dataset node and dataset contains a list of the results of StringExport query from LocDirect where\n # list items returned did not have field names but returned in order of query [ identifierName, folderPath, sourceLanguageText ]\n datasets = ijson.items(f,'resultset.item.dataset')\n\n \n for dataset in datasets:\n key, path, text = dataset\n ResultList2DF.append( {'identifierName':key, 'folderPath':path, 'sourceLanguageText':text} )\n\n f.close()\n\n StringsDF = pd.DataFrame(ResultList2DF)\n #StringsDF = StringsDF.set_index('identifierName')\n print(StringsDF)\n return StringsDF\n\ndef FolderPathResults():\n \n ResultList2DF = []\n with open(basepath+'\\\\StringFolders.json','r') as f:\n\n #parser = ijson.parse(f)\n #for parsertuple in parser:\n # print(parsertuple)\n\n datasets = ijson.items(f,'datasets.item')\n for datasetmap in datasets:\n ResultList2DF.append(datasetmap)\n\n f.close()\n PathsDF = pd.DataFrame(ResultList2DF)\n \n PathInfoDF = PathsDF[ ['childrenDataTypeId','path']]\n \n SubPathsDF = PathInfoDF[ PathInfoDF['path'].str.contains(\"Strings/Text/Temp\",regex=False) == True ]\n\n print(SubPathsDF)\n\n return PathsDF\n\n\nFolderPathResults()\n\n# Debug point stops and exits here if checking on data before pandastable is displayed\n#sys.exit(0)\n\n#YeeTable class is based on pandastable Table class\nclass YeeTable( Table ):\n #Override the mouse left button release and add detection and printing of row and column selected\n def handle_left_release(self, event):\n print(\"Hello left click!\")\n print(event)\n\n rowclicked = super(YeeTable,self).get_row_clicked(event)\n colclicked = super(YeeTable,self).get_col_clicked(event)\n print(\"[row={}, col={}]\".format(rowclicked,colclicked))\n\n #self.model.df.iloc[rowclicked,colclicked] = 666\n \n\n super(YeeTable,self).handle_left_release(event)\n\n self.redraw()\n\n #Override drawCellEntry to detect if row=1 and col=1 is selected and do not allow editing by not calling super drawCellEntry (not letting user use Cell Entry)\n def drawCellEntry(self, row, col, text=None):\n\n if (row,col) == (1,1):\n print(\"Whomp, Whomp, read-only!\")\n messagebox.showwarning(\"Warning!\",\n \"Whomp, Whomp, read-only!\",\n parent=self.parentframe)\n return\n else:\n super(YeeTable,self).drawCellEntry(row, col, text)\n return\n\n# Create a TKinter app based on Frame\nclass TestApp(Frame):\n \"\"\"Basic test frame for the table\"\"\"\n def __init__(self, parent=None):\n self.parent = parent\n Frame.__init__(self)\n self.main = self.master\n self.main.geometry('600x400+200+100')\n self.main.title('Table app')\n f = Frame(self.main)\n f.pack(fill=BOTH,expand=1)\n #df = TableModel.getSampleData()\n df = StringResults()\n self.table = pt = YeeTable(f, dataframe=df,\n showtoolbar=False, showstatusbar=True)\n\n # pt.model.df.set_index('identifierName')\n\n # Cool! bind a control-b input to a function that gets called\n pt.bind(\"\", self.HelloBenson )\n pt.show()\n\n \n return\n \n def HelloBenson(self, event):\n print(\"Hello Benson!!!\")\n\n\n\napp = TestApp()\n#launch the app\napp.mainloop()","sub_path":"PandasTEST/Pandas_PandasTable.py","file_name":"Pandas_PandasTable.py","file_ext":"py","file_size_in_byte":5093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"339957288","text":"#/###################/#\n# Import modules\n#\n\n#ImportModules\nimport ShareYourSystem as SYS\n\n#/###################/#\n# Build the model\n#\n\n#Define\nMyLeaker=SYS.LeakerClass(\n\t).mapSet(\n\t\t{\n\t\t\t'-Populations':{\n\t\t\t\t'|Default':{\n\t\t\t\t\t'LeakingUnitsInt':1,\n\t\t\t\t\t'LeakingSymbolPrefixStr':'r',\n\t\t\t\t\t'-Inputs':{\n\t\t\t\t\t\t'|Default':{\n\t\t\t\t\t\t\t'LeakingWeightVariable':5.\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\t'-Interactions':{\n\t\t\t\t\t\t'|/':{\n\t\t\t\t\t\t\t'LeakingWeightVariable':-1.,\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\t'LeakingTransferVariable':'1.*mV*tanh((#CurrentStr)/(1.*mV))',\n\t\t\t\t\t#'LeakingTransferVariable':lambda __Float:__Float,\n\t\t\t\t\t#'BrianingDebugVariable':100\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t).leak(\n\t)\n\n#/###################/#\n# Do one simulation\n#\n\nMyLeaker.simulate(\n\t\t500.\n\t)\n\n#/###################/#\n# View\n#\n\nMyLeaker.mapSet(\n\t\t{\n\t\t\t'PyplotingGridVariable':(20,20)\n\t\t}\n\t).view(\n\t).pyplot(\n\t).show(\n\t)\n\n#/###################/#\n# Print\n#\n\n#Definition the AttestedStr\nprint('MyLeaker is ')\nSYS._print(MyLeaker) \n\n\n","sub_path":"Pythonlogy/build/lib/ShareYourSystem/Standards/Recorders/Leaker/07_ExampleCell.py","file_name":"07_ExampleCell.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"388552722","text":"import codecs\nimport hashlib\nimport os\nimport sys\nimport inspect\nimport traceback\nimport sj\n\nfrom mitmproxy import ctx\nfrom mitmproxy.script import concurrent\n\nfrom subprocess import CalledProcessError, Popen, PIPE, STDOUT\n\nJALANGI_HOME = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getframeinfo(inspect.currentframe()).filename\n)), os.pardir))\nWORKING_DIR = os.getcwd()\n\nsys.path.insert(0, JALANGI_HOME+'/scripts')\n\ndef start():\n print('Jalangi home is ' + JALANGI_HOME)\n print('Current working directory is ' + WORKING_DIR)\n\ndef load(l):\n l.add_option('args', str, \"\", \"Jalangi2 Arguments\")\n l.add_option('cache', bool, True, \"Jalangi2 use cache\")\n\ndef processFile (flow, content, ext):\n\n try:\n\n url = flow.request.scheme + '://' + flow.request.host + ':' + str(flow.request.port) + flow.request.path\n name = os.path.splitext(flow.request.path_components[-1])[0] if hasattr(flow.request,'path_components') and len(flow.request.path_components) else 'index'\n\n hash = hashlib.md5(content.encode('utf-8')).hexdigest()\n baseName = 'cache/' + flow.request.host + '/' + hash + '/' + hashlib.md5(name.encode('utf-8')).hexdigest()\n fileName = baseName + '.' + ext\n instrumentedFileName = baseName + '_jalangi_.' + ext\n \n if not os.path.exists('cache/' + flow.request.host + '/' + hash):\n os.makedirs('cache/' + flow.request.host + '/' + hash)\n \n if not ctx.options.cache or not os.path.isfile(instrumentedFileName):\n print('Instrumenting: ' + fileName + ' from ' + url)\n with open(fileName, 'w') as file:\n file.write(content)\n sub_env = { 'JALANGI_URL': url }\n sj.execute(sj.INSTRUMENTATION_SCRIPT + ' ' + ctx.options.args + ' ' + fileName + ' --out ' + instrumentedFileName + ' --outDir ' + os.path.dirname(instrumentedFileName), None, sub_env)\n else:\n print('Already instrumented: ' + fileName + ' from ' + url)\n \n with open (instrumentedFileName, \"r\") as file:\n data = file.read()\n \n return data\n\n except:\n print('Exception in processFile() @ proxy.py')\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join(lines))\n return content\n\n@concurrent\ndef response(flow):\n\n # Do not invoke jalangi if the requested URL contains the query parameter noInstr\n # (e.g. https://cdn.com/jalangi/jalangi.min.js?noInstr=true)\n if flow.request.query and flow.request.query.get('noInstr', None):\n return\n\n try:\n flow.response.decode()\n\n content_type = None\n csp_key = None\n for key in flow.response.headers.keys():\n if key.lower() == \"content-type\":\n content_type = flow.response.headers[key].lower()\n elif key.lower() == \"content-security-policy\":\n csp_key = key\n\n if content_type:\n if content_type.find('javascript') >= 0:\n flow.response.text = processFile(flow, flow.response.text, 'js')\n if content_type.find('html') >= 0:\n flow.response.text = processFile(flow, flow.response.text, 'html')\n\n # Disable the content security policy since it may prevent jalangi from executing\n if csp_key:\n flow.response.headers.pop(csp_key, None)\n except:\n print('Exception in response() @ proxy.py')\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join(lines))\n","sub_path":"scripts/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"115841725","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\nimport contextlib\nimport os\nimport tempfile\nfrom typing import List\n\nimport numpy\nimport onnx\n\nfrom deepsparse.utils.log import log_init\n\n\n__all__ = [\n \"get_external_inputs\",\n \"get_external_outputs\",\n \"get_input_names\",\n \"get_output_names\",\n \"generate_random_inputs\",\n \"override_onnx_batch_size\",\n]\n\nlog = log_init(os.path.basename(__file__))\n\nonnx_tensor_type_map = {\n 1: numpy.float32,\n 2: numpy.uint8,\n 3: numpy.int8,\n 4: numpy.uint16,\n 5: numpy.int16,\n 6: numpy.int32,\n 7: numpy.int64,\n 9: numpy.bool_,\n 10: numpy.float16,\n 11: numpy.float64,\n 12: numpy.uint32,\n 13: numpy.uint64,\n 14: numpy.complex64,\n 15: numpy.complex128,\n}\n\n\ndef translate_onnx_type_to_numpy(tensor_type: int):\n \"\"\"\n Translates ONNX types to numpy types\n :param tensor_type: Integer representing a type in ONNX spec\n :return: Corresponding numpy type\n \"\"\"\n if tensor_type not in onnx_tensor_type_map:\n raise Exception(\"Unknown ONNX tensor type = {}\".format(tensor_type))\n return onnx_tensor_type_map[tensor_type]\n\n\ndef get_external_inputs(onnx_filepath: str) -> List:\n \"\"\"\n Gather external inputs of ONNX model\n :param onnx_filepath: File path to ONNX model\n :return: List of input objects\n \"\"\"\n model = onnx.load(onnx_filepath)\n all_inputs = model.graph.input\n initializer_input_names = [node.name for node in model.graph.initializer]\n external_inputs = [\n input for input in all_inputs if input.name not in initializer_input_names\n ]\n return external_inputs\n\n\ndef get_external_outputs(onnx_filepath: str) -> List:\n \"\"\"\n Gather external outputs of ONNX model\n :param onnx_filepath: File path to ONNX model\n :return: List of output objects\n \"\"\"\n model = onnx.load(onnx_filepath)\n return [output for output in model.graph.output]\n\n\ndef get_input_names(onnx_filepath: str) -> List[str]:\n \"\"\"\n Gather names of all external inputs of ONNX model\n :param onnx_filepath: File path to ONNX model\n :return: List of string names\n \"\"\"\n return [input.name for input in get_external_inputs(onnx_filepath)]\n\n\ndef get_output_names(onnx_filepath: str) -> List[str]:\n \"\"\"\n Gather names of all external outputs of ONNX model\n :param onnx_filepath: File path to ONNX model\n :return: List of string names\n \"\"\"\n return [output.name for output in get_external_outputs(onnx_filepath)]\n\n\ndef generate_random_inputs(\n onnx_filepath: str, batch_size: int = None\n) -> List[numpy.array]:\n \"\"\"\n Generate random data that matches the type and shape of ONNX model,\n with a batch size override\n :param onnx_filepath: File path to ONNX model\n :param batch_size: If provided, override for the batch size dimension\n :return: List of random tensors\n \"\"\"\n input_data_list = []\n for i, external_input in enumerate(get_external_inputs(onnx_filepath)):\n input_tensor_type = external_input.type.tensor_type\n in_shape = [int(d.dim_value) for d in input_tensor_type.shape.dim]\n\n if batch_size is not None:\n in_shape[0] = batch_size\n\n log.info(\"-- generating random input #{} of shape = {}\".format(i, in_shape))\n input_data_list.append(\n numpy.random.rand(*in_shape).astype(\n translate_onnx_type_to_numpy(input_tensor_type.elem_type)\n )\n )\n return input_data_list\n\n\n@contextlib.contextmanager\ndef override_onnx_batch_size(onnx_filepath: str, batch_size: int):\n \"\"\"\n Rewrite batch sizes of ONNX model, saving the modified model and returning its path\n :param onnx_filepath: File path to ONNX model\n :param batch_size: Override for the batch size dimension\n :return: File path to modified ONNX model\n \"\"\"\n model = onnx.load(onnx_filepath)\n all_inputs = model.graph.input\n initializer_input_names = [node.name for node in model.graph.initializer]\n external_inputs = [\n input for input in all_inputs if input.name not in initializer_input_names\n ]\n for external_input in external_inputs:\n external_input.type.tensor_type.shape.dim[0].dim_value = batch_size\n\n # Save modified model\n shaped_model = tempfile.NamedTemporaryFile(mode=\"w\", delete=False)\n onnx.save(model, shaped_model.name)\n\n try:\n yield shaped_model.name\n finally:\n os.unlink(shaped_model.name)\n shaped_model.close()\n","sub_path":"src/deepsparse/utils/onnx.py","file_name":"onnx.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"504737570","text":"# Problem available at: https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3379/\n\n# Question: \n'''\nThere are 8 prison cells in a row, and each cell is either occupied or vacant.\n\nEach day, whether the cell is occupied or vacant changes according to the following rules:\n\nIf a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.\nOtherwise, it becomes vacant.\n(Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.)\n\nWe describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.\n\n'''\n\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:\n \n def nextDay(cells):\n mask = cells.copy()\n for i in range(1, len(cells) - 1):\n if mask[i-1] ^ mask[i+1] == 0:\n cells[i] = 1\n else:\n cells[i] = 0\n cells[0] = 0\n cells[-1] = 0 \n return cells\n \n day1 = tuple(nextDay(cells))\n N -= 1\n count = 0\n \n while N > 0:\n day = tuple(nextDay(cells))\n N -= 1\n count += 1\n \n if day == day1:\n N = N % count\n return cells","sub_path":"PrisonCellsAfterNDays.py","file_name":"PrisonCellsAfterNDays.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"303457210","text":"# -*- coding: utf-8 -*-\n\"\"\"\nOríon is an asynchronous distributed framework for black-box function optimization.\n\nIts purpose is to serve as a hyperparameter optimizer for\nmachine learning models and training, as well as a flexible experimentation\nplatform for large scale asynchronous optimization procedures.\n\nIt has been designed firstly to disrupt a user's workflow at minimum, allowing\nfast and efficient hyperparameter tuning, and secondly to provide secondary APIs\nfor more advanced features, such as dynamically reporting validation scores on\ntraining time for automatic early stopping or on-the-fly reconfiguration.\n\nStart by having a look here: https://github.com/epistimio/orion\n\"\"\"\nimport logging\nimport os\nimport socket\n\nfrom appdirs import AppDirs\n\nfrom orion.core.io.config import Configuration\nfrom ._version import get_versions\n\n\nlogger = logging.getLogger(__name__)\n\n\nVERSIONS = get_versions()\ndel get_versions\n\n__descr__ = 'Asynchronous [black-box] Optimization'\n__version__ = VERSIONS['version']\n__license__ = 'BSD-3-Clause'\n__author__ = u'Epistímio'\n__author_short__ = u'Epistímio'\n__author_email__ = 'xavier.bouthillier@umontreal.ca'\n__copyright__ = u'2017-2019, Epistímio'\n__url__ = 'https://github.com/epistimio/orion'\n\nDIRS = AppDirs(__name__, __author_short__)\ndel AppDirs\n\nDEF_CONFIG_FILES_PATHS = [\n os.path.join(DIRS.site_data_dir, 'orion_config.yaml.example'),\n os.path.join(DIRS.site_config_dir, 'orion_config.yaml'),\n os.path.join(DIRS.user_config_dir, 'orion_config.yaml')\n ]\n\n\ndef define_config():\n \"\"\"Create and define the fields of the configuration object.\"\"\"\n config = Configuration()\n define_database_config(config)\n define_worker_config(config)\n\n config.add_option(\n 'user_script_config', option_type=str, default='config')\n\n return config\n\n\ndef define_database_config(config):\n \"\"\"Create and define the fields of the database configuration.\"\"\"\n database_config = Configuration()\n\n try:\n default_host = socket.gethostbyname(socket.gethostname())\n except socket.gaierror:\n default_host = 'localhost'\n\n database_config.add_option(\n 'name', option_type=str, default='orion', env_var='ORION_DB_NAME')\n database_config.add_option(\n 'type', option_type=str, default='MongoDB', env_var='ORION_DB_TYPE')\n database_config.add_option(\n 'host', option_type=str, default=default_host, env_var='ORION_DB_ADDRESS')\n database_config.add_option(\n 'port', option_type=int, default=27017, env_var='ORION_DB_PORT')\n\n config.database = database_config\n\n\ndef define_worker_config(config):\n \"\"\"Create and define the fields of the worker configuration.\"\"\"\n worker_config = Configuration()\n\n worker_config.add_option(\n 'heartbeat', option_type=int, default=120)\n worker_config.add_option(\n 'max_broken', option_type=int, default=3)\n worker_config.add_option(\n 'max_idle_time', option_type=int, default=60)\n\n config.worker = worker_config\n\n\ndef build_config():\n \"\"\"Define the config and fill it based on global configuration files.\"\"\"\n config = define_config()\n for file_path in DEF_CONFIG_FILES_PATHS:\n if not os.path.exists(file_path):\n logger.debug('Config file not found: %s', file_path)\n continue\n\n config.load_yaml(file_path)\n\n return config\n\n\nconfig = build_config()\n","sub_path":"src/orion/core/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"592319268","text":"import os\nimport shutil\nimport tempfile\nimport time\n\nfrom flask import Response, Blueprint, send_from_directory\n\nfrom platypush.backend.http.app import template_folder\nfrom platypush.backend.http.app.utils import authenticate, send_request\n\ncamera = Blueprint('camera', __name__, template_folder=template_folder)\n\n# Declare routes list\n__routes__ = [\n camera,\n]\n\n\ndef get_device_id(device_id=None):\n if device_id is None:\n device_id = str(send_request(action='camera.get_default_device_id').output)\n return device_id\n\n\ndef get_frame_file(device_id=None):\n device_id = get_device_id(device_id)\n was_recording = True\n frame_file = None\n status = send_request(action='camera.status', device_id=device_id).output\n\n if device_id not in status:\n was_recording = False\n send_request(action='camera.start_recording',\n device_id=device_id)\n\n while not frame_file:\n frame_file = send_request(action='camera.status', device_id=device_id). \\\n output.get(device_id, {}).get('image_file')\n\n if not frame_file:\n time.sleep(0.1)\n\n if not was_recording:\n with tempfile.NamedTemporaryFile(prefix='camera_capture_', suffix='.jpg',\n delete=False) as f:\n # stop_recording will delete the temporary frames. Copy the image file\n # to a temporary file before stopping recording\n tmp_file = f.name\n\n shutil.copyfile(frame_file, tmp_file)\n frame_file = tmp_file\n send_request(action='camera.stop_recording', device_id=device_id)\n\n return frame_file\n\n\ndef video_feed(device_id=None):\n device_id = get_device_id(device_id)\n send_request(action='camera.start_recording', device_id=device_id)\n last_frame_file = None\n\n try:\n while True:\n frame_file = get_frame_file(device_id)\n if frame_file == last_frame_file:\n continue\n\n with open(frame_file, 'rb') as f:\n frame = f.read()\n\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n\n last_frame_file = frame_file\n finally:\n send_request(action='camera.stop_recording', device_id=device_id)\n\n\n@camera.route('/camera//frame', methods=['GET'])\n@authenticate()\ndef get_camera_frame(device_id):\n frame_file = get_frame_file(device_id)\n return send_from_directory(os.path.dirname(frame_file),\n os.path.basename(frame_file))\n\n\n@camera.route('/camera/frame', methods=['GET'])\n@authenticate()\ndef get_default_camera_frame():\n frame_file = get_frame_file()\n return send_from_directory(os.path.dirname(frame_file),\n os.path.basename(frame_file))\n\n\n@camera.route('/camera/stream', methods=['GET'])\n@authenticate()\ndef get_default_stream_feed():\n return Response(video_feed(),\n mimetype='multipart/x-mixed-replace; boundary=frame')\n\n\n@camera.route('/camera//stream', methods=['GET'])\n@authenticate()\ndef get_stream_feed(device_id):\n return Response(video_feed(device_id),\n mimetype='multipart/x-mixed-replace; boundary=frame')\n\n\n# vim:sw=4:ts=4:et:\n","sub_path":"platypush/backend/http/app/routes/plugins/camera/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"433380712","text":"\nimport tkinter\nimport time\nfrom tkinter import messagebox\nfrom tkinter import OptionMenu\nfrom tkinter import *\n\n\ndef acceso():\n \n ventana=tkinter.Tk()\n ventana.title(\"Biblioteca\")\n ventana.geometry( \"600x500+100+50\")\n\n\n user=tkinter.Label(ventana,text=\"Usuario\").place ( x = 170, y = 40)\n\n password=tkinter.Label(ventana, text=\"Contraseña\").place(x=170, y=80)\n\n textBox_user = tkinter.Entry(ventana)#.place ( x = 170, y = 60)\n textBox_user.pack(side=tkinter.TOP)\n textBox_password = tkinter.Entry(ventana)#.place ( x = 170, y = 100)\n textBox_password.pack(side=tkinter.TOP)\n \n\n def ingresar():\n textous=textBox_user.get()\n textopass=textBox_password.get()\n us=\"\"\n con=\"\"\n \n if textous== us and textopass==con:\n ventana.destroy()\n menu()\n else:\n correcto = messagebox.showerror(message=\"\"\"Usuario o contraseña incorrectos.\n Intente de nuevo\"\"\")\n acceso()\n\n boton_ingresar = tkinter.Button(ventana, text = \"Ingresar\", command=ingresar).place(x = 170, y = 200 )\n\n boton_salir = tkinter.Button(ventana, text = \"Salir\", command=ventana.destroy).place(x = 170, y = 250 )\n \n\n boton_color=tkinter.Button(ventana, height=500, width=20, bg= \"#3439E1\").place (x=0, y=0)\n texto1 = tkinter.Label(ventana, bg= \"#3439E1\", text = \"Base\", font = (\"Arial\", 20)).place( x = 15, y = 120)\n texto2 = tkinter.Label(ventana, bg= \"#3439E1\", text = \"De\", font = (\"Arial\", 20)).place( x = 15, y = 190)\n texto3 = tkinter.Label(ventana, bg= \"#3439E1\", text = \"Datos\", font = (\"Arial\", 20)).place( x = 15, y = 250)\n texto4 = tkinter.Label(ventana, bg= \"#3439E1\", text = \"Biblioteca\", font = (\"Arial\", 20)).place( x = 15, y = 320)\n\ndef menu():\n def combine_funcs(*funcs):\n def combined_func(*args, **kwargs):\n for f in funcs:\n f(*args, **kwargs)\n return combined_func\n \n ventana2=tkinter.Tk()\n ventana2.title(\"Menú\")\n ventana2.geometry( \"600x500+100+50\")\n def consulta():\n \n ventana3=tkinter.Tk()\n ventana3.title(\"Consulta\")\n ventana3.geometry( \"600x500+100+50\")\n\n def usuarioBD():\n tablaUsuario=tkinter.Tk()\n tablaUsuario.geometry( \"+400+100\")\n usuarioDisplay = tkinter.Label(tablaUsuario, text = \"\"\"Aqui se muestra\n la tabla \"\"\").grid(row=0, column=0, sticky=\"nsew\")\n \"\"\"en esta label se debera \n de mostrar el DB\"\"\"\n salir = tkinter.Button(tablaUsuario, text = \"Cerrar\", command= tablaUsuario.destroy).grid(row=1, column=1, sticky=\"nsew\")\n return\n def prestamoBD():\n tablaPrestamo=tkinter.Tk()\n tablaPrestamo.geometry( \"+400+100\")\n prestamoDisplay = tkinter.Label(tablaPrestamo, text = \"\"\"Aqui se muestra\n la tabla \"\"\").grid(row=0, column=0, sticky=\"nsew\")\n salir = tkinter.Button(tablaPrestamo, text = \"Cerrar\", command= tablaPrestamo.destroy).grid(row=1, column=1, sticky=\"nsew\")\n return\n def libroBD():\n tablaLibro=tkinter.Tk()\n tablaLibro.geometry( \"+400+100\")\n libroDisplay = tkinter.Label(tablaLibro, text = \"\"\"Aqui se muestra\n la tabla \"\"\").grid(row=0, column=0, sticky=\"nsew\")\n salir = tkinter.Button(tablaLibro, text = \"Cerrar\", command= tablaLibro.destroy).grid(row=1, column=1, sticky=\"nsew\")\n return\n\n #texto2 = tkinter.Label(ventana3, text = \"Consulta\", font = (\"Arial\", 30)).place( x = 275, y = 400)\n boton_usuario = tkinter.Button(ventana3, text = \"Usuario\", command = usuarioBD).place(x = 170, y = 50 )\n boton_color=tkinter.Button(ventana3, height=500, width=20, bg= \"#3439E1\").place (x=0, y=0)\n texto = tkinter.Label(ventana3, bg= \"#3439E1\", text = \"Consulta\", font = (\"Arial\", 20)).place( x = 15, y = 200)\n\n #Se despliega tabla de datos de usuarioBD\n #---------------------------------------------\n\n boton_prestamo2 = tkinter.Button(ventana3, text = \"Préstamo\", command = prestamoBD).place(x = 170, y =90 )\n\n #Se despliega tabla de datos de prestamoBD\n #---------------------------------------------\n\n boton_libro = tkinter.Button(ventana3, text = \"Libro\", command = libroBD).place(x = 170, y = 130 )\n\n #Se despliega tabla de datos de libroBD\n #---------------------------------------------\n self.boton_menu = Button(ventana3, text = \"Menú\", \n command = combine_funcs(menu, ventana3.destroy)).place(x = 170, y = 250)\n \n def registro():\n \n def registrarBD():\n \"\"\"añadir datos a Base de datos\"\"\"\n correcto = messagebox.showinfo(message=\"Se ha registrado con exito\", title=\"Exito\")\n return\n \n ventana4=tkinter.Tk()\n ventana4.title(\"Registro\")\n ventana4.geometry( \"600x500+100+50\")\n #texto3 = tkinter.Label(ventana4, text = \"Registro de Usuarios\", font = (\"Arial\", 30)).place( x = 160, y = 400)\n boton_color=tkinter.Button(ventana4, height=500, width=20, bg= \"#3439E1\").place (x=0, y=0)\n texto = tkinter.Label(ventana4, bg= \"#3439E1\", text = \"Registro\", font = (\"Arial\", 20)).place( x = 15, y = 200)\n boton_registrar = tkinter.Button(ventana4, text = \"Registrar\", command= registrarBD).place(x = 170, y = 190)\n\n #funcion para agregar datos de persona registrada a base de datos\n #-----------------------------------------------\n\n nombre=tkinter.Label(ventana4,text=\"Nombre\").place ( x = 170, y = 5)\n apellidop=tkinter.Label(ventana4,text=\"Apellido Paterno\").place ( x = 170, y = 25)\n apellidom=tkinter.Label(ventana4,text=\"Apellido Materno\").place ( x = 170, y = 50)\n edad=tkinter.Label(ventana4,text=\"Edad\").place ( x = 170, y = 73)\n genero=tkinter.Label(ventana4,text=\"Género\").place ( x = 170, y = 95)\n escolaridad=tkinter.Label(ventana4,text=\"Escolaridad\").place ( x = 170, y = 115)\n ocupacion=tkinter.Label(ventana4,text=\"Ocupación\").place ( x = 170, y = 140)\n \n textBox_nombre = tkinter.Entry(ventana4).place ( x = 300, y = 5)\n #textBox_nombre.pack(side=tkinter.TOP)\n textBox_apellidop = tkinter.Entry(ventana4).place ( x = 300, y = 25)\n #textBox_apellidop.pack(side=tkinter.TOP)\n textBox_apellidom = tkinter.Entry(ventana4).place ( x = 300, y = 50)\n #textBox_apellidom.pack(side=tkinter.TOP)\n textBox_edad = tkinter.Entry(ventana4).place ( x = 300, y = 73)\n #textBox_edad.pack(side=tkinter.TOP)\n textBox_genero = tkinter.Entry(ventana4).place ( x = 300, y = 95)\n #textBox_genero.pack(side=tkinter.TOP)\n textBox_escolaridad = tkinter.Entry(ventana4).place ( x = 300, y = 115)\n #textBox_escolaridad.pack(side=tkinter.TOP)\n textBox_ocupacion = tkinter.Entry(ventana4).place ( x = 300, y = 140)\n #textBox_ocupacion.pack(side=tkinter.TOP)\n if textBox_nombre or textBox_apellidop or textBox_apellidom or textBox_edad or textBox_genero or textBox_escolaridad or textBox_ocupacion == \"\":\n pass\n self.boton_menu2 = Button(ventana4, text = \"Menú\", \n command = combine_funcs(menu, ventana4.destroy)).place(x = 320, y = 250)\n \n def libros():\n \n def registarLibro():\n #---------------------------------\n #---------Registro en DB \n #------------------------------\n correcto = messagebox.showinfo(message=\"Se ha registrado con exito\", title=\"Exito\")\n return\n \n ventana5=tkinter.Tk()\n ventana5.title(\"Libros\")\n ventana5.geometry( \"600x500+100+50\")\n #texto4 = tkinter.Label(ventana5, text = \"Registro Libros\", font = (\"Arial\", 30)).place( x = 230, y = 400)\n boton_color=tkinter.Button(ventana5, height=500, width=20, bg= \"#3439E1\").place (x=0, y=0)\n texto = tkinter.Label(ventana5, bg= \"#3439E1\", text = \"Libros\", font = (\"Arial\", 20)).place( x = 15, y = 200)\n \n \n boton_registrar2 = tkinter.Button(ventana5, text = \"Registrar\", command=registarLibro).place(x = 170, y = 190)\n autor=tkinter.Label(ventana5,text=\"Autor\").place ( x = 170, y = 5)\n titulo=tkinter.Label(ventana5,text=\"Titulo\").place ( x = 170, y = 25)\n clave=tkinter.Label(ventana5,text=\"Clave\").place ( x = 170, y = 45)\n cantidad=tkinter.Label(ventana5,text=\"Cantidad\").place ( x = 170, y = 69)\n coleccion=tkinter.Label(ventana5,text=\"Colección\").place ( x = 170, y = 93)\n cantidad_prestados=tkinter.Label(ventana5,text=\"Cantidad prestados\").place ( x = 170, y = 115)\n numero_ejemplar=tkinter.Label(ventana5,text=\"N° de ejemplar\").place ( x = 170, y = 137)\n textBox_autor = tkinter.Entry(ventana5).place ( x = 300, y = 5)\n #textBox_autor.pack(side=tkinter.TOP)\n textBox_titulo = tkinter.Entry(ventana5).place ( x = 300, y = 25)\n #textBox_titulo.pack(side=tkinter.TOP)\n textBox_clave = tkinter.Entry(ventana5).place ( x = 300, y = 45)\n #textBox_clave.pack(side=tkinter.TOP)\n textBox_cantidad = tkinter.Entry(ventana5).place ( x = 300, y = 69)\n #textBox_cantidad.pack(side=tkinter.TOP)\n textBox_coleccion = tkinter.Entry(ventana5).place ( x = 300, y = 93)\n #textBox_coleccion.pack(side=tkinter.TOP)\n textBox_cantidad_prestados = tkinter.Entry(ventana5).place ( x = 300, y = 115)\n #textBox_cantidad_prestados.pack(side=tkinter.TOP)\n textBox_numero_ejemplar = tkinter.Entry(ventana5).place ( x = 300, y = 137)\n #textBox_numero_ejemplar.pack(side=tkinter.TOP)\n self.boton_menu3 = Button(ventana5, text = \"Menú\", \n command = combine_funcs(menu, ventana5.destroy)).place(x = 170, y = 250)\n\n def prestamo():\n \n def registarPrestamo():\n #---------------------------------\n #---------Registro en DB \n #------------------------------\n correcto = messagebox.showinfo(message=\"Se ha registrado con exito\", title=\"Exito\")\n return\n \n ventana6=tkinter.Tk()\n ventana6.title(\"Préstamo\")\n ventana6.geometry( \"600x500+100+50\")\n #texto5 = tkinter.Label(ventana6, text = \"Préstamo\", font = (\"Arial\", 30)).place( x = 250, y = 400)\n boton_color=tkinter.Button(ventana6, height=500, width=20, bg= \"#3439E1\").place (x=0, y=0)\n texto = tkinter.Label(ventana6, bg= \"#3439E1\", text = \"Préstamo\", font = (\"Arial\", 20)).place( x = 15, y = 200)\n \n \n boton_registrar3 = tkinter.Button(ventana6, text = \"Registrar\", command=registarPrestamo).place(x = 170, y = 140) \n fechain=tkinter.Label(ventana6,text=\"Fecha Inicial\").place ( x = 170, y = 5)\n fechafi=tkinter.Label(ventana6,text=\"Fecha Final\").place ( x = 170, y = 25)\n libros=tkinter.Label(ventana6,text=\"Libros\").place ( x = 170, y = 45)\n estado=tkinter.Label(ventana6,text=\"Estado\").place ( x = 170, y = 65)\n textBox_fechain = tkinter.Entry(ventana6).place ( x = 300, y = 5)\n #textBox_fechain.pack(side=tkinter.TOP)\n textBox_fechafi = tkinter.Entry(ventana6).place ( x = 300, y = 25)\n #textBox_fechafi.pack(side=tkinter.TOP)\n textBox_libros = tkinter.Entry(ventana6).place ( x = 300, y = 45)\n #textBox_libros.pack(side=tkinter.TOP)\n textBox_estado = tkinter.Entry(ventana6).place ( x = 300, y = 65)\n #textBox_estado.pack(side=tkinter.TOP)\n self.boton_menu4 = Button(ventana6, text = \"Menú\", \n command = combine_funcs(menu, ventana6.destroy)).place(x = 170, y = 180)\n \n def busqueda():\n \n def buscarBD():\n #----------------------------\n #Buscar en base de datos seleccion de tablaUsuario\n #---------------------------\n return\n ventana7=tkinter.Tk()\n ventana7.title(\"Búsqueda\")\n ventana7.geometry( \"600x500+100+50\")\n boton_color=tkinter.Button(ventana7, height=500, width=20, bg= \"#3439E1\").place (x=0, y=0)\n texto = tkinter.Label(ventana7, bg= \"#3439E1\", text = \"Búsqueda\", font = (\"Arial\", 20)).place( x = 15, y = 200)\n #texto6 = tkinter.Label(ventana7, text = \"Búsqueda\", font = (\"Arial\", 30)).place( x = 270, y = 400)\n \n \n textBox_buscar = tkinter.Entry(ventana7).place(x = 170 , y = 270)\n boton_buscar = tkinter.Button(ventana7, text = \"Buscar\",command = buscarBD).place(x = 170, y = 320)\n \n varDes = StringVar(ventana7)\n varDes.set('Seleccionar tabla')\n\n varModo = StringVar(ventana7)\n varModo.set('Seleccionar rubro')\n\n opciones = ['Usuario','Prestamo', 'Libro']\n ventanaDeslizante = OptionMenu(ventana7, varDes, *opciones)\n ventanaDeslizante.config(width=20)\n ventanaDeslizante.place(x = 170, y = 50)\n opciones2 = ['Nombre','Fecha','Cantidad','Autor']\n ventanaModoTrans = OptionMenu(ventana7, varModo, *opciones2)\n ventanaModoTrans.config(width=20)\n ventanaModoTrans.place(x = 170, y = 150)\n self.boton_menu5 = Button(ventana7, text = \"Menú\", \n command = combine_funcs(menu, ventana7.destroy)).place(x = 170, y = 370)\n \n \n boton_consulta = Button(ventana2, text = \"Consulta\", \n command = combine_funcs(ventana2.destroy, consulta)).place(x = 170, y = 50)\n \n boton_registro = Button(ventana2, text = \"Registro de usuarios\", \n command = combine_funcs(ventana2.destroy, registro)).place(x = 170, y = 90)\n \n boton_prestamo = Button(ventana2, text = \"Préstamo\", \n command = combine_funcs(ventana2.destroy, prestamo)).place(x = 170, y = 130)\n \n boton_registro_libro = Button(ventana2, text = \"Registro de libros\", \n command = combine_funcs(ventana2.destroy, libros)).place(x = 170, y = 170)\n \n #boton_edicion_datos = Button(ventana2, text = \"Edicion de datos\", \n #command = combine_funcs(ventana2.destroy, libros)).place(x = 170, y = 210)\n \n boton_busqueda = Button(ventana2, text = \"Busqueda\", \n command = combine_funcs(ventana2.destroy, busqueda)).place(x = 170, y = 250)\n\n boton_salir2 = tkinter.Button(ventana2, text = \"Salir\", command= ventana2.destroy).place(x = 170, y = 330 )\n \n boton_color=tkinter.Button(ventana2, height=500, width=20, bg= \"#3439E1\").place (x=0, y=0)\n texto = tkinter.Label(ventana2, bg= \"#3439E1\", text = \"Menú\", font = (\"Arial\", 20)).place( x = 15, y = 200)\n \nacceso()\n","sub_path":"prueba.py","file_name":"prueba.py","file_ext":"py","file_size_in_byte":14441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"583808678","text":"#Python TurtleArt script\n#produced by 0p3r4t0r\n\nimport turtle\nimport random\nimport math\n\n#canvas\nwin=turtle.Screen()\nwin.screensize(500,500)\nwin.bgcolor(\"black\")\n\n#spawn a turtle\noliver = turtle.Turtle()\noliver.shape(\"turtle\")\noliver.pencolor(\"white\")\n\n#Oliver introduces himself\noliver.speed(0)\noliver.penup()\noliver.setheading(180)\noliver.setx(-250)\noliver.setheading(90)\noliver.sety(250)\noliver.setheading(0)\n#oliver.speed(3)\noliver.write(\"My name is Oliver, and I am an artist.\", \\\nfont=(\"Comic Sans MS\", 24, \"normal\"))\n\n#Draw a rainbow line\noliver.pensize(5)\ncolors=['red','orange','yellow','green','blue1','purple','darkviolet']\nfor color in colors:\n\toliver.color(color)\n\toliver.pencolor(color)\n\toliver.pendown()\n\toliver.forward(60)\noliver.color(\"black\")\noliver.pencolor(\"white\")\n\n#Back to center\noliver.penup()\noliver.tilt(oliver.towards(0,0))\noliver.goto(0,0)\noliver.tilt(-oliver.tiltangle())\noliver.setheading(90)\n\n#Random colors\nrandcolors=['red','blue']\nfor color in randcolors:\n\toliver.color(color)\t\n\n#Initial conditions\nG = 100\nY_c = 40\ntime = 0\ndt = 1\nv_c = 1\ntheta = random.uniform(0,360) #initial turtle angle\nv = v_c #initial turtle speed\noliver.speed(round(v))\noliver.forward(v)\noliverX=oliver.pos()[0]\noliverY=oliver.pos()[1]\nr0_squared = (oliverX)**2 + (oliverY - Y_c)**2\nr0 = math.sqrt(r0_squared)\n\n#Start motion\nprint('r','v','delta_v')\noliver.pendown()\noliver.pensize(2)\noliver.setheading(theta)\n\n#gravity on\nwhile time <= 1000:\n\toliverX=oliver.pos()[0]\n\toliverY=oliver.pos()[1]\n\tr_squared = oliverX**2 + oliverY**2\n\tr = math.sqrt(r_squared)\n\tif(r > r0):\n\t\tdelta_v = -dt*G/r_squared\n\telse:\n\t\tdelta_v = dt*G/r_squared\n\n\tv = v + delta_v\n\toliver.speed(round(v))\n\toliver.forward(v)\n\ttime = time+dt\n\tprint(r, v, delta_v)\n\nwin.exitonclick()\n","sub_path":"Python/PythonSandbox/02TurtleTest.py","file_name":"02TurtleTest.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"335883605","text":"import os\n\nfrom selenium import webdriver\nfrom helpers.read_settings import settings\nfrom subprocess import call\n\ndef run_chrome(context):\n\n run_mode = settings(\"run\", \"mode\")\n\n if run_mode == 'dev':\n\n # call([\"PATH=$PATH:/usr/lib/chromium-browser/\"])\n os.environ[\"PATH\"] += \"/usr/lib/chromium-browser/\"\n\n chromeOptions = webdriver.ChromeOptions()\n preferences = {\"download.default_directory\": settings(\"csv_path\",\"path\"),\n \"download.prompt_for_download\": False,\n \"download.directory_upgrade\": True,\n \"credentials_enable_service\": False,\n \"profile\": {\n \"password_manager_enabled\": False\n },\n \"performance\": \"ALL\"\n }\n\n chromeOptions.add_experimental_option(\"prefs\", preferences)\n chromeOptions.add_argument(\"--kiosk\")\n # chromeOptions.add_argument('headless')\n context.browser = webdriver.Chrome(chrome_options=chromeOptions)\n else:\n call([\"docker\", \"run\", \"-d\", \"-p\", \"4444:4444\", \"selenium/standalone-chrome\"])\n\n desired_capabilities = webdriver.DesiredCapabilities.CHROME\n desired_capabilities['browserName'] = 'chrome'\n\n chromeOptions = webdriver.ChromeOptions()\n preferences = {\"download.default_directory\": settings(\"csv_path\",\"path\"),\n \"download.prompt_for_download\": False,\n \"download.directory_upgrade\": True,\n \"credentials_enable_service\": False,\n \"profile\": {\n \"password_manager_enabled\": False\n },\n \"performance\": \"ALL\"\n }\n\n chromeOptions.add_experimental_option(\"prefs\", preferences)\n chromeOptions.add_argument(\"--kiosk\")\n\n context.browser = webdriver.Remote(\n command_executor = 'http://0.0.0.0:4444/wd/hub',\n desired_capabilities = chromeOptions.to_capabilities()\n )\n","sub_path":"runner/run_chrome.py","file_name":"run_chrome.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"85932555","text":"\n# Тест проверяет возможность создания делегата и его запуска для тестового регламента\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait as WDW\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException\nimport pytest\nimport time\nimport math\n\nDEF_NAME = \"РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ\"\nDELEGAT_NAME = \"Стартовый делегат\"\n\n\n#@pytest.mark.skip()\ndef test_1_create_definition(browser, help):\n\n # заходим в главное меню регламенты - регаламенты\n href = '[href=\"#/definitions\"]'\n help.definition(browser, href)\n\n # нажимаем кнопку Добавить\n xpath = '//*[text()=\"Добавить \"]'\n help.f_xpath(browser, xpath )\n\n # заполняем поле Код\n text = \"РД\"\n selector = '#code_a'\n help.past_text( browser, selector, text)\n\n # заполняем поле Наименование\n text = \"Регламент для создания делегатов\"\n selector = '#name_a'\n help.past_text( browser, selector, text)\n\n # выбираем Группу\n selector = '#group_a'\n help.f_selectors(browser, selector)\n selector = 'div>select>option'\n help.f_selectors( browser, selector)\n\n # выбираем Состояние \"Открытый\"\n selector = '#state_a'\n help.f_selectors(browser, selector)\n selector = '[value=\"О\"]'\n help.f_selectors( browser, selector)\n\n # вводим Описание\n text = \"Регламент для создания делегатов\"\n selector = '#description_a'\n help.past_text(browser, selector, text)\n\n # нажимаем кнопку Сохранить\n xpath = '//button[text()=\"Сохранить\"]'\n help.f_xpath(browser, xpath )\n\n # Проверяем наличие нового регламена\n xpath = '//*[text() = \"РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ\"]'\n assert help.check_exists_by_xpath(browser, xpath), \"Регламент для создания делегатов не создан\"\n\n#@pytest.mark.skip()\n# Тест 2 \"Добавление нового делегата\ndef test_2_create_delegation(browser, help):\n\n # заходим в главное меню регламенты - регаламенты\n href = '[href=\"#/definitions\"]'\n help.definition(browser, href)\n\n # Выбираем строку Регламента для создания делегатов\n xpath = '//b[text()=\"РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ\"]'\n help.f_xpath(browser, xpath)\n browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n # выбираем кнопку Делегаты\n xpath = '//*[text()=\"Делегаты \"]'\n help.f_xpath(browser, xpath )\n #browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n browser.execute_script(\"window.scrollBy(0,-250)\", \"\")\n\n # нажимаем кнопку Добавить\n xpath = '//button[text()=\"Добавить \"]'\n help.f_xpath(browser, xpath )\n #selector = 'class = add-icon.text-black'\n #help.f_selectors(browser, selector)\n\n\n # заполняем поле Название\n text = \"Стартовый делегат\"\n selector = '#name'\n help.past_text( browser, selector, text)\n time.sleep(1)\n # выбираем Тип \"Делегат выполнения\"\n selector = '#type'\n help.f_selectors(browser, selector)\n selector = '[value=\"E\"]'\n help.f_selectors( browser, selector)\n\n\n # выбираем Вид \"Скрипт\"\n selector = '#kind'\n help.f_selectors(browser, selector)\n selector = '[value=\"Q\"]'\n help.f_selectors( browser, selector)\n\n # Вводим текст скрипта\n text = \"print('Скрипт делегата выполнен')\"\n selector = '#configuration'\n help.past_text( browser, selector, text)\n\n # нажимаем кнопку Сохранить\n xpath = '//*[text()=\"Сохранить\"]'\n help.f_xpath(browser, xpath )\n time.sleep(1)\n # Проверяем наличие нового делегата в списке\n xpath = '//*[text() = \"Стартовый делегат\"]'\n assert help.check_exists_by_xpath(browser, xpath), \"Делегат для Регламента не создан\"\n\n\n#@pytest.mark.skip()\n# Тест 3 \"Выполнение нового делегата напримере стартового узла\"\ndef test_3_done_delegation(browser, help):\n\n # заходим в главное меню регламенты - регаламенты\n href = '[href=\"#/definitions\"]'\n help.definition(browser, href)\n\n # Выбираем строку Регламента для создания делегатов\n xpath = '//b[text()=\"РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ\"]'\n help.f_xpath(browser, xpath)\n browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n # нажимаем кнопку Редактор\n xpath = '//*[text()=\"Редактор \"]'\n help.f_xpath(browser, xpath )\n\n # создаем карточку Стартового узла\n # нажимаем кнопку Карточка\n xpath = '//*[text()=\"Карточка\"]'\n help.f_xpath(browser, xpath)\n\n # нажимаем кнопку Форма\n browser.execute_script(\"window.scrollBy(0,-250)\", \"\")\n xpath = '//*[text()=\"Форма\"]'\n help.f_xpath(browser, xpath)\n\n # добавляем блоки в форму\n j = 0\n while j < 3 :\n # нажимаем кнопку Добавить блок\n xpath = '//*[text()=\"Добавить блок\"]'\n help.f_xpath(browser, xpath)\n j = j+1\n\n # нажимаем кнопку Сохранить\n xpath = '//*[text()=\"Сохранить\"]'\n help.f_xpath(browser, xpath)\n\n # подтверждаем сохранение\n #wait = WDW(browser, 10)\n alert = WDW(browser, 10).until(EC.alert_is_present())\n #alert = browser.switch_to.alert\n alert.accept()\n\n # возвращаемся к редактору регламента\n xpath = '//*[text()=\"Отмена\"]'\n help.f_xpath(browser, xpath)\n\n # вводим наименование узла Стартовый узел\n browser.execute_script(\"window.scrollBy(0,-250)\", \"\")\n text = \"Стартовый узел\"\n selector = '#name'\n help.past_text(browser, selector, text)\n\n # выбираем Обработчик событий окончания обработки\n selector = '#outDelegation'\n help.f_selectors(browser, selector)\n\n #list = browser.execute_script(presence_of_element_located(By.xpath('//*[text()= \" Стартовый делегат\"]')))\n #list[1].click()\n\n xpath = ('//*[text()= \" Стартовый делегат\"]')\n help.f_xpath(browser, xpath)\n browser.execute_script(\"window.scrollBy(0,-250)\", \"\")\n\n # нажимаем кнопку Сохранить\n xpath = '//*[text()=\"Сохранить\"]'\n help.f_xpath(browser, xpath)\n\n # нажимаем кнопку К списку регламентов\n xpath = '//button[text()=\"К списку регламентов\"]'\n help.f_xpath(browser, xpath)\n\n\n # Ищем строку РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ\n line_definition = browser.find_elements_by_css_selector('[class=\"text-pointer\"]')\n deleg_definition = browser.find_element_by_xpath('//b[text()=\"РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ\"]')\n deleg_definition.click()\n i = 0\n while line_definition[i] != deleg_definition:\n i += 1\n #time.sleep(2)\n # browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n # запускаем регламент\n selector = '[class=\"start-icon text-black\"]'\n j = i*2\n help.f_selectors(browser, selector, j)\n #del_definition_group = browser.find_elements_by_css_selector('[class=\"start-icon text-black\"]')\n #del_definition_group[i].click()\n #browser.implicitly_wait(5)\n\n # заполняем карточку процесса\n # заполняем поле Название процесса\n text = \"Тестовый процесс делегата\"\n selector = '#processInstanceSubject'\n help.past_text( browser, selector, text)\n\n # выбираем Тип Важности\n selector = '#processInstanceImportance'\n help.f_selectors(browser, selector)\n selector = '[value=\"N\"]'\n help.f_selectors( browser, selector)\n\n # нажимаем кнопку Подтвердить\n xpath = '//*[text()=\"Подтвердить\"]'\n help.f_xpath(browser, xpath)\n\n # подтверждаем форму\n alert = WDW(browser, 10).until(EC.alert_is_present())\n alert.accept()\n\n # заходим в главное меню регламенты - задачи\n href = '[href=\"#/instances\"]'\n help.definition(browser, href)\n\n # выбираем задачу \"Тестовый процесс делегата\"\n xpath = '//*[text()=\"Тестовый процесс делегата\"]'\n help.f_xpath(browser, xpath)\n\n # Ищем строку Тестовый процесс делегата\n line_definition = browser.find_elements_by_css_selector('[class=\"text-pointer\"]')\n deleg_definition = browser.find_element_by_xpath('//*[text()=\"Тестовый процесс делегата\"]')\n deleg_definition.click()\n i = 0\n while line_definition[i] != deleg_definition:\n i += 1\n browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n print(i)\n time.sleep(1)\n # открываем Журнал\n #browser.execute_script(\"window.scrollBy(0,-250)\", \"\")\n selector = 'td>button.card-icon.text-black'#>font>font'\n #selector = '[style=\"vertical-align: inherit;\"]'\n help.f_selectors(browser, selector,i)\n\n #xpath = '//*[text()=\"Журнал\"]' #@and contains(@class, \"x-grid3-cell-inner\")]'\n #help.f_xpath(browser, xpath)\n time.sleep(1)\n # Проверяем наличие вызова делегата\n xpath = '//*[contains(text(), \"Вызов делегата\") ]'\n help.f_xpath(browser, xpath)\n assert help.check_exists_by_xpath(browser, xpath), \"Делегат для Регламента не вызван\"\n\n # Проверяем отсутствие ошибок вызова делегата\n xpath = '//*[text() = \"Ошибка делегата\"]'\n assert help.check_no_exists_by_xpath(browser, xpath), \"Ошибка делегата\"\n\n\n# удаление тестового регламента\n#@pytest.mark.skip()\ndef test_clean (browser, help):\n\n # заходим в главное меню регламенты - регаламенты\n href = '[href=\"#/definitions\"]'\n help.definition(browser, href)\n\n # Выбираем строку Регламента для создания делегатов\n xpath = '//b[text()=\"РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ\"]'\n help.f_xpath(browser, xpath)\n browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n\n if help.check_no_exists_by_xpath(browser, xpath) == True:\n print(\"Тестовый делегат не удален\")\n\n # заходим в главное меню регламенты - регаламенты\n href = '[href=\"#/definitions\"]'\n help.definition(browser, href)\n\n xpath = '//b[text()=\"РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ\"]'\n if help.check_exists_by_xpath(browser, xpath) == True :\n\n # Ищем строку РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ\n line_definition = browser.find_elements_by_css_selector('[class=\"text-pointer\"]')\n deleg_definition = browser.find_element_by_xpath('//b[text()=\"РЕГЛАМЕНТ ДЛЯ СОЗДАНИЯ ДЕЛЕГАТОВ\"]')\n deleg_definition.click()\n i = 0\n while line_definition[i] != deleg_definition:\n i += 1\n # browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n # удаляем регламент\n selector = '[class=\"remove-icon text-black\"]'\n help.f_selectors(browser, selector, i)\n\n # подтверждаем удаление\n alert = WDW(browser, 10).until(EC.alert_is_present())\n alert.accept()\n\n if help.check_no_exists_by_xpath(browser, xpath) == True:\n print(\"Тестовый регламент для делегата не удален\")\n\n print(\"Тестовые данные удалены\")\n\n\n#test_clean(browser, help)","sub_path":"onegin_delegation.py","file_name":"onegin_delegation.py","file_ext":"py","file_size_in_byte":13059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"294890424","text":"\n# Using Pandas\n# import pandas as pd\n\n# # Reading entire file\n# data = pd.read_excel(\n# r'C:\\Users\\Gautam\\Downloads\\session 1 Budding Entrepreneurs _ India is waiting for startups to innovate (Responses) (1).xlsx')\n\n# # Reading a column\n# df = pd.DataFrame(data, columns=['First Name'])\n# print(df[0])\n\n\n# Using xlrd\n\nimport xlrd\npath = r'C:\\Users\\Gautam\\Downloads\\session 1 Budding Entrepreneurs _ India is waiting for startups to innovate (Responses) (1).xlsx'\n# Give the location of the file\nloc = (path)\n\n# To open Workbook\nwb = xlrd.open_workbook(loc)\nsheet = wb.sheet_by_index(0)\n\n# For row 0 and column 0\nprint(sheet.cell_value(1, 2)+sheet.cell_value(1, 3))\n","sub_path":"src/excelSheet/importExcelData.py","file_name":"importExcelData.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"347176352","text":"'''Simple program to take a file having one column of IDs and check for duplicate IDs in file.\nRudimentary at best...\nWritten by Stacy Howerton, last modified 1 April 2015'''\n\n#INPUT: 1) a .txt file having one column of IDs to use. Other columns don't matter\n#OUTPUT: results to screen \n\n#!/usr/bin/python\nimport os.path\n\ndef main():\n listMembers = parseFile(readFile(input(R'Enter the name of file:')))\n compareIDs(listMembers)\n\ndef compareIDs(AFile):\n ListUniques, ListDuplicates = [], []\n for item in AFile:\n if item not in ListUniques: ListUniques.append(item) \n else: ListDuplicates.append(item)\n print (\"There are %s duplicate IDs\"%s(count(ListDuplicates)))\n \n\ndef readFile(AFileName):\n resultsLines = []\n if os.path.isfile(AFileName):\n results = open(AFileName, \"r\")\n resultsLines = results.readlines()\n results.close()\n return resultsLines\n else:\n print(R'Unable to find that file')\n exit(0)\n \ndef parseFile(content):\n i = int(input(R'What column are your IDs in? (number 1 - n)'))\n listInfo = []\n it = 0\n for line in content:\n item = line.split(\"\\t\")\n if it == 0: pass\n else: listInfo.append(item[i - 1].strip())\n it = it + 1\n return listInfo\n \n\n\nif __name__ == \"__main__\": main()\n","sub_path":"CompareFiles.py","file_name":"CompareFiles.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"363560722","text":"import sqlite3\n\n# Project resolution (width + height) - global resolution for all shots.\n# If SHOT has resolution - it is override for global resolution\n\n\ndef init_database(connection, cursor):\n \"\"\"\n Create database tables\n :return:\n \"\"\"\n\n # TYPES\n cursor.execute('''CREATE TABLE asset_types (\n id integer primary key autoincrement,\n name text,\n description text\n )''')\n\n cursor.execute('''CREATE TABLE file_types (\n id integer primary key autoincrement,\n name text,\n description text\n )''')\n\n # MAIN ITEMS\n cursor.execute('''CREATE TABLE projects (\n id integer primary key autoincrement,\n name text,\n houdini_build text,\n width integer,\n height integer,\n description text\n )''')\n\n cursor.execute('''CREATE TABLE assets (\n id integer primary key autoincrement,\n name text,\n project integer,\n type integer,\n description text,\n FOREIGN KEY(project) REFERENCES projects(id)\n FOREIGN KEY(type) REFERENCES asset_types(id)\n )''')\n\n cursor.execute('''CREATE TABLE sequences (\n id integer primary key autoincrement,\n name text,\n project integer,\n description text,\n FOREIGN KEY(project) REFERENCES projects(id)\n )''')\n\n cursor.execute('''CREATE TABLE shots (\n id integer primary key autoincrement,\n name text,\n sequence integer,\n start_frame integer,\n end_frame integer,\n width integer, \n height integer,\n description text,\n FOREIGN KEY(sequence) REFERENCES sequences(id)\n )''')\n\n # FILES\n cursor.execute('''CREATE TABLE asset_files (\n id integer primary key autoincrement,\n type integer,\n asset integer,\n snapshot integer,\n description text,\n FOREIGN KEY(type) REFERENCES file_types(id)\n FOREIGN KEY(asset) REFERENCES assets(id)\n FOREIGN KEY(snapshot) REFERENCES asset_snapshots(id)\n )''')\n\n cursor.execute('''CREATE TABLE shot_files (\n id integer primary key autoincrement,\n type integer,\n shot integer,\n snapshot integer,\n description text,\n FOREIGN KEY(type) REFERENCES file_types(id)\n FOREIGN KEY(shot) REFERENCES shots(id)\n FOREIGN KEY(snapshot) REFERENCES shot_snapshots(id)\n )''')\n\n # LINKS\n # Link assets to the shots\n cursor.execute('''CREATE TABLE shot_assets (\n id integer primary key autoincrement,\n shot_id integer,\n asset_id integer,\n FOREIGN KEY(shot_id) REFERENCES shots(id)\n FOREIGN KEY(asset_id) REFERENCES assets(id)\n )''')\n\n # SNAPSHOTS\n cursor.execute('''CREATE TABLE asset_snapshot (\n id integer primary key autoincrement,\n asset_name text,\n asset_id text,\n asset_version text,\n description text\n )''')\n\n connection.commit()\n\n\ndef init_asset_types(connection, cursor):\n \"\"\"\n Fill asset types table in the DB (character, environment, prop, FX)\n\n :param connection:\n :param cursor:\n :return:\n \"\"\"\n\n for name, data in Asset.asset_types.iteritems():\n cursor.execute(\"INSERT INTO asset_types VALUES (\"\n \":id,\"\n \":name,\"\n \":description)\",\n\n {'id': data['id'],\n 'name': name,\n 'description': data['description']})\n\n connection.commit()\n\n\ndef init_file_types(connection, cursor):\n \"\"\"\n Fill file types table in the DB.\n\n Any file used in Eve should has a particular type. Here is the full list of all possible types in Eve.\n\n asset_hip:\n Working scene for Assets. Here we store all source data to build an asset. Results are exported as caches,\n and caches used in asset_hda files.\n\n asset_hda:\n Houdini Digital Asset for ASSETS. Used to load assets of any type (char, env, props, fx) into shots.\n Contain cached data with interface. Source of cached data is stored in asset_hip\n\n :param connection:\n :param cursor:\n :return:\n \"\"\"\n\n for name, data in EveFile.file_types.iteritems():\n\n cursor.execute(\"INSERT INTO file_types VALUES (\"\n \":id,\"\n \":name,\"\n \":description)\",\n\n {'id': data['id'],\n 'name': name,\n 'description': data['description']})\n\n connection.commit()\n\n\ndef convert_to_project(project_tuples):\n \"\"\"\n Convert list of projects tuples to list of Eve Project objects\n\n :param project_tuples: list of tuples, project data: [(id, name, houdini_build, width, height, description)]\n :return:\n \"\"\"\n\n projects = []\n for project_tuple in project_tuples:\n project = Project(project_tuple[1])\n project.id = project_tuple[0]\n project.houdini_build = project_tuple[2]\n project.width = project_tuple[3]\n project.height = project_tuple[4]\n project.description = project_tuple[5]\n projects.append(project)\n\n return projects\n\n\ndef convert_to_asset(asset_tuples):\n \"\"\"\n Convert list of assets tuples to list of athena Asset objects\n :param asset_tuples: [(id, name, project, type, description)]\n :return:\n \"\"\"\n\n assets = []\n\n for asset_tuple in asset_tuples:\n asset = Asset(asset_tuple[1], asset_tuple[2])\n asset.id = asset_tuple[0]\n asset.type = asset_tuple[3]\n asset.description = asset_tuple[4]\n assets.append(asset)\n\n return assets\n\n\ndef convert_to_sequence(sequence_tuples):\n \"\"\"\n Convert list of sequence tuples to list of athena Sequence objects\n :param sequence_tuples: [(id, name, project, description)]\n :return:\n \"\"\"\n\n sequences = []\n\n for sequence_tuple in sequence_tuples:\n sequence = Sequence(sequence_tuple[1], sequence_tuple[2])\n sequence.id = sequence_tuple[0]\n sequence.description = sequence_tuple[3]\n sequences.append(sequence)\n\n return sequences\n\n\ndef convert_to_shot(shot_tuples):\n \"\"\"\n Convert list of shot tuples to list of athena Shot objects\n :param shot_tuples: [(id, name, sequence, start_frame, end_frame, width, height, description)]\n :return:\n \"\"\"\n\n shots = []\n\n for shot_tuple in shot_tuples:\n shot = Shot(shot_tuple[1], shot_tuple[2])\n shot.id = shot_tuple[0]\n shot.start_frame = shot_tuple[3]\n shot.end_frame = shot_tuple[4]\n shot.width = shot_tuple[5]\n shot.height = shot_tuple[6]\n shot.description = shot_tuple[7]\n shots.append(shot)\n\n return shots\n\n\ndef convert_to_asset_types(asset_types_tuples):\n \"\"\"\n Convert list of asset types tuples to list of Eve AssetType objects\n :param asset_types_tuples: list of tuples, asset type data: [(id, name, description)]\n :return:\n \"\"\"\n\n asset_types = []\n for asset_types_tuple in asset_types_tuples:\n asset_type = AssetType(asset_types_tuple[0], asset_types_tuple[1], asset_types_tuple[2])\n asset_types.append(asset_type)\n\n return asset_types\n\n\nclass Project:\n def __init__(self, project_name):\n self.id = None\n self.name = project_name\n self.houdini_build = ''\n self.width = ''\n self.height = ''\n self.description = ''\n\n\nclass Asset:\n\n asset_types = {\n 'character':\n {'id': 1,\n 'name': 'character',\n 'description': 'Character asset'},\n\n 'environment':\n {'id': 2,\n 'name': 'environment',\n 'description': 'Environment asset'},\n\n 'prop':\n {'id': 3,\n 'name': 'prop',\n 'description': 'Animated asset with rig'},\n\n 'static':\n {'id': 4,\n 'name': 'static',\n 'description': 'Non animated asset'},\n\n 'fx':\n {'id': 5,\n 'name': 'fx',\n 'description': 'FX asset'}}\n\n def __init__(self, asset_name, project_id):\n self.id = None\n self.name = asset_name\n self.project = project_id\n self.type = None\n self.description = ''\n\n\nclass Sequence:\n def __init__(self, sequence_name, project_id):\n self.id = None\n self.name = sequence_name\n self.project = project_id\n self.description = ''\n\n\nclass Shot:\n def __init__(self, shot_name, sequence_id):\n self.id = None\n self.name = shot_name\n self.sequence = sequence_id\n self.start_frame = ''\n self.end_frame = ''\n self.width = ''\n self.height = ''\n self.description = ''\n\n\nclass AssetType:\n def __init__(self, id, name, description):\n self.id = id\n self.name = name\n self.description = description\n\n\nclass EveFile:\n\n file_types = {\n 'asset_hip':\n {'id': 1,\n 'name': 'asset_hip',\n 'prefix': 'ast',\n 'description': 'Houdini working scene for assets'},\n\n 'asset_hda':\n {'id': 2,\n 'name': 'asset_hda',\n 'prefix': '',\n 'description': 'Houdini digital asset for assets'},\n\n 'asset_fx':\n {'id': 3,\n 'name': 'asset_hip',\n 'prefix': '',\n 'description': ''},\n\n 'shot_animation':\n {'id': 4,\n 'name': 'asset_hip',\n 'prefix': '',\n 'description': ''},\n\n 'shot_render':\n {'id': 5,\n 'name': 'asset_hip',\n 'prefix': '',\n 'description': ''},\n\n 'shot_fx':\n {'id': 6,\n 'name': 'asset_hip',\n 'prefix': '',\n 'description': 'Houdini working scene for assets.'}}\n\n def __init__(self, file_type_id, source_id):\n self.id = None\n self.type = file_type_id\n self.source = source_id # Source DB item id (asset, shot etc)\n self.snapshot = None\n self.description = ''\n\n\nclass EveData:\n def __init__(self, SQL_FILE_PATH):\n # Load database\n self.SQL_FILE_PATH = SQL_FILE_PATH\n\n # Data attributes\n # INTERNAL SET\n self.projects = []\n self.project_assets = []\n self.asset_types = []\n self.project_sequences = []\n self.sequence_shots = []\n self.shot_assets = []\n # EXTERNAL SET\n self.selected_project = None\n self.selected_asset = None\n self.selected_sequences = None\n self.selected_shot = None\n self.asset_type_string = None\n\n # Initialize data\n self.init_data()\n\n # UI\n def init_data(self):\n \"\"\"\n Populate data when create a EveData instance\n \"\"\"\n\n self.get_projects()\n self.get_asset_types()\n\n # CRUD\n # Project\n def add_project(self, project):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n # Add project to DB\n cursor.execute(\"INSERT INTO projects VALUES (\"\n \":id,\"\n \":name,\"\n \":houdini_build,\"\n \":width,\"\n \":height,\"\n \":description)\",\n\n {'id': cursor.lastrowid,\n 'name': project.name,\n 'houdini_build': project.houdini_build,\n 'width': project.width,\n 'height': project.height,\n 'description': project.description})\n\n connection.commit()\n project.id = cursor.lastrowid # Add database ID to the project object\n connection.close()\n\n # Add project to data instance\n self.projects.append(project)\n\n def get_project(self, project_id):\n \"\"\" Get project by id \"\"\"\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM projects WHERE id=:id\",\n {'id': project_id})\n project_tuple = cursor.fetchone()\n project_object = convert_to_project([project_tuple])[0]\n\n connection.close()\n\n if project_object:\n return project_object\n\n def get_project_by_name(self, project_name):\n \"\"\" Get project by id \"\"\"\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM projects WHERE name=:name\",\n {'name': project_name})\n project_tuple = cursor.fetchone()\n project_object = convert_to_project([project_tuple])[0]\n\n connection.close()\n\n if project_object:\n return project_object\n\n def get_projects(self):\n \"\"\" Get all project items from projects table in db \"\"\"\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM projects\")\n project_tuples = cursor.fetchall()\n project_objects = convert_to_project(project_tuples)\n\n connection.close()\n\n self.projects.extend(project_objects)\n\n def get_project_assets(self, project):\n \"\"\" Get all project assets from assets table in db \"\"\"\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM assets WHERE project=:project\",\n {'project': project.id})\n\n asset_tuples = cursor.fetchall()\n asset_objects = convert_to_asset(asset_tuples)\n\n connection.close()\n\n # Clear list and append assets\n del self.project_assets[:]\n for asset in asset_objects:\n self.project_assets.append(asset)\n\n def get_project_sequences(self, project):\n \"\"\" Get all project sequences from sequences table in db \"\"\"\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM sequences WHERE project=:project\",\n {'project': project.id})\n\n sequence_tuples = cursor.fetchall()\n sequence_objects = convert_to_sequence(sequence_tuples)\n\n connection.close()\n\n # Clear list and append assets\n del self.project_sequences[:]\n for sequence in sequence_objects:\n self.project_sequences.append(sequence)\n\n def get_sequence_shots(self, sequence_id):\n \"\"\"\n Get all sequence shots from shots table in db\n \"\"\"\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM shots WHERE sequence=:sequence\",\n {'sequence': sequence_id})\n\n shot_tuples = cursor.fetchall()\n shot_objects = convert_to_shot(shot_tuples)\n\n connection.close()\n\n # Clear list and append assets\n del self.sequence_shots[:]\n for shot in shot_objects:\n self.sequence_shots.append(shot)\n\n def update_project(self, project):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"UPDATE projects SET \"\n \"houdini_build=:houdini_build,\"\n \"width=:width,\"\n \"height=:height,\"\n \"description=:description \"\n\n \"WHERE id=:id\",\n\n {'id': project.id,\n 'houdini_build': project.houdini_build,\n 'width': project.width,\n 'height': project.height,\n 'description': project.description})\n\n connection.commit()\n connection.close()\n\n self.selected_project = project\n\n def del_project(self, project_id):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"DELETE FROM projects WHERE id=:id\",\n {'id': project_id})\n\n connection.commit()\n connection.close()\n\n for project in self.projects:\n if project.id == project_id:\n self.projects.remove(project)\n\n # Assets\n def add_asset(self, asset, project_id):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"INSERT INTO assets VALUES (\"\n \":id,\"\n \":name,\"\n \":project,\"\n \":type,\"\n \":description)\",\n\n {'id': cursor.lastrowid,\n 'name': asset.name,\n 'project': project_id,\n 'type': asset.type,\n 'description': asset.description})\n\n connection.commit()\n asset.id = cursor.lastrowid # Add database ID to the asset object\n connection.close()\n\n self.project_assets.append(asset)\n\n def get_asset(self, asset_id):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM assets WHERE id=:id\",\n {'id': asset_id})\n\n asset_tuple = cursor.fetchone()\n\n connection.close()\n\n if asset_tuple:\n return convert_to_asset([asset_tuple])[0]\n\n def get_asset_by_name(self, project_id, asset_name):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM assets WHERE \"\n \"name=:name \"\n \"AND project=:project\",\n\n {'name': asset_name,\n 'project': project_id})\n\n asset_tuple = cursor.fetchone()\n\n connection.close()\n\n if asset_tuple:\n return convert_to_asset([asset_tuple])[0]\n\n def get_asset_types(self):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM asset_types\")\n asset_types_tuples = cursor.fetchall()\n asset_types_objects = convert_to_asset_types(asset_types_tuples)\n\n connection.close()\n\n self.asset_types.extend(asset_types_objects)\n\n def get_asset_type_string(self, asset_type_id):\n \"\"\"\n Get asset type name by asset type id in Asset.asset_types dictionary\n :return:\n \"\"\"\n\n for name, data in Asset.asset_types.iteritems():\n if data['id'] == asset_type_id:\n self.asset_type_string = name\n\n def update_asset(self, asset):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"UPDATE assets SET \"\n \"project=:project,\"\n \"type=:type,\"\n \"description=:description \"\n\n \"WHERE id=:id\",\n\n {'id': asset.id,\n 'project': asset.project,\n 'type': asset.type,\n 'description': asset.description})\n\n connection.commit()\n connection.close()\n\n self.selected_asset = asset\n\n def del_asset(self, asset_id):\n\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n # Delete ASSET\n cursor.execute(\"DELETE FROM assets WHERE id=:id\",\n {'id': asset_id})\n\n # Delete asset LINK\n cursor.execute(\"DELETE FROM shot_assets WHERE asset_id=:asset_id\",\n\n {'asset_id': asset_id})\n\n connection.commit()\n connection.close()\n\n for asset in self.project_assets:\n if asset.id == asset_id:\n self.project_assets.remove(asset)\n\n # Sequence\n def add_sequence(self, sequence, project_id):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"INSERT INTO sequences VALUES (\"\n \":id,\"\n \":name,\"\n \":project,\"\n \":description)\",\n\n {'id': cursor.lastrowid,\n 'name': sequence.name,\n 'project': project_id,\n 'description': sequence.description})\n\n connection.commit()\n sequence.id = cursor.lastrowid # Add database ID to the sequence object\n connection.close()\n\n self.project_sequences.append(sequence)\n\n def get_sequence(self, sequence_id):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM sequences WHERE id=:id\",\n {'id': sequence_id})\n\n sequence_tuple = cursor.fetchone()\n\n connection.close()\n\n if sequence_tuple:\n return convert_to_sequence([sequence_tuple])[0]\n\n def update_sequence(self, sequence):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"UPDATE sequences SET \"\n \"description=:description \"\n\n \"WHERE id=:id\",\n\n {'id': sequence.id,\n 'description': sequence.description})\n\n connection.commit()\n connection.close()\n\n self.selected_sequences = sequence\n\n def del_sequence(self, sequence_id):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"DELETE FROM sequences WHERE id=:id\",\n {'id': sequence_id})\n\n connection.commit()\n connection.close()\n\n for sequence in self.project_sequences:\n if sequence.id == sequence_id:\n self.project_sequences.remove(sequence)\n\n # Shot\n def add_shot(self, shot, sequence_id):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"INSERT INTO shots VALUES (\"\n \":id,\"\n \":name,\"\n \":sequence,\"\n \":start_frame,\"\n \":end_frame,\"\n \":width,\"\n \":height,\"\n \":description)\",\n\n {'id': cursor.lastrowid,\n 'name': shot.name,\n 'sequence': sequence_id,\n 'start_frame': shot.start_frame,\n 'end_frame': shot.end_frame,\n 'width': shot.width,\n 'height': shot.height,\n 'description': shot.description})\n\n connection.commit()\n shot.id = cursor.lastrowid # Add database ID to the shot object\n connection.close()\n\n self.sequence_shots.append(shot)\n\n def get_shot(self, sequence_id):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM shots WHERE id=:id\",\n {'id': sequence_id})\n\n shot_tuple = cursor.fetchone()\n\n connection.close()\n\n if shot_tuple:\n return convert_to_shot([shot_tuple])[0]\n\n def get_shot_assets(self, shot_id):\n\n # Clear shot_assets list\n del self.shot_assets[:]\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM shot_assets WHERE shot_id=:shot_id\",\n {'shot_id': shot_id})\n\n link_tuples = cursor.fetchall()\n\n connection.close()\n\n if link_tuples:\n # Append assets\n for link_tuple in link_tuples:\n self.shot_assets.append(self.get_asset(link_tuple[2]))\n\n def update_shot(self, shot):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"UPDATE shots SET \"\n \"sequence=:sequence,\"\n \"start_frame=:start_frame,\"\n \"end_frame=:end_frame,\"\n \"width=:width,\"\n \"height=:height,\"\n \"description=:description \"\n\n \"WHERE id=:id\",\n\n {'id': shot.id,\n 'sequence': shot.sequence,\n 'start_frame': shot.start_frame,\n 'end_frame': shot.end_frame,\n 'width': shot.width,\n 'height': shot.height,\n 'description': shot.description})\n\n connection.commit()\n connection.close()\n\n self.selected_shot = shot\n\n def del_shot(self, shot_id):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"DELETE FROM shots WHERE id=:id\",\n {'id': shot_id})\n\n connection.commit()\n connection.close()\n\n for shot in self.sequence_shots:\n if shot.id == shot_id:\n self.sequence_shots.remove(shot)\n\n def link_asset(self, asset_id, shot_id):\n \"\"\"\n Link asset to the shot\n \"\"\"\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n # Check if the asset link exists:\n cursor.execute(\"SELECT * FROM shot_assets WHERE asset_id=:asset_id AND shot_id=:shot_id\",\n\n {'asset_id': asset_id, 'shot_id': shot_id})\n\n if cursor.fetchone():\n connection.close()\n return\n\n cursor.execute(\"INSERT INTO shot_assets VALUES (\"\n \":id,\"\n \":shot_id,\"\n \":asset_id)\",\n\n {'id': cursor.lastrowid,\n 'shot_id': shot_id,\n 'asset_id': asset_id})\n\n connection.commit()\n connection.close()\n return True\n\n def unlink_asset(self, asset_id, shot_id):\n\n connection = sqlite3.connect(self.SQL_FILE_PATH)\n cursor = connection.cursor()\n\n cursor.execute(\"DELETE FROM shot_assets WHERE asset_id=:asset_id AND shot_id=:shot_id\",\n\n {'asset_id': asset_id, 'shot_id': shot_id})\n\n connection.commit()\n connection.close()\n\n for asset in self.shot_assets:\n if asset.id == asset_id:\n self.shot_assets.remove(asset)\n","sub_path":"Eve/tools/core/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":27563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"263358030","text":"import requests\nfrom tld import get_fld\n\nfrom ..base import socweb\nfrom project import create_app\nfrom project.api.bizs import SearchEngineBiz\nfrom project.api.bizs import DomainArchivedBiz\nfrom project.api.models import db, WebsiteNews, DomainArchived\n\n\n@socweb.task(queue='discover')\ndef generater_search():\n \"\"\"\n 搜索引擎\n http://192.168.199.220:9700/api/subdomains/query\n :return:\n \"\"\"\n app = create_app()\n app.app_context().push()\n\n search_engine_biz = SearchEngineBiz()\n res = requests.post(search_engine_biz.server + '/api/subdomains/query', json={\"query_all\": True}, timeout=60)\n\n for url in res.json()['data']['subdomains']:\n domain_name = get_fld(url)\n website_new = WebsiteNews(url=url, domain=domain_name)\n website_new.source = ['search_engine']\n\n # 赋予主域名id\n domain = db.session.query(DomainArchived).filter_by(name=domain_name).first()\n if domain:\n website_new.domain_id = domain.id\n\n db.session.add(website_new)\n try:\n db.session.commit()\n except:\n db.session.rollback()\n\n\n@socweb.task(queue='discover')\ndef deal_subs():\n \"\"\"\n 爆破\n :return:\n \"\"\"\n domain_biz = DomainArchivedBiz()\n domains = {\n \"domains\": domain_biz.get_total_domain()\n }\n response = requests.post(url='http://192.168.199.221/api/socweb/subs', json=domains)\n subs = response.json()['data']\n for sub in subs:\n wensite_news = WebsiteNews()\n wensite_news.url = sub\n wensite_news.source = wensite_news.source.append('brute')\n db.session.add(wensite_news)\n db.session.commit()\n\n","sub_path":"project/api/tasks/celery/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"463112790","text":"from cv2 import cv2\nimport tello\nimport time\nimport numpy as np\nimport math\nfrom enum import Enum\n\n\ndef main():\n drone = tello.Tello('', 8889)\n time.sleep(10)\n f = cv2.FileStorage('calibration.xml', cv2.FILE_STORAGE_READ)\n\n cameraMatrix = f.getNode(\"intrinsic\").mat()\n distCoeffs = f.getNode('distortion').mat()\n dictionary = cv2.aruco.Dictionary_get(cv2.aruco.DICT_6X6_250)\n parameters = cv2.aruco.DetectorParameters_create()\n\n intrinsic = cameraMatrix\n distortion = distCoeffs\n\n state = 0\n \n while(True):\n frame = drone.read()\n imageSize = (frame.shape[0], frame.shape[1])\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n markerCorners, markerIds, rejectedCandidates = cv2.aruco.detectMarkers(frame, dictionary, parameters=parameters)\n if len(markerCorners) > 0:\n frame = cv2.aruco.drawDetectedMarkers(frame, markerCorners, markerIds)\n\n rvec, tvec, _objPoints = cv2.aruco.estimatePoseSingleMarkers(markerCorners, 15, intrinsic, distortion)\n #frame = cv2.aruco.drawAxis(frame, intrinsic, distortion, rvec, tvec, 0.1)\n\n #text = 'x = ' + str(tvec[0][0][0]) + 'y = ' + str(tvec[0][0][1]) + 'z = ' + str(tvec[0][0][2])\n\n cv2.putText(frame, str(tvec), (10, 40), cv2.FONT_HERSHEY_PLAIN,1, (0, 255, 255), 1, cv2.LINE_AA)\n cv2.putText(frame, str(rvec), (10, 400), cv2.FONT_HERSHEY_PLAIN,1, (0, 255, 255), 1, cv2.LINE_AA)\n\n key = cv2.waitKey(33)\n \n\n if key != -1:\n drone.keyboard(key)\n cv2.destroyAllWindows()\n else:\n id = markerIds[0][0]\n\n if id == 2:\n drone.flip('f') \n \n ##tvec is (LR, UPDOWN, distance)\n up_down = tvec[0][0][1] - 5\n if up_down > 10:\n drone.move_down(up_down/100)\n elif up_down < -10:\n drone.move_up(-up_down/100)\n\n distance = tvec[0][0][2] - 120\n if distance > 0:\n drone.move_forward(distance/100)\n else:\n drone.move_backward(-distance/100)\n\n left_right = tvec[0][0][0]\n if left_right > 10:\n drone.move_right(left_right/100)\n elif left_right < -10:\n drone.move_left(-left_right/100)\n\n\n\n\n dst, jaco = cv2.Rodrigues(rvec[0][0])\n z_ = np.array([dst[0][2], dst[1][2], dst[2][2]])\n v = np.array([z_[0], 0, z_[2]])\n \n degree = math.atan2(z_[2], z_[0])\n degree = -degree * 180 / math.pi\n cv2.putText(frame, str(degree), (10, 200), cv2.FONT_HERSHEY_PLAIN,1, (0, 255, 255), 1, cv2.LINE_AA)\n\n if degree > 100:\n drone.rotate_cw(10)\n elif degree < 80:\n drone.rotate_ccw(10)\n \n\n cv2.imshow('frame', frame)\n\n key = cv2.waitKey(33)\n if key != -1:\n drone.keyboard(key)\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"lab6.py","file_name":"lab6.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"579908161","text":"\n__author__ = 'ALAN TURNER'\n\"\"\"This program uses Brom's method to calculate the embedment depth and\n moment load for bored piers in cohesive soil\"\"\"\n\nimport math\nimport datetime\n\n\n# INPUT JOB DETAILS\njob_number = \"18027\"\n\n# INPUT LOADS\np = 6.43 # Ultimate Wind Load (kN)\ne = 1.3 # Load eccentricity (m)\nc_u = 70 # Un-drained shear strength (kPa)\nD = 0.45 # Dia. of pier (m)\n\n# INPUT LOAD FACTORS\nD = 0.85 * D # Shape factor - 0.85 for round pier\nc_u = 0.5 * c_u # Uncertainty factor for un-drained shear strength (TABLE 5.1B - AS4678-2002)\np = 1.35 * p # load factor for stability\n\n# BROM'S CALCULATION\nf = p/(9*c_u*D)\ng = math.sqrt((p*(e+1.5*D+0.5*f)/(2.25*D*c_u)))\nL_embed = (1.5*D)+f+g\n\n# CALCULATE DEPTH TO SHEAR CENTRE\nd_shear = (e+1.5*D+0.5*f)\n\n# PRINT RESULTS\ndate = datetime.datetime.now().strftime(\"%d-%m-%y\")\nprint('RESULTS \\nJN: {:s} \\nDate: {:s} \\nMinimum Pier Embedment Depth = {:.2f}m'.format(job_number, date, L_embed))\n\n\n'''\nRESULTS\nJN: 18027\nDate: 20-06-18\nMinimum Pier Embedment Depth = 1.39m\n'''\n\n","sub_path":"Retaining Walls/Software/Broms Method/Broms_Cohesive_Pile.py","file_name":"Broms_Cohesive_Pile.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"332928083","text":"\n\nfrom xai.brain.wordbase.nouns._inheritor import _INHERITOR\n\n#calss header\nclass _INHERITORS(_INHERITOR, ):\n\tdef __init__(self,): \n\t\t_INHERITOR.__init__(self)\n\t\tself.name = \"INHERITORS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"inheritor\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_inheritors.py","file_name":"_inheritors.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"122017246","text":"import numpy as np\nfrom tqdm import *\n\nfrom drl_sample_project_python.do_not_touch.contracts import SingleAgentEnv\nfrom drl_sample_project_python.do_not_touch.result_structures import PolicyAndActionValueFunction\n\n\ndef get_q_learning(env: SingleAgentEnv, alpha: float, epsilon: float, gamma: float, max_iter: int) -> PolicyAndActionValueFunction:\n assert(epsilon > 0)\n\n pi = {}\n b = {}\n q = {}\n\n for it in tqdm(range(max_iter)):\n env.reset()\n\n while not env.is_game_over():\n s = env.state_id()\n available_actions = env.available_actions_ids()\n if s not in pi:\n pi[s] = {}\n q[s] = {}\n b[s] = {}\n for a in available_actions:\n pi[s][a] = 1.0 / len(available_actions)\n q[s][a] = 0.0\n b[s][a] = 1.0 / len(available_actions)\n\n available_actions_count = len(available_actions)\n optimal_a = list(q[s].keys())[np.argmax(list(q[s].values()))]\n for a_key, q_s_a in q[s].items():\n if a_key == optimal_a:\n b[s][a_key] = 1 - epsilon + epsilon / available_actions_count\n else:\n b[s][a_key] = epsilon / available_actions_count\n\n chosen_action = np.random.choice(list(b[s].keys()), 1, False, p=list(b[s].values()))[0]\n old_score = env.score()\n env.act_with_action_id(chosen_action)\n r = env.score() - old_score\n s_p = env.state_id()\n next_available_action = env.available_actions_ids()\n\n if env.is_game_over():\n q[s][chosen_action] += alpha * (r + 0.0 - q[s][chosen_action])\n else:\n if s_p not in pi:\n pi[s_p] = {}\n q[s_p] = {}\n b[s_p] = {}\n for a in next_available_action:\n pi[s_p][a] = 1.0 / len(next_available_action)\n q[s_p][a] = 0.0\n b[s_p][a] = 1.0 / len(next_available_action)\n q[s][chosen_action] += alpha * (r + gamma * np.max(list(q[s_p].values())) - q[s][chosen_action])\n\n for s in q.keys():\n optimal_a_t = list(q[s].keys())[np.argmax(list(q[s].values()))]\n for a_key, q_s_a in q[s].items():\n if a_key == optimal_a_t:\n pi[s][a_key] = 1.0\n else:\n pi[s][a_key] = 0.0\n\n return PolicyAndActionValueFunction(pi=pi, q=q)\n","sub_path":"drl_sample_project_python/algos/q_learning.py","file_name":"q_learning.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"623589036","text":"##############################################\n## Author: I-No Liao ##\n## Date of update: 2018/10/19 ##\n## Description: Leetcode #102 ##\n##############################################\n\n# Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).\n# For example:\n# Given binary tree [3,9,20,null,null,15,7],\n# 3\n# / \\\n# 9 20\n# / \\\n# 15 7\n# return its level order traversal as:\n# [\n# [3],\n# [9,20],\n# [15,7]\n# ]\n\nfrom Tree import TreeNode, BinaryTree\n\n# Recursion\nclass Solution:\n # @param root: TreeNode\n # @return List[List[int]]\n def levelOrder(self, root):\n def helper(root, depth, LUT):\n if not root:\n return None\n if depth in LUT:\n LUT[depth].append(root.val)\n else:\n LUT[depth] = [root.val]\n helper(root.left, depth+1, LUT)\n helper(root.right, depth+1, LUT)\n return None\n \n LUT = {}\n helper(root, 0, LUT)\n ans = [] \n for x in LUT:\n ans.append(LUT[x])\n return ans\n\n# Iteration\nclass Solution_2:\n # @param root: TreeNode\n # @return List[List[int]]\n def levelOrder(self, root):\n if not root:\n return []\n ans = []\n curLevel, nextLevel = [root], []\n while curLevel:\n val = []\n for node in curLevel:\n if node.left:\n nextLevel.append(node.left)\n if node.right:\n nextLevel.append(node.right)\n val.append(node.val)\n curLevel, nextLevel = nextLevel, []\n ans.append(val)\n return ans\n\n# Main\nif __name__ == '__main__':\n nodes = [3, 9, 20, 'null', 'null', 15, 7]\n nodes = [1, 2, 3, 4, 5]\n root = BinaryTree().makeTree(nodes, 0)\n print('----- Answer -----')\n print(BinaryTree().levelOrderTopDown(root))\n\n print('----- Solution 1 -----')\n print(Solution().levelOrder(root))\n print('----- Solution 2 -----')\n print(Solution_2().levelOrder(root))\n","sub_path":"102_LevelOrderTraversal.py","file_name":"102_LevelOrderTraversal.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"573908444","text":"import os\nimport logging\nimport shutil\nimport json\n\nfrom experimentarchiver import Version\nfrom experimentarchiver import version as current_version\nimport experimentarchiver.state as experimentstate\nimport os_utils\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Experiment:\n \n def __init__(self, archive_path, experiment_name):\n experiment_path = os.path.join(archive_path, experiment_name)\n self._paths = {'archive-path': archive_path,\n 'experiment-path': experiment_path,\n 'parameter-path': os.path.join(experiment_path, 'parameters/'),\n 'output-path': os.path.join(experiment_path, 'outputs/'),\n 'parameter-list': os.path.join(experiment_path, 'parameters/parameter-list'),\n 'commit-hash': os.path.join(experiment_path, 'commit-hash'),\n 'last-command': os.path.join(experiment_path, 'last-command'),\n 'input-files': os.path.join(experiment_path, 'input-files'),\n 'description': os.path.join(experiment_path, 'description'),\n 'version': os.path.join(experiment_path, 'version')}\n\n def path(self, key):\n return self._paths[key]\n\n def _check_version(self):\n logger.debug('Reading version number from file %s', self.path('version'))\n if os.path.isfile(self.path('version')):\n try:\n stored_version = Version(*experimentstate.read_json(self.path('version')))\n except (ValueError, TypeError):\n logger.warning('The version file is corrupted. Cannot parse the version number.')\n return\n if current_version == stored_version:\n logger.info('The current program version %s matches the version used to record the experiment.',\n str(current_version))\n else:\n if current_version > stored_version:\n comp = 'NEWER'\n else:\n comp = 'OLDER'\n logger.warning('The current program version %s is %s'\n ' than the version %s used to record the experiment.',\n str(current_version), comp, str(stored_version))\n else:\n logger.warning('There is no version file for this experiment. '\n 'This experiment seems to be very old.')\n\n def read_from_archive(self):\n state = experimentstate.ExperimentState()\n logger.info('Reading from archive.')\n self._check_version()\n logger.debug('Experiment directory is %s', self.path('experiment-path'))\n state.commitHash = experimentstate.read_json(self.path('commit-hash'))\n state.pathsToParameters = experimentstate.read_json(self.path('parameter-list'))\n state.inputData = experimentstate.read_json(self.path('input-files'))\n state.command = experimentstate.read_json(self.path('last-command'))\n state.environment = None # not yet implemented\n with open(self.path('description'), 'r') as f:\n state.description = f.readline().strip('\\n')\n logger.info('Experiment description: %s ...', state.description)\n state.pathsToOutputData = [] # nothing to do\n return state\n\n def write_to_archive(self, project, state):\n logger.info('Writing experiment to archive.')\n os_utils.make_all_directories(self.path('experiment-path'))\n logger.debug('Experiment directory is %s', self.path('experiment-path'))\n if not current_version.is_release():\n logger.warning('This version of the archiving program is not a release and potentially unstable. '\n 'Consider using a stable version instead.')\n experimentstate.write_json(current_version.get_version_tuple(), self.path('version'))\n experimentstate.write_json(state.commitHash, self.path('commit-hash'))\n os_utils.make_directory_if_nonexistent(self.path('parameter-path'))\n experimentstate.write_json(state.pathsToParameters, self.path('parameter-list'))\n os_utils.copy_files(project.path('top-path'),\n self.path('parameter-path'),\n state.pathsToParameters,\n create_directories=True)\n experimentstate.write_json(state.inputData, self.path('input-files'))\n experimentstate.write_json(state.command, self.path('last-command'))\n # environment not yet implemented\n with open(self.path('description'), 'w') as f:\n f.write(state.description)\n if project.option('do-record-outputs'):\n logger.info('Copying outputs to archive.')\n os_utils.make_directory_if_nonexistent(self.path('output-path'))\n os_utils.copy_changed_files(project.path('output-data-path'), self.path('output-path'), state.pathsToOutputData)\n\n def archive_project(self, project, description=None):\n state = project.read_from_project()\n if description is not None:\n state.description = description\n if state.command['status'] != 0:\n raise Exception('Archiving failed runs is not allowed.')\n try:\n self.write_to_archive(project, state)\n except Exception:\n logger.warning('Cleaning up failed archiving attempt.')\n logger.debug('Removing directory %s', self.path('experiment-path'))\n shutil.rmtree(self.path('experiment-path'), ignore_errors=True)\n raise\n","sub_path":"experimentarchiver/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":5596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"327299382","text":"\n#!/usr/bin/env python\n\nimport gi\ngi.require_version(\"Gst\", \"1.0\")\nfrom gi.repository import Gst, GObject, Gtk\n\nclass GTK_Main:\n \n def __init__(self):\n window = Gtk.Window(Gtk.WindowType.TOPLEVEL)\n window.set_title(\"Videotestsrc-Player\")\n window.set_default_size(300, -1)\n window.connect(\"destroy\", Gtk.main_quit, \"WM destroy\")\n vbox = Gtk.VBox()\n window.add(vbox)\n #button start/stop\n self.button = Gtk.Button(\"Start\")\n self.button.connect(\"clicked\", self.start_stop)\n vbox.add(self.button)\n\n #button dynamic change\n self.buttonDyn = Gtk.Button(\"change\")\n self.buttonDyn.connect(\"clicked\", self.dyn)\n self.pattern = 0\n vbox.add(self.buttonDyn)\n window.show_all()\n self.player = Gst.Pipeline.new(\"player\")\n source = Gst.ElementFactory.make(\"videotestsrc\", \"video-source\")\n clock = Gst.ElementFactory.make(\"clockoverlay\", \"clock-effect\")\n sink = Gst.ElementFactory.make(\"xvimagesink\", \"video-output\")\n caps = Gst.Caps.from_string(\"video/x-raw, width=320, height=230\")\n filter = Gst.ElementFactory.make(\"capsfilter\", \"filter\")\n filter.set_property(\"caps\", caps)\n self.player.add(source)\n self.player.add(filter)\n self.player.add(clock)\n self.player.add(sink)\n source.link(filter)\n filter.link(clock)\n clock.link(sink)\n\n def start_stop(self, w):\n if self.button.get_label() == \"Start\":\n self.button.set_label(\"Stop\")\n self.player.set_state(Gst.State.PLAYING)\n else:\n self.player.set_state(Gst.State.NULL)\n self.button.set_label(\"Start\")\n #self.player.get_by_name(\"video-source\").set_property(\"pattern\", 1)\n\n def dyn(self, w):\n self.pattern+=1\n self.player.get_by_name(\"video-source\").set_property(\"pattern\", self.pattern)\n print(self.pattern)\n if (self.pattern==24):\n self.pattern=-1\n\n\nGObject.threads_init()\nGst.init(None) \nGTK_Main()\nGtk.main()\n","sub_path":"server/gstreamer/python/pygst-examples/capabilities-example2.py","file_name":"capabilities-example2.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"6718490","text":"# --- https://www.tensorflow.org/api_docs/python/tf/placeholder\n\nimport tensorflow as tf\n\n# --- Addition and multiplication with constants.\na = tf.constant(5)\nb = tf.constant(6)\n\nsess1 = tf.Session()\nprint(\"Addition with constants : %i\" % sess1.run(a + b))\nprint(\"Multiplication with constants : %i\" % sess1.run(a * b))\n\n# --- Addition and multiplication with placeholders.\na = tf.placeholder(tf.int16)\nb = tf.placeholder(tf.int16)\n\nadd = tf.add(a, b)\nmul = tf.multiply(a, b)\n\nsess2 = tf.Session()\nprint(\"Addition with variables : %i\" % sess2.run(add, feed_dict={a: 5, b: 6}))\nprint(\"Multiplication with variables : %i\" % sess2.run(mul, feed_dict={a: 5, b: 6}))\n\n# --- Matrix-matrix multiplication.\nmatrix1 = tf.constant([[3., 3.]])\nmatrix2 = tf.constant([[2.],[2.]])\nproduct = tf.matmul(matrix1, matrix2)\n\nsess3 = tf.Session()\nprint(sess3.run(product))\n\n","sub_path":"tensorflow/example_2.py","file_name":"example_2.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"319084254","text":"# Tools to help the user engage with our package\n# :)\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport graddog as gd\nfrom graddog.functions import sin, cos, tan, exp, log\n\n \ndef plot_derivative(function, xmin, xmax, n_pts=100, figsize=(6,6), xlabel='x', ylabel='y', plotTitle='Derivative', verbose = False):\n '''\n Plot the derivative of a function between xmin and xmax, using n_pts linearly spaced points to evaluate it.\n \n Inputs:\n function[function]: the function of which you'd like to plot the derivative (must only take single input)\n xmin: lower bound on which to calculate derivative\n xmax: upper bound on which to calculate derivative\n n_pts [int](Default: 100): how many points to use when evaluating derivative (more = better resolution but slower)\n figsize [tuple](Default: (6,6)): figsize in inches (see matplotlib documentation)\n xlabel [string](Default: 'x'): Label for x axis of plot\n ylabel [string](Default: 'y'): Label for y axis of plot\n plotTitle [string](Default: 'Derivative'): Label for title of plot\n \n '''\n xs = np.linspace(xmin, xmax, num=n_pts)\n # derivative comes as a matrix since we are passing in a vectorized input to a single-variable function\n # the only entries in the derivative matrix are therefore the diagonals, since it is a single-variable function\n f_ = gd.trace(function, xs, verbose = verbose)\n y_ders = [f_[i,i] for i in range(n_pts)]\n\n \n plt.figure(figsize=figsize)\n plt.plot(xs, y_ders, color = 'red', label = 'f\\'(x)')\n plt.title(plotTitle)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.xlim(xmin, xmax)\n plt.legend()\n plt.show()\n\n return xs, y_ders\n\n\ndef find_extrema_firstorder(function, xmin, xmax, n_pts=100, tolerance = 1e-10, verbose = False):\n '''\n Locate the point where the derivative is closest to zero on the given interval.\n \n Inputs:\n function[function]: the function of which you'd like to plot the derivative. (one scalar input)\n xmin: lower bound on which to calculate derivative\n xmax: upper bound on which to calculate derivative\n n_pts [int](Default: 100): how many points to use when evaluating derivative (more = better resolution but slower)\n tolerance [float](Default: 1e-10): how close to zero should a value be before it's considered an extrema?\n \n Outputs:\n If it can locate your extrema exactly, it will return only the x value(s) of the extrema.\n If not it will return:\n xs: a tuple containing the two x values between which the extrema is located\n '''\n xs = np.linspace(xmin, xmax, num=n_pts) \n # derivative comes as a matrix since we are passing in a vectorized input to a single-variable function\n # the only entries in the derivative matrix are therefore the diagonals, since it is a single-variable function\n f_ = gd.trace(function, xs, verbose = verbose)\n y_ders = np.array([f_[i,i] for i in range(n_pts)])\n\n zeroidx = np.where(np.abs(y_ders) < tolerance)[0].astype(int)\n if len(zeroidx) != 0:\n return xs[zeroidx]\n else:\n decreasingIDX = np.where(y_ders < tolerance)[0].astype(int)\n increasingIDX = np.where(y_ders > tolerance)[0].astype(int)\n\n if len(decreasingIDX) == 0 or len(increasingIDX) == 0:\n print(f'No extrema located in the interval {xmin} to {xmax}.')\n return None\n\n if decreasingIDX[-1] == increasingIDX[0]-1: # Function goes from decreasing -> increasing\n print(f'Extrema located between x={xs[decreasingIDX[-1]]} and {xs[increasingIDX[0]]}')\n return (xs[decreasingIDX[-1]],xs[increasingIDX[0]])\n elif increasingIDX[-1] == decreasingIDX[0]-1: #Function goes from inc -> dec\n print(f'Extrema located between x={xs[increasingIDX[-1]]} and {xs[decreasingIDX[0]]}')\n return (xs[increasingIDX[-1]],xs[decreasingIDX[0]])\n\ndef find_increasing(function, xmin, xmax, n_pts=100, verbose = False):\n '''\n Locate the region in a given interval where function is increasing.\n \n Inputs:\n function[function]: the function that you want to locate increasing regions on (one scalar input)\n xmin: lower bound of interval\n xmax: upper bound of interval\n n_pts (default = 100): how many points to use when evaluating derivative (more = better resolution but slower)\n \n Outputs:\n xs: the x values where the function is increasing\n ys: the y values where the function is increasing\n '''\n xs = np.linspace(xmin, xmax, num=n_pts)\n # derivative comes as a matrix since we are passing in a vectorized input to a single-variable function\n # the only entries in the derivative matrix are therefore the diagonals, since it is a single-variable function\n f_ = gd.trace(function, xs, verbose = verbose)\n y_ders = np.array([f_[i,i] for i in range(n_pts)])\n\n idx = np.where(y_ders > 0)[0].astype(int)\n if len(idx) == 0:\n print(f'No increasing values located in the interval {xmin} to {xmax}')\n return None\n return xs[idx], y_ders[idx]\n\n\n# xdec, ydec = find_decreasing(quadratic, -10, 10)\n\ndef find_decreasing(function, xmin, xmax, n_pts=100, verbose = False):\n '''\n Locate the region in a given interval where function is decreasing.\n \n Inputs:\n function[function]: the function that you want to locate decreasing regions on (one scalar input)\n xmin: lower bound of interval\n xmax: upper bound of interval\n n_pts (default = 100): how many points to use when evaluating derivative (more = better resolution but slower)\n \n Outputs:\n xs: the x values where the function is decreasing\n ys: the y values where the function is decreasing\n '''\n xs = np.linspace(xmin, xmax, num=n_pts)\n # derivative comes as a matrix since we are passing in a vectorized input to a single-variable function\n # the only entries in the derivative matrix are therefore the diagonals, since it is a single-variable function\n f_ = gd.trace(function, xs, verbose = verbose)\n y_ders = np.array([f_[i,i] for i in range(n_pts)])\n\n idx = np.where(y_ders < 0)[0].astype(int)\n if len(idx) == 0:\n print(f'No decreasing values located in the interval {xmin} to {xmax}')\n return None\n return xs[idx], y_ders[idx]\n\n# xs, functionvalues = plot_with_tangent_line(quadratic, 5, -10, 10)\n\ndef plot_with_tangent_line(function, xtangent, xmin, xmax, n_pts=100, figsize=(6,6), xlabel='x', ylabel='y', plotTitle='Function with tangent line', verbose = False):\n '''\n Plot the a function between xmin and xmax, with a tangent line at xtangent, using n_pts linearly spaced points to evaluate it.\n \n Inputs:\n function[function]: the function you'd like to plot.\n xtangent: value at which you want the tangent line to intersect the function\n xmin: lower bound on which to calculate derivative\n xmax: upper bound on which to calculate derivative\n n_pts [int](Default: 100): how many points to use when plotting function (more = better resolution but slower)\n figsize [tuple](Default: (6,6)): figsize in inches (see matplotlib documentation)\n xlabel [string](Default: 'x'): Label for x axis of plot\n ylabel [string](Default: 'y'): Label for y axis of plot\n plotTitle [string](Default: 'Derivative'): Label for title of plot\n \n Outputs: \n xs: the array of linearly spaced x values between xmin and xmax\n ys: the derivative evaluated at the values in xs\n '''\n deriv = gd.trace(function,xtangent, verbose = verbose)\n xs = np.linspace(xmin, xmax, num=n_pts)\n values = function(xs)\n ytangent = function(xtangent)\n plt.figure(figsize=figsize)\n derivativevalue = deriv[0,0]\n print(f'At the point x={xtangent}, the function has a slope of {derivativevalue}')\n plt.plot(xs, values)\n plt.plot(xs, derivativevalue*(xs-xtangent) + ytangent)\n plt.title(plotTitle)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.xlim(xmin, xmax)\n plt.show()\n return xs, values\n","sub_path":"graddog/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":7983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"339596770","text":"\nimport sys\nimport time\n\n\n\ndef torre(n, * , side = \"C\", rows = 1) :\n\t\n\tif side == \"C\" :\n\t\tsepar = 29\n\telif side == \"L\" :\t\n\t\tsepar = n*2-1\n\t\t\n\t''' esto es solo un adorno en la cima '''\n\tprint(\" \"*(separ-1)+\"|\")\n\tprint(\" \"*(separ-3)+\"-----\")\n\tprint(\" \"*(separ-1)+\"|\")\n\t''' ------------------ '''\n\t\n\treturn \"\\n\".join([\" \"*(separ-(i+1+i)\n\t) + \".\"*(i+1+i*3) for i in range(n) for j in range(rows)])\n\t\n\t\nprint(torre(10, rows = 1, side = \"C\"))\n\t\n\t\t\t\n\t\n\ndef crespas(n) :\n\t\n\treturn \"\\n\".join( [\n\t(\" \"*(6-i+1) + \"*\"*(i+1+i) + \" \"*(n-i+1))*n for i in range(5)\n\t] )\n\t\n\t\n\n\n\n\n\n\n\nprint()\n\n\ndef crespas(n, *, rows = 6 ) :\n\t\n\tif n <= 0 :\n\t\treturn \"\"\n\t\n\te = \" \"\n\tx = rows-1\n\t\n\treturn \"\\n\".join(\n\t [\n\t f\"{e:>{x}}*{e:>{x}}\"*n if i == 0 \\\n\t else f\"{e*(x-(i))}*{e*(1+(i+i-2))}*{e*(x-(i))}\"*n for i in range(rows)\n\t\n\t ]\n\t \t) \t\n\n\n\n\n\n\n\n\n\n\ndef crespas(n) :\n\t\n\t\n\trows = 6\n\tsep = (rows-1)*2\n\t\n\tlista = [\" \"]\n\tlista.extend([\" \"]* sep * n )\n\t\n\tlistaR = [ ]\n\t\n\tfor i in range(rows) :\n\t\tprint(lista, lista.__len__())\n\t\tinput()\n\t\t\n\t\tlista = [ \" \" if x == \"*\" else x for x in lista ]\n\t\n\t\t\n\t\tfor j in range(n) :\n\t\t\t\n\t\t\t__import__(\"os\").system(\"clear\")\n\t\t\n\t\t\t\n\t\t\tpos = (sep//2)*(2*j+1)\n\t\t\tlista[pos-i] = \"*\"\n\t\t\tlista[pos+i] = \"*\"\n\t\t\t\n\t\t\tprint(lista, pos, i)\n\t\t\tinput() \n\t\t\t\n\t\tprint(\"Salio\")\n\t\tprint(\"\".join(lista))\n\t\tlistaR.append(\"[\" + \"\".join(lista) + \"]\")\n\t\t\n\t\n\treturn listaR","sub_path":"works_Telegram/crespas.py","file_name":"crespas.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"109622909","text":"for j in range(int(input())):\r\n ans = False\r\n digits = [None] * 10\r\n for i in range(10):\r\n digits[i] = 0\r\n n = input()\r\n print('Case #' + str(j+1)+':', end=' ')\r\n if int(n) == 0:\r\n print('INSOMNIA')\r\n continue\r\n i = 1\r\n while(ans == False):\r\n num = str(i * int(n))\r\n for c in num:\r\n x = int(c)\r\n if digits[x] == 0:\r\n digits[x] = 1\r\n for k in range(10):\r\n if digits[k] == 1:\r\n ans = True\r\n else:\r\n ans = False\r\n break\r\n i += 1\r\n if ans == True:\r\n print(num)\r\n else:\r\n print('INSOMNIA')\r\n","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_Thrashans_codejam!.py","file_name":"16_0_1_Thrashans_codejam!.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"134869931","text":"\"\"\"\nAsk the user to enter a 3 digit number till he enters 0\nPrint the square root of only 3 digit positive numbers.\n\"\"\"\ndef get_number():\n \"\"\"\n this function is to get a positive input number\n \"\"\"\n num=int(input('Enter the number:'))\n while num<0:\n print('Please enter a positive number')\n num=int(input('Enter the number again:'))\n return num\n\ndef num_of_dgt(number):\n \"\"\"\n this function is to find the no. of digits\n \"\"\"\n count=0\n while number>0:\n number=number//10\n count+=1\n return count\n\ndef print_sqrt_of_number(number):\n \"\"\"\n this fn prints the sqrt of the num\n \"\"\"\n print('square root is',number**0.5)\n\ndef sqrt_of_3digit_num():\n \"\"\"\n this function is to check the input is 3 dgt or not and\n it gets the input till user enters 0\n \"\"\"\n number=get_number()\n while number!=0:\n digit_num=num_of_dgt(number)\n if digit_num!=3:\n print('input a 3 digit number')\n number=get_number()\n else:\n print_sqrt_of_number(number)\n number=get_number()\n else:\n print('End')\n \n#main starts from here\nsqrt_of_3digit_num()\n","sub_path":"Question_13_sqrt_3_digit.py","file_name":"Question_13_sqrt_3_digit.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"408303532","text":"## Author(s): Daniel Yan\n## Date: 2018-11-11\n## Email: daniel.yan@vanderbilt.edu\n\n## Description: Implements Dijkstra's shortest path to find the shortest path\n## from each location to any other location.\n\n## Constants\nINFINITY = 999999 # Placeholder to initialize distances to \"infinity\"\n\n# Import libraries\nfrom . import data_loader as dl\n\nclass shortest_path:\n def __init__(self):\n pass\n\n def shortest_path_getter(self, graph, start):\n \"\"\"\n Run Dijkstra's algorithm to find the shortest paths from the given location\n to all other locations.\n :param graph: Graph containing the locations to run the shortest paths.\n Should contain a list of all location nodes.\n :param start: Start location to get paths from.\n :return: Dictionary containing each location mapped to a list of\n locations representing the shortest path from the start location to that\n location. A location mapped to an empty list means that there is no path\n from the start location to the end location. Return false if the start\n location is not in the graph.\n \"\"\"\n # Create initial set of unvisited nodes.\n unvisited = set(location for location in graph)\n\n # Return false if the start location is not in the graph.\n if start not in unvisited:\n return False\n\n # Create a dictionary to map each location to its estimated distance,\n # with the initial distance set to infinity except for the start\n # location, which has its distance set to 0.\n distances = {location: INFINITY for location in graph}\n distances[start] = 0\n\n # Create a dictionary to map each location to the shortest path. Paths\n # are initially empty except for the start node, which is mapped to\n # itself. Each path is a list of locations with the start location as the\n # first element and the end location as the last element.\n paths = {location: [] for location in graph}\n paths[start] = [start]\n\n # Set minimum path length in the unvisited set to be 0 initially to\n # represent the start node.\n min_len = 0\n min_node = start\n\n # Keep finding shortest path unless the minimum in the unvisited set is\n # infinity, in which case the remaining locations are not reachable.\n while (min_len < INFINITY):\n # Mark the minimum node as visited\n unvisited.remove(min_node)\n # Get path to minimum node.\n min_node_path = paths[min_node]\n # Get all the neighbors of minimum node and see if they are visited.\n # If they are unvisited, check if the path through the minimum node\n # has a smaller length than the current path length for that node. If\n # so, update with the path through the minimum node.\n for location in min_node.adjList:\n old_length = distances[location]\n new_length = min_len + location.length\n if location in unvisited and new_length < old_length:\n distances[location] = new_length\n # Copy old path and append the current location\n new_path = min_node_path.copy()\n new_path.append(location)\n # Set minimum path to the new path\n paths[location] = new_path\n\n # Get the new minimum length and node for next iteration of algorithm\n min_len = INFINITY\n for location in unvisited:\n if distances[location] < min_len:\n min_len = distances[location]\n min_node = location\n\n # Return map of paths\n return paths\n\n\n def get_path_from_rooms(self, start_room, end_room):\n \"\"\"\n Given two strings representing a room, use the dictionary mapping the\n rooms to hallways to find a start and end location, and use the\n stevenson_paths dictionary to find and return the shortest path, which is\n a list of locations to traverse.\n :param start_room: String representing room to start from.\n :param end_room: String representing room to end at.\n :return: List of locations representing a path from the start room to the\n end room. If either of the rooms do not exist in Stevenson, return False.\n \"\"\"\n\n # Dictionary containing mapping each location in Stevenson to shortest path\n # map for each location.\n stevenson_paths = dict()\n data_load_object = dl.data_loader()\n for location in data_load_object.graph:\n stevenson_paths[location] = self.shortest_path_getter(graph=data_load_object.graph, start=location)\n\n # Get the corresponding locations for the start and end room\n start_loc = data_load_object.rooms_map.get(start_room)\n end_loc = data_load_object.rooms_map.get(end_room)\n # Return false if either of the rooms does not exist.\n if start_loc is None or end_loc is None:\n return False\n # Get dictionary with all shortest paths for the start location.\n all_paths = stevenson_paths.get(start_loc)\n # Return the shortest path to the end location from the dictionary of all\n # shortest paths. Return false if there is not a corresponding location.\n path = all_paths.get(end_loc)\n if path is None:\n return False\n else:\n return path\n","sub_path":"backend/backendServer/routeFinder/src/shortest_path.py","file_name":"shortest_path.py","file_ext":"py","file_size_in_byte":5510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"459088465","text":"from openpyxl import load_workbook\nfrom openpyxl import Workbook\nimport os\nimport csv\nimport matplotlib.pyplot as plt\n\n\nimport numpy as np\nfrom scipy import optimize as sci\nfrom scipy import stats as stat\n\n\nimport re\n\nclass WhiteLight_Data_Reader():\n\n def natural_key(self,string_):\n return [int(s) if s.isdigit() else s for s in re.split(r'(\\d+)', string_)]\n\n\n def single_file(self,directory,output_filename):\n\n output_directory = '../Results/'\n collected = Workbook()\n results_file = os.path.join(output_directory, output_filename + '.npy')\n\n if not os.path.exists(output_directory):\n os.mkdir(output_directory)\n\n files = [f for f in os.listdir(directory) if '.csv' in f]\n files = sorted(files, key=self.natural_key)\n\n refletance_array = list()\n for file in files:\n print(file)\n reflectance = np.genfromtxt(os.path.join(directory,file),delimiter=',')\n refletance_array.append(reflectance)\n np.save(results_file, np.asarray(refletance_array))\n\n\n # output_filename = os.path.join(output_directory,'Sorted.csv')\n # print(files)\n # with open(output_filename,'w') as output_file:\n # writer = csv.writer(output_file)\n # for file in files:\n # with open(os.path.join(directory, file)) as input_file:\n # reader = csv.reader(input_file,delimiter=',')\n # for row in reader:\n # time = file.split('.')[0]\n # row.insert(0, time)\n # writer.writerow(row)\n\ndef chunker(seq, size):\n return (seq[pos:pos + size] for pos in range(0, len(seq), size))\n\ndef grating_fit(wavelength, scaling_factor,fano_parameter,resonance_linewidth,resonance_wavelength,vertical_shift):\n numerator = np.square(fano_parameter*resonance_linewidth+ wavelength- resonance_wavelength)\n demonimator = np.square(resonance_linewidth) + np.square(wavelength-resonance_wavelength)\n quotient = numerator/demonimator\n result = scaling_factor * quotient + vertical_shift\n return result\n\n\nif __name__ == '__main__':\n sorted_file = '/Users/st659/Documents/SiN Grating Local/MannoseConA_270317/Output/Sorted.csv'\n\n\n fit_initial = [float(6), 10, 4, 852, 0.63235924622541]\n spectrum = np.linspace(498.6174,1103.161,3648)\n\n fig = plt.figure()\n ax3 = fig.add_subplot(111)\n with open(sorted_file, 'r') as input_file:\n reader = csv.reader(input_file, delimiter=',')\n\n wavelength = list()\n time = list()\n time_peak = list()\n peaks = list()\n for row in reader:\n data = row[1:]\n\n peak = detect_peaks.detect_peaks(data, mph=5.7, mpd = 1000)\n if peak and peak >2000:\n peaks.append(peak[0])\n time_peak.append(row[0])\n peak_data = data[2110:2300]\n x = spectrum[2110:2300]\n\n peak_data = [float(data) for data in peak_data]\n\n try:\n a = sci.curve_fit(grating_fit,x, peak_data, p0 =fit_initial)\n ax3.plot(peak_data)\n print(row[0])\n time.append(row[0])\n wavelength.append(a[0][3])\n except RuntimeError:\n print(\"Fit Failed\")\n\n\n #if int(row[0]) > 100 and int(row[0])< 104 :\n #ax3.plot(peak_data)\n #if int(row[0]) > 2100 and int(row[0])< 2110:\n #ax3.plot(peak_data)\n\n #if int(row[0]) > 2200:\n #break\n\n plt.style.use(['seaborn-white', 'seaborn-notebook'])\n wavelength_mean = list()\n wavelength_std = list()\n time_mean = list()\n for values, times in zip(chunker(wavelength, 50), chunker(time, 50)):\n wavelength_mean.append(np.mean(values, axis=0))\n wavelength_std.append(stat.sem(values, axis=0))\n time_mean.append(float(times[0])/60)\n\n figure = plt.figure()\n ax = figure.add_subplot(111)\n\n ax.set_xlabel('Time (min)')\n ax.set_ylabel('Peak Wavelength (nm)')\n\n print(len(time_mean))\n print(wavelength_mean)\n print(wavelength_std)\n ax.set_ylim(851.0,852.4)\n ax.errorbar(time_mean, wavelength_mean, wavelength_std, fmt='o')\n ax.errorbar((4410.0/60, 4410.0/60), (851.0, 852.4),(0,0), fmt='--', color='k')\n ax.text(4490.0/60, 851.63, 'AMP +')\n ax.text(4490.0/60, 851.57, 'Sulfo SMCC')\n ax.errorbar((7800.0/60, 7800.0/60), (851.0, 852.4),(0,0), fmt='--', color='k')\n ax.text(7890.0/60, 851.8, 'ConA')\n ax.errorbar((11000.0/60, 11000.0/60), (851.0, 852.4),(0,0), fmt='--', color='k')\n ax.text(11090.0/60, 851.8, 'D-Mannose')\n\n plt.show()","sub_path":"src/GratingDataCollector.py","file_name":"GratingDataCollector.py","file_ext":"py","file_size_in_byte":4689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"323679005","text":"import random\nlist = []\nfor i in range(0,200):\n list.append((i,''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'], 5))))\nfor j,k in list:\n print(j,k)\nimport pymysql\n\n# 打开数据库连接\ndb = pymysql.connect('127.0.0.1', 'root', '123456', \"test\")\n\n# 使用 cursor() 方法创建一个游标对象 cursor\ncursor = db.cursor()\n# 使用 execute() 方法执行 SQL 查询\ntry:\n # 执行sql语句\n cursor.executemany(\"insert into shopcard(id,card) values(%s,%s)\",list)\n # 提交到数据库执行\n db.commit()\n\nexcept:\n # 如果发生错误则回滚\n db.rollback()\n print(\"发生错误\")\n# 使用 fetchone() 方法获取单条数据.\n\n# 关闭数据库连接\ndb.close()","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"645638582","text":"import tornado.web\nfrom app.domain.task import Task\nfrom app.service import token_service\nfrom app.database import task_db\nfrom app.utils import mytime\nimport json\n\n\nclass TaskApiA(tornado.web.RequestHandler):\n\n async def post(self, *args, **kwargs):\n token = token_service.get_token(self.request)\n if not token.is_valid:\n self.send_error(403)\n return\n\n task = Task()\n task.__dict__ = json.loads(str(self.request.body, encoding='utf-8'))\n task.description = ''\n task.startDate = mytime.now()\n task.endDate = mytime.now()\n\n user_login = token.username\n if user_login != task.userLogin:\n self.send_error(403)\n return\n\n await task_db.create_task(task)\n self.set_status(201)\n self.finish()\n\n async def put(self, *args, **kwargs):\n token = token_service.get_token(self.request)\n if not token.is_valid:\n self.send_error(403)\n return\n\n user_login = token.username\n # updateTask只能由umu微服务中的异步任务OnBoardingServie调用,不能由前端用户调用\n if user_login != 'internal':\n self.send_error(403)\n return\n\n task = Task()\n task.__dict__ = json.loads(str(self.request.body, encoding='utf-8'))\n task.endDate = mytime.now()\n\n await task_db.update_task(task)\n self.set_status(201)\n self.finish()\n\n async def get(self, *args, **kwargs):\n uuid = self.get_argument('uuid', None)\n userLogin = self.get_argument('userLogin', None)\n taskStatus = self.get_argument('taskStatus', None)\n\n pageable = {\n 'page': self.get_argument('page', None),\n 'size': self.get_argument('size', None),\n 'sort': self.get_arguments('sort'),\n }\n\n where = ''\n if uuid is not None:\n where += 'and uuid = \"{}\" '.format(uuid)\n if userLogin is not None:\n where += 'and user_login = \"{}\" '.format(userLogin)\n if taskStatus is not None:\n where += 'and task_status = \"{}\" '.format(taskStatus)\n where = where[4:]\n\n if where != '':\n where = 'WHERE ' + where\n total_count, result = await task_db.get_tasks(where, pageable)\n self.set_header('X-Total-Count', total_count)\n\n self.write(json.dumps(result))\n\n\nclass TaskApiB(tornado.web.RequestHandler):\n\n async def get(self, id, *args, **kwargs):\n result = await task_db.get_task(id)\n self.write(result)\n\n async def delete(self, id, *args, **kwargs):\n token = token_service.get_token(self.request)\n if not token.is_valid:\n self.send_error(403)\n return\n\n has_role = token.has_role('ROLE_ADMIN')\n if not has_role:\n self.send_error(403)\n return\n\n await task_db.delete_task(id)\n self.set_status(200)\n self.finish()\n","sub_path":"umm-python/app/web/rest/task_api.py","file_name":"task_api.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"264193360","text":"from random import randint, choice\nfrom PIL import Image, ImageDraw, ImageFont\n\n\ndef get_value():\n operations = ['+', '-', '/', '*']\n cur_oper = choice(operations)\n a = randint(-999, 1000)\n b = randint(-999, 1000)\n if cur_oper == '+':\n result = a + b\n elif cur_oper == '-':\n result = a - b\n elif cur_oper == '/':\n if b == 0:\n b = 1\n result = round(a/b, 3) #округление до 3 знака тк при крайних значениях 1/999 = 0.001\n else:\n result = a * b\n a = get_word(a)\n b = get_word(b)\n text_field = str('{} {} {}').format(a, cur_oper, b)\n return text_field, result\n\n\ndef get_word(value):\n znak = ''\n value = str(value)\n if value[0] == '-':\n znak = 'минус'\n value = value[1:]\n\n dict1 = {1: \"один\", 2: \"два\", 3: \"три\", 4: \"четыре\", 5: \"пять\", 6: \"шесть\", 7: \"семь\", 8: \"восемь\", 9: \"девять\",\n 0: \"ноль\"}\n dict10 = {0: \"десять\", 1: \"одиннадцать\", 2: \"двенадцать\", 3: \"тринадцать\", 4: \"четырнадцать\", 5: \"пятнадцать\",\n 6: \"шестнадцать\", 7: \"семнадцать\", 8: \"восемнадцать\", 9: \"девятнадцать\"}\n dict100 = {2: \"двадцать\", 3: \"тридцать\", 4: \"сорок\", 5: \"пятьдесят\", 6: \"шестьдесят\", 7: \"семьдесят\",\n 8: \"восемьдесят\", 9: \"девяносто\"}\n dict1000 = {1: \"сто\", 2: \"двести\", 3: \"триста\", 4: \"че��ыреста\", 5: \"пятьсот\", 6: \"шестьсот\", 7: \"семьсот\",\n 8: \"восемьсот\", 9: \"девятьсот\"}\n word = znak\n value = int(value)\n if (value//100) > 0:\n word = word + ' ' + dict1000[value//100]\n value = value % 100\n if (value//10) > 1:\n word = word + ' ' + dict100[value//10]\n value = value % 10\n if (value // 10) == 1:\n word = word + ' ' + dict10[value % 10]\n elif value%10 > 0:\n word = word + ' ' + dict1[value % 10]\n return word\n\n\ndef get_image():\n text_to_render, result = get_value()\n font = ImageFont.truetype(\"Arial Italic.ttf\", 18)\n img = Image.new('RGB', (800, 100), color=(255, 255, 255))\n d = ImageDraw.Draw(img)\n d.text((10, 10), text_to_render, fill=(95, 22, 112), font=font)\n img.save('images/pil_text.png')\n return text_to_render, result\n\n#get_image()\n#get_value()\nprint(round(0.5))\n","sub_path":"capch/home/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"17262548","text":"from sys import argv\nfrom numpy import *\nc=c=2.997924562e5\ndef comov_dist(z, ol, om, h0):\t\t#expression for lum distance\n\tq0=(om/2)-ol\n\ta=z*(1-q0)/(sqrt(1+2*q0*z)+1+q0*z )\n\tdl=(1+a)*c*z/h0\n\treturn dl\ninf=loadtxt(argv[1], dtype='string', usecols=(0, 1, 2, 3))\nz=inf[:,1].astype('float32')\nld=comov_dist(z, 0.73, 0.27, 70)\ninf[:,2]=inf[:,2].astype('float32')+5*log10(ld)+25-1.28\noutf=open(argv[2], 'w')\nfor j in inf:\n\tfor i in j:\n\t\toutf.write(i+'\\t')\n\toutf.write('\\n')\noutf.close()\n","sub_path":"src/abs2app.py","file_name":"abs2app.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"298130257","text":"\"\"\"\nGiven an array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.\n\nReturn the minimum size of the set so that at least half of the integers of the array are removed.\n\nExample 1:\n Input: arr = [3,3,3,3,5,5,5,2,2,7]\n Output: 2\n Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\n Possible sets of size 2 are {3,5},{3,2},{5,2}.\n Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has size greater than half of the size of the old array.\n\n\nExample 2:\n Input: arr = [7,7,7,7,7,7]\n Output: 1\n Explanation: The only possible set you can choose is {7}. This will make the new array empty.\n\n\nExample 3:\n Input: arr = [1,9]\n Output: 1\n\n\nExample 4:\n Input: arr = [1000,1000,3,7]\n Output: 1\n\n\nExample 5:\n Input: arr = [1,2,3,4,5,6,7,8,9,10]\n Output: 5\n\n\nConstraints:\n 1 <= arr.length <= 10^5\n arr.length is even.\n 1 <= arr[i] <= 10^5\n\"\"\"\n\n\ndef minSetSize(arr):\n num_freq = dict()\n for num in arr:\n if num not in num_freq:\n num_freq[num] = 1\n else:\n num_freq[num] += 1\n repeated_times = sorted(list(num_freq.values()), reverse=True)\n\n total_num_of_integers = len(arr)\n num_of_integers = 0\n\n for i in range(len(repeated_times)):\n num_of_integers += repeated_times[i]\n if num_of_integers >= total_num_of_integers / 2:\n return i + 1\n\n\n\n\narr = [3,3,3,3,5,5,5,2,2,7]\nprint(minSetSize(arr))\n\n\narr = [7,7,7,7,7,7]\nprint(minSetSize(arr))\n\n\narr = [1,9]\nprint(minSetSize(arr))\n\n\narr = [1000,1000,3,7]\nprint(minSetSize(arr))\n\n\narr = [1,2,3,4,5,6,7,8,9,10]\nprint(minSetSize(arr))\n","sub_path":"LeetCode-Python/1338 Reduce Array Size to The Half.py","file_name":"1338 Reduce Array Size to The Half.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"517117351","text":"data_path = 'C:\\\\Users\\\\Mig\\\\WoundImageAugmentation\\\\Data\\\\'\n\nfile_name = 'train-data'\nfile_extension = '.txt'\nversion = '-3'\n\nline_count = 1\nnew_data = []\nwith open(data_path + file_name+file_extension, 'r') as datafile:\n for line in datafile:\n p = line.split('|')\n #print(p[1]) # no 1\n #print(p[2]) # labels\n #print(p[3]) # features\n value = p[2].split(' ')\n center1 = value[73]\n center2 = value[74]\n center3 = value[75]\n l = \"|\" + p[1] + \"|labels \" + center1 + \" \" + center2 + \" \" + center3 + \" |features \"\n\n piece = p[3].split(' ')\n piece.pop(0)\n #print(len(piece))\n for index, item in enumerate(piece):\n string = ''\n if index % 3 == 0 and index <= len(piece) - 2:\n string = piece[index] + \" \" + piece[index + 1] + \" \" + piece[index + 2]\n #print(l + str)e\n new_data.append(l + string + '\\n')\n #print(l)\n #print(index)\n print('finish line : ' + str(line_count))\n line_count += 1\n\nwrite_count = 1\nfor line in new_data:\n if write_count % 1000 == 0:\n print(\"write line : \" + str(write_count))\n with open(data_path + file_name + version + file_extension, 'a') as outfile:\n outfile.write(line)\n write_count += 1\n\nprint('finish')\n","sub_path":"Code/utilities/arrange_data.py","file_name":"arrange_data.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"340900360","text":"# // Time Complexity : O(1) to get next element \n# // Space Complexity : O(n) all the elements can be list. stack will contain them all\n# // Did this code successfully run on Leetcode : Yes\n# // Any problem you faced while coding this : No\n\n# EXPLAINATION\n# We use the iterator interface\n# in python we can convert any list to iterator using iter(list_name)\n# we convert every list to iterator and iterate on it\n# We keep next_element updated and return its value on next() call\n# in hasNext function we handle 3 cases\n# when indexed element is Integer, None or List\n# when its integer we update next_element value and return true\n# when its list we append it to the stack with iter(list.getList())\n# whem its none we are out of list hence we pop that list from the stack\n# so... \n# 1. append to stack\n# 2. upodate value and return True\n# 3. pop from stack\nclass NestedIterator:\n def __init__(self, nestedList: [NestedInteger]):\n self.nextE = None\n # convert list to the iterator \n self.stack = [iter(nestedList)]\n \n \n def next(self) -> int:\n # return the integer\n return self.nextE.getInteger() \n \n \n def hasNext(self) -> bool:\n while self.stack:\n iterator = self.stack[-1]\n curr = next(iterator, None)\n if curr is None:\n self.stack.pop()\n elif curr.isInteger():\n self.nextE = curr\n return True\n else:\n self.stack.append(iter(curr.getList()))\n \n\n# Your NestedIterator object will be instantiated and called as such:\n# i, v = NestedIterator(nestedList), []\n# while i.hasNext(): v.append(i.next())","sub_path":"flatten Nested Iterator.py","file_name":"flatten Nested Iterator.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"351289031","text":"\ndef maxDepth(root):\n if root is None:\n return 0\n else:\n return 1 + max(maxDepth(root.left),maxDepth(root.right))\n\nclass Node:\n def __init__(self,key):\n self.left = None\n self.right = None\n self.val = key\n\n\nroot = Node(1)\nroot.left = Node(2)\nroot.right = Node(3)\nroot.left.left = Node(4)\nroot.left.right = Node(5)\nroot.right.left = Node(6)\nroot.left.left.left = Node(7)\n\nprint(maxDepth(root))","sub_path":"BST/MaxDepth.py","file_name":"MaxDepth.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"234869965","text":"import json\nfrom feed import models\nfrom django.http import HttpResponse\nfrom feed.service import contract_feed\nimport requests\n\ndef token_username(request):\n token = request.COOKIES['token']\n user = models.user.objects.get(token = token)\n return_result = json.dumps({\n 'code':200,\n 'data':user.username\n })\n return HttpResponse(return_result)\n\ndef get_user_role(dict):\n admin = models.user.objects.get(token = dict['token'])\n address = admin.address\n data = {\n \"groupId\": \"1\",\n \"user\": address,\n \"contractName\": contract_feed.feed_name,\n # \"contractPath\": \"FeedTrace\",\n \"version\": \"\",\n \"funcName\": \"getUserRole\",\n \"funcParam\": [address],\n \"contractAddress\": contract_feed.feed_address,\n \"contractAbi\": contract_feed.feed_abi,\n \"useAes\": False,\n \"useCns\": False,\n \"cnsName\": \"\"\n }\n headers = {'Content-Type': 'application/json'}\n res = requests.post(url='http://192.168.145.148:5002/WeBASE-Front/trans/handle',\n headers = headers,\n data = json.dumps(data).replace(\"False\", \"false\").replace(\"True\", \"true\"))\n print(res)\n if res.status_code == 200:\n role = json.loads(res.text)[0]\n return_result = json.dumps({\n 'code': 200,\n 'data': role\n })\n return return_result\n else:\n return_result = json.dumps({\n 'code': res.status_code,\n 'data': res.text\n })\n return return_result\n\ndef user_info():\n objects = models.user.objects.all().order_by('id')\n return_data = []\n for i in objects:\n address = i.address\n data = {\n \"groupId\": \"1\",\n \"user\": address,\n \"contractName\": contract_feed.feed_name,\n # \"contractPath\": \"FeedTrace\",\n \"version\": \"\",\n \"funcName\": \"getUserRole\",\n \"funcParam\": [address],\n \"contractAddress\": contract_feed.feed_address,\n \"contractAbi\": contract_feed.feed_abi,\n \"useAes\": False,\n \"useCns\": False,\n \"cnsName\": \"\"\n }\n headers = {'Content-Type': 'application/json'}\n res = requests.post(url='http://192.168.145.148:5002/WeBASE-Front/trans/handle',\n headers = headers,\n data = json.dumps(data).replace(\"False\", \"false\").replace(\"True\", \"true\"))\n real_role = json.loads(res.text)[0]\n return_data.append({'username':i.username,\n 'password':i.password,\n 'address':i.address,\n 'role':i.role,\n 'real_role':real_role})\n return_result = json.dumps({\n 'code':200,\n 'data':return_data\n })\n return return_result\n\ndef role_change(dict):\n # 查询原来的role\n root = models.user.objects.get(username = '123')\n root_address = root.address\n address = dict['address']\n role = dict['real_role']\n data = {\n \"groupId\": \"1\",\n \"user\": root_address,\n \"contractName\": contract_feed.feed_name,\n # \"contractPath\": \"FeedTrace\",\n \"version\": \"\",\n \"funcName\": \"changeRole\",\n \"funcParam\": [address, role],\n \"contractAddress\": contract_feed.feed_address,\n \"contractAbi\": contract_feed.feed_abi,\n \"useAes\": False,\n \"useCns\": False,\n \"cnsName\": \"\"\n }\n headers = {'Content-Type': 'application/json'}\n res = requests.post(url='http://192.168.145.148:5002/WeBASE-Front/trans/handle',\n headers = headers,\n data = json.dumps(data).replace(\"False\", \"false\").replace(\"True\", \"true\"))\n\n\n","sub_path":"Django_demo/feed/service/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"590809123","text":"\"\"\"\nDjango settings for jpy001 project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\n#BASE_DIR = os.path.dirname(os.path.dirname(__file__))\nBASE_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\nKEY_DIR = os.path.join(BASE_DIR, 'keys')\n\nAUTH_USER_MODEL = 'jpyuser.User'\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '8ca$r2-yghym)#+py3b4wbm6k@u6uxh(+lu@nv5j!u8+&o=zx$'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.humanize',\n 'bootstrapform', \n 'jpy001',\n 'jpyasset',\n 'utility',\n 'jpyapi',\n 'jpyuser',\n 'jpyperm',\n 'jpydispose',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n #'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n #'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'jpy001.urls'\n\nWSGI_APPLICATION = 'jpy001.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\n# DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.sqlite3',\n# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n# }\n# }\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'jpy001',\n 'USER': 'root',\n 'PASSWORD': '123456',\n 'HOST': '127.0.0.1',\n 'PORT': 3306,\n }\n}\n\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, 'templates'),\n)\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, \"static\"),\n)\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'Asia/Shanghai'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = False\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nMEDIA_ROOT = os.path.join(BASE_DIR, 'utility')\n\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n },\n },\n 'loggers': {\n 'django.db.backends': {\n 'handlers': ['console'],\n 'level': 'DEBUG' if DEBUG else 'INFO',\n },\n },\n}\n\n#SESSION_EXPIRE_AT_BROWSER_CLOSE = True\n#SESSION_COOKIE_AGE = 10","sub_path":"jpy001/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"379406157","text":"from trac.core import *\nfrom trac.admin import IAdminCommandProvider\nfrom trac.util.text import print_table, printout\nfrom tracker.lib.TicketTable import TicketTable\n\n\nclass UpdateTrackedTimeAdminCommandProvider(Component):\n\n implements(IAdminCommandProvider)\n\n # IAdminCommandProvider methods\n\n def get_admin_commands(self):\n yield ('update-tracked-time', '',\n 'Update tracked time',\n None, self._do_update)\n\n def _do_update(self):\n print('Update tracked time for tickets is starting now. Please wait...')\n TicketTable.update_tracked_time_for_tickets(self.env)\n print('Update complete.')","sub_path":"plugin/Tracker/tracker/update_tracked_time.py","file_name":"update_tracked_time.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"308414138","text":"from django.utils.deprecation import MiddlewareMixin\nfrom django.shortcuts import HttpResponse\nfrom rbac import config\nimport re\n\n\nclass RbacMiddleware(MiddlewareMixin):\n\n def process_request(self,request,*args,**kwargs):\n for pattern in config.VALID_URL:\n if re.match(pattern,request.path_info):\n return None\n\n action = request.GET.get('md') # GET\n user_permission_dict = request.session.get('user_permission_dict')\n if not user_permission_dict:\n return HttpResponse('无权限')\n\n # action_list = user_permission_dict.get(request.path_info)\n flag = False\n for k,v in user_permission_dict.items():\n if re.match(k,request.path_info):\n if action in v:\n flag = True\n break\n if not flag:\n return HttpResponse('无权限')\n","sub_path":"rbac/middleware/md.py","file_name":"md.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"310948998","text":"from Agenda import *\np = 0\n\n#Inicio do programa\nload()\n\nwhile p != 1:\n imprimir_menu()\n try:\n opcao = int(input(\"Escolha uma opcao: \"))\n if opcao == 1:\n mostrar_agenda()\n elif opcao == 2:\n nome = input(\"Insira o nome do contato a ser buscado: \")\n buscar_contato(nome)\n elif opcao == 3 :\n nome = input(\"Insira o nome do contato: \")\n try:\n AGENDA[nome]\n print(\">>>>>>>>Contato já existe: \")\n continue\n except KeyError:\n print(\">>>>>>>>Incluindo contato\", nome)\n a = False\n incluir_editar_contato(nome, a)\n elif opcao == 4:\n nome = input(\"Insira o nome do contato: \")\n try:\n AGENDA[nome]\n print(\">>>>>>>>Editando contato: \", nome)\n a = True\n incluir_editar_contato(nome, a)\n\n except KeyError:\n print(\">>>>>>>>Contato inexistente\")\n elif opcao == 5:\n nome = input(\"Insira o nome do contato a ser removido: \")\n remover_contato(nome)\n elif opcao == 6:\n name_file = input(\"Insira o nome/caminho do arquivo:\")\n exportar_contatos(name_file)\n elif opcao == 7:\n name_file = input(\"Insira o nome/caminho do arquivo:\")\n importar_contatos(name_file)\n elif opcao == 8:\n print(\">>>>>>>>Agenda fechada\")\n p += 1\n else:\n print(\"Escolha uma opcao valida\")\n except ValueError as error:\n print(\"Input inválido, insira apenas numeros\")\n print(error)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"392398153","text":"import argparse\nimport asyncio\nimport os\nimport ipaddress\nimport json\nimport logging\nimport sys\n\nimport netifaces as ni\nimport websockets\n\nimport gi\n\ngi.require_version(\"Gst\", \"1.0\")\ngi.require_version(\"GstWebRTC\", \"1.0\")\ngi.require_version(\"GstSdp\", \"1.0\")\nfrom gi.repository import Gst, GstSdp, GstWebRTC\n\n\nGst.init(None)\n\nPIPELINE_DESC = \"\"\"\n tcpclientsrc host=127.0.0.1 port=33141 do-timestamp=true\n ! application/x-rtp-stream,encoding-name=VP8\n ! rtpstreamdepay\n ! rtpjitterbuffer\n ! rtpvp8depay\n ! rtpvp8pay\n ! application/x-rtp,media=video,encoding-name=VP8,payload=97\n ! webrtcbin name=sendrecv bundle-policy=max-bundle\n\"\"\"\n\n# Doesn't work for me in both Chrome and Firefox:\n# ! x264enc tune=zerolatency speed-preset=superfast bitrate=1000\n# ! rtph264pay\n# ! application/x-rtp,media=video,encoding-name=H264,payload=96\n\nlogger = logging.getLogger(\"signalling\")\n\nlogger.setLevel(logging.INFO)\nlogger.addHandler(logging.StreamHandler())\n\nICE_ALLOWED_NETWORKS = []\nKEEPALIVE_TIMEOUT = 0\n\n\ndef get_nic_networks(nic):\n networks = []\n ifaddresses = ni.ifaddresses(nic)\n for family, addresses in ifaddresses.items():\n for address in addresses:\n try:\n net = ipaddress.ip_network(\n f'{address[\"addr\"]}/{address[\"netmask\"]}',\n strict=False, # ignore host bits\n )\n except (KeyError, ValueError):\n logger.info(\n \"Failed to parse a network on %s: %r\", nic, address, exc_info=True\n )\n else:\n networks.append(net)\n assert networks\n return networks\n\n\nasync def recv_msg_ping(ws, raddr):\n \"\"\"\n Wait for a message forever, and send a regular ping to prevent bad routers\n from closing the connection.\n \"\"\"\n msg = None\n while msg is None:\n try:\n msg = await asyncio.wait_for(ws.recv(), KEEPALIVE_TIMEOUT)\n except asyncio.TimeoutError:\n logger.info(\"Sending keepalive ping to %r in recv\", raddr)\n await ws.ping()\n return msg\n\n\ndef start_pipeline(conn):\n def send_ice_candidate_message(_, mlineindex, candidate):\n remote_ip, _ = conn.remote_address # (host, port)\n # \"candidate:26 2 TCP 1015023870 10.60.130.20 9 typ host tcptype active\"\n candidate_ip = candidate.split(\" \")[4]\n if not keep_ice_candidate(candidate_ip, remote_ip):\n logger.info(\"skipping candidate %r\", candidate)\n return\n\n icemsg = json.dumps(\n {\"ice\": {\"candidate\": candidate, \"sdpMLineIndex\": mlineindex}}\n )\n logger.info(\"sending ice candidate %r\", icemsg)\n loop = asyncio.new_event_loop()\n loop.run_until_complete(conn.send(icemsg))\n\n def keep_ice_candidate(candidate_ip, ws_ip):\n # Filter out docker, localhost and other private ip addresses\n\n if not ICE_ALLOWED_NETWORKS:\n # If no nics were provided -- don't filter anything out.\n return True\n\n ip = ipaddress.ip_address(candidate_ip)\n for net in ICE_ALLOWED_NETWORKS:\n if ip in net:\n return True\n return False\n\n def on_negotiation_needed(element):\n promise = Gst.Promise.new_with_change_func(on_offer_created, element, None)\n element.emit(\"create-offer\", None, promise)\n\n def send_sdp_offer(offer):\n text = offer.sdp.as_text()\n logger.info(\"Sending offer:\\n%s\", text)\n msg = json.dumps({\"sdp\": {\"type\": \"offer\", \"sdp\": text}})\n loop = asyncio.new_event_loop()\n loop.run_until_complete(conn.send(msg))\n\n def on_offer_created(promise, _, __):\n nonlocal webrtc\n promise.wait()\n reply = promise.get_reply()\n offer = reply[\"offer\"]\n promise = Gst.Promise.new()\n webrtc.emit(\"set-local-description\", offer, promise)\n promise.interrupt()\n send_sdp_offer(offer)\n\n pipe = Gst.parse_launch(PIPELINE_DESC)\n webrtc = pipe.get_by_name(\"sendrecv\")\n webrtc.connect(\"on-negotiation-needed\", on_negotiation_needed)\n webrtc.connect(\"on-ice-candidate\", send_ice_candidate_message)\n pipe.set_state(Gst.State.PLAYING)\n return pipe, webrtc\n\n\nasync def connection_handler(ws):\n raddr = ws.remote_address\n try:\n pipe, webrtc = start_pipeline(ws)\n except Exception:\n ws.close()\n raise\n\n try:\n while True:\n # Receive command, wait forever if necessary\n msg = await recv_msg_ping(ws, raddr)\n handle_sdp(webrtc, msg)\n finally:\n ws.close()\n pipe.set_state(Gst.State.NULL)\n\n\ndef handle_sdp(webrtc, message):\n msg = json.loads(message)\n if \"sdp\" in msg:\n sdp = msg[\"sdp\"]\n assert sdp[\"type\"] == \"answer\"\n sdp = sdp[\"sdp\"]\n logger.info(\"Received answer:\\n%s\", sdp)\n res, sdpmsg = GstSdp.SDPMessage.new()\n GstSdp.sdp_message_parse_buffer(bytes(sdp.encode()), sdpmsg)\n answer = GstWebRTC.WebRTCSessionDescription.new(\n GstWebRTC.WebRTCSDPType.ANSWER, sdpmsg\n )\n promise = Gst.Promise.new()\n webrtc.emit(\"set-remote-description\", answer, promise)\n promise.interrupt()\n elif \"ice\" in msg:\n ice = msg[\"ice\"]\n candidate = ice[\"candidate\"]\n sdpmlineindex = ice[\"sdpMLineIndex\"]\n webrtc.emit(\"add-ice-candidate\", sdpmlineindex, candidate)\n\n\nasync def hello_peer(ws):\n \"\"\"\n Exchange hello, register peer\n \"\"\"\n raddr = ws.remote_address\n hello = await ws.recv()\n if hello != \"HELLO\":\n await ws.close(code=1002, reason=\"invalid protocol\")\n raise Exception(\"Invalid hello from {!r}\".format(raddr))\n # Send back a HELLO\n await ws.send(\"HELLO\")\n\n\nasync def handler(ws, path):\n \"\"\"\n All incoming messages are handled here. @path is unused.\n \"\"\"\n raddr = ws.remote_address\n logger.info(\"Connected to %r\", raddr)\n await hello_peer(ws)\n try:\n await connection_handler(ws)\n finally:\n logger.info(\"Connection to peer %r closed, exiting handler\", raddr)\n\n\ndef main():\n global ICE_ALLOWED_NETWORKS, KEEPALIVE_TIMEOUT\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument(\"--addr\", default=\"0.0.0.0\", help=\"Address to listen on\")\n parser.add_argument(\"--port\", default=8443, type=int, help=\"Port to listen on\")\n parser.add_argument(\n \"--keepalive-timeout\",\n dest=\"keepalive_timeout\",\n default=30,\n type=int,\n help=\"Timeout for keepalive (in seconds)\",\n )\n\n options = parser.parse_args(sys.argv[1:])\n\n addr_port = (options.addr, options.port)\n KEEPALIVE_TIMEOUT = options.keepalive_timeout\n\n # The list of IP networks which are allowed to be sent out as the ICE candidates.\n # This allows to filter out the internal and definitely unreachable interfaces,\n # such as docker bridges, loopback and so on.\n ICE_ALLOWED_NETWORKS = [\n network\n for nic in os.getenv(\"WS_SIG_INTERFACES_FOR_ICE\").split(\" \")\n for network in get_nic_networks(nic)\n ]\n\n logger.info(\"ICE allowed networks: %s\", ICE_ALLOWED_NETWORKS)\n\n logger.info(\"Listening on https://{}:{}\".format(*addr_port))\n # Websocket server\n wsd = websockets.serve(\n handler,\n *addr_port,\n # Maximum number of messages that websockets will pop\n # off the asyncio and OS buffers per connection. See:\n # https://websockets.readthedocs.io/en/stable/api.html#websockets.protocol.WebSocketCommonProtocol\n max_queue=16,\n )\n\n asyncio.get_event_loop().run_until_complete(wsd)\n asyncio.get_event_loop().run_forever()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"detector_back/worker/detector/gstreamer/webrtc/signalling/signalling.py","file_name":"signalling.py","file_ext":"py","file_size_in_byte":7746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"398918965","text":"# License: Creative Commons Zero (almost public domain) http://scpyce.org/cc0\r\nfrom __future__ import print_function, division\r\nfrom pylab import *\r\nimport numpy as np\r\nfrom scipy import stats\r\n\r\n\r\n'''This script can be used to understand the relationship between the signal\r\nabsent and signal present distributions and the ROC curve which they generate.\r\nThe distributions are assumed to be Gaussian and of equal variance.\r\nThe sliders at the bottom can be used to change the position the mean of each\r\ndistribution as well as the threshold.\r\n\r\nThis code was influenced by the matplotlib slider demo:\r\nmatplotlib.sourceforge.net/examples/widgets/slider_demo.html'''\r\n\r\n#Generate the x values that the two distributions will be plotted against \r\nx = linspace(0,25,100) \r\n\r\n#Create the figure and two subplots\r\nfig = figure('ROC curve demonstration')\r\nax1 = fig.add_subplot(212)\r\nax2 = fig.add_subplot(211,aspect='equal',title='ROC curve',\r\n xlabel='1-specificity',ylabel='sensitivity')\r\nsubplots_adjust(bottom=0.25)\r\n\r\n\r\n#Create the axes for the sliders\r\naxthreshold = axes([0.2, 0.15, 0.65, 0.03])#, axisbg=axcolor)\r\naxmean1 = axes([0.2, 0.1, 0.25, 0.03])#, axisbg=axcolor)\r\naxmean2 = axes([0.2, 0.05, 0.25, 0.03])#, axisbg=axcolor)\r\naxstd1 = axes([0.6, 0.1, 0.25, 0.03])#, axisbg=axcolor)\r\naxstd2 = axes([0.6, 0.05, 0.25, 0.03])#, axisbg=axcolor)\r\n\r\n#Plot the signal absent distribution\r\nax1.plot(x,stats.norm.pdf(x,loc=12)) \r\nax1.plot(x,stats.norm.pdf(x,loc=13)) \r\n\r\n#Create sliders, and their initial values\r\nthreshold = Slider(axthreshold, 'Threshold', 5, 20.0, valinit=14)\r\nmean1 = Slider(axmean1, 'Mean1', 5, 20.0, valinit=12)\r\nmean2 = Slider(axmean2, 'Mean2', 5, 20.0, valinit=13)\r\nstd1 = Slider(axstd1, 'Std1', 0.1, 10, valinit = 1)\r\nstd2 = Slider(axstd2, 'Std1', 0.1, 10, valinit = 1)\r\n\r\ndef roc_curve(threshold_values,mean1,mean2,std1=1,std2=1):\r\n '''This function returns and an array of sensitivity and 1 - specificity\r\n values from the given threshold values'''\r\n sensitivity = zeros(threshold_values.size)\r\n one_minus_specificity = zeros(threshold_values.size)\r\n for index, value in enumerate(threshold_values):\r\n sensitivity[index] = 1 - stats.norm.cdf(value,loc=mean2, scale=std2)\r\n one_minus_specificity[index] = 1 - stats.norm.cdf(value,loc=mean1, scale=std1)\r\n return sensitivity, one_minus_specificity\r\n\r\n'''\r\nsensitivity, one_minus_specificity = roc_curve(x,12,13)\r\nax2.plot(one_minus_specificity,sensitivity,'b',linewidth=2)\r\nmean1val = 12\r\nmean2val = 13 \r\n'''\r\ndef update(val):\r\n '''Updates the two distributions, threshold values, and point on the \r\n ROC curve when the sliders are changes'''\r\n global mean1val\r\n global mean2val\r\n \r\n mean1val = mean1.val\r\n mean2val = mean2.val\r\n std1val = std1.val\r\n std2val = std2.val\r\n \r\n thresholdval = threshold.val\r\n \r\n ax1.cla()\r\n\r\n ax1.plot(x,stats.norm.pdf(x,loc=mean1val, scale=std1val)) \r\n ax1.plot(x,stats.norm.pdf(x,loc=mean2val, scale=std2val)) \r\n ax1.vlines(thresholdval,0,0.40,color='r')\r\n ax1.set_ylim(0,0.40)\r\n\r\n ax2.cla()\r\n sensitivity, one_minus_specificity = roc_curve(x,mean1val,mean2val,std1val, std2val)\r\n ax2.plot(one_minus_specificity,sensitivity,'b',linewidth=3)\r\n ax2.plot( 1 - stats.norm.cdf(thresholdval,loc=mean1val,scale=std1val),\r\n 1 - stats.norm.cdf(thresholdval,loc=mean2val,scale=std2val),'ro')\r\n ax2.set_title('ROC curve')\r\n #xlabel = 'sensitivity'\r\n #ylabel = 'specificity'\r\n \r\n \r\n draw()\r\n\r\nmean1.on_changed(update)\r\nmean2.on_changed(update)\r\nstd1.on_changed(update)\r\nstd2.on_changed(update)\r\nthreshold.on_changed(update)\r\nupdate(None)\r\nshow()","sub_path":"SPC Static Data/code/2012/03/000038/roc_curve_demo.py","file_name":"roc_curve_demo.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"310976197","text":"import cv2\nimport numpy as np\nimport imutils\nimport base64\nfrom scipy.spatial import distance as dist\n\ncap = cv2.VideoCapture(1)\n\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 320);\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240);\n\n# Ancho en cm del robot (circulo)\nWIDTH = 16.0\n\ndef midpoint(ptA, ptB):\n return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)\n\ndef get_approx(c, value, peri):\n return cv2.approxPolyDP(c, value * peri, True)\n\ndef is_shape(approx, area, hullArea):\n (x, y, w, h) = cv2.boundingRect(approx)\n solidity = area / float(hullArea)\n keepDims = w > 12 and h > 12\n keepSolidity = solidity > 0.9\n\n return keepDims and keepSolidity\n\ndef minimum(value, data, minim, datamin):\n if value < minim:\n return value, data\n else:\n return minim, datamin\n\nwhile True:\n _, frame = cap.read()\n # Bajo la resolucion de la imagen\n encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 5]\n result, encimg = cv2.imencode('.jpg', frame, encode_param) \n \n # Simulo lo que seria encodear y desencodear la imagen\n stream = base64.b64encode(encimg.tostring())\n encimg = base64.b64decode(stream)\n frame = cv2.imdecode(np.frombuffer(encimg, np.uint8), 1)\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n blurred = cv2.GaussianBlur(gray, (7, 7), 0)\n edged = cv2.Canny(blurred, 50, 150)\n _, cnts, _ = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n\n refObj = None\n objects = []\n for c in cnts:\n peri = cv2.arcLength(c, True)\n area = cv2.contourArea(c)\n hullArea = cv2.contourArea(cv2.convexHull(c))\n\n\n extLeft = tuple(c[c[:, :, 0].argmin()][0])\n extRight = tuple(c[c[:, :, 0].argmax()][0])\n extTop = tuple(c[c[:, :, 1].argmin()][0])\n extBot = tuple(c[c[:, :, 1].argmax()][0])\n\n # Radio y centro (en este archivo no se necesitan pero para el path puede ser)\n (cX, cY), radius = cv2.minEnclosingCircle(c)\n\n # Detecta triangulo (destino)\n approx = get_approx(c, 0.05, peri)\n if len(approx) == 3:\n if is_shape(approx, area, hullArea):\n cv2.drawContours(frame, [c], 0, (0, 255, 0), 3)\n\n # Guardo los puntos extremos\n objects.append([(extLeft, extRight, extTop, extBot)])\n continue\n\n # Detecta cuadrado (obstaculo)\n approx = get_approx(c, 0.04, peri)\n if len(approx) == 4:\n if is_shape(approx, area, hullArea):\n cv2.drawContours(frame, [c], 0, (0, 0, 255), 3)\n\n # Guardo los puntos extremos\n objects.append([(extLeft, extRight, extTop, extBot)])\n continue\n\n\n # Detecta circulo (robot)\n approx = get_approx(c, 0.01, peri)\n if len(approx) > 6:\n if is_shape(approx, area, hullArea):\n \n # Distancia en pixels\n D = dist.euclidean(extLeft, extRight)\n\n # En el contorno de referencia guardo centro, distancia en cm, y\n # los puntos extremos.\n refObj = ((cX, cY), D / WIDTH, (extLeft, extRight, extTop, extBot))\n cv2.drawContours(frame, [c], 0, (255, 0, 0), 3)\n continue\n if refObj: \n for o in objects:\n\n xA, yA = refObj[0] # Puntos extremos del robot\n color = (0, 165, 255)\n\n\n # Calculo la distancia entre el extremo minimo del obstaculo con\n # el del robot\n minim = 9999\n pointRef, pointObj = None, None\n # Itero por los extremos del obstaculo\n for p2 in o[0]:\n # Itero por los extremos del robot\n for p1 in refObj[2]:\n D = (dist.euclidean(p1, p2)) / refObj[1] # Calculo la distancia en cm\n # Calculo el minimo\n minim, (pointRef, pointObj) = minimum(D, [p1, p2], minim, [pointRef, pointObj])\n\n xA, yA = pointRef\n xB, yB = pointObj\n cv2.circle(frame, (int(xA), int(yA)), 5, color, -1)\n cv2.circle(frame, (int(xB), int(yB)), 5, color, -1)\n cv2.line(frame, (int(xA), int(yA)), (int(xB), int(yB)),\n color, 2)\n (mX, mY) = midpoint((xA, yA), (xB, yB))\n cv2.putText(frame, \"{:.1f}cm\".format(minim), (int(mX), int(mY - 10)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.55, color, 2)\n\n cv2.imshow('frame', frame)\n cv2.waitKey(5)","sub_path":"misc_code/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"246898582","text":"import os\nimport uuid\nimport random\nimport tensorflow as tf\nimport hypergan as hg\nimport hyperchamber as hc\nimport numpy as np\nfrom hypergan.viewer import GlobalViewer\nfrom hypergan.samplers.base_sampler import BaseSampler\nfrom hypergan.samplers.random_walk_sampler import RandomWalkSampler\nfrom hypergan.gans.standard_gan import StandardGAN\nfrom common import *\n\nfrom hypergan.gans.alpha_gan import AlphaGAN\n\nx_v = None\nz_v = None\nlayer_filter = None\n\nclass Sampler(BaseSampler):\n\n def sample(self, path, save_samples):\n gan = self.gan\n generator = gan.uniform_sample\n z_t = gan.latent.sample\n x_t = gan.inputs.x\n n_samples = 25\n \n sess = gan.session\n config = gan.config\n global x_v\n global z_v\n global layer_filter\n x_v = sess.run(x_t)\n x_v = np.tile(x_v[0], [gan.batch_size(),1,1,1])\n if layer_filter == None:\n layer_filter = gan.generator.config.layer_filter(gan, gan.generator.config, x_t)\n if(gan.ops.shape(layer_filter)[-1] == 1):\n layer_filter = tf.tile(layer_filter,[1,1,1,3])\n\n \n layer_filter_v = sess.run(layer_filter, {x_t: x_v})\n\n samples = [sess.run(generator, {x_t: x_v})[0] for n in range(n_samples)]\n stacks = []\n width = 5\n #stacks.append([x_v[0], layer_filter_v[0]] + samples[-4:0])\n \n for i in range(n_samples//width-1):\n stacks.append([samples[i*width+width+j] for j in range(width)])\n\n stacks[0][0]=x_v[0]\n print(np.shape(layer_filter),\"----\")\n stacks[0][1]=layer_filter_v[0]\n images = np.vstack([np.hstack(s) for s in stacks])\n\n self.plot(images, path, save_samples)\n return [{'images': images, 'label': 'tiled x sample'}]\n\ndef apply_mask(gan, config, net,x=None):\n if x == None:\n x = gan.inputs.x\n filtered = net\n shape = gan.ops.shape(x)\n mask = tf.ones([shape[1], shape[2], shape[3]])\n mask = tf.greater(mask, 0)\n scaling = 0.6\n mask = tf.image.central_crop(mask, scaling)\n left = (shape[1]*scaling)//2 * 0.75\n top = (shape[2]*scaling)//2 * 0.75\n mask = tf.image.pad_to_bounding_box(mask, int(top), int(left), shape[1], shape[2])\n mask = tf.cast(mask, tf.float32)\n backmask = (1.0-mask) \n filtered = backmask* x + mask * filtered\n print(\"FRAMING IMAGE\", filtered) \n return filtered\n\ndef add_bw(gan, config, net):\n x = gan.inputs.x\n s = [int(x) for x in net.get_shape()]\n print(\"S IS \", s)\n shape = [s[1], s[2]]\n x = tf.image.resize_images(x, shape, 1)\n bwnet = tf.slice(net, [0, 0, 0, 0], [s[0],s[1],s[2], 3])\n \n if not gan.config.add_full_image:\n print( \"[colorizer] Adding black and white image\", x)\n filtered = tf.image.rgb_to_grayscale(x)\n if config.blank_black_and_white is not None:\n filtered = tf.zeros_like(filtered)\n if config.colorizer_noise is not None:\n filtered += tf.random_normal(filtered.get_shape(), mean=0, stddev=config.colorizer_noise, dtype=tf.float32)\n\n if gan.config.add_full_image_frame:\n bw = tf.image.rgb_to_grayscale(filtered)\n bw = tf.tile(bw,[1,1,1,3])\n filtered = apply_mask(gan,config,bw, x)\n else:\n print( \"[colorizer] Adding full image\", x)\n filtered = x\n\n return filtered\n\narg_parser = ArgumentParser(\"Colorize an image\")\narg_parser.add_image_arguments()\narg_parser.parser.add_argument('--add_full_image', type=bool, default=False, help='Instead of just the black and white X, add the whole thing.')\narg_parser.parser.add_argument('--add_full_image_frame', type=bool, default=False, help='Frame the corners of the image. Incompatible with add_full_image.')\nargs = arg_parser.parse_args()\n\nwidth, height, channels = parse_size(args.size)\n\nconfig = lookup_config(args)\n\nif args.add_full_image:\n config[\"add_full_image\"]=True\nif args.add_full_image_frame:\n config[\"add_full_image_frame\"]=True\n\nif args.action == 'build':\n flattened = tf.zeros([args.batch_size * width * height * channels], name=\"flattened_x\")\n x = tf.reshape(flattened, [args.batch_size, width, height, channels])\n inputs = hc.Config({\"x\": x, \"flattened\": flattened})\n\n\nelse:\n inputs = hg.inputs.image_loader.ImageLoader(args.batch_size)\n inputs.create(args.directory,\n channels=channels, \n format=args.format,\n crop=args.crop,\n width=width,\n height=height,\n resize=True)\n\nconfig_name = args.config\nsave_file = \"saves/\"+config_name+\"/model.ckpt\"\nos.makedirs(os.path.expanduser(os.path.dirname(save_file)), exist_ok=True)\n\ndef setup_gan(config, inputs, args):\n gan = hg.GAN(config, inputs=inputs, name=args.config)\n\n if(os.path.isfile(save_file+\".meta\")):\n gan.load(save_file)\n\n tf.train.start_queue_runners(sess=gan.session)\n\n config_name = args.config\n GlobalViewer.title = \"[hypergan] colorizer \" + config_name\n GlobalViewer.enabled = args.viewer\n\n return gan\n\ndef train(config, inputs, args):\n gan = setup_gan(config, inputs, args)\n gan.name = config_name\n sampler = lookup_sampler(args.sampler or Sampler)(gan)\n samples = 0\n\n metrics = [batch_accuracy(gan.inputs.x, gan.uniform_sample), batch_diversity(gan.uniform_sample)]\n sum_metrics = [0 for metric in metrics]\n for i in range(args.steps):\n gan.step()\n\n if args.action == 'train' and i % args.save_every == 0 and i > 0:\n print(\"saving \" + save_file)\n gan.save(save_file)\n\n if i % args.sample_every == 0:\n sample_file=\"samples/\"+config_name+\"/%06d.png\" % (samples)\n os.makedirs(os.path.expanduser(os.path.dirname(sample_file)), exist_ok=True)\n samples += 1\n sampler.sample(sample_file, args.save_samples)\n\n if i > args.steps * 9.0/10:\n for k, metric in enumerate(gan.session.run(metrics)):\n print(\"Metric \"+str(k)+\" \"+str(metric))\n sum_metrics[k] += metric \n\n tf.reset_default_graph()\n return sum_metrics\n\ndef build(config, inputs, args):\n def input_nodes():\n return [\n gan.inputs.flattened\n ]\n gan = setup_gan(config, inputs, args)\n gan.build(input_nodes=gan.input_nodes() + input_nodes())\n\ndef sample(config, inputs, args):\n gan = setup_gan(config, inputs, args)\n sampler = lookup_sampler(args.sampler or RandomWalkSampler)(gan)\n samples = 0\n for i in range(args.steps):\n sample_file=\"samples/\"+config_name+\"/%06d.png\" % (samples)\n samples += 1\n sampler.sample(sample_file, args.save_samples)\n\nif args.action == 'train':\n metrics = train(config, inputs, args)\n print(\"Resulting metrics:\", metrics)\nelif args.action == 'sample':\n sample(config, inputs, args)\nelif args.action == 'build':\n build(config, inputs, args)\nelse:\n print(\"Unknown action: \"+args.action)\n","sub_path":"examples/colorizer.py","file_name":"colorizer.py","file_ext":"py","file_size_in_byte":6935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"85368644","text":"def printMatrix(matrix):\n print(\"PRINTING MATRIX\")\n for row in matrix:\n print(row)\n\ndef getSwapedValues(value1, value2):\n temp = value1\n value1 = value2\n value2 = temp\n\n return [value1,value2]\n\ndef rotateMatrix(matrix):\n # diagonal is the same, then ignore it\n # a b\n # c d\n\n # After rotate\n # a c\n # b d\n\n matrixLength = len(matrix)\n\n #optimization\n # 1x1 matrix\n if matrixLength == 1:\n return matrix\n\n\n # NxN matrix\n for column in range(matrixLength):\n for row in range(column+1,matrixLength):\n swappedValues = getSwapedValues(matrix[column][row], matrix[row][column])\n matrix[column][row] = swappedValues[0]\n matrix[row][column] = swappedValues[1]\n\n return matrix\n\n\nif __name__ == '__main__':\n matrix = [[0,1,2],[3,4,5],[6,7,8]]\n printMatrix(matrix)\n\n result = rotateMatrix(matrix)\n printMatrix(result)\n","sub_path":"CrackingTheCode/Chapter1_Arrays_Strings/question_1_7.py","file_name":"question_1_7.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"476524346","text":"# The MIT License (MIT)\n\n# Copyright (c) 2012 Robin Duda, (chilimannen)\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\n# Camera module will keep track of sprite offset.\n\n# Map file.\nimport math\nimport random\nimport pygame\nfrom loader import load_image\n\n\nclass TrafficLamp(pygame.sprite.Sprite):\n # LAMP status\n GREEN = 1\n RED = 2\n YELLOW = 3\n\n # time out from lamp switch from GREEN to RED And backward\n TIMEOUT = 600\n\n LAMP_RED_IMG = None\n LAMP_GREEN_IMG = None\n LAMP_YELLOW_IMG = None\n\n def __init__(self, init_x, init_y, dir, status=None, remaining_time=None):\n self.LAMP_IMG = load_image('traffic_lamp.png')\n self.RED_RECT = ((0, 0), (41, 100))\n self.GREEN_RECT = ((42, 0), (42, 100))\n self.YELLOW_RECT = ((82, 0), (125, 100))\n pygame.sprite.Sprite.__init__(self)\n if status is not None and status != TrafficLamp.GREEN and \\\n status != TrafficLamp.YELLOW:\n raise Exception(\"init status of traffic lamp must be RED or GREEN\")\n if status is None:\n status = random.randint(1, 2)\n if remaining_time is None:\n remaining_time = random.randint(60, 600)\n # previous status of traffic lamp\n self.prev_status = TrafficLamp.YELLOW\n # current status of traffic lamp\n self.status = status\n # time remaining before traffic lamp change status\n self.remaining_time = remaining_time\n # print(self.remaining_time)\n # traffic lamp position\n self.x = init_x\n self.y = init_y\n # traffic lamp direction (0,90,180,270)\n self.dir = dir\n # self.image = self.set_traffic_lamp_img()\n self.image = self.LAMP_IMG\n self.sprite_rect = self.set_traffic_lamp_img()\n self.rect = self.image.get_rect()\n # self.rect_w = self.rect.size[0]\n # self.rect_h = self.rect.size[1]\n self.rect.center = self.x, self.y\n\n def set_traffic_lamp_img(self):\n if self.status == TrafficLamp.RED:\n return self.RED_RECT\n elif self.status == TrafficLamp.GREEN:\n return self.GREEN_RECT\n elif self.status == TrafficLamp.YELLOW:\n return self.YELLOW_RECT\n\n def switch_status(self):\n if self.status == TrafficLamp.YELLOW:\n if self.prev_status == TrafficLamp.RED:\n self.prev_status = TrafficLamp.YELLOW\n self.status = TrafficLamp.GREEN\n else:\n self.prev_status = TrafficLamp.YELLOW\n self.status = TrafficLamp.RED\n self.remaining_time = 600\n\n elif self.status == TrafficLamp.RED:\n self.prev_status = TrafficLamp.RED\n self.status = TrafficLamp.YELLOW\n self.remaining_time = 60\n else:\n self.prev_status = TrafficLamp.GREEN\n self.status = TrafficLamp.YELLOW\n self.remaining_time = 60\n self.sprite_rect = self.set_traffic_lamp_img()\n # self.rect = self.image.get_rect()\n pass\n\n # Realign the map\n def update(self, cam_x, cam_y):\n self.rect.center = self.x - cam_x + 600, self.y - cam_y + 300\n self.remaining_time -= 1\n if self.remaining_time == 0:\n self.switch_status()\n # print(self.rect.topleft)\n # print(str(cam_x)+\" : \"+str(cam_y))\n\n def render(self, screen):\n lamp_font = pygame.font.SysFont(None, 25)\n # render text\n label = lamp_font.render(str(int(self.remaining_time / 60)), 1,\n (255, 255, 255))\n screen.blit(label, (self.rect.center[0] + 60, self.rect.center[1]))\n screen.blit(self.image, (self.rect.topleft[0], self.rect.topleft[1]),\n pygame.Rect(self.sprite_rect))\n","sub_path":"traffic_lamp_1.py","file_name":"traffic_lamp_1.py","file_ext":"py","file_size_in_byte":4806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"127066121","text":"\"\"\"Keyword args for selecting annotation lines.\"\"\"\n\n__copyright__ = \"Copyright (C) 2016-2019, DV Klopfenstein, H Tang. All rights reserved.\"\n__author__ = \"DV Klopfenstein\"\n\n\nclass AnnoOptions:\n \"\"\"Keyword args for selecting annotation lines.\"\"\"\n\n keys_exp = set(['evidence_set',\n 'b_geneid2gos', 'go2geneids',\n 'keep_ND', 'keep_NOT'])\n\n def __init__(self, **kws):\n # Get associations only for specified Evidence_Codes\n # kws: evidence_set keep_ND keep_NOT b_geneid2gos go2geneids\n self.evidence_set = kws.get('evidence_set', None)\n # Associations are normally gene2gos\n # Return go2genes, if desired\n self.b_geneid2gos = self._init_b_geneid2gos(kws)\n # Keep annotation, even if:\n # * Evidence_Code == ND -> No biological data No biological Data available\n self._keep_nd = kws.get('keep_ND', False)\n # * Qualifiers contain NOT\n self._keep_not = kws.get('keep_NOT', False)\n self._keep_qualified = not self._keep_nd and not self._keep_not\n self._keep_unqualified = self._keep_nd and self._keep_not\n\n def keep(self, qualifiers, evidence_code):\n \"\"\"Keep annotaion if it passes potentially modified selection.\"\"\"\n return self.keep_qualified(qualifiers, evidence_code) and self.keep_evidence(evidence_code)\n\n def keep_qualified(self, qualifiers, evidence_code):\n \"\"\"Normally keeps qualified associations, but can keep more.\"\"\"\n # NOT: Used when gene is expected to have function F, but does NOT.\n # ND : GO function not seen after exhaustive annotation attempts to the gene.\n if self._keep_qualified:\n # Keep everything but these:\n # Qualifiers contain NOT\n # Evidence_Code == ND -> No biological data No biological Data available\n return 'not' not in qualifiers and evidence_code != 'ND'\n if self._keep_unqualified:\n return True\n if self._keep_nd:\n return 'not' not in qualifiers\n if self._keep_not:\n return evidence_code != 'ND'\n\n def keep_evidence(self, evidence_code):\n \"\"\"Keep all evidence (default) or selected Evidence_Codes.\"\"\"\n if self.evidence_set is None:\n return True\n return evidence_code in self.evidence_set\n\n @staticmethod\n def _init_b_geneid2gos(kws):\n \"\"\"GEt b_geneid2gos.\"\"\"\n if 'b_geneid2gos' in kws:\n return kws['b_geneid2gos']\n if 'go2geneids' in kws:\n return not kws['go2geneids']\n return True\n\n\n# Copyright (C) 2016-2019, DV Klopfenstein, H Tang. All rights reserved.\"\n","sub_path":"goatools/anno/opts.py","file_name":"opts.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"232794733","text":"import pymysql\nfrom neo4j.v1 import GraphDatabase, basic_auth\nfrom katherine import d6_config\nimport os\n\nif __name__ != '__main__':\n os.chdir(os.path.abspath(os.path.dirname(__file__)))\n\n\nd8757_5 = GraphDatabase.driver('bolt://comercialpicazo.com', auth=basic_auth('alejandro', '47exI4'))\nd8757_6 = pymysql.connect(**d6_config)\n\nd6_cursor = d8757_6.cursor(pymysql.cursors.DictCursor)\nd5_session = d8757_5.session()\nr = d6_cursor.execute('select sku, description, modified, created from itzamara.item;')\n\nitems = list()\nitems_sku_d6 = list()\nitems_sku_d5 = list()\nfor item in d6_cursor:\n items.append(item)\n items_sku_d6.append(item['sku'])\n rr = d5_session.run('MERGE (item{sku:{item_sku}}) SET item :itzamara_item, item += {item};',\n {'item_sku': item['sku'], 'item': item})\n\nrr = d5_session.run('match (item:itzamara_item) return item.sku as item_sku;')\nfor rec in rr:\n items_sku_d5.append(rec['item_sku'])\ndeleted = list()\nfor sku in items_sku_d5:\n if sku not in items_sku_d6:\n rr = d5_session.run('match (item{sku:{sku}}) optional match (item)-[rel]-() delete rel, item;', {'sku': sku})\n deleted.append(sku)\n\nfrom pprint import pprint\n\npprint(deleted)\n\nrr = d5_session.run('match (:itzamara_item)-[rel:pack]-(:itzamara_item) delete rel;')\nrr = rr.single()\nd6_cursor.execute('select * from itzamara.item_pack;')\nfor item_pack in d6_cursor:\n rr = d5_session.run('match (item{sku:{item_sku}}) '\n 'match (pack{sku:{pack_sku}}) '\n 'create unique (pack)<-[:pack{quanty:{pack_quanty}}]-(item);',\n {'item_sku': item_pack['item_factor_id'], 'pack_sku': item_pack['item_pack_id'],\n 'pack_quanty': float(item_pack['factor'])})\n rr.single()\nprint('ready')\n","sub_path":"share/itzamara/sync_items_in_dbs.py","file_name":"sync_items_in_dbs.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"266996969","text":"import random\n\n\nclass Wizard:\n def __init__(self, name, level):\n self.level = level\n self.name = name\n\n def attack(self, creature):\n print('The wizard {} attacks {}!'.format(\n self.name,\n creature.name\n ))\n\n my_roll = random.randint(1, 12) * self.level\n # creature_roll = random.randint(1, 12) * creature.level\n creature_roll = creature.get_defensive_roll()\n\n print('My roll: {}'.format(str(my_roll)))\n print('Creature roll: {}'.format(str(creature_roll)))\n\n if my_roll >= creature_roll:\n print('The wizard has triumphed over the {}'.format(creature.name))\n return True\n else:\n print('The wizard has been DEFEATED from a {}!!!'.format(creature.name))\n return False\n\n\nclass Creature:\n def __init__(self, name, level=10):\n self.name = name\n self.level = level\n\n def __repr__(self):\n return 'Creature {}'.format(self.name)\n\n def get_defensive_roll(self):\n return random.randint(1, 12) * self.level\n","sub_path":"actors.py","file_name":"actors.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"59242322","text":"# author: Robin Petit\n\nimport numpy as np\nimport pyomo.environ as pyo\nfrom pyomo.opt import SolverStatus, TerminationCondition\n\nfrom linear import LinearRelaxationSolver\n\nclass DiveAndFixSolver(LinearRelaxationSolver):\n def __init__(self, path, max_depth=np.inf, max_nb_relaxations=np.inf, max_fixes_per_depth=np.inf):\n LinearRelaxationSolver.__init__(self, path)\n self.nb_relaxations = 0\n self.max_depth = max_depth\n self.max_nb_relaxations = max_nb_relaxations\n self.max_fixes_per_depth = max_fixes_per_depth\n\n def solve(self, depth=0):\n if depth >= self.max_depth:\n return None\n if depth == 0:\n super().solve()\n else:\n self.sol = self.opt.solve(self.model)\n status = self.sol.solver.status\n termination_condition = self.sol.solver.termination_condition\n if status == SolverStatus.ok:\n if termination_condition == TerminationCondition.infeasible:\n return None\n elif termination_condition != TerminationCondition.optimal:\n raise ValueError('Unknown status: {}'.format((status, termination_condition)))\n else:\n raise ValueError('Unknown status: {}'.format((status, termination_condition)))\n if self.nb_relaxations >= self.max_nb_relaxations:\n return None\n self.nb_relaxations += 1\n current_x = self.get_x()\n current_y = self.get_y()\n non_binary_xs = np.where(np.logical_and(current_x != 0, current_x != 1))\n non_binary_ys = np.where(np.logical_and(current_y != 0, current_y != 1))\n if len(non_binary_xs[0]) > 0:\n indices = np.argsort(np.minimum(1-current_x[non_binary_xs], current_x[non_binary_xs]))\n i, j, t = non_binary_xs[0][0], non_binary_xs[1][0], non_binary_xs[2][0]\n for argmin in indices[:self.max_fixes_per_depth]:\n i, j, t = non_binary_xs[0][argmin], non_binary_xs[1][argmin], non_binary_xs[2][argmin]\n self.model.x[i+1, j+1, t+1].fix(0 if pyo.value(self.model.x[i+1, j+1, t+1]) < .5 else 1)\n ret = self.solve(depth+1)\n if ret is not None:\n return ret\n self.model.x[i+1, j+1, t+1].unfix()\n if len(non_binary_ys[0]) > 0:\n indices = np.argsort(np.minimum(1-current_y[non_binary_ys], current_y[non_binary_ys]))\n for argmin in indices[:self.max_fixes_per_depth]:\n assert (argmin == indices[0]).all()\n j, t = non_binary_ys[0][argmin], non_binary_ys[1][argmin]\n self.model.y[j+1, t+1].fix(0 if pyo.value(self.model.y[j+1, t+1]) < .5 else 1)\n ret = self.solve(depth+1)\n if ret is not None:\n return ret\n self.model.y[j+1, t+1].unfix()\n if len(non_binary_xs[0]) == len(non_binary_ys[0]) == 0:\n assert termination_condition == TerminationCondition.optimal and status == SolverStatus.ok\n return pyo.value(self.model.obj)\n # D&F might not settle to a solution since variables are only fixed to 0 or 1 depending on\n # the closest value. The other value is not tested\n # Also, if one of (max_nb_relaxations, max_fixes_per_depth, max_depth) is less than np.inf,\n # then it is possible that the optimal fix is not encountered\n # Anyway this is a heuristic and don't make fun of it. At least it's trying.\n return None\n\n","sub_path":"scripts/heuristic.py","file_name":"heuristic.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"267355989","text":"#!/usr/bin/python3\n#this script resort the distance and atomic positions outputed by Calatom, distance \n#has been transfered to nm \n#ponychen\n#20191206\n\nimport sys\n\nfilename = sys.argv[1]\n\nwith open(filename, \"r\") as f:\n lines = f.readlines()\n\nrow = []\nfor i in range(len(lines)):\n row.append(list(map(float,lines[i].split())))\n\nfor i in range(len(row)):\n if row[i][1] > row[i][3]:\n tmp1 = row[i][1]\n tmp2 = row[i][2]\n row[i][1] = row[i][3]\n row[i][2] = row[i][4]\n row[i][3] = tmp1\n row[i][4] = tmp2\n\nwith open(\"sorted.txt\",\"w+\") as f:\n for i in range(len(row)):\n f.write(\"%12.7f %12.7f %12.7f \\n\" % (\\\n row[i][3],row[i][4],row[i][0]/10.0))\n\n","sub_path":"dis_sort.py","file_name":"dis_sort.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"212514031","text":"'''\nprototypedatasrouce.py\n\nCode containing query object as well as methods that allow for queries\n\nauthor: Tony Ngo, Ben Preiss, Cam Brown\ndate: 22 October 2019\nAdapted from code originally written by Jeff Ondich\n'''\n\nimport psycopg2\nimport getpass\nfrom CourseObj import*\n\n\n\n\nclass CourseQuery:\n\t'''\n\t\tobject that when created will contain all criteria from a single user query\n\t'''\n\n\tdef __init__(self, dept, number, name, term, requirements, period):\n\t\tself.courseTerm = term\n\t\tself.courseNumber = number\n\t\tself.courseName = name\n\t\tself.courseDeptTag = dept\n\t\tself.courseRequirements = requirements\n\t\tself.coursePeriod = period\n\t\tself.user = \"ngot\"\n\t\tself.password = \"lamp792corn\"\n\t\tself.connection = self.connect()\n\t\t\n\tdef createCourse(self, courses):\n\t\t'''\n\t\tHelper method that takes in a list of courses in the form of tuples\n\t\tand creates a CourseObj for each course in the list\n\n\t\tPARAMETERS:\n\t\t\tcourses - lists of tuples for courses\n\n\t\tReturns: \n\t\t\ta new list of CourseObj objects\n\t\t'''\n\t\tcourseResults =[]\n\t\tfor course in courses:\n\t\t\tcourseObj = CourseObj(course)\n\t\t\tcourseResults.append(courseObj)\n\t\treturn courseResults\n\t\n\tdef connect(self):\t\n\t\t'''\n\t\tEstablishes a connection to the database with the following credentials:\n\t\t\tuser - username, which is also the name of the database\n\t\t\tpassword - the password for this database on perlman\n\n\t\tReturns: \n\t\t\ta database connection.\n\n\t\tNote: exits if a connection cannot be established.\n\t\t'''\n\n\t\ttry:\n\t\t\tconnection = psycopg2.connect(database= self.user, user=self.user, password=self.password)\n\t\texcept Exception as e:\n\t\t\tprint(\"Connection error: \", e)\n\t\t\texit()\n\t\treturn connection\n\n\t\n\tdef getCourseByNumber(self):\n\t\t'''\n\t\tReturns a list of all coursees with the specified course number.\n\n\t\tPARAMETERS:\n\t\t\tconnection - connection to database\n\n\t\tRETURN:\n\t\t\ta list of course objects with the specified course number.\n\n\t\t'''\n\t\ttry:\n\t\t\tcursor = self.connection.cursor()\n\t\t\tquery = \"SELECT\t* FROM classes WHERE coursenum = \" + str(self.courseNumber) + \" ORDER BY coursename DESC\"\n\t\t\tcursor.execute(query)\n\t\t\tcourses = cursor.fetchall()\n\t\t\tcourseResults = self.createCourse(courses)\n\t\t\treturn courseResults\n\n\t\texcept Exception as e:\n\t\t\tprint (\"Something went wrong when executing the query: \", e)\n\t\t\treturn None\n\n\t\n\n\tdef getCourseByDeptTag(self):\n\t\t'''\n\t\tReturns a list of all of the coursees within the specified subject.\n\n\t\tPARAMETERS:\n\t\t\tconnection - connection to database\n\n\t\tRETURN:\n\t\t\ta list of course objects within the department\n\n\t\t'''\n\t\ttry:\n\t\t\tcursor = self.connection.cursor()\n\t\t\tquery = \"SELECT\t* FROM classes WHERE depttag LIKE '%\" + self.courseDeptTag + \"%' ORDER BY coursename DESC\"\n\t\t\tcursor.execute(query)\n\t\t\tcourses = cursor.fetchall()\n\t\t\tcourseResults = self.createCourse(courses)\n\t\t\treturn courseResults\n\n\t\texcept Exception as e:\n\t\t\tprint (\"Something went wrong when executing the query: \", e)\n\t\t\treturn None\n\n\tdef getCourseByName(self):\n\t\t'''\n\t\t\tReturns a list of all of the coursees the contain the course name from user input.\n\n\t\t\tPARAMETERS:\n\t\t\t\tconnection - connection to database\n\n\t\t\tRETURN:\n\t\t\t\ta list of course objects that contain that string\n\n\t\t\t'''\n\t\ttry:\n\t\t\tcursor = self.connection.cursor()\n\t\t\tquery = \"SELECT\t* FROM classes WHERE coursename LIKE '%\" + self.courseName + \"%' ORDER BY coursename DESC\"\n\t\t\tcursor.execute(query)\n\t\t\tcourses = cursor.fetchall()\n\t\t\tcourseResults = self.createCourse(courses)\n\t\t\treturn courseResults\n\n\n\t\texcept Exception as e:\n\t\t\tprint (\"Something went wrong when executing the query: \", e)\n\t\t\treturn None\n\n\tdef getCourseByPeriod(self):\n\t\t'''\n\t\tReturns a list of all of the coursees during the specified course period.\n\n\t\tPARAMETERS:\n\t\t\tconnection - connection to database\n\n\t\tRETURN:\n\t\t\ta list of course objects during the period\n\n\t\t'''\n\n\tdef getCourseByRequirements(self):\n\t\t'''\n\t\t\tReturns a list of all of the coursees during the specified course period.\n\n\t\t\tPARAMETERS:\n\t\t\t\tconnection - connection to database\n\n\t\t\tRETURN:\n\t\t\t\ta list of course objects that fulfill the requirements\n\n\t\t'''\n\t\ttry:\n\t\t\tcursor = self.connection.cursor()\n\t\t\tquery = \"SELECT\t* FROM classes WHERE reqsFilled LIKE '%\" + self.courseRequirements + \"%' ORDER BY coursename DESC\"\n\t\t\tcursor.execute(query)\n\t\t\tcourses = cursor.fetchall()\n\t\t\tcourseResults = self.createCourse(courses)\n\t\t\treturn courseResults\n\n\t\texcept Exception as e:\n\t\t\tprint(\"Something went wrong when executing the query: \", e)\n\t\t\treturn None\n\n\tdef getCourseByTerm(self):\n\t\t'''\n\t\tReturns a list of all coursees within the specified term.\n\n\t\tPARAMETERS:\n\t\t\tconnection - connection to database\n\n\t\tRETURN:\n\t\t\ta list of course objects within the specified term.\n\n\t\t'''\n\t\ttry:\n\t\t\tcursor = self.connection.cursor()\n\t\t\tquery = \"SELECT\t* FROM classes WHERE termsoffered LIKE '%\" + self.courseTerm + \"%' ORDER BY coursename DESC\"\n\t\t\tcursor.execute(query)\n\t\t\tcourses = cursor.fetchall()\n\t\t\tcourseResults = self.createCourse(courses)\n\t\t\treturn courseResults\n\n\t\texcept Exception as e:\n\t\t\tprint(\"Something went wrong when executing the query: \", e)\n\t\t\treturn None\n\n\tdef masterQuery(self):\n\t\t'''\n\t\tTakes checks all query parameters and creates a query compiled of the intersects of all th queries\n\n\t\tPARAMETERS:\n\t\t\tconnection - connection to database\n\n\t\tRETURN:\n\t\t\ta list of course objects which satifies all criteria\n\n\t\t'''\n\ndef main():\n\t\n\n\t# Initialize query object and test queries\n\tquery = CourseQuery(\"ENGL\", 251, \"Data Structures\", \"Winter 2020\", None, None)\n\n\t#test queries\n\t#results = query.getCourseByName()\n\t#results = query.getCourseByDeptTag()\n\t#results = query.getCourseByTerm()\n\tresults = query.getCourseByNumber()\n\n\tif results is not None:\n\t\tprint(\"Query results: \")\n\t\tfor item in results:\n\t\t\titem.printCourseInfo()\n\n\t# Disconnect from database\n\tquery.connection.close()\n\nmain()\n","sub_path":"backend/updatedDatasource.py","file_name":"updatedDatasource.py","file_ext":"py","file_size_in_byte":5734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"545325361","text":"import os\nimport numpy as np\n\n#from PrepareAndLoadData.prepare_dataset_utils import butter_bandpass_filter\nfrom prepare_dataset_utils import butter_bandpass_filter\n\n\n\n\n\ndef get_data_and_process_it_from_file(get_train_data, path, number_of_gestures=7, number_of_cycles=16, window_size=151,\n size_non_overlap=50):\n examples_datasets, labels_datasets = [], []\n train_or_test_str = \"train\" if get_train_data else \"test\"\n\n participants_directories = os.listdir(path)\n for participant_directory in participants_directories:\n print(\"Preparing data of: \" + participant_directory)\n\n examples_participants, labels_participant = [], []\n for cycle in range(number_of_cycles):\n path_emg = path + \"/\" + participant_directory + \"/\" + \"%s/EMG/gesture_%d_\" % (train_or_test_str, cycle)\n examples, labels = [], []\n for gesture_index in range(1,number_of_gestures+1): # modify if including resting\n examples_to_format = read_emg_from_txt(path_emg, gesture_index)\n # print(np.shape(examples_to_format)) # (604, 16)\n examples_formatted = format_examples(examples_to_format, window_size=window_size, size_non_overlap=size_non_overlap)\n examples.extend(examples_formatted)\n labels.extend(np.ones(len(examples_formatted)) * (gesture_index-1)) # remove '-1' when including resting \n examples_participants.append(examples)\n labels_participant.append(labels)\n\n examples_datasets.append(examples_participants)\n labels_datasets.append(labels_participant)\n\n #print(np.shape(examples_datasets)) # sb * cycle * seg * channel * samples\n #print(np.shape(labels_datasets))\n return examples_datasets, labels_datasets\n\n\n\n\n\ndef get_data_and_process_it_from_file_ours(target_sb, path, number_of_gestures=7, number_of_cycles=16, window_size=151,\n size_non_overlap=50):\n examples_train, labels_train = [], []\n examples_valid, labels_valid = [], []\n examples_test, labels_test = [], []\n # Get the new max and new min from the first cycle of the target subject\n path_emg = path + \"/Participant\" + str(target_sb) + \"/train/EMG/gesture_0_\"\n ref_max, ref_min = [], []\n for gesture_index in range(1,number_of_gestures+1): # modify if including resting\n examples_to_format = read_emg_from_txt(path_emg, gesture_index)\n # (604, 16)\n ref_max.append(np.max(examples_to_format,axis=0))\n ref_min.append(np.min(examples_to_format,axis=0))\n # the shape of ref_max and ref_min: [gesture_n, channel_n]\n\n # Get the training, validation, and testing ready\n # For the target subject, no normalisation is required\n # For other subjects, half of the total cycles are used for training and validation set. Normalisation is required.\n participants_directories = os.listdir(path)\n for participant_directory in participants_directories:\n if participant_directory == 'Participant'+str(target_sb):\n examples_participant, labels_participant = [], []\n # Prepare for the testing data\n for cycle in range(number_of_cycles):\n path_emg = path + \"/Participant\" + str(target_sb) + \"/test/EMG/gesture_%d_\" % (cycle)\n examples, labels = segment_emg_gestures(path_emg, number_of_gestures, window_size, size_non_overlap)\n examples_participant.append(examples)\n labels_participant.append(labels)\n examples_test.append(examples_participant)\n labels_test.append(labels_participant)\n else:\n # Prepare for the training and validation data\n examples_participant_train, labels_participant_train = [], []\n examples_participant_valid, labels_participant_valid = [], []\n for cycle in range(number_of_cycles):\n path_emg_train = path + \"/\" + participant_directory + \"/train/EMG/gesture_%d_\" % (cycle)\n examples, labels = segment_emg_gestures(path_emg_train, number_of_gestures, window_size, size_non_overlap,ref_max=ref_max,ref_min=ref_min) # segmentation before normalisation\n\n examples_participant_train.append(examples)\n labels_participant_train.append(labels)\n\n path_emg_valid = path + \"/\" + participant_directory + \"/test/EMG/gesture_%d_\" % (cycle)\n examples, labels = segment_emg_gestures(path_emg_valid, number_of_gestures, window_size, size_non_overlap,ref_max=ref_max,ref_min=ref_min) # segmentation before normalisation\n examples_participant_valid.append(examples)\n labels_participant_valid.append(labels)\n examples_train.append(examples_participant_train)\n labels_train.append(labels_participant_train)\n examples_valid.append(examples_participant_train)\n labels_valid.append(labels_participant_train)\n #print(np.shape(examples_datasets)) # sb * cycle * seg * channel * samples\n #print(np.shape(labels_datasets))\n return examples_train, labels_train, examples_valid, labels_valid, examples_test, labels_test\n\n\ndef read_data(path, number_of_gestures=7, number_of_cycles=16, window_size=200, size_non_overlap=50):\n print(\"Loading and preparing datasets...\")\n 'Get and process the train data'\n print(\"Taking care of the training data...\")\n list_dataset_train_emg, list_labels_train_emg = get_data_and_process_it_from_file(get_train_data=True, path=path, number_of_gestures=number_of_gestures, number_of_cycles=number_of_cycles, window_size=window_size, size_non_overlap=size_non_overlap)\n np.save(\"Dataset/ours/processed_dataset/RAW_INT_train.npy\", (list_dataset_train_emg, list_labels_train_emg))\n print(\"Finished with the training data...\")\n 'Get and process the test data'\n print(\"Starting with the test data...\")\n list_dataset_train_emg, list_labels_train_emg = get_data_and_process_it_from_file(get_train_data=False, path=path, number_of_gestures=number_of_gestures, number_of_cycles=number_of_cycles, window_size=window_size, size_non_overlap=size_non_overlap)\n np.save(\"Dataset/processed_dataset/RAW_INT_test.npy\", (list_dataset_train_emg, list_labels_train_emg))\n print(\"Finished with the test data\")\n\n\ndef read_data_ours(path, number_of_gestures=7, number_of_cycles=16, window_size=200, size_non_overlap=50):\n target_sb=1\n print(\"Target subject: \", target_sb)\n examples_train, labels_train, examples_valid, labels_valid, examples_test, labels_test = get_data_and_process_it_from_file_ours(target_sb=target_sb, path=path, number_of_gestures=number_of_gestures, number_of_cycles=number_of_cycles, window_size=window_size, size_non_overlap=size_non_overlap)\n\n datapath = \"Dataset/ours/processed_dataset/Participant\"+str(target_sb)\n if not(os.path.exists(datapath)):\n os.makedirs(datapath)\n np.save(datapath+\"/RAW_INT_train.npy\", (examples_train, labels_train))\n np.save(datapath+\"/RAW_INT_valid.npy\", (examples_valid, labels_valid))\n np.save(datapath+\"/RAW_INT_test.npy\", (examples_test, labels_test))\n\n\nif __name__ == '__main__':\n #read_data(path=\"Dataset/Intact_dataset\", number_of_gestures=6,number_of_cycles=3,window_size=50,size_non_overlap=15)\n read_data_ours(path=\"Dataset/Intact_dataset\", number_of_gestures=6,number_of_cycles=3,window_size=50,size_non_overlap=15)\n\n\n","sub_path":"load_raw_data_and_prepare_dataset.py","file_name":"load_raw_data_and_prepare_dataset.py","file_ext":"py","file_size_in_byte":7447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"413160975","text":"# -*- coding: utf-8 -*-\n# coding: utf-8\nimport chardet\nimport xlwt\nimport numpy as np\nimport pandas as pd\nimport os\nimport sys\n\n# stdi, stdo, stde = sys.stdin, sys.stdout, sys.stderr\n# reload(sys)\n# sys.stdin, sys.stdout, sys.stderr = stdi, stdo, stde\n# sys.setdefaultencoding('utf-8')\n\n# 张老师安排,将黄河流域各县的数据整理到一个表格中\n# 第三阶段,添加2000年之前的数据\n\n\n# 输出print内容\nclass Logger(object):\n def __init__(self, filename=\"Default.log\"):\n self.terminal = sys.stdout\n self.log = open(filename, \"a\")\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n\n def flush(self):\n pass\n\n\nprintpath = os.path.abspath(os.path.dirname(__file__))\ntype = sys.getfilesystemencoding()\nsys.stdout = Logger('OutLog_ShanXi_repairQin.txt')\nprint(printpath)\n\n\ndef Findfilename(path, findstr):\n \"\"\"寻找特定文件名\"\"\"\n filenames = os.listdir(path)\n pxlsList = list()\n for i, filename in enumerate(filenames):\n # # 转码\n # filename = filename.decode('gbk')\n findresult = filename.find(findstr)\n if findresult != -1:\n pxlsList.append(filename)\n else:\n continue\n return pxlsList\n\n\ndef is_number(s):\n \"\"\"是否是数字\"\"\"\n if s == '.':\n return True\n try:\n float(s)\n return True\n except ValueError:\n pass\n try:\n import unicodedata\n unicodedata.numeric(s)\n return True\n except (TypeError, ValueError):\n pass\n return False\n\n\ndef GetValueandUnit(pStrVandU):\n \"\"\"拆分出数值和单位\"\"\"\n try:\n filterResult = filter(is_number, pStrVandU)\n number = ''.join(list(filterResult))\n unit = pStrVandU.replace(number, '')\n return float(number), unit\n except:\n return None, None\n\n\ndef Changevalue(pOldValue, pOldUnit, pNeedUnit):\n \"\"\"转换单位\"\"\"\n returnmes = '单位特殊,未能转换!'\n # 不用转换\n if pOldUnit == pNeedUnit:\n return float(pOldValue), '转换成功'\n # * → 万*\n if pNeedUnit == '万' + pOldUnit:\n try:\n newValue = float(pOldValue) / 10000\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # * → 千*\n if pNeedUnit == '千' + pOldUnit:\n try:\n newValue = float(pOldValue) / 1000\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 万* → *\n if pOldUnit == '万' + pNeedUnit:\n try:\n newValue = float(pOldValue) * 10000\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 千* → *\n if pOldUnit == '千' + pNeedUnit:\n try:\n newValue = float(pOldValue) * 1000\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 千* → 万*\n if pOldUnit[0] == '千' and pNeedUnit[0] == '万':\n try:\n newValue = float(pOldValue) / 10\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 千* → 亿*\n if pOldUnit[0] == '千' and pNeedUnit[0] == '亿':\n try:\n newValue = float(pOldValue) / 100000\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 亿* → 万*\n if pOldUnit[0] == '亿' and pNeedUnit[0] == '万':\n try:\n newValue = float(pOldValue)*10000\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 万* → 亿*\n if pOldUnit[0] == '万' and pNeedUnit[0] == '亿':\n try:\n newValue = float(pOldValue)/10000\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 亩 → 公顷\n if pOldUnit == '亩' and pNeedUnit == '公顷':\n try:\n newValue = float(pOldValue)*(1/15)\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 亩 → 千公顷\n if pOldUnit == '亩' and pNeedUnit == '千公顷':\n try:\n newValue = float(pOldValue)*(1/15000)\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 公斤 → 吨\n if pOldUnit == '公斤' and pNeedUnit == '吨':\n try:\n newValue = float(pOldValue)*0.001\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 万亩 → 公顷\n if pOldUnit == '万亩' and pNeedUnit == '公顷':\n try:\n newValue = float(pOldValue)*666.7\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 公顷 → 平方公里\n if pOldUnit == '公顷' and pNeedUnit == '平方公里':\n try:\n newValue = float(pOldValue)*0.01\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n # 万斤 → 吨\n if pOldUnit == '万斤' and pNeedUnit == '吨':\n try:\n newValue = float(pOldValue)*5\n return newValue, '转换成功'\n except:\n return None, '数值转换失败,可能不是个数字,未能转换!'\n return None, returnmes\n\n\n# 以山西省晋城市为例提取的参数\n# 1 能找到的对应参数,key是2000之前的参数名称,value是2000年后的参数名称\nparsDic = {\n '乡镇及街道办': '乡(镇)个数',\n '村民委员会/社区居委会': '村民委员会个数',\n '土地总面积': '行政区域土地面积',\n '生产总值': '国内生产总值',\n '第一产业': '第一产业生产总值',\n '第二产业': '第二产业生产总值',\n '#工业': '工业生产总值',\n '第三产业': '第三产业生产总值',\n '人均地区生产总值': '人均国内生产总值',\n '总户数': '年末总户数',\n '年末总户数': '年末总户数',\n '单位从业人员': '年末单位从业人员数',\n '在岗职工数': '在岗职工数',\n '全社会固定资产投资': '全社会固定资产投资',\n '#城镇固定资产投资': '城镇固定资产投资',\n '一般预算收入': '地方财政一般预算收入',\n '一般预算支出': '地方财政一般预算支出',\n '城乡居民储蓄存款余额': '居民储蓄存款余额',\n '#乡村户数': '乡村户数',\n '#乡村人口数': '乡村人口',\n '#乡村人口': '乡村人口',\n '#农业人口数': '乡村人口',\n '#农业人口': '乡村人口',\n '#农林牧渔业': '农林牧渔业从业人员数',\n '农林牧渔及服务业总产值': '农林牧渔服务业总产值',\n '#农业总产值': '农业产值',\n '#林业总产值': '林业产值',\n '#牧业总产值': '牧业产值',\n '#渔业总产值': '渔业产值',\n '#农林牧渔服务业': '农林牧渔服务业总产值',\n '耕地面积': '耕地面积',\n '有效灌溉面积': '有效灌溉面积',\n '农村用电量': '农村用电量',\n '农用化肥施用折纯量': '化肥使用量(折纯量)',\n '农用化肥施用量': '化肥使用量(折纯量)',\n '农用化肥使用折纯量': '化肥使用量(折纯量)',\n '农用塑料薄膜使用量': '农用塑料薄膜使用量',\n '#地膜': '农用地膜使用量',\n '农药使用量': '农药使用量',\n '总播种面积': '农作物播种面积',\n '粮食作物播种面积': '粮食作物播种面积',\n '粮食总产量': '粮食产量',\n '油料播种面积': '油料播种面积',\n '油料总产量': '油料产量',\n '棉花播种面积': '棉花播种面积',\n '棉花总产量': '棉花产量',\n '蔬菜种植面积': '蔬菜播种面积',\n '蔬菜总产量': '蔬菜产量',\n '大牲畜年末存栏': '大牲畜年末存栏',\n '大牲畜年末头数': '大牲畜年末存栏',\n '肉类总产量': '肉类总产量',\n '奶类总产量': '奶类产量',\n '禽蛋总产量': '禽蛋产量',\n '水产品产量': '水产品产量',\n '水果总产量': '园林水果产量',\n '当年造林面积': '当年造林面积',\n '城镇居民人均可支配收入': '城镇居民人均可支配收入',\n '农村居民人均纯收入': '农村居民人均纯收入',\n '公路长度': '公路里程',\n '社会消费品零售总额': '社会消费品零售总额',\n '普通中学在校学生数': '普通中学在校学生数',\n '小学在校学生数': '小学在校学生数',\n '规模以上工业企业数': '工业企业数',\n '工业企业数': '工业企业数',\n '规模以上工业总产值': '工业总产值',\n '工业总产值': '工业总产值',\n '工业增加值(现价)': '工业生产总值',\n '工业增加值': '工业生产总值',\n '工业增加值(生产法)': '��业生产总值',\n '床位数': '医院、卫生院床位数',\n '社会福利院床位数(床)': '医院、卫生院床位数',\n '总人口': '年末总人口',\n '年末常住人口': '年末总人口',\n '乡村从业人员数': '乡村从业人员数',\n '农业机械总动力': '农业机械总动力',\n '家禽年末存栏数': '家禽存栏',\n '果园面积': '果园面积',\n '水田': '水田面积',\n '#水田': '水田面积',\n '#非农业人口': '城镇人口',\n '#水浇地': '水浇地面积',\n '社会福利院数(个)': '各种社会福利收养性单位数',\n '旱涝保收面积': '旱涝保收面积',\n '#内资企业': '内资企业',\n '内资企业': '内资企业',\n '#港澳台商投资企业': '港、澳、台商投资企业',\n '港澳台商投资企业': '港、澳、台商投资企业',\n '#外商投资企业': '外商投资企业',\n '外商投资企业': '外商投资企业',\n '农林牧渔业从业人数': '农林牧渔业从业人员数',\n '#农林牧渔业从业人数': '农林牧渔业从业人员数',\n '#农林牧渔业从业人': '农林牧渔业从业人员数',\n '森林面积': '森林面积',\n '瓜类面积': '瓜果种植面积',\n '社会从业人数': '',\n '在岗职工平均工资': '',\n '单位GDP能耗': '',\n '单位产值能耗': '单位GDP能耗',\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 '单位GDP电耗': '',\n '建成区绿地覆盖率': '',\n '建成区绿化覆盖率': '',\n '企业数': '',\n '花椒产量': '',\n '工业企业产品销售收入': '',\n '工业产品销售收入': '工业企业产品销售收入',\n '中药材面积': '',\n '中药材产量': '',\n '#退耕造林面积': '',\n '森林覆盖率': '',\n '瓜类总产量': '',\n '人均公共绿地面积': '',\n '#国有经济': '',\n '##国有经济': '#国有经济',\n '#国有': '#国有经济',\n '#集体经济': '',\n '##集体经济': '#集体经济',\n '#集体': '#集体经济',\n '#其他经济类型': '',\n '#其他': '#其他经济类型',\n '#原油': '',\n '#原油加工量': '',\n '土地调查面积': '',\n '农用地': '',\n '建设用地': '',\n '城镇从业人员': '',\n '#国有单位': '',\n '#集体单位': '',\n '#其他单位': '',\n '#私营和个体': '',\n '乡村劳动力': '',\n '#国有及国有控股企业': '',\n '#集体企业': '',\n '枸杞面积': '',\n '枸杞总产量': '',\n '内资企业数': '',\n '#内资企业数': '内资企业数',\n '港澳台投资企业数': '',\n '#港澳台投资企业数': '港澳台投资企业数',\n '#外商投资企业数': '',\n '#国有企业': '',\n '农牧民人均纯收入': '',\n '甜菜总产量': '',\n '草原总面积': '',\n '#天然气': '',\n '常用耕地面积': '',\n '人均公园绿地面积': '',\n '#化学肥料': '',\n '#化肥': '#化学肥料',\n '#山地': '',\n '#川地': '',\n '#塬地': '',\n}\n\n# 2 参数对应单位\nparsUni = {\n '乡镇及街道办': '个',\n '村民委员会/社区居委会': '个',\n '土地总面积': '平方公里',\n '生产总值': '万元',\n '第一产业': '万元',\n '第二产业': '万元',\n '#工业': '万元',\n '第三产业': '万元',\n '人均地区生产总值': '元/人',\n '总户数': '户',\n '年末总户数': '户',\n '单位从业人员': '人',\n '在岗职工数': '人',\n '全社会固定资产投资': '万元',\n '#城镇固定资产投资': '万元',\n '一般预算收入': '万元',\n '一般预算支出': '万元',\n '城乡居民储蓄存款余额': '万元',\n '#乡村户数': '户',\n '#乡村人口数': '万人',\n '#乡村人口': '万人',\n '#农业人口数': '万人',\n '#农业人口': '万人',\n '#农林牧渔业': '人',\n '农林牧渔及服务业总产值': '万元',\n '#农业总产值': '万元',\n '#林业总产值': '万元',\n '#牧业总产值': '万元',\n '#渔业总产值': '万元',\n '#农林牧渔服务业': '万元',\n '耕地面积': '公顷',\n '有效灌溉面积': '公顷',\n '农村用电量': '万千瓦时',\n '农用化肥施用折纯量': '吨',\n '农用化肥施用量': '吨',\n '农用化肥使用折纯量': '吨',\n '农用塑料薄膜使用量': '吨',\n '#地膜': '吨',\n '农药使用量': '吨',\n '总播种面积': '公顷',\n '粮食作物播种面积': '公顷',\n '粮食总产量': '吨',\n '油料播种面积': '公顷',\n '油料总产量': '吨',\n '棉花播种面积': '公顷',\n '棉花总产量': '吨',\n '蔬菜种植面积': '公顷',\n '蔬菜总产量': '吨',\n '大牲畜年末存栏': '头',\n '大牲畜年末头数': '头',\n '肉类总产量': '吨',\n '奶类总产量': '吨',\n '禽蛋总产量': '吨',\n '水产品产量': '吨',\n '水果总产量': '吨',\n '当年造林面积': '公顷',\n '城镇居民人均可支配收入': '元',\n '农村居民人均纯收入': '元',\n '公路长度': '公里',\n '社会消费品零售总额': '万元',\n '普通中学在校学生数': '人',\n '小学在校学生数': '人',\n '规模以上工业企业数': '个',\n '工业企业数': '个',\n '规模以上工业总产值': '万元',\n '工业总产值': '万元',\n '工业增加值(现价)': '万元',\n '工业增加值': '万元',\n '工业增加值(生产法)': '万元',\n '床位数': '张',\n '社会福利院床位数(床)': '张',\n '总人口': '万人',\n '年末常住人口': '万人',\n '乡村从业人员数': '人',\n '农业机械总动力': '万千瓦',\n '家禽年末存栏数': '万只',\n '果园面积': '公顷',\n '水田': '公顷',\n '#水田': '公顷',\n '#非农业人口': '万人',\n '#水浇地': '公顷',\n '社会福利院数(个)': '个',\n '旱涝保收面积': '公顷',\n '#内资企业': '万元',\n '内资企业': '万元',\n '#港澳台商投资企业': '万元',\n '港澳台商投资企业': '万元',\n '#外商投资企业': '万元',\n '外商投资企业': '万元',\n '农林牧渔业从业人数': '人',\n '#农林牧渔业从业人数': '人',\n '#农林牧渔业从业人': '人',\n '森林面积': '公顷',\n '瓜类面积': '公顷',\n '社会从业人数': '万人',\n '在岗职工平均工资': '元',\n '单位GDP能耗': '吨标准煤/万元',\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 '单位GDP电耗': '千瓦时/万元',\n '建成区绿地覆盖率': '%',\n '建成区绿化覆盖率': '%',\n '企业数': '个',\n '花椒产量': '吨',\n '工业企业产品销售收入': '万元',\n '工业产品销售收入': '万元',\n '中药材面积': '亩',\n '中药材产量': '公斤',\n '#退耕造林面积': '亩',\n '森林覆盖率': '%',\n '瓜类总产量': '吨',\n '人均公共绿地面积': '平方米',\n '#国有经济': '亿元',\n '##国有经济': '亿元',\n '#国有': '亿元',\n '#集体经济': '亿元',\n '##集体经济': '亿元',\n '#集体': '万元',\n '#其他经济类型': '亿元',\n '#其他': '万元',\n '#原油': '万吨',\n '#原油加工量': '吨',\n '土地调查面积': '万公顷',\n '农用地': '万公顷',\n '建设用地': '万公顷',\n '城镇从业人员': '人',\n '#国有单位': '人',\n '#集体单位': '人',\n '#其他单位': '人',\n '#私营和个体': '人',\n '乡村劳动力': '人',\n '#国有及国有控股企业': '万元',\n '#集体企业': '万元',\n '枸杞面积': '公顷',\n '枸杞总产量': '吨',\n '内资企业数': '个',\n '#内资企业数': '个',\n '港澳台投资企业数': '个',\n '#港澳台投资企业数': '个',\n '#外商投资企业数': '个',\n '#国有企业': '千元',\n '农牧民人均纯收入': '元',\n '甜菜总产量': '吨',\n '草原总面积': '千公顷',\n '#天然气': '万立方米',\n '常用耕地面积': '千公顷',\n '人均公园绿地面积': '平方米',\n '#化学肥料': '吨',\n '#化肥': '吨',\n '#山地': '万亩',\n '#川地': '万亩',\n '#塬地': '万亩',\n}\n\n\n\n# shanxi\npath = 'D:\\\\OneDrive\\\\SharedFile\\\\EXCEL 数据处理\\\\EXCELwork201908_linux_2ED\\\\Data_Shanxi'\nallCountryData = pd.read_excel(\n 'C:\\\\Users\\\\thril\\\\Desktop\\\\OutputAll_forQin.xlsx', sheet_name=\"Sheet1\")\nonetoN_Code = pd.read_excel(\n 'D:\\\\OneDrive\\\\SharedFile\\\\EXCEL 数据处理\\\\EXCELwork201908_linux_2ED\\\\OnetoN_Code_2ED.xlsx', sheet_name=\"Code\")\n\n\nfindresultSP = allCountryData[allCountryData[\"Province_name\"] == '山西省']\n\n\n# 循环每个县\nfor tIndex, tRow in findresultSP.iterrows():\n countryName = tRow[\"County_name\"]\n thisCountryshortName = countryName[0:len(countryName) - 1]\n thisCountryCity = tRow[\"City_name\"]\n thisCountryCityshortName = thisCountryCity[0:len(thisCountryCity) - 1]\n getCityFilename = Findfilename(path, thisCountryCityshortName)\n if len(getCityFilename) == 0:\n continue\n # 找到文件\n print('#region 开始整理:'+thisCountryCity+'_'+countryName)\n if not pd.isnull(getCityFilename[0]):\n # thisSheet = pd.read_excel((path + \"\\\\\" + getCityFilename[0]).encode('gbk'))\n thisSheet = pd.read_excel((path + \"\\\\\" + getCityFilename[0]))\n countryPars = thisSheet.iloc[0][5:thisSheet.columns.size]\n countryParsUnit = thisSheet.iloc[2][5:thisSheet.columns.size]\n # 循环这个市的每一个行(很多县)\n for oIndex, oRow in thisSheet.iterrows():\n ocountryName = oRow['Name-of-District-and-County']\n # 筛选出目标县的行数据\n if oIndex > 4 and countryName == ocountryName:\n timeYear = str(oRow['Temporal_Period_Begin'])[0:4]\n # 循环每个参数\n for num in range(0, countryPars.size):\n pParStr = countryPars[num]\n # 是需要的参数\n if pParStr in parsDic.keys():\n pParIndex = countryPars.index[num]\n realParField = parsDic[pParStr] + '_' + timeYear\n realParUnit = parsUni[pParStr]\n pUnit = countryParsUnit[num]\n findresultSP = pUnit.find('以前为')\n if findresultSP != -1:\n print('Warning! '+thisCountryCity+'的参数:' + pParStr +\n '的单位是:'+pUnit+';处理数据时CELL中没有标明单位的已经按照括号之前的单位处理,使用前请注意!')\n pValue = thisSheet.loc[oIndex, pParIndex]\n if pd.isnull(pValue):\n continue\n if pValue == '':\n continue\n if pValue == ' ':\n continue\n if pValue == '-':\n continue\n if pValue is None:\n continue\n # 2000年前特有的参数\n if parsDic[pParStr] == '':\n realParField = pParStr + '_' + timeYear\n # 需要新建表头\n if realParField not in allCountryData.columns:\n allCountryData[realParField] = None\n # ---------------\n # 对城区代码进行处理\n if thisCountryCity in onetoN_Code.columns and ocountryName == onetoN_Code.loc[0, thisCountryCity]:\n thisCityNName = onetoN_Code.loc[1:,\n thisCountryCity]\n urbanValue = 0\n for nName in thisCityNName:\n nChangeValue = None\n nChangeMes = None\n if pd.isnull(nName):\n continue\n nfindresult = thisSheet[(thisSheet[\"Name-of-District-and-County\"] == nName) & (\n thisSheet[\"Temporal_Period_Begin\"] == oRow['Temporal_Period_Begin'])]\n if nfindresult.empty:\n continue\n nValue = nfindresult[countryPars.index[num]].values[0]\n # 单位时间段内不统一,是数字的特殊处理(直接跳出循环),不是数字的交给下文一样处理(不用跳出循环)\n if findresultSP != -1:\n if is_number(str(nValue)):\n # 例子:公顷(1992年及以前为万亩)\n # 元数据描述不一定可信,此处的处理方式为,得到的值为数字,则直接按照括号前的单位处理,如果是“值+单位”的形式,则正常处理\n # pbeforeYear1st = pUnit.split('年')[0]\n # pbeforeYear=pbeforeYear1st[len(pbeforeYear1st)-4:len(pbeforeYear1st)]\n # pbeforeUnit1st = pUnit.split('及以前为')[1]\n # pbeforeUnit = pbeforeUnit1st.split(')')[0]\n # if pbeforeUnit == pbeforeUnit1st:\n # pbeforeUnit=pbeforeUnit1st.split(')')[0]\n pUnitshort = pUnit.split('(')[0]\n if pUnitshort == pUnit:\n pUnitshort = pUnit.split('(')[0]\n if pUnitshort == pUnit:\n print('Error!在计算'+thisCountryCity+ocountryName+'【城区】的_'+pParStr + '_时,出现问题,寻找到的' + str(\n nName) + '区县' + timeYear + '年的单位有误! 忽略这个值,请检查!')\n print('-------------------------')\n else:\n nChangeValue, nChangeMes = Changevalue(\n nValue, pUnitshort, realParUnit)\n if nChangeMes == '转换成功':\n try:\n urbanValue = urbanValue + nChangeValue\n except:\n print('Error!在计算'+thisCountryCity+ocountryName+'【城区】的_'+pParStr + '_时,出现问题,寻找到的' + str(\n nName) + '区县' + timeYear + '年的值有误! 忽略这个值,请检查!')\n print(\n '-------------------------')\n else:\n print('Error!在计算'+thisCountryCity+ocountryName+'【城区】的_'+pParStr +\n '_时,出现问题,寻找到的' + str(nName) + '区县' + timeYear + '年的值有误!')\n print('单位未能转换,请手动转换!具体信息如下:')\n print(nChangeMes)\n print('得到的单位:'+pUnitshort)\n print(\n '应该的单位:' + str(realParUnit))\n print(\n '+++++++++++++++++++++++++')\n continue\n # 不是数字,拆分,不需要考虑原本单位\n if not is_number(str(nValue)):\n # 拆分开值和单位\n nsplitValue, nsplitUnit = GetValueandUnit(\n str(nValue))\n if pd.isnull(nsplitValue):\n continue\n # 转换单位\n nChangeValue, nChangeMes = Changevalue(\n nsplitValue, nsplitUnit, realParUnit)\n if nChangeMes == '转换成功':\n try:\n urbanValue = urbanValue + nChangeValue\n except:\n print('Error!在计算'+thisCountryCity+ocountryName+'【城区】的_'+pParStr + '_时,出现问题,寻找到的' + str(\n nName) + '区县' + timeYear + '年的值有误! 忽略这个值,请检查!')\n print('-------------------------')\n else:\n print('Error!在计算'+thisCountryCity+ocountryName+'【城区】的_'+pParStr +\n '_时,出现问题,寻找到的' + str(nName) + '区县' + timeYear + '年的值有误!')\n print('单位未能转换,请手动转换!具体信息如下:')\n print(nChangeMes)\n print('得到的单位:'+nsplitUnit)\n print('应该的单位:' + str(realParUnit))\n print('+++++++++++++++++++++++++')\n # 是数字,再判断要不要转换单位\n else:\n # 不用转换单位\n if realParUnit == pUnit:\n try:\n urbanValue = urbanValue + \\\n float(nValue)\n except:\n print('Error!在计算'+thisCountryCity+ocountryName+'【城区】的_'+pParStr + '_时,出现问题,寻找到的' + str(\n nName) + '区县' + timeYear + '年的值有误! 忽略这个值,请检查!')\n print('-------------------------')\n # 转换单位\n else:\n nChangeValue, nChangeMes = Changevalue(\n nValue, pUnit, realParUnit)\n if nChangeMes == '转换成功':\n try:\n urbanValue = urbanValue + nChangeValue\n except:\n print('Error!在计算'+thisCountryCity+ocountryName+'【城区】的_'+pParStr + '_时,出现问题,寻找到的' + str(\n nName) + '区县' + timeYear + '年的值有误,忽略这个值,请检查!')\n print(\n '-------------------------')\n else:\n print('Error!在计算'+thisCountryCity+ocountryName+'【城区】的_'+pParStr +\n '_时,出现问题,寻找到的' + str(nName) + '区县' + timeYear + '年的值有误!')\n print('单位未能转换,请手动转换!具体信息如下:')\n print(nChangeMes)\n print(\n '得到的单位:'+pUnit)\n print('应该的单位:' + str(realParUnit))\n print('+++++++++++++++++++++++++')\n if urbanValue != 0 and pd.isnull(allCountryData.loc[tIndex, realParField]):\n allCountryData.loc[tIndex,\n realParField] = urbanValue\n continue\n # ---------------\n # 处理普通区县\n pChangeValue = None\n pChangeMes = None\n # 单位时间段内不统一,是数字的特殊处理(直接跳出循环),不是数字的交给下文一样处理(不用跳出循环)\n if findresultSP != -1:\n if is_number(str(pValue)):\n # 例子:公顷(1992年及以前为万亩)\n # 元数据描述不一定可信,此处的处理方式为,得到的值为数字,则直接按照括号前的单位处理,如果是“值+单位”的形式,则正常处理\n # pbeforeYear1st = pUnit.split('年')[0]\n # pbeforeYear=pbeforeYear1st[len(pbeforeYear1st)-4:len(pbeforeYear1st)]\n # pbeforeUnit1st = pUnit.split('以前为')[1]\n # pbeforeUnit = pbeforeUnit1st.split(')')[0]\n # if pbeforeUnit == pbeforeUnit1st:\n # pbeforeUnit=pbeforeUnit1st.split(')')[0]\n pUnitshort = pUnit.split('(')[0]\n if pUnitshort == pUnit:\n pUnitshort = pUnit.split('(')[0]\n if pUnitshort == pUnit:\n print('Error!在计算' + thisCountryCity + ocountryName + '的_' +\n pParStr + '_时,出现问题,寻找到的' + timeYear + '年的单位有误,忽略这个值,请检查!')\n print('-------------------------')\n else:\n pChangeValue, pChangeMes = Changevalue(\n pValue, pUnitshort, realParUnit)\n if pChangeMes == '转换成功':\n try:\n if pd.isnull(allCountryData.loc[tIndex, realParField]):\n allCountryData.loc[tIndex,\n realParField] = pChangeValue\n except:\n print('Error!在计算'+thisCountryCity+ocountryName+'的_'+pParStr +\n '_时,出现问题,寻找到的' + timeYear + '年的值有误,忽略这个值,请检查!')\n print('-------------------------')\n else:\n print('Error!在计算'+thisCountryCity+ocountryName+'的_' +\n pParStr + '_时,出现问题,寻找到的' + timeYear + '年的值有误!')\n print('单位未能转换,请手动转换!具体信息如下:')\n print(pChangeMes)\n print('得到的单位:'+pUnitshort)\n print('应该的单位:' + str(realParUnit))\n print('+++++++++++++++++++++++++')\n continue\n # 不是数字,拆分,不需要考虑原本单位\n if not is_number(str(pValue)):\n # 拆分开值和单位\n nsplitValue, nsplitUnit = GetValueandUnit(\n str(pValue))\n if pd.isnull(nsplitValue):\n continue\n # 转换单位\n pChangeValue, pChangeMes = Changevalue(\n nsplitValue, nsplitUnit, realParUnit)\n if pChangeMes == '转换成功':\n try:\n if pd.isnull(allCountryData.loc[tIndex, realParField]):\n allCountryData.loc[tIndex,\n realParField] = pChangeValue\n except:\n print('Error!在计算'+thisCountryCity+ocountryName+'的_'+pParStr +\n '_时,出现问题,寻找到的' + timeYear + '年的值有误,忽略这个值,请检查!')\n print('-------------------------')\n else:\n print('Error!在计算'+thisCountryCity+ocountryName+'的_' +\n pParStr + '_时,出现问题,寻找到的' + timeYear + '年的值有误!')\n print('单位未能转换,请手动转换!具体信息如下:')\n print(pChangeMes)\n print('得到的单位:'+nsplitUnit)\n print('应该的单位:' + str(realParUnit))\n print('+++++++++++++++++++++++++')\n # 是数字,再判断要不要转换单位\n else:\n # 不用转换单位\n if realParUnit == pUnit:\n try:\n if pd.isnull(allCountryData.loc[tIndex, realParField]):\n allCountryData.loc[tIndex,\n realParField] = pValue\n except:\n print('Error!在计算'+thisCountryCity+ocountryName+'的_'+pParStr +\n '_时,出现问题,寻找到的' + timeYear + '年的值有误,忽略这个值,请检查!')\n print('-------------------------')\n # 转换单位\n else:\n pChangeValue, pChangeMes = Changevalue(\n pValue, pUnit, realParUnit)\n if pChangeMes == '转换成功':\n try:\n if pd.isnull(allCountryData.loc[tIndex, realParField]):\n allCountryData.loc[tIndex,\n realParField] = pChangeValue\n except:\n print('在计算'+thisCountryCity+ocountryName+'的_'+pParStr +\n '_时,出现问题,寻找到的' + timeYear + '年的值有误,忽略这个值,请检查!')\n print('-------------------------')\n else:\n print('Error!在计算'+thisCountryCity+ocountryName+'的_' +\n pParStr + '_时,出现问题,寻找到的' + timeYear + '年的值有误!')\n print('单位未能转换,请手动转换!具体信息如下:')\n print(pChangeMes)\n print('得到的单位:'+pUnit)\n print('应该的单位:' + str(realParUnit))\n print('+++++++++++++++++++++++++')\n print('##################################################')\n print('#endregion')\nallCountryData.to_excel(\n 'D:\\\\OneDrive\\\\SharedFile\\\\EXCEL 数据处理\\\\EXCELwork201908_linux_2ED\\\\AfterSX_repairQin.xlsx', encoding='gbk')\nprint('Already Finish Work! Good! THRILLER柠檬!')\n","sub_path":"Excel_Pandas/YR_StatisticsData/Repair_Qin_YR_AddBefore2000_ShanXi.py","file_name":"Repair_Qin_YR_AddBefore2000_ShanXi.py","file_ext":"py","file_size_in_byte":40321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"276368612","text":"class Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n # return sum([min(costs[i][0], costs[i][1])] for i in range(len(costs)))\n \n N = len(costs)/2\n \n difference = [(abs(cost[0]-cost[1]),i) for i,cost in enumerate(costs)]\n \n difference.sort(key=lambda x: x[0], reverse=True)\n # print(difference)\n \n cityA = []\n cityB = []\n \n for diff in difference:\n idx = diff[1]\n cost = costs[idx] \n \n if cost[0] Import > Mabinogi Mesh Group (.pmg)\",\n \"description\": \"Imports a Mabinogi Mesh Group file\",\n \"warning\": \"\",\n \"support\": \"TESTING\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"\",\n \"category\": \"Import\"\n}\n\nimport os\nimport struct\n\nimport bpy\nimport mathutils\nfrom bpy_extras.image_utils import load_image\n\nmaterial_dict = None\n\nclass Vertex:\n x,y,z = 0,0,0 # axis\n nx,ny,nz = 0,0,0 # normals\n rgba = 0 # color\n u,v = 0,0 # uv\n\nclass Skin:\n n = 0\n a = 0\n weight = 1.0\n b = 1\n \nclass MabinogiMesh:\n bone_name = \"\"\n mesh_name = \"\"\n texture_name = \"\"\n MinorMatrix = [[]*4 for i in range(4)]\n MajorMatrix = [[]*4 for i in range(4)]\n partNo = 0\n isAnimated = 0\n faceVertexCount = 0\n faceCount = 0\n stripFaceVertexCount = 0\n stripFaceCount = 0\n vertCount = 0\n skinCount = 0\n physicsCount = 0\n vertexList = list()\n stripVertexList = list()\n vertexArray = list()\n skinArray = list()\n physicsArray = list()\n morphFrameSize = 0\n morphFrameCount = 0\n morphFrames = \"\" # placeholder, not used\n\ndef load_matrix4x4(file):\n m = mathutils.Matrix()\n for n in range(4):\n m[n][0:4] = struct.unpack(\"<4f\", file.read(16))\n return m\n\ndef save_matrix4x4(file, m):\n for n in range(4):\n [file.write(struct.pack(\" 0:\n sel_ob = context.selected_objects[0]\n if type(sel_ob.data) == bpy.types.Armature:\n armature = sel_ob.data\n eb = armature.bones\n for i in range(len(eb)):\n bone_id = eb[i].name[eb[i].name.index('__')+3:]\n edit_bones[bone_id] = eb[i]\n else:\n # todo: deselect\n sel_ob.select_set(False)\n print(\"Selected object isn't armature\")\n sel_ob = None\n scn = context.scene\n prev_ob = None\n import_list = []\n\n#Add to blender\n print(\"---Add to blender---\")\n\n for sgi in range(len(pm_subgroups)):\n pm = pm_subgroups[sgi]\n if prev_ob is not None:\n prev_ob.select_set(False)\n prev_ob = None\n\n for i in range(len(pm)):\n #Add to blender\n print(\"adding mesh\", pm[i].mesh_name)\n bmesh = bpy.data.meshes.new(pm[i].mesh_name)\n\n # 頂点を設定\n bmesh.vertices.add(pm[i].vertCount)\n for v in range(pm[i].vertCount):\n bmesh.vertices[v].co = (pm[i].vertexArray[v].x, pm[i].vertexArray[v].y, pm[i].vertexArray[v].z)\n\n # ポリゴンを設定\n bmesh.polygons.add(pm[i].faceCount)\n for v in range(pm[i].faceCount):\n bmesh.polygons[v].loop_start = v*3\n bmesh.polygons[v].loop_total = 3\n\n # ループを設定\n bmesh.loops.add(pm[i].faceVertexCount)\n for v in range(pm[i].faceVertexCount):\n bmesh.loops[v].vertex_index = pm[i].vertexList[v]\n\n # マテリアルを設定\n name = pm[i].texture_name\n if name not in bpy.data.materials:\n print(\"-ADD MATERIAL-\", name)\n material = setup_material(name,filename)\n else:\n print(\"-REF MATERIAL-\", name)\n material = bpy.data.materials[name]\n\n bmesh.materials.append(material)\n\n # UVを設定\n bmesh.uv_layers.new(name=\"uv0\")\n uvl = bmesh.uv_layers.active.data[:]\n for v in range(pm[i].faceVertexCount):\n idx = pm[i].vertexList[v]\n uvl[v].uv = (pm[i].vertexArray[idx].u, 1-pm[i].vertexArray[idx].v)\n\n bmesh.validate()\n bmesh.update()\n\n ob = bpy.data.objects.new(pm[i].mesh_name + \"_subgroup\" + str(sgi), bmesh)\n (vector, rot, scale) = pm[i].MinorMatrix.decompose()\n #ob.location = rot @ vector\n if sel_ob is not None:\n ob.parent = sel_ob\n ob.parent_type = 'OBJECT'\n bone_M = edit_bones[pm[i].bone_name].matrix_local * bone_space.inverted()\n ob.matrix_world = bone_M * pm[i].MinorMatrix\n else:\n ob.matrix_world = pm[i].MajorMatrix\n scn.collection.objects.link(ob)\n\n #add skins\n skinList = list()\n for s in pm[i].skinArray:\n skinList += (s.n,)\n vgroup = ob.vertex_groups.new()\n vgroup.name = \"_\" + pm[i].bone_name\n vgroup.add(pm[i].vertexList,1.0,'REPLACE')\n if armature is not None:\n bones = dict()\n for bone in armature.bones:\n bone_name = bone.name[bone.name.index('__')+3:]\n bones[bone_name] = bone\n if pm[i].bone_name in bones:\n vgroup.name = bones[pm[i].bone_name].name\n #bone = armature.bones.get('_' + pm[i].bone_name)\n #if bone is None: bone = armature.bones.get('-' + pm[i].bone_name)\n #if bone is not None:\n # vgroup.name = bone.name\n ob.select_set(True)\n if prev_ob is not None: prev_ob.select_set(True)\n\n bpy.context.view_layer.objects.active = ob\n bpy.ops.object.join()\n\n### オブジェクトのクリーンナップ\n# bpy.ops.object.mode_set(mode='EDIT')\n# bpy.ops.mesh.remove_doubles(threshold=0.1)\n# bpy.ops.object.mode_set(mode='OBJECT')\n\n prev_ob = ob\n\n # add armature modifiers\n for v in prev_ob.vertex_groups:\n m = prev_ob.modifiers.new(v.name, 'ARMATURE')\n m.object = sel_ob\n m.vertex_group = v.name\n\n import_list.append(ob)\n\n file.close()\n\n## インポートしたオブジェクトを選択する\n for in_ob in import_list:\n in_ob.select_set(True)\n\n if addon_prefs.adjust_sw == True :\n bpy.ops.object.origin_set(type='ORIGIN_CURSOR')\n bpy.ops.transform.resize(value=(0.01,0.01,0.01))\n bpy.ops.transform.rotate(value=-1.5708, orient_axis='X')\n bpy.ops.transform.mirror(constraint_axis=(True, False, False))\n bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)\n\n bpy.ops.object.parent_set(type='OBJECT', keep_transform=True)\n\n for in_ob in import_list:\n in_ob.select_set(False)\n\n\n# basename_without_ext = os.path.splitext(os.path.basename(filename))[0]\n\n\nfrom bpy.props import StringProperty,BoolProperty\n\n#---------------------------------------------------------\n# オペレータークラス\n#---------------------------------------------------------\nclass MABINOGI_OT_ImportPmg(bpy.types.Operator):\n\n bl_idname= \"import.pmg\"\n bl_label= \"Import PMG\"\n bl_description= \"Import a Mabinogi Mesh Group file\"\n bl_options= {'REGISTER', 'UNDO'}\n\n filepath : StringProperty(name=\"File Path\", description=\"Filepath used for importing the PMG file\", maxlen=1024, default=\"\")\n \n filter_glob : StringProperty(\n default = \"*.pmg\",\n options = {'HIDDEN'},\n )\n \n def execute(self, context):\n load_pmg(self.filepath,\n context)\n\n return {'FINISHED'}\n\n def invoke(self, context, event):\n wm= context.window_manager\n wm.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\n\n#---------------------------------------------------------\n# プリファレンス\n#---------------------------------------------------------\nclass MABINOGI_Import_prefs(bpy.types.AddonPreferences):\n bl_idname = __name__\n materials_path : StringProperty(\n name=\"Path to materials:\",\n subtype='DIR_PATH'\n )\n\n adjust_sw : BoolProperty(\n name=\"Adjust\",\n default=False\n )\n\n\n def draw(self, context):\n layout = self.layout\n layout.label(text=\"Import PMG preferences\")\n layout.prop(self, \"materials_path\")\n layout.prop(self, \"adjust_sw\")\n\n\n#---------------------------------------------------------\n# メニュー\n#---------------------------------------------------------\ndef menu_func_mabinogi_pmg(self, context):\n self.layout.separator()\n self.layout.operator(MABINOGI_OT_ImportPmg.bl_idname, text=\"Mabinogi Mesh Group (.pmg)\")\n\n# Blenderに登録するクラス\nclasses = [\n MABINOGI_OT_ImportPmg,\n MABINOGI_Import_prefs,\n]\n\ndef register():\n print(\"Enable Mabinogi\")\n global material_dict\n material_dict = None\n\n for c in classes:\n bpy.utils.register_class(c)\n\n bpy.types.TOPBAR_MT_file_import.append(menu_func_mabinogi_pmg)\n\n\ndef unregister():\n print(\"Disable Mabinogi\")\n\n for c in classes:\n bpy.utils.unregister_class(c)\n\n bpy.types.TOPBAR_MT_file_import.remove(menu_func_mabinogi_pmg)\n\nif __name__ == \"__main__\":\n register()\n","sub_path":"io_import_mabinogi_pmg.py","file_name":"io_import_mabinogi_pmg.py","file_ext":"py","file_size_in_byte":18893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"168481332","text":"# encoding: UTF-8\n\nfrom lxml import html\nimport requests\n\nURL = \"https://32blanche.lecointreparis.com/LP\"\n\n\ndef get_menu():\n page = requests.get(URL)\n tree = html.fromstring(page.content)\n tds = tree.xpath('//div[@class=\"pos20\"]/descendant::td')\n # Remove \"Menu du Jour\"\n tds = tds[1:]\n\n menu = []\n cpt = -1\n for td in tds:\n if td.text is not None:\n if is_section(td):\n cpt += 1\n menu.append({\"name\": td.text, \"sub\": []})\n else:\n menu[cpt]['sub'].append(td.text)\n return menu\n\n\ndef is_section(td):\n id_has_len_5 = len(td.get('id')) == 5\n text_is_short = len(td.text) < 10\n is_pdc = \"du chef\" in td.text.lower()\n return (id_has_len_5 and text_is_short) or is_pdc\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"416867783","text":"# timerConvert\n# takes number of minutes and returns the time in hour:minute form\n\ndef TimeConvert(num):\n try:\n num = (str(int((int(num) - int(num) % 60) / 60)) + \":\" + str(int(num) % 60))\n except ValueError:\n num = \"please enter a number!\"\n return num\nwhile True:\n user_input = input(\"Please type the number of minutes: \")\n print(TimeConvert(user_input))\n","sub_path":"no-require-server/CoderByte Challenges/Python/challenge_9.py","file_name":"challenge_9.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"553451998","text":"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\nimport pathlib\r\nimport os\r\nimport random\r\nimport warnings\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport argparse\r\nfrom tqdm import tqdm\r\nfrom Data import roll, CHANNEL_NUM, CLASS_NUM, INPUT_LENGTH, BATCH_SIZE\r\nfrom Model import get_noise, generator1, generator2, generator3, generator4, \\\r\n noise_generator, time_seq_noise_generator, discriminator1, \\\r\n discriminator2, discriminator3, \\\r\n discriminator4, encoder, NOISE_LENGTH\r\nfrom Convert import unpack_sample\r\nimport memory_saving_gradients\r\ntf.__dict__[\"gradients\"] = memory_saving_gradients.gradients_speed\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\nTOTAL_TRAIN_EPOCH = 100\r\nLAMBDA = 10\r\nLAMBDA1 = 1\r\nLAMBDA2 = 5\r\nTRAIN_RATIO_DIS = 5\r\nTRAIN_RATIO_GEN = 1\r\n\r\ndef gradient_penalty(real, gen, encode, discriminator):\r\n alpha = tf.random_uniform(shape=[BATCH_SIZE] + [1] * (gen.shape.ndims - 1), minval=0., maxval=1.)\r\n interpolate = real + alpha * (gen - real)\r\n gradients = tf.gradients(discriminator(inputs=interpolate, encode=encode), interpolate)[0]\r\n slopes = tf.sqrt(1e-10 + tf.reduce_sum(tf.square(gradients), axis=list(range(1, gradients.shape.ndims))))\r\n output = tf.reduce_mean((slopes - 1.) ** 2)\r\n return LAMBDA * output\r\n\r\ndef main():\r\n\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-s', '--sample', type=str, default='', \\\r\n help='Samples based on input song. Empty string means training.')\r\n parser.add_argument('-c', '--concat', type=bool, default=False, \\\r\n help='Enable Concatenation. Defaults to False.')\r\n args = parser.parse_args()\r\n sampling = args.sample != ''\r\n\r\n if not os.path.exists('Checkpoints'):\r\n os.makedirs('Checkpoints')\r\n if not os.path.exists('train'):\r\n os.makedirs('train')\r\n if not os.path.exists('Samples'):\r\n os.makedirs('Samples')\r\n \r\n with tf.name_scope('inputs'):\r\n filename = 'Dataset/dataset.tfrecord'\r\n dataset = tf.data.TFRecordDataset(filename)\r\n def _parse(example_proto):\r\n feature = {'roll' : tf.FixedLenFeature((6, 72, 384), tf.float32)}\r\n parsed = tf.parse_single_example(example_proto, feature)\r\n return parsed['roll']\r\n dataset = dataset.map(_parse, num_parallel_calls=8).repeat().shuffle(buffer_size=2000)\r\n dataset = dataset.apply(tf.contrib.data.batch_and_drop_remainder(BATCH_SIZE))\r\n iterator = dataset.make_one_shot_iterator()\r\n real_input_4 = iterator.get_next()\r\n\r\n input_noise1 = tf.placeholder(dtype=tf.float32, shape=[None, 1, 1, NOISE_LENGTH], name='input_noise1')\r\n input_noise2 = tf.placeholder(dtype=tf.float32, shape=[None, 1, 1, NOISE_LENGTH], name='input_noise2')\r\n input_noise3 = tf.placeholder(dtype=tf.float32, shape=[None, CHANNEL_NUM, 1, NOISE_LENGTH], name='input_noise3')\r\n input_noise4 = tf.placeholder(dtype=tf.float32, shape=[None, CHANNEL_NUM, 1, NOISE_LENGTH], name='input_noise4')\r\n\r\n train = tf.placeholder(dtype=tf.bool, name='traintest')\r\n noise1 = tf.tile(input=input_noise1, multiples=[1, CHANNEL_NUM, 4, 1], name='noise1')\r\n # shape: [None, CHANNEL_NUM, 4, NOISE_LENGTH]\r\n noise2_gen = noise_generator(noise=input_noise2, train=train)\r\n # shape: [None, 1, 4, NOISE_LENGTH]\r\n noise2 = tf.tile(input=noise2_gen, multiples=[1, CHANNEL_NUM, 1, 1], name='noise2')\r\n # shape: [None, CHANNEL_NUM, 4, NOISE_LENGTH]\r\n noise3 = tf.tile(input=input_noise3, multiples=[1, 1, 4, 1], name='noise3')\r\n # shape: [None, CHANNEL_NUM, 4, NOISE_LENGTH]\r\n input_noise4_split = tf.split(input_noise4, num_or_size_splits=CHANNEL_NUM, axis=1)\r\n # shape: [CHANNEL_NUM, None, 1, NOISE_LENGTH]\r\n noise4_split = [time_seq_noise_generator(noise=j, num=i, train=train) for i, j in enumerate(input_noise4_split)]\r\n # shape: [CHANNEL_NUM, None, 4, NOISE_LENGTH]\r\n noise4 = tf.concat(values=noise4_split, axis=1, name='noise4')\r\n # shape: [None, CHANNEL_NUM, 4, NOISE_LENGTH]\r\n #real_input_4 = tf.placeholder(dtype=tf.float32, \\\r\n # shape=[None, CHANNEL_NUM, CLASS_NUM, INPUT_LENGTH], name='real_input_4')\r\n real_input_4_split = tf.split(real_input_4, num_or_size_splits=4, axis=-1, name='real_input_4_split')\r\n # shape: [4, None, CHANNEL_NUM, CLASS_NUM, INPUT_LENGTH // 4]\r\n real_input_3 = tf.stack(real_input_4_split, axis=2, name='real_input_3')\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM, INPUT_LENGTH // 4]\r\n real_input_2 = tf.layers.average_pooling3d(inputs=real_input_3, pool_size=[1, 2, 2], strides=(1, 2, 2), \\\r\n padding='same', data_format='channels_first', name='real_input_2')\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM // 2, INPUT_LENGTH // 8]\r\n real_input_1 = tf.layers.average_pooling3d(inputs=real_input_2, pool_size=[1, 2, 2], strides=(1, 2, 2), \\\r\n padding='same', data_format='channels_first', name='real_input_1')\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM // 4, INPUT_LENGTH // 16]\r\n real_input_3_split = tf.split(real_input_3, num_or_size_splits=CHANNEL_NUM, axis=1, name='real_input_3_split')\r\n # shape: [CHANNEL_NUM, None, 1, 4, CLASS_NUM, INPUT_LENGTH // 4]\r\n encode_split = [encoder(inputs=j, num=i, train=train) for i, j in enumerate(real_input_3_split)]\r\n # shape: [CHANNEL_NUM, None, 4, 16]\r\n encode = tf.stack(encode_split, axis=1, name='encode')\r\n # shape: [None, CHANNEL_NUM, 4, 16]\r\n\r\n input_noise = tf.concat(values=[noise1, noise2, noise3, noise4], axis=3, name='input_noise')\r\n # shape: [None, CHANNEL_NUM, 4, NOISE_LENGTH * 4]\r\n\r\n real_input_4_image = tf.expand_dims(real_input_4[:1], axis=-1, name='real_input_4_image_expand')\r\n # shape: [1, CHANNEL_NUM, CLASS_NUM, INPUT_LENGTH, 1]\r\n real_input_4_image = tf.unstack(real_input_4_image, axis=1, name='real_input_4_image_unstack')\r\n # shape: [CHANNEL_NUM, 1, CLASS_NUM, INPUT_LENGTH, 1]\r\n for i, j in enumerate(real_input_4_image):\r\n tf.summary.image('real_input_4_' + str(i), j)\r\n \r\n real_input_3_image = tf.unstack(real_input_3[:1], axis=2, name='real_input_3_image_unstack')\r\n # shape: [4, 1, CHANNEL_NUM, CLASS_NUM, INPUT_LENGTH // 4]\r\n real_input_3_image = tf.concat(real_input_3_image, axis=-1, name='real_input_3_image_concat')\r\n # shape: [1, CHANNEL_NUM, CLASS_NUM, INPUT_LENGTH]\r\n real_input_3_image = tf.expand_dims(real_input_3_image, axis=-1, name='real_input_3_expand')\r\n # shape: [1, CHANNEL_NUM, CLASS_NUM, INPUT_LENGTH, 1]\r\n real_input_3_image = tf.unstack(real_input_3_image, axis=1, name='real_input_3_image')\r\n # shape: [CHANNEL_NUM, 1, CLASS_NUM, INPUT_LENGTH, 1]\r\n for i, j in enumerate(real_input_3_image):\r\n tf.summary.image('real_input_3_' + str(i), j)\r\n \r\n real_input_2_image = tf.unstack(real_input_2[:1], axis=2, name='real_input_2_unstack')\r\n # shape: [4, 1, CHANNEL_NUM, CLASS_NUM // 2, INPUT_LENGTH // 8]\r\n real_input_2_image = tf.concat(real_input_2_image, axis=-1, name='real_input_2_concat')\r\n # shape: [1, CHANNEL_NUM, CLASS_NUM // 2, INPUT_LENGTH // 2]\r\n real_input_2_image = tf.expand_dims(real_input_2_image, axis=-1, name='real_input_2_expand')\r\n # shape: [1, CHANNEL_NUM, CLASS_NUM // 2, INPUT_LENGTH // 2, 1]\r\n real_input_2_image = tf.unstack(real_input_2_image, axis=1, name='real_input_2_image')\r\n # shape: [CHANNEL_NUM, 1, CLASS_NUM // 2, INPUT_LENGTH // 2, 1]\r\n for i, j in enumerate(real_input_2_image):\r\n tf.summary.image('real_input_2_' + str(i), j)\r\n \r\n real_input_1_image = tf.unstack(real_input_1[:1], axis=2, name='real_input_1_unstack')\r\n # shape: [4, 1, CHANNEL_NUM, CLASS_NUM // 4, INPUT_LENGTH // 16]\r\n real_input_1_image = tf.concat(real_input_1_image, axis=-1, name='real_input_3_concat')\r\n # shape: [1, CHANNEL_NUM, CLASS_NUM // 4, INPUT_LENGTH // 4]\r\n real_input_1_image = tf.expand_dims(real_input_1_image, axis=-1, name='real_input_1_expand')\r\n # shape: [1, CHANNEL_NUM, CLASS_NUM // 4, INPUT_LENGTH // 4, 1]\r\n real_input_1_image = tf.unstack(real_input_1_image, axis=1, name='real_input_1_image')\r\n # shape: [CHANNEL_NUM, 1, CLASS_NUM // 4, INPUT_LENGTH // 4, 1]\r\n for i, j in enumerate(real_input_1_image):\r\n tf.summary.image('real_input_1_' + str(i), j)\r\n\r\n with tf.name_scope('generator'):\r\n input_noise_split = tf.unstack(input_noise, axis=1, name='input_noise_split')\r\n # shape: [CHANNEL_NUM, None, 4, NOISE_LENGTH * 4]\r\n input_gen1, gen1 = zip(*[generator1(noise=input_noise_split[i], encode=encode[:, i], \\\r\n num=i, train=train) for i in range(CHANNEL_NUM)])\r\n # shape: [CHANNEL_NUM, None, 4, CLASS_NUM // 4, INPUT_LENGTH // 16]\r\n # shape: [CHANNEL_NUM, None, NOISE_LENGTH * 2, 4, CLASS_NUM // 4, INPUT_LENGTH // 16]\r\n input_gen1 = tf.stack(input_gen1, axis=1, name='input_gen1_stack')\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM // 4, INPUT_LENGTH // 16]\r\n gen1 = [tf.concat(values=[i, input_gen1], axis=1) for i in gen1]\r\n # shape: [CHANNEL_NUM, None, NOISE_LENGTH * 2 + CHANNEL_NUM, 4, CLASS_NUM // 4, INPUT_LENGTH // 16]\r\n input_gen2, gen2 = zip(*[generator2(inputs=gen1[i], encode=encode, \\\r\n num=i, train=train) for i in range(CHANNEL_NUM)])\r\n # shape: [CHANNEL_NUM, None, 4, CLASS_NUM // 2, INPUT_LENGTH // 8]\r\n # shape: [CHANNEL_NUM, None, 32, 4, CLASS_NUM // 2, INPUT_LENGTH // 8]\r\n input_gen2 = tf.stack(input_gen2, axis=1, name='input_gen2_stack')\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM // 2, INPUT_LENGTH // 8]\r\n gen2 = [tf.concat(values=[i, input_gen2], axis=1) for i in gen2]\r\n # shape: [CHANNEL_NUM, None, 32 + CHANNEL_NUM, 4, CLASS_NUM // 4, INPUT_LENGTH // 16]\r\n input_gen3, gen3 = zip(*[generator3(inputs=gen2[i], encode=encode, \\\r\n num=i, train=train) for i in range(CHANNEL_NUM)])\r\n # shape: [CHANNEL_NUM, None, 4, CLASS_NUM, INPUT_LENGTH // 4]\r\n # shape: [CHANNEL_NUM, None, 16, 4, CLASS_NUM, INPUT_LENGTH // 4]\r\n input_gen3 = tf.stack(input_gen3, axis=1, name='input_gen3_stack')\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM, INPUT_LENGTH // 4]\r\n gen3 = [tf.concat(values=[i, input_gen3], axis=1) for i in gen3]\r\n # shape: [CHANNEL_NUM, None, 16 + CHANNEL_NUM, 4, CLASS_NUM // 4, INPUT_LENGTH // 16]\r\n input_gen4 = [generator4(inputs=gen3[i], encode=encode, \\\r\n num=i, train=train) for i in range(CHANNEL_NUM)]\r\n # shape: [CHANNEL_NUM, None, CLASS_NUM, INPUT_LENGTH]\r\n input_gen4 = tf.stack(input_gen4, axis=1, name='input_gen4_stack')\r\n # shape: [None, CHANNEL_NUM, CLASS_NUM, INPUT_LENGTH]\r\n print('Generators set')\r\n with tf.name_scope('discriminator'):\r\n dis1_real = discriminator1(inputs=real_input_1, encode=encode)\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM // 4, INPUT_LENGTH // 16]\r\n dis1_gen = discriminator1(inputs=input_gen1, encode=encode)\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM // 4, INPUT_LENGTH // 16]\r\n dis2_real = discriminator2(inputs=real_input_2, encode=encode)\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM // 2, INPUT_LENGTH // 8]\r\n dis2_gen = discriminator2(inputs=input_gen2, encode=encode)\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM // 2, INPUT_LENGTH // 8]\r\n dis3_real = discriminator3(inputs=real_input_3, encode=encode)\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM, INPUT_LENGTH // 4]\r\n dis3_gen = discriminator3(inputs=input_gen3, encode=encode)\r\n # shape: [None, CHANNEL_NUM, 4, CLASS_NUM, INPUT_LENGTH // 4]\r\n dis4_real = discriminator4(inputs=real_input_4, encode=encode)\r\n # shape: [None, CHANNEL_NUM, CLASS_NUM, INPUT_LENGTH]\r\n dis4_gen = discriminator4(inputs=input_gen4, encode=encode)\r\n # shape: [None, CHANNEL_NUM, CLASS_NUM, INPUT_LENGTH]\r\n print('Discriminators set')\r\n with tf.name_scope('loss'):\r\n loss_dis1 = tf.reduce_mean(dis1_gen - dis1_real) + gradient_penalty(real=real_input_1, \\\r\n gen=input_gen1, encode=encode, discriminator=discriminator1)\r\n mean_gen1, dev_gen1 = tf.nn.moments(input_gen1, axes=list(range(2, input_gen1.shape.ndims)))\r\n loss_gen1 = -tf.reduce_mean(dis1_gen)\r\n loss_dis2 = tf.reduce_mean(dis2_gen - dis2_real) + gradient_penalty(real=real_input_2, \\\r\n gen=input_gen2, encode=encode, discriminator=discriminator2)\r\n mean_gen2, dev_gen2 = tf.nn.moments(input_gen2, axes=list(range(2, input_gen2.shape.ndims)))\r\n loss_gen2 = -tf.reduce_mean(dis2_gen) + LAMBDA1 * tf.reduce_mean(tf.squared_difference(mean_gen1, mean_gen2)) \\\r\n + LAMBDA2 * tf.reduce_mean(tf.squared_difference(dev_gen1, dev_gen2))\r\n loss_dis3 = tf.reduce_mean(dis3_gen - dis3_real) + gradient_penalty(real=real_input_3, \\\r\n gen=input_gen3, encode=encode, discriminator=discriminator3)\r\n mean_gen3, dev_gen3 = tf.nn.moments(input_gen3, axes=list(range(2, input_gen3.shape.ndims)))\r\n loss_gen3 = -tf.reduce_mean(dis3_gen) + LAMBDA1 * tf.reduce_mean(tf.squared_difference(mean_gen2, mean_gen3)) \\\r\n + LAMBDA2 * tf.reduce_mean(tf.squared_difference(dev_gen2, dev_gen3))\r\n loss_dis4 = tf.reduce_mean(dis4_gen - dis4_real) + gradient_penalty(real=real_input_4, \\\r\n gen=input_gen4, encode=encode, discriminator=discriminator4)\r\n mean_gen4, dev_gen4 = tf.nn.moments(input_gen4, axes=list(range(2, input_gen4.shape.ndims)))\r\n loss_gen4 = -tf.reduce_mean(dis4_gen) + LAMBDA1 * tf.reduce_mean(tf.squared_difference(mean_gen3, mean_gen4)) \\\r\n + LAMBDA2 * tf.reduce_mean(tf.squared_difference(dev_gen3, dev_gen4))\r\n loss_gen = (loss_gen1 + loss_gen2 + loss_gen3 + loss_gen4) / 4.0\r\n tf.summary.scalar('loss_dis1', loss_dis1)\r\n tf.summary.scalar('loss_gen1', loss_gen1)\r\n tf.summary.scalar('dis1_real', tf.reduce_mean(dis1_real))\r\n tf.summary.scalar('loss_dis2', loss_dis2)\r\n tf.summary.scalar('loss_gen2', loss_gen2)\r\n tf.summary.scalar('dis2_real', tf.reduce_mean(dis2_real))\r\n tf.summary.scalar('loss_dis3', loss_dis3)\r\n tf.summary.scalar('loss_gen3', loss_gen3)\r\n tf.summary.scalar('dis3_real', tf.reduce_mean(dis3_real))\r\n tf.summary.scalar('loss_dis4', loss_dis4)\r\n tf.summary.scalar('loss_gen4', loss_gen4)\r\n tf.summary.scalar('dis4_real', tf.reduce_mean(dis4_real))\r\n tf.summary.scalar('loss_gen', loss_gen)\r\n print('Losses set')\r\n gen_var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Noise_generator')\r\n for i in range(CHANNEL_NUM):\r\n gen_var += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Encoder' + str(i))\r\n gen_var += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Time_seq_noise_generator' + str(i))\r\n gen_var += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Generator1_' + str(i))\r\n gen_var += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Generator2_' + str(i))\r\n gen_var += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Generator3_' + str(i))\r\n gen_var += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Generator4_' + str(i))\r\n dis1_var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Discriminator1')\r\n dis2_var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Discriminator2')\r\n dis3_var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Discriminator3')\r\n dis4_var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Discriminator4')\r\n gen_extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Noise_generator')\r\n for i in range(CHANNEL_NUM):\r\n gen_extra_update_ops += tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Encoder' + str(i))\r\n gen_extra_update_ops += tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Time_seq_noise_generator' + str(i))\r\n gen_extra_update_ops += tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Generator1_' + str(i))\r\n gen_extra_update_ops += tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Generator2_' + str(i))\r\n gen_extra_update_ops += tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Generator3_' + str(i))\r\n gen_extra_update_ops += tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Generator4_' + str(i))\r\n dis1_extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Discriminator1')\r\n dis2_extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Discriminator2')\r\n dis3_extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Discriminator3')\r\n dis4_extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='Discriminator4')\r\n with tf.name_scope('optimizers'):\r\n with tf.control_dependencies(dis1_extra_update_ops):\r\n dis1_train = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5, beta2=0.99).minimize(\\\r\n loss=loss_dis1, var_list=dis1_var, name='dis1_train')\r\n print('dis1_train setup')\r\n with tf.control_dependencies(dis2_extra_update_ops):\r\n dis2_train = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5, beta2=0.99).minimize(\\\r\n loss=loss_dis2, var_list=dis2_var, name='dis2_train')\r\n print('dis2_train setup')\r\n with tf.control_dependencies(dis3_extra_update_ops):\r\n dis3_train = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5, beta2=0.99).minimize(\\\r\n loss=loss_dis3, var_list=dis3_var, name='dis3_train')\r\n print('dis3_train setup')\r\n with tf.control_dependencies(dis4_extra_update_ops):\r\n dis4_train = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5, beta2=0.99).minimize(\\\r\n loss=loss_dis4, var_list=dis4_var, name='dis4_train')\r\n print('dis4_train setup')\r\n with tf.control_dependencies(gen_extra_update_ops):\r\n gen_train = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5, beta2=0.99).minimize(\\\r\n loss=loss_gen, var_list=gen_var, name='gen_train')\r\n print('gen_train setup')\r\n print('Optimizers set')\r\n gpu_options = tf.GPUOptions(allow_growth=True, allocator_type='BFC')\r\n config = tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_options)\r\n saver = tf.train.Saver()\r\n with tf.Session(config=config) as sess:\r\n merged = tf.summary.merge_all()\r\n sess.run(tf.global_variables_initializer())\r\n if tf.train.latest_checkpoint('Checkpoints') is not None:\r\n print('Restoring...')\r\n saver.restore(sess, tf.train.latest_checkpoint('Checkpoints'))\r\n train_count = 0\r\n feed_dict = {input_noise1: None, input_noise2: None, input_noise3: None, input_noise4: None, train: True}\r\n print('preparing complete')\r\n if sampling:\r\n feed_dict = {input_noise1: None, input_noise2: None, input_noise3: None, \\\r\n input_noise4: None, real_input_4: None, train: True}\r\n path = args.sample\r\n try:\r\n feed_dict[real_input_4] = roll(path)[:BATCH_SIZE]\r\n except:\r\n print('Error while opening file.')\r\n return\r\n feed_dict[input_noise1] = get_noise([BATCH_SIZE, 1, 1, NOISE_LENGTH])\r\n feed_dict[input_noise2] = get_noise([BATCH_SIZE, 1, 1, NOISE_LENGTH])\r\n feed_dict[input_noise3] = get_noise([BATCH_SIZE, CHANNEL_NUM, 1, NOISE_LENGTH])\r\n feed_dict[input_noise4] = get_noise([BATCH_SIZE, CHANNEL_NUM, 1, NOISE_LENGTH])\r\n feed_dict[train] = True\r\n samples = sess.run(input_gen4, feed_dict=feed_dict)\r\n path = path.split('/')[-1]\r\n if not os.path.exists('Samples/sample_%s'):\r\n os.mkdir('Samples/sample_%s' % path)\r\n np.save(file='Samples/sample_%s' % path + '/%s' % path, arr=samples)\r\n unpack_sample(name='Samples/sample_%s' % path+ '/%s.npy' % path, concat=args.concat)\r\n return\r\n writer = tf.summary.FileWriter('train', sess.graph)\r\n run_options = tf.RunOptions(report_tensor_allocations_upon_oom=True)\r\n epoch_num = 1000000\r\n for ___ in tqdm(range(epoch_num)):\r\n feed_dict[train] = True\r\n for i in range(TRAIN_RATIO_DIS):\r\n feed_dict[input_noise1] = get_noise([BATCH_SIZE, 1, 1, NOISE_LENGTH])\r\n feed_dict[input_noise2] = get_noise([BATCH_SIZE, 1, 1, NOISE_LENGTH])\r\n feed_dict[input_noise3] = get_noise([BATCH_SIZE, CHANNEL_NUM, 1, NOISE_LENGTH])\r\n feed_dict[input_noise4] = get_noise([BATCH_SIZE, CHANNEL_NUM, 1, NOISE_LENGTH])\r\n _, loss_val_dis1 = sess.run([dis1_train, loss_dis1], feed_dict=feed_dict, options=run_options)\r\n _, loss_val_dis2 = sess.run([dis2_train, loss_dis2], feed_dict=feed_dict, options=run_options)\r\n _, loss_val_dis3 = sess.run([dis3_train, loss_dis3], feed_dict=feed_dict, options=run_options)\r\n _, loss_val_dis4 = sess.run([dis4_train, loss_dis4], feed_dict=feed_dict, options=run_options)\r\n for i in range(TRAIN_RATIO_GEN):\r\n feed_dict[input_noise1] = get_noise([BATCH_SIZE, 1, 1, NOISE_LENGTH])\r\n feed_dict[input_noise2] = get_noise([BATCH_SIZE, 1, 1, NOISE_LENGTH])\r\n feed_dict[input_noise3] = get_noise([BATCH_SIZE, CHANNEL_NUM, 1, NOISE_LENGTH])\r\n feed_dict[input_noise4] = get_noise([BATCH_SIZE, CHANNEL_NUM, 1, NOISE_LENGTH])\r\n summary, _, loss_val_gen = sess.run([merged, gen_train, loss_gen], \\\r\n feed_dict=feed_dict, options=run_options)\r\n writer.add_summary(summary, train_count)\r\n tqdm.write('%06d' % train_count, end=' ')\r\n tqdm.write('Discriminator1 loss : %.7f' % loss_val_dis1, end=' ')\r\n tqdm.write('Discriminator2 loss : %.7f' % loss_val_dis2, end=' ')\r\n tqdm.write('Discriminator3 loss : %.7f' % loss_val_dis3, end=' ')\r\n tqdm.write('Discriminator4 loss : %.7f' % loss_val_dis4, end=' ')\r\n tqdm.write('Generator loss : %.7f' % loss_val_gen)\r\n train_count += 1\r\n if train_count % 1000 == 1:\r\n feed_dict[input_noise1] = get_noise([BATCH_SIZE, 1, 1, NOISE_LENGTH])\r\n feed_dict[input_noise2] = get_noise([BATCH_SIZE, 1, 1, NOISE_LENGTH])\r\n feed_dict[input_noise3] = get_noise([BATCH_SIZE, CHANNEL_NUM, 1, NOISE_LENGTH])\r\n feed_dict[input_noise4] = get_noise([BATCH_SIZE, CHANNEL_NUM, 1, NOISE_LENGTH])\r\n samples = sess.run(input_gen4, feed_dict=feed_dict)\r\n np.save(file='Samples/song_%06d' % train_count, arr=samples)\r\n unpack_sample('Samples/song_%06d' % train_count)\r\n save_path = saver.save(sess, 'Checkpoints/song_%06d' % train_count + '.ckpt')\r\n tqdm.write('Model Saved: %s' % save_path)\r\n writer.close()\r\nif __name__ == '__main__':\r\n with warnings.catch_warnings():\r\n warnings.simplefilter('ignore')\r\n main()\r\n","sub_path":"ClassicGAN.py","file_name":"ClassicGAN.py","file_ext":"py","file_size_in_byte":24342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"507265014","text":"from PyQt5 import QtGui, QtCore,QtWidgets\r\nimport sys\r\nimport random\r\n\r\nclass Example(QtCore.QObject):\r\n\r\n signalStatus = QtCore.pyqtSignal(str)\r\n\r\n def __init__(self, parent=None):\r\n super(self.__class__, self).__init__(parent)\r\n\r\n # Create a gui object.\r\n self.gui = Window()\r\n\r\n # Create a new worker thread.\r\n self.createWorkerThread()\r\n\r\n # Make any cross object connections.\r\n self._connectSignals()\r\n\r\n self.gui.show()\r\n\r\n\r\n def _connectSignals(self):\r\n self.gui.button_cancel.clicked.connect(self.forceWorkerReset)\r\n self.signalStatus.connect(self.gui.updateStatus)\r\n self.parent().aboutToQuit.connect(self.forceWorkerQuit)\r\n\r\n\r\n def createWorkerThread(self):\r\n\r\n # Setup the worker object and the worker_thread.\r\n self.worker = WorkerObject()\r\n self.worker_thread = QtCore.QThread()\r\n self.worker.moveToThread(self.worker_thread)\r\n self.worker_thread.start()\r\n\r\n # Connect any worker signals\r\n self.worker.signalStatus.connect(self.gui.updateStatus)\r\n self.gui.button_start.clicked.connect(self.worker.startWork)\r\n\r\n\r\n def forceWorkerReset(self):\r\n if self.worker_thread.isRunning():\r\n print('Terminating thread.')\r\n self.worker_thread.terminate()\r\n\r\n print('Waiting for thread termination.')\r\n self.worker_thread.wait()\r\n\r\n self.signalStatus.emit('Idle.')\r\n\r\n print('building new working object.')\r\n self.createWorkerThread()\r\n\r\n\r\n def forceWorkerQuit(self):\r\n if self.worker_thread.isRunning():\r\n self.worker_thread.terminate()\r\n self.worker_thread.wait()\r\n\r\n\r\nclass WorkerObject(QtCore.QObject):\r\n\r\n signalStatus = QtCore.pyqtSignal(str)\r\n\r\n def __init__(self, parent=None):\r\n super(self.__class__, self).__init__(parent)\r\n\r\n @QtCore.pyqtSlot()\r\n def startWork(self):\r\n for ii in range(7):\r\n number = random.randint(0,5000**ii)\r\n self.signalStatus.emit('Iteration: {}, Factoring: {}'.format(ii, number))\r\n factors = self.primeFactors(number)\r\n print('Number: ', number, 'Factors: ', factors)\r\n self.signalStatus.emit('Idle.')\r\n\r\n def primeFactors(self, n):\r\n i = 2\r\n factors = []\r\n while i * i <= n:\r\n if n % i:\r\n i += 1\r\n else:\r\n n //= i\r\n factors.append(i)\r\n if n > 1:\r\n factors.append(n)\r\n return factors\r\n\r\n\r\nclass Window(QtWidgets.QWidget):\r\n\r\n def __init__(self):\r\n QtWidgets.QWidget.__init__(self)\r\n self.button_start = QtWidgets.QPushButton('Start', self)\r\n self.button_cancel = QtWidgets.QPushButton('Cancel', self)\r\n self.label_status = QtWidgets.QLabel('', self)\r\n\r\n layout = QtWidgets.QVBoxLayout(self)\r\n layout.addWidget(self.button_start)\r\n layout.addWidget(self.button_cancel)\r\n layout.addWidget(self.label_status)\r\n\r\n self.setFixedSize(400, 200)\r\n\r\n @QtCore.pyqtSlot(str)\r\n def updateStatus(self, status):\r\n self.label_status.setText(status)\r\n\r\n\r\nif __name__=='__main__':\r\n app = QtWidgets.QApplication(sys.argv)\r\n example = Example(app)\r\n sys.exit(app.exec_())","sub_path":"cc.py","file_name":"cc.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"144333053","text":"# Discrete Optimization: Travelling Salesman Problem\n# Qatar - 194 cities\n\n# Import all the necessary packages\nimport mlrose\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport time\n\n# Read data from csv\ncities_raw = pd.read_csv(\"Data/qa194.csv\")\nprint(cities_raw)\nprint(type(cities_raw))\n\n# Create a matrix of city coordinates from the DataFrame\ncities_list = cities_raw[['x','y']].values.tolist()\nprint(cities_list)\nprint(type(cities_list))\n\n# Initialize function parameters\nnb_cities = int(len(cities_list))\nprint(nb_cities)\npopulation = 500\n\n# Initialize fitness function object\nfitness_coords = mlrose.TravellingSales(coords=cities_list)\n\n# Define an Optimization Problem Object with TSPOpt()\nproblem_fit = mlrose.TSPOpt(length=nb_cities,\n fitness_fn=fitness_coords,\n maximize=False)\n\n# Start timer to get computational time\nt1 = time.time()\n\n# Solve the problem using the genetic algorithm\nbest_state, best_fitness, fitness_curve = mlrose.genetic_alg(problem=problem_fit,\n pop_size=population,\n mutation_prob=0.1,\n max_attempts=1000,\n max_iters=10000,\n curve=True)\n\n# Stop timer and compute computational time\nt2 = time.time()\ncomp_time = t2 - t1\n\n# Print parameters and solutions\nprint(\"==========================================================================\\n\")\nprint(\"Travelling Salesman Problem: Qatar - 194 cities\\n\")\nprint(\"01. Chosen algorithm to solve the problem: Genetic Algorithm from mlrose\\n\")\nprint(\"02. Parameters:\")\nprint(\"\\nNumber of cities:\", nb_cities)\nprint(\"\\nPopulation:\", population)\nprint(\"\\nMutation prob: 0.1\")\nprint(\"\\nMax attempts: 1000\")\nprint(\"\\nMax iterations: 10000\")\nprint(\"\\nNumber of cities:\", nb_cities)\nprint(\"\\n03. Final results:\")\nsol_df = pd.DataFrame(best_state, columns=[''])\nsol_df.to_csv(\"Qatar194_sol.csv\", sep=\",\")\nprint(\"\\n - Solutions:\", sol_df)\nprint(\"\\n - Fitness:\", round(best_fitness, 2))\nprint(\"\\nStopping criterion: 1000 iterations\")\nprint(\"\\nComputational time:\", round(comp_time, 2), \"seconds\\n\")\nprint(\"==========================================================================\")\n\n# Plot the convergence curve\nfig = plt.figure(figsize=(16, 13))\nplt.plot(-(fitness_curve))\nplt.title(\"Convergence curve: Travelling Salesman Problem: Qatar - 194 cities\", fontsize=16)\nplt.xlabel(\"Time (iterations)\", fontsize=12)\nplt.ylabel(\"Fitness\", fontsize=12)\nplt.savefig(\"Screenshots/TSP_convergence_qatar194.png\")\nplt.show()\n\n# Plot route\nfig = plt.figure(figsize=(16, 16))\nplt.plot([cities_list[best_state[i % nb_cities]][0] for i in range(nb_cities+1)], [cities_list[best_state[i % nb_cities]][1] for i in range(nb_cities+1)], 'ro-', linewidth=1)\nplt.title(\"Best route: Travelling Salesman Problem: Qatar - 194 cities\", fontsize=16)\nplt.xlabel(\"x coord\", fontsize=12)\nplt.ylabel(\"y coord\", fontsize=12)\nplt.savefig(\"Screenshots/TSP_route_qatar194.png\")\nplt.show()","sub_path":"02-TSP_Qatar/TSP_Qatar.py","file_name":"TSP_Qatar.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"2026765","text":"import random\nimport sys\n\nimport numpy as np\nimport torch\n\nfrom mdp.replay_buffer import Transition\nfrom mdp.sum_tree import SumTree\n\n\nclass Memory: # stored as ( s, a, r, s_ ) in SumTree\n e = sys.float_info.epsilon\n\n def __init__(self, capacity, alpha=None, beta=None, beta_increment=None, p=None):\n self.tree = SumTree(capacity)\n self.capacity = capacity\n # self.geo_weights = np.geomspace(1, 256, num=capacity)\n self.p = p or 0.5\n self.geo_weights = np.flip([(self.p)*(1-self.p)**n for n in range(self.capacity)]).copy()\n self.weights_sum = self.geo_weights.sum()\n self.num_ele = 0\n self.a = alpha or 0.6\n self.beta = beta or 0.4\n self.beta_increment_per_sampling = beta_increment or 0.001\n\n def _get_priority(self, error):\n return (np.abs(error) + self.e) ** self.a\n\n def add(self, error, *args):\n p = self._get_priority(error)\n self.tree.add(p, Transition(*args))\n if self.num_ele < self.capacity:\n self.num_ele += 1\n\n def maxp(self):\n return self.tree.maxp()\n\n def sample(self, n):\n batch = []\n idxs = []\n segment = self.tree.total() / n\n priorities = []\n\n self.beta = np.min([1., self.beta + self.beta_increment_per_sampling])\n\n for i in range(n):\n a = segment * i\n b = segment * (i + 1)\n\n s = random.uniform(a, b)\n (idx, p, data) = self.tree.get(s)\n priorities.append(p)\n batch.append(data)\n idxs.append(idx)\n\n sampling_probabilities = priorities / self.tree.total()\n\n # recency biased correction\n # data_idx = [idx - self.capacity + 1 for idx in idxs]\n # if self.num_ele < self.capacity:\n # weights = self.geo_weights[-self.num_ele:]\n # weights_sum = self.geo_weights[-self.num_ele:].sum()\n # else:\n # weights = self.geo_weights\n # weights_sum = self.weights_sum\n # geo_sampling_probabilities = weights[np.array(data_idx)] / weights_sum\n # is_weight = np.power(geo_sampling_probabilities / sampling_probabilities, self.beta)\n\n is_weight = np.power(self.tree.n_entries * sampling_probabilities, -self.beta)\n is_weight /= is_weight.max()\n\n return batch, idxs, is_weight\n\n def update(self, idx, error):\n p = self._get_priority(error)\n self.tree.update(idx, p)\n\n def last_n(self, seq_len):\n return self.tree.last_n(seq_len)\n\n # \\beta^(t-s) / (\\sum_{k=1}^t \\beta^{t-k})\n def sample_geo(self, n):\n self.beta = np.min([1., self.beta + self.beta_increment_per_sampling])\n if self.num_ele < self.capacity:\n weights = self.geo_weights[-self.num_ele:]\n weights_sum = self.geo_weights[-self.num_ele:].sum()\n else:\n weights = self.geo_weights\n weights_sum = self.weights_sum\n idxes = torch.multinomial(torch.from_numpy(weights).float(), n, replacement=False)\n batch = []\n idxs = []\n for x in idxes:\n (idx, p, data) = self.tree.get_by_idx(x)\n batch.append(data)\n idxs.append(idx)\n print(idxes,idxs)\n sampling_probabilities = weights[idxes.numpy()] / weights_sum\n is_weight = np.power(self.tree.n_entries * sampling_probabilities, -self.beta)\n is_weight /= is_weight.max()\n return batch, idxs, is_weight\n\n def __len__(self):\n return self.tree.n_entries\n\n # per_agent_trace\n def last_n_idxes(self, seq_len):\n return self.tree.last_n_idxes(seq_len)\n\n def multiply_update(self, idx, multiplier):\n self.tree.multiply_update(idx, multiplier)\n","sub_path":"mdp/prioritized_memory.py","file_name":"prioritized_memory.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"38105986","text":"from importlib import import_module\nfrom json import loads\n\nfrom django.apps import apps\nfrom django.core.management import BaseCommand, call_command\nfrom django.utils.module_loading import module_has_submodule\nfrom kafka import KafkaConsumer\n\nfrom stream_analytics.models import StreamAnalytic\n\n\nclass Command(BaseCommand):\n \"\"\"\n A command to setup common initialization parameters used across our\n applications\n \"\"\"\n\n def handle(self, *args, **options):\n \"\"\"\n Runs the command\n \"\"\"\n consumer = KafkaConsumer(\n 'quickstart-events',\n bootstrap_servers=['10.7.213.152:9092'],\n auto_offset_reset='latest',\n enable_auto_commit=True,\n group_id='none',\n value_deserializer=lambda x: loads(x.decode('utf-8')))\n for message in consumer:\n frame_id = message.value['analyticsModule']['Frame_ID']\n tracking_id = message.value['analyticsModule']['Tracking-ID']\n x_coordinate = message.value['analyticsModule']['X_Coordinate']\n y_coordinate = message.value['analyticsModule']['Y_Coordinate']\n camera_id = message.value['CameraID']\n time = message.value['@timestamp']\n\n analytics = StreamAnalytic.objects.create(\n frame_id=frame_id, tracking_id=tracking_id, x_coordinate=x_coordinate, y_coordinate=y_coordinate, time=time, camera_id=camera_id)\n # print(message.value['analyticsModule']['Frame_ID'])\n","sub_path":"core/management/commands/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"58230691","text":"# -*- coding: utf-8 -*-\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom pipobot.bot_test import TestBot\nfrom pipobot.lib.bdd import Base\n\n\nDOMAIN = \"domain.tld\"\nCHAN = \"test@%s\" % DOMAIN\n\n\nclass FakeUser:\n def __init__(self, name, bot, tester, jid=None, role=\"moderator\", chan=CHAN):\n self.name = name\n self.bot = bot\n if jid is None:\n jid = \"%s@%s\" % (name, DOMAIN)\n self.jid = jid\n self.role = role\n self.chan = chan\n self.tester = tester\n self.bot.occupants.add_user(name, jid, role)\n\n def ask(self, msg, expected):\n ret = self.bot.create_msg(self.name, msg)\n self.tester.assertEqual(ret, expected)\n\n def change_nick(self, new_nick):\n self.bot.users.rm_user(self.name)\n self.name = new_nick\n self.bot.occupants.add_user(new_nick, self.jid, self.role)\n\n def leave(self):\n self.bot.users.rm_user(self.name)\n\ndef create_test_bot(mods):\n engine = create_engine('sqlite:///:memory:')\n Session = sessionmaker(bind=engine)\n session = Session()\n Base.metadata.create_all(engine)\n return TestBot(\"pipotest\", \"login\", CHAN, mods, session)\n","sub_path":"tests/base_test.py","file_name":"base_test.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"595415724","text":"###10t.py - 2011_gap_filling/2011_week39/20110928 ### make summary output for elements\n### Usages: nice -n 19 python 10t.py rep_pos \"$dat\"_summary.txt.1 \"$dat\"_summary.txt.2 \"$dat\"_summary.txt.3\n\nimport sys\n\nsummary={}\nfor i in range(2,5):\n\tfor line in open(sys.argv[i],'r'):\n\t\tline=line.strip()\n\t\ttoken=line.split('\\t')\n\t\tpos=int(token[0])\n\t\tsummary[i,pos]=token[1]+'\\t'+str(round(float(token[2])/100,2))+'\\t'+token[3]\n\n\n### print header\n\nprint ('#count'+'\\t'+'Chromosome'+'\\t'+'gap_start'+'\\t'+'gap_end'+'\\t'+'5-3_best_hit'+'\\t'+'Score'+'\\t'+'orientation'+'\\t'+'5_best_hit'+'\\t'+'Score'+'\\t'+'orientation'+'\\t'+'3_best_hit'+'\\t'+'Score'+'\\t'+'orientation')\n### open rep_pos file\nfor line in open(sys.argv[1],'r'):\n\tline=line.strip()\n\ttoken=line.split('\\t')\n\tcount=int(token[0])\n\tchro=(token[1]).replace('_test','')\n\tstart=int(token[2])\n\ten=int(token[3])\n\tst=10000000000*start\n\tkey=st+count\n\tstring=str(str(count)+'\\t'+str(chro)+'\\t'+str(start)+'\\t'+str(en))\n\tfor i in range(2,5):\n\t\tstring += ('\\t'+summary[i,key])\n\tprint (string)\t","sub_path":"repos/python/13k.py","file_name":"13k.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"37183011","text":"\"\"\"Initiate pygame, logging and other things\"\"\"\n\nimport pygame\nimport os\nimport logging\n\nfrom options import Options\n\ninitiated = False\n\nif not initiated:\n pygame.mixer.pre_init(44100, -16, 1, 512) # Makes all gun sound play\n # Without this, only some play because they are so close together\n\n pygame.init()\n pygame.display.set_caption(\"Zombie Survival\")\n\n if not Options.not_log:\n logging.basicConfig(filename=\"src/logging.log\", level=logging.NOTSET,\n filemode=\"w\",\n format=\"%(asctime)s:%(msecs)03d %(filename)s \"\n \"%(levelname)s %(funcName)s -> %(message)s\",\n datefmt=\"%d.%m.%Y %H:%M:%S\")\n else:\n logging.basicConfig(filename=\"src/logging.log\",\n filemode=\"w\", level=logging.DEBUG)\n logging.info(\"Optimisation mode set. Logging was disabled\")\n logging.disable(50)\n os.environ[\"SDL_VIDEO_WINDOW_POS\"] = \"1, 1\"\n initiated = True\n","sub_path":"src/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"195175551","text":"##encoding=UTF8\n\n\"\"\"\nLinear Regression Tool Box\n\nimoprt:\n from HSH.DataSci.linreg import linreg_predict\n\"\"\"\n\nfrom __future__ import print_function\nfrom sklearn.linear_model import LinearRegression\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\ndef linreg_predict(X, y, X1):\n \"\"\"多元线性回归预测器\n \"\"\"\n if type(X) != np.ndarray: # 如果x不是np.ndarray\n X = np.array(X) # 则转换成np.ndarray\n if len(X.shape) == 1: # 如果是一维行向量\n X = X[np.newaxis].transpose() # 转化成列向量\n if type(X1) != np.ndarray: # 如果x不是np.ndarray\n X1 = np.array(X1) # 则转换成np.ndarray\n if len(X1.shape) == 1: # 如果是一维行向量\n X1 = X1[np.newaxis].transpose() # 转化成列向量\n clf = LinearRegression()\n clf.fit(X,y)\n return clf.predict(X1) \n\ndef linreg_coef(X, y):\n \"\"\"多元线性回归预测器\n \"\"\"\n if type(X) != np.ndarray: # 如果x不是np.ndarray\n X = np.array(X) # 则转换成np.ndarray\n if len(X.shape) == 1: # 如果是一维行向量\n X = X[np.newaxis].transpose() # 转化成列向量\n clf = LinearRegression()\n clf.fit(X,y)\n return clf.intercept_, clf.coef_\n\ndef glance_2d(x, y):\n \"\"\"多元线性回归一瞥\n \"\"\"\n if type(x) != np.ndarray: # 如果x不是np.ndarray\n x = np.array(x) # 则转换成np.ndarray\n if len(x.shape) == 1: # 如果是一维行向量\n x = x[np.newaxis].transpose() # 转化成列向量\n clf = LinearRegression()\n clf.fit(x,y)\n print(\"coef = %s, constant = %s\" % (clf.coef_, clf.intercept_))\n y2 = clf.predict(x)\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n plt.plot(x, y, \".\")\n plt.plot(x, y2, \"-\")\n ax.set_xlabel(\"x\") # 子图的 x axis label\n ax.set_ylabel(\"y\")\n plt.show()\n","sub_path":"angora/DATASCI/linreg.py","file_name":"linreg.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"432012433","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"Test #03.\"\"\"\n\nimport sys\nfrom PyQt4 import QtGui\n\nclass Tooltip(QtGui.QWidget):\n \"\"\"Widget with tooltip.\"\"\"\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n\n self.setGeometry(300, 300, 250, 150)\n self.setWindowTitle('Tooltip')\n\n self.setToolTip('This is a QWidget widget')\n QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10))\n\ndef main():\n \"\"\"Test #03.\"\"\"\n app = QtGui.QApplication(sys.argv)\n tooltip = Tooltip()\n tooltip.show()\n app.exec_()\n","sub_path":"tests/t_03.py","file_name":"t_03.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"393348771","text":"from base.models.model import Model\nfrom base.descriptors import ValueSubfield\nfrom base.exceptions import NoContentRawDataException\n\nfrom patent.utils import clean_application_number, clean_open_number, clean_granted_number, get_node_value, \\\n get_root, get_last, is_granted_number, clean_pre_granted_number, console_log, is_utility_from_document_type\nfrom patent import repair\n\n\nclass PatentRawKr(Model):\n class Meta:\n proxy = True\n\n application_number = ValueSubfield('data', str) # 출원번호\n open_number = ValueSubfield('data', str) # 공개번호\n pre_granted_number = ValueSubfield('data', str) # 공고번호\n granted_number = ValueSubfield('data', str) # 등록번호\n\n def init_data_by_raw(self):\n raw = self.raw\n self.uname = raw['item']\n\n def set_publication_number(self, publication_number, document_type):\n is_utility = is_utility_from_document_type(document_type)\n\n if '공개' in document_type or 'A' in document_type or 'U' in document_type:\n self.open_number = clean_open_number(publication_number, is_utility)\n elif '등록' in document_type or 'B1' in document_type or 'Y1' in document_type:\n if is_granted_number(publication_number):\n self.granted_number = clean_granted_number(publication_number)\n else:\n self.pre_granted_number = clean_pre_granted_number(publication_number, is_utility)\n else:\n self.pre_granted_number = clean_pre_granted_number(publication_number, is_utility)\n\n\nclass PatentRawKr기계번역국문초록(PatentRawKr):\n class Meta:\n proxy = True\n\n\nclass PatentRawKr특허영문초록(PatentRawKr):\n class Meta:\n proxy = True\n\n\nclass PatentRawKr한국특실공개등록공보_ST96(PatentRawKr):\n class Meta:\n proxy = True\n\n def init_data_by_raw(self):\n super().init_data_by_raw()\n raw = get_root(self.raw['content'])\n biblio = raw['krpat_PatentBibliographicData']\n # 출원번호\n self.application_number = clean_application_number(get_node_value(\n biblio['pat_ApplicationIdentification']['com_ApplicationNumber']['com_ApplicationNumberText']))\n # 출판번호 : 공개번호 or 공고번호 or 등록번호\n publications = get_last(biblio['krpat_PatentPublicationIdentificationBag'])\n for publication in publications if isinstance(publications, list) else [publications]:\n document_type = get_node_value(publication['com_PatentDocumentKindCode'])\n assert document_type in ('A', 'B1', 'Y1', 'U')\n if 'pat_PublicationNumber' in publication:\n publication_number = get_node_value(publication['pat_PublicationNumber'])\n self.set_publication_number(publication_number, document_type)\n # 등록번호\n raw_granted_number = None\n if 'pat_PatentGrantIdentification' in biblio:\n raw_granted_number = biblio['pat_PatentGrantIdentification']['pat_PatentNumber']\n elif 'krpat_PatentGrantIdentification' in biblio:\n raw_granted_number = biblio['krpat_PatentGrantIdentification']['pat_PatentNumber']\n if raw_granted_number:\n if is_granted_number(raw_granted_number):\n self.granted_number = clean_granted_number(raw_granted_number)\n else:\n assert self.pre_granted_number == clean_pre_granted_number(raw_granted_number)\n\n\nclass PatentRawKr한국특실공개공보_ST36(PatentRawKr):\n class Meta:\n proxy = True\n\n def init_data_by_raw(self):\n super().init_data_by_raw()\n raw = get_root(self.raw['content'])\n if 'KR_Bibliographic' in raw:\n biblio = raw['KR_Bibliographic']\n document_type = biblio['KR_DocumentType'].split('(')[0]\n self.application_number = clean_application_number(get_node_value(biblio['KR_ApplicationInformation']['KR_ApplicationNumber']))\n if 'KR_OpenNumber' in biblio:\n publication_number = get_node_value(biblio['KR_OpenNumber'])\n self.set_publication_number(publication_number, document_type)\n assert self.open_number\n else:\n assert '등록' in document_type\n publication_number = get_node_value(biblio['KR_RegisterNumber'])\n self.set_publication_number(publication_number, document_type)\n assert self.granted_number\n elif 'SDOBI' in raw:\n biblio = raw['SDOBI']\n document_type = biblio['B121'].split('(')[0]\n self.application_number = clean_application_number(get_node_value(biblio['B200']['B210']))\n publication_number = get_node_value(biblio['B110'])\n self.set_publication_number(publication_number, document_type)\n else:\n assert False, console_log('처리 불가능한 형식의 raw data 입니다.', extra=raw)\n\n\nclass PatentRawKr한국특실공개공보_ST36_sgml(PatentRawKr):\n class Meta:\n proxy = True\n\n def init_data_by_raw(self):\n super().init_data_by_raw()\n body = self.raw['content']['html']['body']\n if 'sdobi' in body:\n biblio = body['sdobi']\n else:\n try:\n biblio = get_root(body)['sdobi']\n except KeyError:\n raise NoContentRawDataException\n document_type = biblio['b121'].split('(')[0]\n try:\n is_utility = is_utility_from_document_type(document_type)\n self.application_number = clean_application_number(get_node_value(biblio['b200']['b210']), is_utility)\n except AssertionError as e:\n file_name = self.raw['item'].split('/')[-1]\n if file_name in repair.파일특허번호:\n numbers = repair.파일특허번호[file_name]\n self.application_number = numbers[0]\n self.open_number = numbers[1]\n self.pre_granted_number = numbers[2]\n self.granted_number = numbers[3]\n return\n raise e\n if 'b110' in biblio:\n publication_number = get_node_value(biblio['b110'])\n try:\n self.set_publication_number(publication_number, document_type)\n except Exception as e:\n if self.application_number == '1019970709480':\n self.open_number = '1019990023010'\n else:\n raise e\n\n\nclass PatentRawKr한국특실등록공보_ST36(PatentRawKr):\n class Meta:\n proxy = True\n\n def init_data_by_raw(self):\n super().init_data_by_raw()\n raw = get_root(self.raw['content'])\n if 'KR_Bibliographic' in raw:\n biblio = raw['KR_Bibliographic']\n self.application_number = clean_application_number(get_node_value(biblio['KR_ApplicationInformation']['KR_ApplicationNumber']))\n if 'KR_RegisterNumber' in biblio:\n self.granted_number = clean_granted_number(get_node_value(biblio['KR_RegisterNumber']))\n else:\n assert 'KR_OpenNumber' in biblio\n self.open_number = clean_open_number(get_node_value(biblio['KR_OpenNumber']))\n # TODO : 공개번호인지 공고번호인지 판단할 수 있는 방법 ���악 후 부활\n # publication_number = get_node_value(biblio['KR_PublicationNumber'])\n # self.set_publication_number(publication_number, document_type)\n elif 'SDOBI' in raw:\n biblio = raw['SDOBI']\n document_type = biblio['B121'].split('(')[0]\n self.application_number = clean_application_number(get_node_value(biblio['B200']['B210']))\n publication_number = get_node_value(biblio['B110'])\n self.set_publication_number(publication_number, document_type)\n else:\n assert False, console_log('처리 불가능한 형식의 raw data 입니다.', extra=raw)\n\n\nclass PatentRawKr한국특실등록공보_ST36_sgml(PatentRawKr한국특실공개공보_ST36_sgml):\n class Meta:\n proxy = True\n","sub_path":"patent/models/raw_kr.py","file_name":"raw_kr.py","file_ext":"py","file_size_in_byte":8145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"174323109","text":"import csv\nfrom data_loader import Data_loader\nfrom preprocess import preprocess\nfrom gensim.models import Word2Vec, KeyedVectors\nimport numpy as np\nimport pickle\n\ndef preprocess_aave():\n path = '../TwitterAAE-full-v1/twitteraae_all_aa'\n sentences = []\n with open(path) as f:\n tsv_reader = csv.reader(f, delimiter='\\t')\n text_idx = 5\n line = 0\n for row in tsv_reader:\n if line % 10000 == 0: print(line)\n text_bytes = preprocess(row[text_idx]) # unicode, non-readable for w2v\n sentences.append(text_bytes.split(b' '))\n line += 1\n print('Num of sentences:', len(sentences))\n print('Check sentence0:', sentences[0])\n pickle.dump(sentences, open('preprocessed_aave.pkl', 'wb'))\n\ndef unicode_to_str_idx(extension):\n unicode_sentences = pickle.load(open('preprocessed_' + extension + '.pkl', 'rb'))\n str_idx_sentences = []\n unicode2idx = {}\n for u_sent in unicode_sentences:\n str_idx_sent = []\n for u_word in u_sent:\n if u_word not in unicode2idx:\n idx = len(unicode2idx)\n unicode2idx[u_word] = idx\n str_idx_sent.append(str(unicode2idx[u_word]))\n str_idx_sentences.append(str_idx_sent)\n print('Num of sentences:', len(str_idx_sentences))\n print('Check sentence0:', str_idx_sentences[0])\n pickle.dump(str_idx_sentences, open('sentences_' + extension + '.pkl', 'wb'))\n pickle.dump(unicode2idx, open('unicode2idx_' + extension + '.pkl', 'wb'))\n\ndef train_embeddings(extension):\n sentences = pickle.load(open('sentences_' + extension + '.pkl', 'rb'))\n # our w2v settings for our dataset\n size = 300\n window = 5\n min_count = 5\n epochs = 20\n print('Training Word2Vec...')\n model = Word2Vec(sentences, size=size, window=window,\n\t\t\t\t\t min_count=min_count, iter=epochs)\n wv = model.wv\n print('Finished. Vocab size:', len(wv.vocab))\n vocab = list(sorted([w for w in wv.vocab], key=lambda x: int(x))) # sort by idx\n print('First 10 words in vocab:', vocab[:10])\n print('Last 10 words in vocab:', vocab[-10:])\n\n out_file = '../data/{0}_w2v_s{1}_w{2}_mc{3}_ep{4}.bin'.format(extension, size, window, min_count, epochs)\n wv.save_word2vec_format(out_file, binary=True)\n print('Word2Vec vectors saved to', out_file)\n\ndef make_word_emb_for_nn(extension):\n size = 300\n window = 5\n min_count = 5\n epochs = 20\n w2v_file = '../data/{0}_w2v_s{1}_w{2}_mc{3}_ep{4}.bin'.format(extension, size, window, min_count, epochs)\n wv = KeyedVectors.load_word2vec_format(w2v_file, binary=True)\n print('Number of embeddings in {}: {}'.format(w2v_file, len(wv.vocab)))\n\n unicode2idx_pkl = 'unicode2idx_' + extension + '.pkl'\n unicode2idx = pickle.load(open(unicode2idx_pkl, 'rb')) # complete vocab\n print('Size of complete vocab:', len(unicode2idx))\n\n dl = Data_loader(labeled_only=True)\n vocab_size = 40000\n dim = 300\n embeds = np.zeros((vocab_size, dim), dtype=np.float)\n embeds[1] = np.random.uniform(-0.25, 0.25, dim)\n not_in_vocab = 0\n not_in_w2v = 0\n for dl_idx in range(2, vocab_size):\n unicode = dl.convert2unicode([dl_idx]).encode('utf-8')\n if unicode in unicode2idx:\n ext_idx = unicode2idx[unicode]\n if str(ext_idx) in wv.vocab:\n embeds[dl_idx] = wv[str(ext_idx)]\n else:\n not_in_w2v += 1\n embeds[dl_idx] = np.random.uniform(-0.25, 0.25, dim)\n else:\n not_in_vocab += 1\n embeds[dl_idx] = np.random.uniform(-0.25, 0.25, dim)\n print(not_in_vocab, 'not in vocab')\n print(not_in_w2v, 'not in word2vec (min_count=5)')\n missed = not_in_vocab + not_in_w2v\n print('Total: got {} embeddings, missed {}, out of {}'.format(vocab_size-missed, missed, vocab_size))\n\n save_file = 'word_emb_' + extension + '.np'\n np.savetxt(save_file, embeds)\n print('Saved embeddings in', save_file)\n\ndef check_our_stats():\n wv = KeyedVectors.load_word2vec_format('../data/w2v_word_s300_w5_mc5_ep20.bin', binary=True)\n print('Number of embeddings in our W2V:', len(wv.vocab))\n\n splex = pickle.load(open('../data/splex_standard_svd_word_s300_seeds_hc.pkl', 'rb'))\n print('Number of embeddings in SPLex:', len(splex))\n\n in_w2v = 2 # everyone gets 0 and 1 as freebies\n in_splex = 2\n vocab_size = 40000\n for idx in range(2, vocab_size):\n str_idx = str(idx)\n if str_idx in wv.vocab:\n in_w2v += 1\n if str_idx in splex:\n in_splex += 1\n print('Our W2V: got {} embeddings, missed {}'.format(in_w2v, vocab_size-in_w2v))\n print('SPLex: got {} embeddings, missed {}'.format(in_splex, vocab_size-in_splex))\n\nif __name__ == '__main__':\n # preprocess_aave()\n # unicode_to_str_idx('aave')\n # train_embeddings('aave')\n # make_word_emb_for_nn('aave')\n check_our_stats()","sub_path":"src/compare_embeddings.py","file_name":"compare_embeddings.py","file_ext":"py","file_size_in_byte":4910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"153659541","text":"import torch\nimport torch.nn as nn \nimport torch.nn.functional as F\nfrom torch.nn.utils import weight_norm as wn\nfrom tqdm import tqdm\nfrom models.interface import ConditionedGenerativeModel\n\ndef normal_init(m, mean, std):\n if isinstance(m, nn.ConvTranspose2d) or isinstance(m, nn.Conv2d):\n m.weight.data.normal_(mean, std)\n m.bias.data.zero_()\n\nclass CDCGAN_D(nn.Module):\n # initializers\n def __init__(self, embed_dim=10, n_filters=128):\n super(CDCGAN_D, self).__init__()\n self.conv1_1 = nn.Conv2d(3, n_filters//2, 4, 2, 1)\n self.conv1_2 = nn.Conv2d(embed_dim, n_filters//2, 4, 2, 1)\n self.conv2 = nn.Conv2d(n_filters, n_filters*2, 4, 2, 1)\n self.conv2_bn = nn.BatchNorm2d(n_filters*2)\n self.conv3 = nn.Conv2d(n_filters*2, n_filters*4, 4, 2, 1)\n self.conv3_bn = nn.BatchNorm2d(n_filters*4)\n self.conv4 = nn.Conv2d(n_filters*4, 1, 4, 1, 0)\n\n # weight_init\n def weight_init(self, mean, std):\n for m in self._modules:\n normal_init(self._modules[m], mean, std)\n\n # forward method\n def forward(self, input, embed):\n x = F.leaky_relu(self.conv1_1(input), 0.2)\n y = F.leaky_relu(self.conv1_2(embed), 0.2)\n x = torch.cat([x, y], 1)\n x = F.leaky_relu(self.conv2_bn(self.conv2(x)), 0.2)\n x = F.leaky_relu(self.conv3_bn(self.conv3(x)), 0.2)\n x = F.sigmoid(self.conv4(x))\n\n return x\n\nclass CDCGAN_G(nn.Module):\n def __init__(self, z_dim=100, embed_dim=10, n_filters=128):\n super(CDCGAN_G, self).__init__()\n self.z_dim = z_dim\n self.deconv1_1 = nn.ConvTranspose2d(z_dim, n_filters*2, 4, 1, 0)\n self.deconv1_1_bn = nn.BatchNorm2d(n_filters*2)\n self.deconv1_2 = nn.ConvTranspose2d(embed_dim, n_filters*2, 4, 1, 0)\n self.deconv1_2_bn = nn.BatchNorm2d(n_filters*2)\n self.deconv2 = nn.ConvTranspose2d(n_filters*4, n_filters*2, 4, 2, 1)\n self.deconv2_bn = nn.BatchNorm2d(n_filters*2)\n self.deconv3 = nn.ConvTranspose2d(n_filters*2, n_filters, 4, 2, 1)\n self.deconv3_bn = nn.BatchNorm2d(n_filters)\n self.deconv4 = nn.ConvTranspose2d(n_filters, 3, 4, 2, 1)\n\n # weight_init\n def weight_init(self, mean, std):\n for m in self._modules:\n normal_init(self._modules[m], mean, std)\n\n # forward method\n def forward(self, input, embed):\n x = F.relu(self.deconv1_1_bn(self.deconv1_1(input)))\n y = F.relu(self.deconv1_2_bn(self.deconv1_2(embed)))\n x = torch.cat([x, y], 1)\n x = F.relu(self.deconv2_bn(self.deconv2(x)))\n x = F.relu(self.deconv3_bn(self.deconv3(x)))\n x = F.tanh(self.deconv4(x))\n \n return x\n\n def sample(self, captions_embd):\n '''\n :param captions_embd: torch.FloatTensor bsize * embd_size\n :return: imgs : torch.FloatTensor of size n_imgs * c * h * w\n '''\n\n z = torch.randn(captions_embd.shape[0], self.z_dim, 1, 1).to(captions_embd.device)\n with torch.no_grad():\n gen_imgs = self.forward(z, captions_embd.unsqueeze(dim=2).unsqueeze(dim=3))\n gen_imgs = (gen_imgs + 1) / 2\n\n return gen_imgs","sub_path":"models/cgan.py","file_name":"cgan.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"515275556","text":"num_charac = []\nword = []\n\naux = 1\nj = 0\n\nwhile aux != 0:\n\n num_charac += [int(input(\"Number of characters: \"))]\n aux = num_charac[len(num_charac)-1]\n if aux > 0:\n word += [input(\"Target word: \")]\n\nfor i in range(len(word)):\n aux = \"\"\n for j in range(len(word[i])-1, -1, -1):\n aux += word[i][j]\n word[i] = aux\n\n\nprint(word)\n\n'''for i in range(len(num_charac)):\n aux = \"\"\n j = len(num_charac)-1\n while j >= 0:\n aux += word[i][j]\n j -= 1\n word[i] = aux\n\nfor i in range(len(word)):\n print(word[i])'''","sub_path":"P1-LP1/lista 2/caracteres invertidos.py","file_name":"caracteres invertidos.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"102301960","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\n ┏┛ ┻━━━━━┛ ┻┓\n ┃       ┃\n ┃   ━   ┃\n ┃ ┳┛  ┗┳ ┃\n ┃       ┃\n ┃   ┻   ┃\n ┃       ┃\n ┗━┓   ┏━━━┛\n ┃   ┃ 神兽保佑\n ┃   ┃ 代码无BUG!\n ┃   ┗━━━━━━━━━┓\n ┃        ┣┓\n ┃     ┏┛\n ┗━┓ ┓ ┏━━━┳ ┓ ┏━┛\n ┃ ┫ ┫ ┃ ┫ ┫\n ┗━┻━┛ ┗━┻━┛\n\"\"\"\n\nimport os\nimport pickle\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport numpy as np\n\n\ndef load_file(file_name):\n with open(file_name, 'r', encoding='utf-8') as f:\n data_line = f.read()\n data_line = data_line.split('\\n')\n text = []\n label = []\n for each in tqdm(data_line):\n if each == '':\n continue\n a, b = each.split('\\t')\n text.append(a)\n label.append(int(b))\n return text, label\n\n\ndef handle_data(data, config):\n input_ids = []\n token_type_ids = []\n attention_mask = []\n tokenizer = config.tokenizer\n for each in tqdm(data):\n temp = tokenizer.encode_plus(each, max_length=32, padding='max_length', truncation=True)\n # input_ids.append(np.asarray(temp['input_ids'], dtype=np.int32))\n # token_type_ids.append(np.asarray(temp['token_type_ids'], dtype=np.int32))\n # attention_mask.append(np.asarray(temp['attention_mask'], dtype=np.int32))\n input_ids.append(temp['input_ids'])\n token_type_ids.append(temp['token_type_ids'])\n attention_mask.append(temp['attention_mask'])\n input_ids = np.asarray(input_ids, dtype=np.int32)\n token_type_ids = np.asarray(token_type_ids, dtype=np.int32)\n attention_mask = np.asarray(attention_mask, dtype=np.int32)\n return [input_ids, token_type_ids, attention_mask]\n\n\ndef load_data(config):\n if os.path.exists(config.save_pkl):\n with open(config.save_pkl, 'rb') as f:\n data = pickle.load(f)\n return data['train_text'], data['train_label'], data['dev_text'], data['dev_label'], data['test_text'], data[\n 'test_label']\n else:\n train_text, train_label = load_file(config.train_path)\n dev_text, dev_label = load_file(config.dev_path)\n test_text, test_label = load_file(config.test_path)\n\n train_text = handle_data(train_text, config)\n dev_text = handle_data(dev_text, config)\n test_text = handle_data(test_text, config)\n\n train_label = tf.keras.utils.to_categorical(train_label, num_classes=config.num_classes)\n dev_label = tf.keras.utils.to_categorical(dev_label, num_classes=config.num_classes)\n test_label = tf.keras.utils.to_categorical(test_label, num_classes=config.num_classes)\n\n # train_text = np.array(train_text, dtype=np.int32)\n # train_label = np.array(train_label, dtype=np.int32)\n # dev_text = np.array(dev_text, dtype=np.int32)\n dev_label = np.array(dev_label, dtype=np.int32)\n test_text = np.array(test_text, dtype=np.int32)\n test_label = np.array(test_label, dtype=np.int32)\n\n data = {'train_label': train_label,\n 'train_text': train_text,\n 'dev_text': dev_text,\n 'dev_label': dev_label,\n 'test_text': test_text,\n 'test_label': test_label,\n }\n with open(config.save_pkl, 'wb') as f:\n pickle.dump(data, f)\n\n return train_text, train_label, dev_text, dev_label, test_text, test_label\n\n\nif __name__ == '__main__':\n from summary.models.BERTFC import Config\n\n c = Config()\n load_data(c)\n","sub_path":"summary/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"331966417","text":"from math import exp\nimport numpy as np\n\n\nclass LogisticRegression:\n \"\"\"\n Fits a logistic curve to the given data set.\n \"\"\"\n\n def __init__(self, l_rate, n_epoch):\n self._l_rate = l_rate\n self._n_epoch = n_epoch\n self._coeff = np.zeros((1, 1))\n\n def predict(self, row):\n return 1.0 / (1.0 + np.exp(- (self._coeff[0] + self._coeff[1] * row)))\n\n def fit(self, train, classes):\n try:\n self._coeff = [0.0 for i in range(train.shape[1] + 1)]\n except IndexError:\n self._coeff = [0.0 for i in range(2)]\n\n for epoch in range(self._n_epoch):\n sum_error = 0\n for i in range(train.shape[0]):\n row = train[i]\n yhat = self.predict(row)\n error = classes[i] - yhat\n sum_error += error ** 2\n self._coeff[0] = self._coeff[0] + self._l_rate * error * yhat * (1.0 - yhat)\n self._coeff[1] = self._coeff[1] + self._l_rate * error * yhat * (1.0 - yhat) * row\n if sum_error == 0:\n break\n\n if sum_error == 0:\n break\n\n print('>epoch=%d, lrate=%.3f, error=%.3f' % (epoch, self._l_rate, sum_error))\n\n def get_coeff(self):\n return self._coeff\n","sub_path":"ML/LogisticRegression.py","file_name":"LogisticRegression.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"183479750","text":"\nimport numpy as np\n\ndef phase_plot(ax, g, h, xmin, xmax, ymin, ymax, gridsize=100):\n \"\"\"\n Plots the phase diagram for the system x' = g(x,y), y' = h(x,y)\n over the square [xmin, xmax] times [ymin, ymax].\n \"\"\"\n\n ax.set_xlim(xmin, xmax)\n ax.set_ylim(ymin, ymax)\n\n delta_g = np.vectorize(lambda x, y: x - g(x, y))\n delta_h = np.vectorize(lambda x, y: y - h(x, y))\n xgrid = np.linspace(xmin, xmax, gridsize)\n ygrid = np.linspace(ymin, ymax, gridsize)\n X, Y = np.meshgrid(xgrid, ygrid)\n Zg, Zh = delta_g(X, Y), delta_h(X, Y)\n \n ax.contour(X, Y, Zg, [.0], lw=2, alpha=0.8)\n ax.contour(X, Y, Zh, [.0], lw=2, alpha=0.8)\n\n def draw_arrow(x, y):\n eps = 0.0001\n v1, v2 = g(x, y) - x, h(x, y) - y\n nrm = np.sqrt(v1**2 + v2**2)\n scale = eps / nrm\n ax.arrow(x, y, scale * v1, scale * v2,\n antialiased=True, \n alpha=0.8,\n head_length=0.025*(xmax - xmin), \n head_width=0.012*(xmax - xmin),\n fill=False)\n\n xgrid = np.linspace(xmin * 1.1, xmax * 0.95, 12)\n ygrid = np.linspace(ymin * 1.1, ymax * 0.95, 12)\n for x in xgrid:\n for y in ygrid:\n draw_arrow(x, y)\n\n\n\n","sub_path":"code/phase_plot.py","file_name":"phase_plot.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"96912508","text":"#!/usr/bin/env python\n'''\nusage: ./gencircle (circle|drop) []\n'''\n\nimport numpy as np;\n\ndef mkcircle(dim=[-5e-4,5e-4,-5e-4,5e-4,],\n No=3e22,\n Ni=3e20,\n ro=5e-4,\n ri=0.0,\n Lo=1.6e-4,\n Li=None,\n floor=0.0,\n zero=0.0,):\n xlim = dim[:2];\n ylim = dim[2:];\n orig = [\n (xlim[1] + xlim[0]) / 2.0,\n (ylim[1] + ylim[0]) / 2.0];\n minL = 1e-9\n if not Lo or np.abs(Lo) < minL:\n outside = lambda r: np.zeroes(r.shape);\n else:\n outside = lambda r: np.exp(-np.abs(r-ro)/Lo)*No;\n \n if not Li or np.abs(Li) < minL:\n inside = lambda r: np.ones(r.shape)*Ni;\n else:\n inside = lambda r: np.exp(-np.abs(ri-r)/Li)*No;\n \n def f(x,y):\n out = np.zeros(x.shape);\n rsq = (orig[0] - x)**2 + (orig[1] - y)**2\n r = np.sqrt(rsq);\n oexp = outside(r);\n out[r>=ro] = oexp[r>=ro];\n \n middle = np.logical_and(r < ro, r > ri)\n out[middle] = No;\n iexp = inside(r);\n out[r<=ri] = iexp[r<=ri];\n out = np.where(out > floor, out, floor);\n \n limout = np.logical_or(x <= xlim[0], x >= xlim[1]);\n limout = np.logical_or(limout, y<=ylim[0]);\n limout = np.logical_or(limout, y>=ylim[1]);\n out[limout] = zero;\n return out;\n return f;\n\nif __name__ == \"__main__\":\n from docopt import docopt\n opts=docopt(__doc__,help=True);\n dx = 0.025\n mn,mx = -16,16\n lmn, lmx = -20,20\n ro,ri = 5,3\n Lo=1.0;\n Li=1.0;\n if opts['circle']:\n F=mkcircle(\n dim=[mn,mx,mn,mx],\n No=1e22,\n Ni=None,\n floor = 1e19,\n ro=ro,\n ri=ri,\n Lo=Lo,\n Li=Li,\n zero=1.0,);\n elif opts['drop']:\n F=mkcircle(\n dim=[mn,mx,mn,mx],\n No=1e22,\n Ni=1e22,\n ro=ro,\n ri=ri,\n Lo=Lo,\n Li=None,\n zero=1.0,);\n else:\n raise ValueError(\"Choose one! See --help\");\n\n X,Y=np.mgrid[\n lmn:lmx + dx:dx,\n lmn:lmx + dx:dx];\n import matplotlib.pyplot as plt;\n from matplotlib.colors import LogNorm;\n S=F(X,Y)*3;\n p=plt.pcolormesh(\n X,Y,S,\n cmap='plasma',\n norm=LogNorm(),\n vmin=1e18,\n vmax=1e23,\n );\n plt.colorbar();\n plt.contour(X,Y,S,[1e19,1.7e21],colors=['gray','darkred']);\n plt.axis('equal');\n if opts['']:\n plt.savefig(opts['']);\n else:\n plt.show();\n \n","sub_path":"targs/gencircle.py","file_name":"gencircle.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"304386424","text":"#imports\nfrom google.cloud import storage\nimport json\nimport pytz\n\nimport os\nfrom dotenv import load_dotenv, find_dotenv\nload_dotenv(find_dotenv())\n\n#By default, the datetime object is naive in Python, so you need to make both of them either naive or aware datetime objects\nutc=pytz.UTC\n\n#main code\ndef returndata(*args):\n\t#creating storage for nodes and relationships\n\tnodes\t \t\t= []\n\trelationships \t= []\n\t#initializing google client and accessing database\n\tgoogle_client \t= storage.Client()\n\tblobs \t\t\t= google_client.list_blobs(str(os.environ.get(\"BUCKET\")))\n\n\tpartial_sync = False\n\tif args[0] != ():\n\t\tpartial_sync = True\n\n\tfor blob in blobs:\n\t\tif((blob.content_type == 'application/json') and (partial_sync == False or (partial_sync == True and args[0][0].replace(tzinfo=utc) a and b > c\n\n\nwhile n != 0:\n magnitudes = [int(x) for x in input().split()]\n peaks = 0\n if is_peak(magnitudes[n-2], magnitudes[n-1], magnitudes[0]):\n peaks += 1\n if is_peak(magnitudes[n-1], magnitudes[0], magnitudes[1]):\n peaks += 1\n \n for i in range(1, n-1):\n a = magnitudes[i -1]\n b = magnitudes[i]\n c = magnitudes[i + 1]\n if is_peak(a,b,c):\n peaks += 1\n print(peaks)\n n= int(input())","sub_path":"f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"550873846","text":"from app import mythic, db_objects\nfrom sanic.response import json\nfrom sanic_jwt.decorators import scoped, inject_user\nimport app.database_models.model as db_model\nfrom sanic.exceptions import abort\nfrom math import ceil\nfrom peewee import fn\n\n\n@mythic.route(mythic.config['API_BASE'] + \"/event_message\", methods=['POST'])\n@inject_user()\n@scoped('auth:user')\nasync def add_event_message(request, user):\n if user['auth'] not in ['access_token', 'apitoken']:\n abort(status_code=403, message=\"Cannot access via Cookies. Use CLI or access via JS in browser\")\n if user['view_mode'] == 'spectator':\n return json({'status': 'error', 'error': 'Spectators cannot send messages'})\n try:\n query = await db_model.operator_query()\n operator = await db_objects.get(query, username=user['username'])\n query = await db_model.operation_query()\n operation = await db_objects.get(query, name=user['current_operation'])\n data = request.json\n if 'message' not in data:\n return json({'status': 'error', 'error': 'message is required'})\n await db_objects.create(db_model.OperationEventLog, operator=operator, operation=operation,\n message=data['message'])\n return json({'status': 'success'})\n except Exception as e:\n return json({'status': 'error', 'error': str(e)})\n\n\n@mythic.route(mythic.config['API_BASE'] + \"/event_message/\", methods=['PUT'])\n@inject_user()\n@scoped('auth:user')\nasync def edit_event_message(request, user, eid):\n if user['auth'] not in ['access_token', 'apitoken']:\n abort(status_code=403, message=\"Cannot access via Cookies. Use CLI or access via JS in browser\")\n if user['view_mode'] == 'spectator':\n return json({'status': 'error', 'error': 'Spectators cannot edit messages'})\n try:\n query = await db_model.operator_query()\n operator = await db_objects.get(query, username=user['username'])\n query = await db_model.operation_query()\n operation = await db_objects.get(query, name=user['current_operation'])\n data = request.json\n query = await db_model.operationeventlog_query()\n msg = await db_objects.get(query, id=eid, operation=operation)\n if 'message' not in data and 'resolved' not in data:\n return json({'status': 'error', 'error': 'message or resolve status is required'})\n else:\n if user['admin'] or msg.operator == operator or operation.name in user['admin_operations']:\n if 'message' in data:\n msg.message = data['message']\n if 'resolved' in data:\n msg.resolved = data['resolved']\n await db_objects.update(msg)\n else:\n return json({'status': 'error', 'error': \"You must be the author of the message, a global admin, or operation admin to edit that message\"})\n return json({'status': 'success', **msg.to_json()})\n except Exception as e:\n return json({'status': 'error', 'error': str(e)})\n\n\n@mythic.route(mythic.config['API_BASE'] + \"/event_message/delete\", methods=['POST'])\n@inject_user()\n@scoped('auth:user')\nasync def remove_event_messagse(request, user):\n if user['auth'] not in ['access_token', 'apitoken']:\n abort(status_code=403, message=\"Cannot access via Cookies. Use CLI or access via JS in browser\")\n if user['view_mode'] == 'spectator':\n return json({'status': 'error', 'error': 'Spectators cannot remove messages'})\n try:\n query = await db_model.operator_query()\n operator = await db_objects.get(query, username=user['username'])\n query = await db_model.operation_query()\n operation = await db_objects.get(query, name=user['current_operation'])\n data = request.json\n query = await db_model.operationeventlog_query()\n not_authorized = False\n for e in data['messages']:\n # given an array of message ids to delete, try to delete them all\n msg = await db_objects.get(query, id=e, operation=operation)\n if user['admin'] or msg.operator == operator or operation.name in user['admin_operations']:\n msg.deleted = True\n await db_objects.update(msg)\n else:\n not_authorized = True\n if not_authorized:\n return json({'status': 'error', 'error': \"Failed to delete some messages since you're not authorized\"})\n else:\n return json({'status': 'success'})\n except Exception as e:\n return json({'status': 'error', 'error': str(e)})\n\n\n@mythic.route(mythic.config['API_BASE'] + \"/event_message/search\", methods=['POST'])\n@inject_user()\n@scoped(['auth:user', 'auth:apitoken_user'], False) # user or user-level api token are ok\nasync def search_event_message(request, user):\n if user['auth'] not in ['access_token', 'apitoken']:\n abort(status_code=403, message=\"Cannot access via Cookies. Use CLI or access via JS in browser\")\n try:\n query = await db_model.operation_query()\n operation = await db_objects.get(query, name=user['current_operation'])\n query = await db_model.operationeventlog_query()\n except Exception as e:\n return json({'status': 'error', 'error': 'failed to find that file browsing object in your current operation'})\n try:\n data = request.json\n count = await db_objects.count(query.where(\n (db_model.OperationEventLog.operation == operation) &\n (fn.encode(db_model.OperationEventLog.message, 'escape').regexp(data['search']))).distinct())\n if 'page' not in data:\n # allow a blanket search to still be performed\n responses = await db_objects.execute(query.where(\n (db_model.OperationEventLog.operation == operation) &\n (fn.encode(db_model.OperationEventLog.message, 'escape').regexp(data['search']))).distinct())\n data['page'] = 1\n data['size'] = count\n else:\n if 'page' not in data or 'size' not in data or int(data['size']) <= 0 or int(data['page']) <= 0:\n return json({'status': 'error', 'error': 'size and page must be supplied and be greater than 0'})\n data['size'] = int(data['size'])\n data['page'] = int(data['page'])\n if data['page'] * data['size'] > count:\n data['page'] = ceil(count / data['size'])\n if data['page'] == 0:\n data['page'] = 1\n responses = await db_objects.execute(query.where(\n (db_model.OperationEventLog.operation == operation) &\n (fn.encode(db_model.OperationEventLog.message, 'escape').regexp(data['search']))).distinct().paginate(data['page'], data['size']))\n output = []\n for r in responses:\n rjson = r.to_json()\n output.append(rjson)\n return json(\n {'status': 'success', 'output': output, 'total_count': count, 'page': data['page'], 'size': data['size']})\n except Exception as e:\n print(e)\n return json({'status': 'error', 'error': str(e)})\n","sub_path":"mythic-docker/app/api/event_message_api.py","file_name":"event_message_api.py","file_ext":"py","file_size_in_byte":7153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"229482581","text":"import json\nfrom time import sleep\n\nfrom gdcdatamodel import models\nfrom gdcdictionary import gdcdictionary as dictionary\nfrom psqlgraph.mocks import NodeFactory\n\nfrom sheepdog.globals import RELEASE_BLOCKED\nfrom tests.integration.submission.test_endpoints import BLGSP_PATH\nfrom tests.integration.utils import convert_to_submission_json\n\nnode_factory = NodeFactory(models, dictionary.schema)\n\n\ndef assert_release_blocking_flag(json_nodes, g):\n with g.session_scope():\n for sub_json in json_nodes:\n node = g.nodes().props(\n project_id='CGCI-BLGSP',\n submitter_id=sub_json['submitter_id']).first()\n assert node\n assert node.sysan.get(RELEASE_BLOCKED) is True\n\n\ndef test_submitting_new_nodes_sets_blocking(\n client, submission_jsons, submitter, indexd_client, graph_fixture):\n \"\"\"\n Test that newly submitted nodes inherit release blocking flag\n \"\"\"\n\n resp = client.post(BLGSP_PATH, headers=submitter,\n data=json.dumps(submission_jsons))\n\n assert resp.status_code == 201\n\n # 2 seconds should be enough for the async tasks to finish\n sleep(2)\n assert_release_blocking_flag(submission_jsons, graph_fixture)\n\n\ndef test_updating_existing_nodes_sets_blocking(\n client, submission_jsons, submitter, indexd_client, graph_fixture,\n release_blocked_case):\n \"\"\"\n Test that updating a block released case doesn't reset the flag\n \"\"\"\n\n with graph_fixture.session_scope():\n case = graph_fixture.nodes().get(release_blocked_case.node_id)\n case_json = convert_to_submission_json(case)\n\n # Update case\n dtype = case_json['disease_type']\n _, dtype_new = node_factory.property_factories['case'].create('disease_type')\n\n while dtype_new == dtype:\n _, dtype_new = node_factory.property_factories['case'].create('disease_type')\n case_json['disease_type'] = dtype_new\n\n submission_with_case = [case_json] + submission_jsons\n resp = client.put(BLGSP_PATH, headers=submitter,\n data=json.dumps(submission_with_case))\n\n assert resp.status_code == 200, resp.json\n\n # 2 seconds should be enough for the async tasks to finish\n sleep(2)\n assert_release_blocking_flag(submission_with_case, graph_fixture)\n\n # Validate case node changes\n with graph_fixture.session_scope():\n case = graph_fixture.nodes().get(release_blocked_case.node_id)\n assert case.disease_type == dtype_new\n","sub_path":"tests/integration/submission/test_release_blocking.py","file_name":"test_release_blocking.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"463529199","text":"class Stack:\n def __init__(self):\n self.s = list()\n \n def push(self, e):\n self.s.append(e)\n \n def pop(self):\n return self.s.pop()\n \n def empty(self):\n return len(self.s) == 0\n \n def top(self):\n return self.s[-1]\n \nclass Solution:\n def trap(self, height: List[int]) -> int:\n \"\"\"\n Constraints:\n - Width of each bar is 1\n - n non-negative integers (0 or positive)\n Goal:\n - How much water it can trap\n Idea:\n - For storing water, boundaries should be higher than inside\n - Water stored is governed by 2 factors: height of bar\n - width between two bars\n - difference between boundaries and lesser hights inside\n store water\n - wait for first non zero boundary\n - look for lesser heights\n - diff between boundary and height is water stored\n - larger height make it boundary\n - First non-zero wall is boundary\n - If greater update boundary,\n - On finding greater\n \n - Select bars to be used as boundaries\n - Water between two bars\n - Remove bars smaller\n \"\"\"\n \"\"\"\n s = Stack() \n N, i = len(height), 0\n sol = 0\n while i < N:\n while not s.empty() and height[s.top()] < height[i]:\n index = s.pop()\n sol += (i-index-1)*height[index]\n s.push(i)\n i += 1\n return sol\n \"\"\"\n N = len(height)\n \n l, r = 1, N-2\n maxL, maxR = height[0], height[N-1]\n sol = 0\n while l <= r:\n if maxL < maxR: # Take the smaller one\n # We are taking smaller one here as\n # min(leftMax, rightMax) was done\n # and smaller is left so thats the bottleneck\n if maxL > height[l]:\n sol += (maxL-height[l])\n else:\n maxL = height[l]\n l += 1\n else:\n if maxR > height[r]:\n sol += (maxR-height[r])\n else:\n maxR = height[r]\n r -= 1\n return sol\n \"\"\"\n N = len(height)\n leftMax, rightMax = [0] * N, [0] * N\n \n leftMax[0] = 0\n for i in range(1, N):\n leftMax[i] = max(leftMax[i-1], height[i-1])\n \n rightMax[N-1] = 0\n for i in range(N-2, -1, -1):\n rightMax[i] = max(rightMax[i+1], height[i+1])\n sol = 0\n #print(leftMax, rightMax)\n for i in range(N):\n sol += max(0, (min(rightMax[i],leftMax[i])-height[i]))\n return sol\n \"\"\"\n \n \n \"\"\"\n def leftMax(i):\n # We are finding leftMax and rightMax again and againa hence Dynamic Programming can be used\n maximum = float('-inf')\n while i >= 0:\n maximum = max(maximum, height[i])\n i -= 1\n return maximum\n\n def rightMax(i):\n maximum = float('-inf')\n while i < N:\n maximum = max(maximum, height[i])\n i += 1\n return maximum\n \n N = len(height)\n sol = 0\n \n for i in range(N):\n sol += (min(leftMax(i), rightMax(i))-height[i])\n \n return sol\n \"\"\"\n","sub_path":"Algorithms/BottomUpProcessing/rainWater.py","file_name":"rainWater.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"304877631","text":"from governor.config import COL_FLAGS, BASE_URL, STATES, NO_STYLE\nfrom governor.scraper.clean_state import clean_state\nfrom selenium import webdriver\nimport time\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport re\n\n# todo: go back and hard code parties for accuarcy\n\n\ndef scrape_all_states(out_path):\n print(\"Initializing all state scrape.\")\n all_states = pd.DataFrame()\n errors = []\n # for state in STATES.keys():\n for state in [\"Montana\", \"Nevada\", \"Washington\", 'Nebraska', 'New Hampshire', 'New Mexico', 'North Carolina', 'North Dakota', 'South Carolina', 'South Dakota', 'Vermont', 'Virginia']:\n try:\n cleaned_state_df = scrape_state(state)\n all_states = all_states.append(cleaned_state_df)\n all_states.to_csv(f\"{out_path}all_states_governors_sample_nolt.csv\", index=False)\n except:\n errors += [state]\n print(f\"done. errors were {errors}\")\n\n\ndef scrape_state(state_to_scrape):\n print(f\"scraping {state_to_scrape}...\")\n scraped_state_df = get_state_df_from_wikipedia(state_to_scrape)\n cleaned_state_df = clean_state(scraped_state_df, state_to_scrape)\n return cleaned_state_df\n\n\ndef get_state_df_from_wikipedia(state_to_scrape, col_flags=COL_FLAGS):\n print(f\"setting up browser for {state_to_scrape}...\")\n soup, browser = set_up_browser(state_to_scrape)\n\n # grab all tables from the page\n tables = soup.find_all(\"table\")\n\n match = None\n i = 0\n for table in tables:\n if state_to_scrape in NO_STYLE.keys():\n if (len(table.attrs) >= 1) & (\"wikitable\" in table.attrs[\"class\"][0]):\n match = table\n i += 1\n if i == NO_STYLE[state_to_scrape]:\n break\n else:\n if (len(table.attrs) >= 1) & (\"style\" in table.attrs.keys()):\n if (\"wikitable\" in table.attrs[\"class\"][0]) & (\"text-align:\" in table.attrs[\"style\"]):\n match = table\n # else:\n # continue\n\n if match is not None:\n table_body = match.find('tbody')\n else:\n raise Exception(\"No valid table on this page.\")\n\n rows = table_body.find_all('tr')\n\n headers = list(col_flags.keys())\n headers.remove(\"war\")\n headers.remove(\"term2\")\n\n scraped_state_df = pd.DataFrame(\n columns=[\"starting_year\"] + headers\n )\n print(f\"mining governor data for {state_to_scrape}...\")\n for row, i in zip(rows, range(0, len(rows))):\n cols = row.find_all(\"td\")\n print(f\"col length: {len(cols)} | row: {i}\")\n row_key = identify_row(cols, col_flags)\n if row_key[\"war\"] != \"no data\":\n continue\n else:\n if len(cols) > 3:\n if row_key[\"party\"] == \"no data\":\n if len(row.find_all(\"th\")) > 0:\n cols = [row.find_all(\"th\")[0]] + cols\n row_key = identify_row(cols, col_flags)\n if row_key[\"party\"] == \"no data\":\n party = \"None\"\n else:\n continue\n else:\n party = cols[row_key[\"party\"]].text.strip()\n if row_key[\"term\"] == \"no data\":\n continue\n else:\n starting_year = cols[row_key[\"term\"]].text.strip().split(\",\")[1].strip()[:4]\n\n df = pd.DataFrame(\n {\n \"order\": [len(scraped_state_df)],\n \"term\": [cols[row_key[\"term\"]].text.strip()],\n \"party\": [party],\n \"starting_year\": [starting_year],\n }\n )\n if \"data-sort-value\" in cols[row_key[\"name\"]].attrs:\n df = df.assign(name=cols[row_key[\"name\"]][\"data-sort-value\"])\n else:\n df = df.assign(name=cols[row_key[\"name\"]].text.strip())\n scraped_state_df = scraped_state_df.append(df)\n else:\n continue\n\n return scraped_state_df\n\n\ndef identify_row(cols, col_flags):\n # make sure that we mirror col flags object.\n key = dict()\n for col in col_flags.keys():\n key[col] = \"no data\"\n # match the columns to their locations by header\n for cell, idx in zip(cols, range(0, len(cols))):\n if \"data-sort-value\" in cell.attrs.keys():\n if key[\"name\"] == \"no data\":\n key[\"name\"] = idx\n else:\n this_col = cell.text.strip()\n for col in key.keys():\n if key[col] == \"no data\":\n if re.search(col_flags[col], this_col):\n key[col] = idx\n break\n if key[\"war\"] != \"no data\":\n break\n return key\n\n\ndef set_up_browser(state_to_scrape):\n option = webdriver.ChromeOptions()\n option.add_argument(\"--incognito\")\n browser = webdriver.Chrome(executable_path=\"/Library/Application Support/Google/chromedriver\",\n options=option)\n browser.get(BASE_URL.format(capitalized_state=state_to_scrape))\n time.sleep(1)\n soup = BeautifulSoup(browser.page_source, 'lxml')\n return soup, browser\n\n\n","sub_path":"governor/scraper/scrape_state.py","file_name":"scrape_state.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"588345383","text":"from io import open\nimport os\nimport yaml\nimport re\n\n\ndef get_version(dunder_file):\n from pkg_resources import get_distribution, DistributionNotFound\n here = os.path.dirname(dunder_file)\n package = os.path.basename(here)\n\n try:\n version = get_distribution(package).version\n except DistributionNotFound:\n version = here\n return version\n\n\ndef dumpPackageData(dunder_file, filename='package.data.yaml'):\n \"\"\"\n Dumps the PackageData yaml to a dictionary form\n\n Returns\n -------\n manifest object : dict\n manifest object with the following structure:\n package_data:\n [path]: [filename1, filename2, ...]\n unpackage_data:\n [path]: [filename1, filename2, ...]\n \"\"\"\n basename, filename, manifest = getPackageData(dunder_file, filename)\n\n basedir = os.path.dirname(dunder_file)\n package_data = {basename: [filename], }\n for package_name, body in manifest['package_data'].items():\n arr = []\n for filepath, filenames in body.items():\n handler = PackageDataHanler(filenames)\n arr.extend(handler(basedir, filepath))\n package_data[package_name] = package_data.get(package_name, []) + arr\n return package_data\n\n\nclass PackageDataHanler:\n def __init__(self, filenames):\n self.nested = [f for f in filenames if '*' in f]\n self.flat = [f for f in filenames if '*' not in f]\n\n def __call__(self, basedir, filepath):\n arr = []\n arr.extend(self.runNested(basedir, filepath, self.nested))\n arr.extend(self.runFlat(filepath, self.flat))\n return arr\n\n @staticmethod\n def runNested(basedir, filepath, nested):\n walkDir = os.path.join(basedir, filepath)\n\n bad = ['__pycache__']\n def filt(tup): return all([b not in tup[0] for b in bad])\n\n arr = []\n for subdir, _, _ in filter(filt, os.walk(walkDir)):\n string = ''.join(subdir.split(basedir)[1:])\n parts = re.split(r'[\\\\/]', string)\n arr.extend([os.path.join(*parts, n) for n in nested])\n return arr\n\n @staticmethod\n def runFlat(filepath, filenames):\n arr = []\n parts = re.split(r'[\\\\/]', filepath)\n arr.extend([os.path.join(*parts, f) for f in filenames])\n return arr\n\n\ndef getPackageData(dunder_file, filename):\n \"\"\"\n Reads the PackageData yaml\n\n Returns\n -------\n basename: str\n filename: str\n manifest: dict\n \"\"\"\n here = os.path.abspath(os.path.dirname(dunder_file))\n basename = os.path.basename(here)\n manifest = yaml.load(\n open(\n os.path.join(\n here,\n filename),\n 'rb'),\n Loader=yaml.SafeLoader)\n return basename, filename, manifest\n","sub_path":"template/infra/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"79908033","text":"#!python\n\n\"\"\"\nPython script to count the number of aminoacids or nucleatides per sequence in a FASTA file\nCall it like so:\n python fasta_length.py sequences.fasta\n\"\"\"\n\nimport sys\n\nsequence_length = 0\nfasta_sequence_lengths = []\n\n\n\n# Getting the filename from the list of arguments\nfasta_filename = sys.argv[1]\n\n# Opening the file:\nfastafile = open(fasta_filename, 'r')\n\n# Iterating over all lines in the file:\nfor line in fastafile.readlines():\n if line.startswith('>'):\n if sequence_length:\n fasta_sequence_lengths.append(sequence_length)\n sequence_length = 0\n else:\n sequence_length += len(line.strip())\nfasta_sequence_lengths.append(sequence_length)\n\n# Closing the file:\nfastafile.close()\n\ndef print_stats(sequence_list):\n \"\"\" \n function which prints the sorted sequence length as well as\n the maximum and minimum sequence length\n \"\"\"\n print(sorted(sequence_list))\n print(\"The max is {} and the min is {}.\".format(max(sequence_list), min(sequence_list)))\n\nprint_stats(fasta_sequence_lengths)\n","sub_path":"fasta_length.py","file_name":"fasta_length.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"351560910","text":"from sys import exit\ndef gcd(a,b):#greatest common divisor\n if (a0):\n a,b = b ,a%b\n return a\nN = int(input())\nA = [int(n) for n in input().split()]\nstraight = [0]*N\nstraight[0] = gcd(A[0],A[0])\nfor i in range(1,len(A)):\n straight[i] = gcd(straight[i-1], A[i])\n\nA = A[::-1]\nback = [0]*N\nback[0] = gcd(A[0],A[0])\nfor i in range(1,len(A)):\n back[i] = gcd(back[i-1], A[i])\n\nback = back[::-1]\n# print(straight)\n# print(back)\nans = straight[-2]\nfor i in range(N-2):\n ans = max(ans, gcd(straight[i], back[i+2]))\n # print(straight[i],back[i+2])\n # print(gcd(straight[i], back[i+2]))\nans = max(ans, back[1])\nprint(ans)\n","sub_path":"problems/Beginner/C/125.py","file_name":"125.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"583594948","text":"\"\"\"\nDijkstra\n\"\"\"\n\ndef mult(e1, e2):\n \"\"\"\n return the multiplication result from the quaternion\n \"\"\"\n if e1 == '':\n return 1, e2\n elif e2 == '':\n return 1, e1\n elif e1 == 'i':\n if e2 == 'i':\n return -1, ''\n elif e2 == 'j':\n return 1, 'k'\n elif e2 == 'k':\n return -1, 'j'\n elif e1 == 'j':\n if e2 == 'i':\n return -1, 'k'\n elif e2 == 'j':\n return -1, ''\n elif e2 == 'k':\n return 1, 'i'\n elif e1 == 'k':\n if e2 == 'i':\n return 1, 'j'\n elif e2 == 'j':\n return -1, 'i'\n elif e2 == 'k':\n return -1, ''\n \ndef collapse(string, target):\n \"\"\"\n collapse the last few of the strings, \n see whether it will reach target\n return: True/False, leftover\n \"\"\"\n useString = ''\n sign = 1\n res = ''\n e2=''\n for i in range(len(string) - 1, -1, -1):\n useString = string[i] + useString\n e1 = string[i]\n res = mult(e1, e2)\n sign = sign * res[0]\n e2 = res[1]\n \n if res[1] == target and sign == 1:\n return True, string[:i]\n return False, ''\n \n \ndef decide(string):\n if len(string) < 3:\n return False\n elif len(string) == 3:\n return string == 'ijk'\n else:\n useString = string\n for target in 'kji':\n res = collapse(useString, target)\n if not res[0]:\n return False\n else:\n useString = res[1]\n return len(useString) == 0\n\nif __name__ == '__main__':\n nAtt = 0\n inputFileName = 'C-small-attempt' + str(nAtt) + '.in'\n outputFileName = 'C-small-attempt' + str(nAtt) + '.out'\n\n ## read input\n file = open(inputFileName)\n nCase = int(file.readline())\n\n rawInput = []\n for line in file:\n rawInput.append(line.split())\n\n cases = []\n for i in range(0, len(rawInput), 2):\n tmp = map(int, rawInput[i])\n cases.append([tmp, rawInput[i+1]])\n\n ## Output file\n outfile = open(outputFileName, 'w')\n count = 1\n for case in cases:\n res = decide(case[1][0] * case[0][1])\n if res:\n out = 'Yes'\n else: \n out = 'No'\n string = \"Case #\" + str(count) + ': ' + str(out) + '\\n'\n outfile.write(string)\n count += 1","sub_path":"_Archive/codeJam/C-Dijkstra.py","file_name":"C-Dijkstra.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"72241473","text":"from mongoengine import *\nfrom flask import *\nimport datetime\nimport time\n\nclass CityTestNumber(Document):\n\tcity = StringField(max_length=100)\n\ttotal_test = IntField()\n\nclass BookedTest(Document):\n\tcity = StringField(max_length=100)\n\tuser_email = StringField(max_length=100)\n\taddress = StringField(max_length=100)\n\tdate = DateTimeField(required=True)\n\tdone = BooleanField(default=False)\n\nclass TestDB():\n\n\tdef __init__(self):\n\t\tpass\n\n\tdef add_test(self, city, num):\n\t\ttest = CityTestNumber.objects(city=city) #first check if there is previous test in that city in CityTestNumber table\n\t\tif len(test) > 0: #if previously test exists in that city\n\t\t\tnew_total_test = test[0].total_test + num\n\t\t\ttest[0].update(total_test = new_total_test) #add number to total_test field\n\t\telse:\n\t\t\tcityTestNumber = CityTestNumber(city=city, total_test=num) #create new CityTestNumber object\t \n\t\t\tcityTestNumber.save() \n\t\treturn {\"Success\" : True}\n\n\t\n\tdef testNumberInCity(self, city):\n\t\ttest = CityTestNumber.objects(city=city)\n\t\treturn test[0].total_test #returns number of test in that city\n\n\n\tdef bookTest(self, city, user_email, address, date, done):\n\t\tbookedTest = BookedTest(city=city, user_email=user_email, address=address, date=date, done=done) #create new entry to bookedNurses field\n\t\tbookedTest.save() \n\t\treturn {\"Success\" : True}\n\n\n\tdef get_number_bookedTest(self, city, date): \n\t\tcnt_test = BookedTest.objects(city=city, date= date)\n\t\treturn len(cnt_test) #returns number of entries mathched with given city in bookedNurses \n\n\tdef remove_bookedTest(self, bookedTest_id ):\n\t\ttest = BookedTest.objects()\n\t\ttest = test.get( pk = bookedTest_id )\n\t\tif len(test) > 0:\n\t\t\ttest.delete()\n\t\t\treturn {\"Success\" : True}\n\t\telse:\n\t\t\t return {\"Success\" : False}\n\n\n\tdef get_users_booked_test(self, user_email):\n\t\ttests = BookedTest.objects(user_email=user_email) #contains test mathched with user_email from bookedNurses \n\t\ttestList = [] #list to store bookednurse details\n\n\t\tfor test in tests:\n\t\t\ttestDict = { #creating a dictionary for each cart\n\t\t\t\t '_id': str(test.pk),\n\t\t\t\t 'city': test.city,\n\t\t\t\t 'user_email': test.user_email,\n\t\t\t\t 'address': test.address,\n\t\t\t\t 'date': test.date,\n\t\t\t\t 'done': test.done\n\t\t\t}\n\t\t\ttestList.append(testDict)\n\t\treturn testList\n\n\tdef get_pending_bookedTest(self):\n\t\ttests = BookedTest.objects(done=False) #getting all entries from bookedNurses which done == false \n\t\ttestList = [] #list to store bookednurse details\n\n\t\tfor test in tests:\n\t\t\ttestDict = { #creating a dictionary with pending test\n\t\t\t\t '_id': str(test.pk),\n\t\t\t\t 'city': test.city,\n\t\t\t\t 'user_email': test.user_email,\n\t\t\t\t 'address': test.address,\n\t\t\t\t 'date': test.date,\n\t\t\t\t 'done': test.done\n\t\t\t}\n\t\t\ttestList.append(testDict)\n\t\treturn testList\n\n\n\tdef change_pending_bookedTest(self, bookedTest_id, done):\n\t\ttest = BookedTest.objects( pk = bookedTest_id )\n\t\ttest = test.get( pk = bookedTest_id ) \n\n\t\tif len(test) > 0:\n\t\t\ttest.update(done=done) #changing done field of the entry of bookedNurses_id table according to done\n\t\t\treturn {\"Success\" : True}\n\t\telse:\n\t\t\treturn {\"Success\" : False}\n\t\t\n\t\t\t\t\t\t\t\t \n\n\tdef get_all_bookedTest(self): \n\t\ttests = BookedTest.objects() #getting all entries from bookedNurses \n\t\ttestList = [] #list to store bookednurse details\n\n\t\tfor test in tests:\n\t\t\ttestDict = { #creating a dictionary with pending test\n\t\t\t\t '_id': str(test.pk),\n\t\t\t\t 'city': test.city,\n\t\t\t\t 'user_email': test.user_email,\n\t\t\t\t 'address': test.address,\n\t\t\t\t 'date': test.date,\n\t\t\t\t 'done': test.done\n\t\t\t}\n\t\t\ttestList.append(testDict)\n\t\treturn testList \n","sub_path":"testDB.py","file_name":"testDB.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"205588265","text":"UNKNOWN_SYMBOL_ERR = 0\nNOT_REACHED_FINAL_STATE = 1\nREACHED_FINAL_STATE = 2\n\n\nclass NewState:\n state = ''\n stack = ''\n\n def __init__(self, cur_state, cur_stack):\n self.state = cur_state\n self.stack = cur_stack\n\n\nclass PDA:\n _states = []\n _inputs = []\n _pd_inputs = []\n _sigma = None\n _start_state = ''\n _start_pd_character = ''\n _final_states = []\n _progress = []\n\n def __init__(self, states: list, inputs: list, pd_inputs: list,\n transitions: dict, start_state: str, start_pd_character: str, final_states: list):\n self._states = states\n self.total_states = len(states)\n\n self._inputs = inputs\n self._alphabet_characters = len(inputs)\n\n self._pd_inputs = pd_inputs\n self._pd_alphabet_characters = len(pd_inputs)\n\n self._sigma = transitions\n\n self._start_state = start_state\n\n self._start_pd_character = start_pd_character\n\n self._final_states = final_states\n self._total_final_states = len(final_states)\n\n self._progress.append(NewState(start_state, start_pd_character))\n\n def makeStep(self, current_symbol: chr) -> int:\n if current_symbol not in self._inputs and current_symbol != '':\n return UNKNOWN_SYMBOL_ERR\n\n new_step = []\n transitions = []\n empty_transitions = []\n\n for cur_state in self._progress:\n state = cur_state.state\n if len(cur_state.stack) == 0:\n top = ''\n else:\n top = cur_state.stack[0]\n\n cur_state.stack = cur_state.stack[1:]\n\n try:\n if (state, current_symbol, top) in self._sigma:\n transitions = self._sigma[(state, current_symbol, top)]\n for temp in transitions:\n print('δ(' + str(cur_state.state) +\n str(', ' + current_symbol + ', ').replace(', ,', ', λ,') +\n top + str(cur_state.stack) + ') -> (' + str(temp[0]) +\n str(', ' + str(temp[1]) + str(cur_state.stack) + ')').replace(', )', ', λ)'))\n\n # if (state, '', top) in self._sigma:\n # empty_transitions = self._sigma[(state, '', top)]\n # for temp in empty_transitions:\n # print('δ(' + str(cur_state.state) + ', ' + 'e' + ', ' + top + str(cur_state.stack) +\n # ') -> (' + str(temp[0]) + ', ' + str(temp[1]) + str(cur_state.stack) + ')')\n\n for transition in transitions:\n # δ(state, input, pop_stack) -> (new_state, push_stack)\n # tuple( , ); transition(state, stack); transition(0, 1)\n new_step.append(NewState(transition[0], transition[1] + cur_state.stack))\n\n # for transition in empty_transitions:\n # new_step.append(NewState(transition[0], transition[1] + cur_state.stack))\n except Exception as e:\n # Чтобы IDE не ругалась\n print(e)\n\n print()\n\n self._progress = new_step\n\n for variable in self._progress:\n if (variable.state in self._final_states and\n (variable.stack == '' or variable.stack == self._start_pd_character)):\n return REACHED_FINAL_STATE\n\n return NOT_REACHED_FINAL_STATE\n\n def is_done(self):\n for res in self._progress:\n if (len(res.stack) == 0 or res.stack == self._start_pd_character) and res.state in self._final_states:\n return False\n else:\n return True\n\n\nif __name__ == \"__main__\":\n result = NOT_REACHED_FINAL_STATE\n\n # PDA description\n cur_pda = PDA(states=['q0', 'q1', 'q2'],\n inputs=['a', 'b', 'c'],\n pd_inputs=['a', 'b', 'c', 'Z'],\n\n # δ(q, a, X) -> (p, γ)\n # δ(state, input, pop_stack) -> (new_state, push_stack)\n transitions={('q0', 'a', 'a'): [('q0', 'aa')],\n ('q0', 'a', 'Z'): [('q0', 'aZ')],\n ('q0', 'b', 'a'): [('q0', 'ba')],\n ('q0', 'b', 'b'): [('q0', 'bb')],\n ('q0', 'b', 'Z'): [('q0', 'bZ')],\n ('q0', 'c', 'b'): [('q0', ''), ('q0', 'bc')],\n ('q0', 'c', 'c'): [('q0', 'cc')],\n ('q0', '', 'Z'): [('q1', 'ZZ')],\n ('q0', '', 'a'): [('q1', '')],\n ('q1', '', 'a'): [('q1', '')],\n ('q1', '', 'Z'): [('q2', '')],\n },\n start_state='q0',\n start_pd_character='Z',\n final_states=['q2']\n )\n\n print(\"Enter a string with 'a's, 'b's and 'c's:\\nPress Enter Key to stop\\n\")\n\n input_str = input()\n i = 0\n\n while cur_pda.is_done():\n if i < len(input_str):\n symbol = input_str[i]\n else:\n symbol = ''\n i += 1\n\n result = cur_pda.makeStep(symbol)\n\n if UNKNOWN_SYMBOL_ERR == result:\n print('Unknown symbol error')\n break\n\n if REACHED_FINAL_STATE == result:\n print('Accepted')\n\n if NOT_REACHED_FINAL_STATE == result:\n print('Rejected')\n","sub_path":"Lab_3/PyPDA/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"454794378","text":"import re\nimport threading\nimport time\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Count\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom fake_useragent import UserAgent\nfrom taggit.models import Tag\n\nfrom .forms import NewAds, AdForm\nfrom .models import Ad\n\n\n@login_required\ndef show_ads(request):\n ads = Ad.objects.filter(owner=request.user).order_by('city')\n return render(request, 'show_ads.html', {'ads': ads, 'tags': Tag.objects.all()})\n\n\n@csrf_exempt\ndef filter_table(request):\n checks = request.POST.getlist('checks')\n if len(checks) > 0:\n return render(request, 'table.html',\n {'ads': Ad.objects.filter(tags__name__in=checks, owner=request.user).annotate(\n num_tags=Count('tags')).filter(num_tags__gte=len(checks)), 'tags': Tag.objects.all()})\n else:\n return render(request, 'table.html', {'ads': Ad.objects.filter(owner=request.user), 'tags': Tag.objects.all()})\n\n\n@csrf_exempt\ndef order_table(request):\n checks = request.POST.getlist('checks[]')\n if len(checks) > 0:\n return render(request, 'table.html',\n {'ads': Ad.objects.filter(tags__name__in=checks, owner=request.user).annotate(\n num_tags=Count('tags')).filter(num_tags__gte=len(checks)).order_by(\n request.POST.get('order')),\n 'tags': Tag.objects.all()})\n else:\n return render(request, 'table.html',\n {'ads': Ad.objects.filter(owner=request.user).order_by(request.POST.get('order')),\n 'tags': Tag.objects.all()})\n\n\n@login_required\ndef add_ads(request):\n form = NewAds\n return render(request, 'add_ads.html', {'form': form})\n\n\n@login_required\ndef edit_ad(request, ad_id):\n form = AdForm(instance=Ad.objects.filter(pk=ad_id).first())\n return render(request, 'edit_ad.html', {'form': form})\n\n\ndef process_ads(request):\n user = request.user\n if request.POST.get('other'):\n query = request.POST.get('other')\n else:\n query = request.POST.get('query')\n for u in request.POST.get('urls').splitlines():\n url = u\n iid = 'i' + re.search(r'\\d*$', url).group()\n city = url.split('/')[3]\n ad = Ad.objects.create(iid=iid, url=url, owner=user, city=city, position=0, query=query.format(city))\n for tag in request.POST.get('m_tags').split(' '):\n print(tag)\n ad.tags.add(tag)\n ad.save()\n return HttpResponseRedirect('/ads')\n\n\ndef save(request, ad_id):\n ad = Ad.objects.filter(pk=ad_id).first()\n ad.title = request.POST.get('title')\n ad.query = request.POST.get('query')\n ad.tags.clear()\n for tag in request.POST.get('tags').split():\n ad.tags.add(tag)\n ad.save()\n return HttpResponseRedirect('/ads')\n\n\n@csrf_exempt\ndef update(request):\n print(request.POST)\n t = threading.Thread(target=f, args=(request,))\n t.setDaemon(True)\n t.start()\n return HttpResponseRedirect('/ads')\n\n\ndef f(request):\n headers = {'User-Agent': str(UserAgent().chrome)}\n proxies = {'https': ''}\n if len(request.POST.getlist('checks[]')) > 0:\n tags = request.POST.getlist('checks[]')\n else:\n tags = list(Tag.objects.all())\n if request.POST.get('id'):\n ads = Ad.objects.filter(pk=int(request.POST.get('id')))\n else:\n ads = Ad.objects.filter(owner=request.user, tags__name__in=tags).annotate(num_tags=Count('tags')).filter(\n num_tags__gte=len(tags))\n for ad in ads:\n r = requests.get(ad.query, headers=headers, proxies=proxies)\n for a in Ad.objects.filter(query=ad.query):\n item = BeautifulSoup(r.text, features='html.parser').find('div', {'id': a.iid})\n try:\n position = int(item['data-position']) - 1\n print(position)\n title = item.find('a', {'class': 'item-description-title-link'})['title']\n except:\n title = 'An error occured'\n position = -1\n if position > 6:\n position = position - 1\n if a.title == '':\n a.title = title\n a.position = position\n a.save()\n time.sleep(2)\n","sub_path":"position_scanner/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"307248464","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('create/', views.create, name='click'),\n path('join/', views.join, name=\"join\"),\n path('check/', views.check, name=\"check\"),\n path('register/' ,views.register, name=\"register\"),\n]","sub_path":"classroom/class/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"467142589","text":"import pygame.font\nclass Linia():\n def __init__(self,settings,screen):\n self.settings = settings\n self.screen = screen\n self.screen_rect = screen.get_rect()\n\n self.image = pygame.image.load(\"images/hp_linia.png\")\n self.image = pygame.transform.scale(self.image, (settings.boss_hp_lenght, 100))\n self.rect = self.image.get_rect()\n\n\n\n self.gameover=pygame.image.load(\"images/game_over.png\")\n self.gameover = pygame.transform.scale(self.gameover, (300, 300))\n self.gameover_rect = self.gameover.get_rect()\n self.gameover_rect.centerx = self.screen_rect.centerx\n self.gameover_rect.centery = self.screen_rect.centery\n\n\n\n def blitme(self):\n self.screen.blit(self.image, self.rect)\n\n def blitme2(self):\n self.screen.blit(self.gameover, self.gameover_rect)\n\n def update(self,bosses,settings):\n for boss in bosses.copy():\n self.image = pygame.transform.scale(self.image, (settings.boss_hp_lenght, 30))\n self.rect.centerx = boss.rect.centerx\n self.rect.bottom = boss.rect.top","sub_path":"Project_line.py","file_name":"Project_line.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"40599736","text":"\nfrom terrascript import Terrascript\nfrom terrascript import provider as provider\nimport terrascript.vsphere.r as r\nimport terrascript.vsphere.d as d\n\n\ndef test_catalog():\n terrascript = Terrascript()\n\n # Provider\n provider_in = terrascript.add(provider(\"vsphere\",user=\"x\",password=\"y\",vsphere_server=\"z\"))\n provider_out = terrascript.get(\"provider\", \"vsphere\", \"__DEFAULT__\")\n assert provider_in == provider_out\n\n # Data\n dc_in = terrascript.add(d.vsphere_datacenter(\"dc\"))\n dc_out = terrascript.get(\"data\", \"vsphere_datacenter\", \"dc\")\n dc_in2 = terrascript.add(d.vsphere_datacenter(\"dc2\"))\n dc_out2 = terrascript.get(\"data\", \"vsphere_datacenter\", \"dc2\")\n assert dc_in == dc_out\n assert dc_in2 == dc_out2\n\n # Resource\n cc_in = terrascript.add(r.vsphere_compute_cluster(\"cc\",name=\"cc_name\",datacenter_id=dc_in.id))\n cc_out = terrascript.get(\"resource\", \"vsphere_compute_cluster\", \"cc\")\n assert cc_in == cc_out\n\n # ... get all resources and data sources by type.\n get_by_type = terrascript.get(None, \"vsphere_datacenter\", None)\n assert isinstance(get_by_type[\"data\"][\"dc\"], d.vsphere_datacenter)\n assert isinstance(get_by_type[\"data\"][\"dc2\"], d.vsphere_datacenter)","sub_path":"tests/test_catalog.py","file_name":"test_catalog.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"307454280","text":"import os\nimport pytest\nfrom fixture.application import Application\nfrom comtypes.client import CreateObject\n\n\n@pytest.fixture(scope=\"session\")\ndef app(request):\n fixture = Application(\"C:\\\\Free Address Book\\\\AddressBook.exe\")\n request.addfinalizer(fixture.destroy)\n return fixture\n\n\ndef pytest_generate_tests(metafunc):\n for fixture in metafunc.fixturenames:\n if fixture.startswith(\"xlsx_\"):\n testdata = load_from_excel(fixture[5:])\n metafunc.parametrize(fixture, testdata)\n\n\ndef load_from_excel(file):\n xlsx_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), f\"fixture/{file}.xlsx\")\n app = CreateObject(\"Excel.Application\")\n wb = app.Workbooks.Open(xlsx_file)\n worksheet = wb.Sheets[1]\n test_data = []\n for row in range(1, 100):\n data = worksheet.Cells[row, 1].Value()\n if data is not None:\n test_data.append(data)\n return test_data","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"523667681","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# 有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。\n\nimport os\nfrom itertools import (takewhile, repeat)\n\ndef iter_count(file_name):\n buffer = 1024 * 1024\n with open(file_name) as f:\n buf_gen = takewhile(lambda x: x, (f.read(buffer) for _ in repeat(None)))\n return sum(buf.count('\\n') for buf in buf_gen)\n\nfor roots,dirs,name in os.walk('/Users/herry/Documents/python/practise/code/'):\n for file_ in name:\n iter_count(file_)","sub_path":"practise/code/0007.py","file_name":"0007.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"427382780","text":"from apps.denuncias.authorizations import DenunciaAuth\nfrom apps.denuncias.models import Denuncia, PerfilDenunciante\nfrom apps.usuarios.models import Perfil\nfrom core.accion import ActionResourceMixin, action, response\nfrom core.autorizacion import es_perfil_denunciante, es_admin\nfrom core.http import HttpOK\nfrom core.recurso import MetaGenerica, RecursoGenerico\nfrom tastypie import fields\nfrom tastypie.exceptions import ImmediateHttpResponse\nfrom tastypie.http import HttpBadRequest, HttpUnauthorized\n\n\nclass DenunciaResource(RecursoGenerico):\n Meta = MetaGenerica(modelo=Denuncia)\n Meta.authorization = DenunciaAuth()\n\n\nclass RecursoDenunciable(ActionResourceMixin, RecursoGenerico):\n denuncias = fields.ToManyField(DenunciaResource, 'denuncias', full=True, null=True)\n\n @action(allowed=('post',), static=False, login_required=True)\n @response(HttpOK, \"Elemento denunciado correctamente\")\n @response(HttpBadRequest, \"No es posible denunciar el elemento\")\n def denunciar(self, request, motivo):\n if not es_perfil_denunciante(request.user):\n raise ImmediateHttpResponse(HttpUnauthorized())\n try:\n modelo = self._meta.object_class.objects.get(pk=request.api['pk'])\n denunciante = Perfil.objects.get_subclass(usuario=request.user)\n Denuncia.objects.create(modelo=modelo, denunciante=denunciante, motivo=motivo)\n return self.create_response(request, {}, HttpOK)\n except Exception:\n raise ImmediateHttpResponse(HttpBadRequest())\n\n @action(allowed=('post',), static=False, login_required=True)\n @response(HttpOK, \"Denuncias descartadas\")\n @response(HttpBadRequest, \"No es posible descartar las denuncias\")\n def descartar_denuncias(self, request):\n if not es_admin(request.user):\n raise ImmediateHttpResponse(HttpUnauthorized())\n try:\n modelo = self._meta.object_class.objects.get(pk=request.api['pk'])\n modelo.denuncias.filter(estado='pendiente').update(estado='desestimada')\n return self.create_response(request, {}, HttpOK)\n except Exception:\n raise ImmediateHttpResponse(HttpBadRequest())","sub_path":"apps/denuncias/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"632349512","text":"import unittest\nimport testutil\nimport shutil\nimport os\nimport time\nimport datetime\n\nimport hdbfs\nimport hdbfs.ark\nimport hdbfs.model\n\nhdbfs.imgdb.MIN_THUMB_EXP = 4\n\nclass ThumbCases( testutil.TestCase ):\n\n def setUp( self ):\n\n self.init_env()\n\n def tearDown( self ):\n\n self.uninit_env()\n\n def test_create_thumb( self ):\n\n blue = self._load_data( self.blue )\n\n h = hdbfs.Database()\n h.enable_write_access()\n\n obj = h.register_file( blue, False )\n\n root_stream = obj.get_root_stream()\n thumb_stream = obj.get_thumb_stream( 4 )\n\n self.assertFalse( thumb_stream.get_stream_id()\n == root_stream.get_stream_id(),\n 'Root returned for small thumb' )\n self.assertFalse( self._diff( root_stream.read(),\n thumb_stream.read() ),\n 'Smaller thumb stream identical' )\n self.assertTrue( thumb_stream.get_priority()\n == hdbfs.model.SP_EXPENDABLE,\n 'Thumb priority not set correctly' )\n\n def test_return_orig( self ):\n\n blue = self._load_data( self.blue )\n\n h = hdbfs.Database()\n h.enable_write_access()\n\n obj = h.register_file( blue, False )\n\n root_stream = obj.get_root_stream()\n thumb_stream = obj.get_thumb_stream( 10 )\n\n self.assertTrue( thumb_stream.get_stream_id()\n == root_stream.get_stream_id(),\n 'Root not returned large small thumb' )\n self.assertTrue( thumb_stream.get_priority()\n == root_stream.get_priority(),\n 'Oddity in return root for large priority' )\n\n def test_rot_does_not_return_orig( self ):\n\n blue = self._load_data( self.blue )\n\n h = hdbfs.Database()\n h.enable_write_access()\n\n obj = h.register_file( blue, False )\n\n obj.rotate_cw()\n\n root_stream = obj.get_root_stream()\n thumb_stream = obj.get_thumb_stream( 10 )\n\n self.assertFalse( thumb_stream.get_stream_id()\n == root_stream.get_stream_id(),\n 'Root returned on rotated image' )\n\n def test_thumb_points_to_root( self ):\n\n blue = self._load_data( self.blue )\n\n h = hdbfs.Database()\n h.enable_write_access()\n\n obj = h.register_file( blue, False )\n\n root_stream = obj.get_root_stream()\n thumb_stream = obj.get_thumb_stream( 4 )\n origin_stream = thumb_stream.get_origin_stream()\n\n self.assertTrue( origin_stream is not None,\n 'Thumb has not origin' )\n self.assertTrue( origin_stream.get_stream_id()\n == root_stream.get_stream_id(),\n 'Origin stream is not root stream' )\n\n def test_create_very_small( self ):\n\n blue = self._load_data( self.blue )\n\n h = hdbfs.Database()\n h.enable_write_access()\n\n obj = h.register_file( blue, False )\n\n thumb_stream = obj.get_thumb_stream( 4 )\n small_stream = obj.get_thumb_stream( 3 )\n\n self.assertTrue( thumb_stream.get_stream_id()\n == small_stream.get_stream_id(),\n 'Very small does not match small' )\n self.assertTrue( small_stream.get_priority()\n == hdbfs.model.SP_EXPENDABLE,\n 'Very small priority not set correctly' )\n\n def test_thumbs_not_moved( self ):\n\n red = self._load_data( self.red )\n blue = self._load_data( self.blue )\n\n h = hdbfs.Database()\n h.enable_write_access()\n\n o1 = h.register_file( blue, False )\n o2 = h.register_file( red, False )\n\n t2_4_hash = o2.get_thumb_stream( 4 ).get_hash()\n t2_5_hash = o2.get_thumb_stream( 5 ).get_hash()\n\n h.merge_objects( o1, o2 )\n\n t1_4_hash = o1.get_thumb_stream( 4 ).get_hash()\n t1_5_hash = o1.get_thumb_stream( 5 ).get_hash()\n\n self.assertFalse( t1_4_hash == t2_4_hash,\n 'New thumb matches moved from o2' )\n self.assertFalse( t1_5_hash == t2_5_hash,\n 'New thumb matches moved from o2' )\n\n def test_thumbs_not_moved_with_existing( self ):\n\n red = self._load_data( self.red )\n blue = self._load_data( self.blue )\n\n h = hdbfs.Database()\n h.enable_write_access()\n\n o1 = h.register_file( blue, False )\n o2 = h.register_file( red, False )\n\n t1_4_hash = o1.get_thumb_stream( 4 ).get_hash()\n t1_5_hash = o1.get_thumb_stream( 5 ).get_hash()\n t2_4_hash = o2.get_thumb_stream( 4 ).get_hash()\n t2_5_hash = o2.get_thumb_stream( 5 ).get_hash()\n\n h.merge_objects( o1, o2 )\n\n tx_4_hash = o1.get_thumb_stream( 4 ).get_hash()\n tx_5_hash = o1.get_thumb_stream( 5 ).get_hash()\n\n self.assertTrue( tx_4_hash == t1_4_hash,\n 'New thumb not matching from o1' )\n self.assertTrue( tx_5_hash == t1_5_hash,\n 'New thumb not matching from o1' )\n self.assertFalse( tx_4_hash == t2_4_hash,\n 'New thumb matches moved from o2' )\n self.assertFalse( tx_5_hash == t2_5_hash,\n 'New thumb matches moved from o2' )\n\nif( __name__ == '__main__' ):\n unittest.main()\n","sub_path":"test/thumb_cases.py","file_name":"thumb_cases.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"283596667","text":"#!/usr/bin/python3\n\n# spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.2.1 spark-kafka-json-consumer.py\n\n# pyspark --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.2.1 \n\n# https://sparkbyexamples.com/spark/spark-streaming-consume-and-produce-kafka-messages-in-avro-format/\n\nimport os, sys, json, io\nfrom pyspark.sql import *\nfrom pyspark.sql.utils import StreamingQueryException\nimport sys\nimport json\n\nos.environ['PYSPARK_PYTHON'] = '/usr/bin/python3'\nos.environ['PYSPARK_DRIVER_PYTHON'] = '/usr/bin/python3'\nsys.path.append('/class')\n\n# Kafka variables\nbrokers = 'localhost:9092'\nkafka_topic = 'stocks-json'\nreceiver_sleep_time = 4\n\n# Connect to Spark \nfrom initspark import initspark\nsc, spark, config = initspark()\n\ndf: DataFrame = (spark.readStream \n .format(\"kafka\") \n .option(\"kafka.bootstrap.servers\", brokers) \n .option(\"subscribe\", kafka_topic) \n# .option(\"startingOffsets\", \"earliest\")\n .load()\n )\n\n# df.createOrReplaceTempView('table')\n# df1 = spark.sql(\"\"\"SELECT 'new data', * from table\"\"\")\ndf1 = df.selectExpr(\"UPPER(CAST(value AS STRING))\")\n\n\"\"\"\ndf2 = df.writeStream \\\n .outputMode(\"append\") \\\n .format(\"console\") \\\n .start()\n\"\"\"\ndf2 = (df1.writeStream.format(\"kafka\")\n .option(\"kafka.bootstrap.servers\", brokers) \n .option(\"topic\",\"classroom\")\n .option(\"checkpointLocation\", \"/tmp\")\n .start()\n )\ndf2.awaitTermination()\n\n#df1.writeStream.outputMode(\"append\").format(\"console\").start()\n\n\n\n\n#print(type(df), type(df1))\n\n# df2 = df.writeStream.queryName(\"df2\").format(\"memory\").start()\n# df3 = spark.sql(\"select * from df2\")\n# df3.show()\n\n#print(type(df), dir(df))\n\n#df2 = df.writeStream.format(\"console\").start()\n\n#df3 = df.foreach(print).writeStream.format(\"console\").start()\n\n#df2.awaitTermination()\n#df3.awaitTermination()\n\n#df2: DataFrame = df.foreach(print) \n#.writeStream.format(\"console\").start()\n#print(type(df2), dir(df2), dir(df2.collect))\n\n#df2.awaitTermination()\n\n#stocks.foreachRDD(lambda rdd: rdd_to_df(rdd))\n\n#print(df.take(5))\n# df2 = df.select(from_avro(\"value\", stock_schema).alias(\"value\"))\n# df2.show(5)\n\n\n\"\"\"\nssc = StreamingContext(sc, batchDuration = receiver_sleep_time)\n\nstock_schema = avro.schema.parse(open(\"stock.avsc\", \"rb\").read())\nprint('Stock Schema:', stock_schema)\n\ndef rdd_to_df(rdd):\n try:\n df = rdd.toDF(schema=['event_time', 'symbol', 'price', 'quantity'])\n print(df.collect())\n except Exception as e:\n print(e)\n return\n\ndef avro_decoder(msg):\n\n bytes_io = io.BytesIO(msg)\n bytes_io.seek(0)\n msg_decoded = fastavro.schemaless_reader(bytes_io, stock_schema)\n print(msg_decoded)\n return msg_decoded\n\nstocks = (\n KafkaUtils.createDirectStream(ssc, [kafka_topic]\n , kafkaParams={\"metadata.broker.list\" : brokers}\n , valueDecoder = avro_decoder)\n )\n\nstocks.foreachRDD(lambda rdd: rdd_to_df(rdd))\n\nssc.start()\nssc.awaitTermination()\n\n\n\n\"\"\" \n\n\n#https://mtpatter.github.io/bilao/notebooks/html/01-spark-struct-stream-kafka.html\n\n\n\"\"\"\nimport os, sys, json\nos.environ['PYSPARK_PYTHON'] = '/usr/bin/python3'\nos.environ['PYSPARK_DRIVER_PYTHON'] = '/usr/bin/python3'\nsys.path.append('/class')\n\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\n\n# Kafka variables\nbrokers = 'localhost:9092'\nkafka_topic = 'stocks-json'\nreceiver_sleep_time = 4\n\n# Connect to Spark \n# sc = SparkContext(master = 'local[*]', appName = 'test')\nfrom initspark import initspark\nsc, spark, config = initspark()\nssc = StreamingContext(sc, batchDuration = receiver_sleep_time)\n\ndef rdd_to_df(rdd):\n try:\n df = rdd.toDF(schema=['event_time', 'symbol', 'price', 'quantity'])\n print(df.collect())\n except Exception as e:\n print(e)\n return\n \nstocks = (\n KafkaUtils.createDirectStream(ssc, [kafka_topic]\n , kafkaParams={\"metadata.broker.list\" : brokers})\n .map(lambda x:json.loads(x[1]))\n )\n\nstocks.foreachRDD(lambda rdd: rdd_to_df(rdd))\n\nssc.start()\nssc.awaitTermination()\n\n\"\"\"\n","sub_path":"scripts/1/ch02/spark-kafka-json-consumer.py","file_name":"spark-kafka-json-consumer.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"72763402","text":"import pickle\nimport cv2\nimport numpy as np\n\n# Camera calibration\nclass Calibration():\n def __init__(self):\n self.mtx = None\n self.dist = None\n def calibrate(self):\n \"\"\"\n Opens calibration image and find chessboard corners in image\n :return: calibration matrix & distance\n \"\"\"\n\n # prepare object points\n nx = 9\n ny = 6\n\n # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\n objp = np.zeros((nx * ny, 3), np.float32)\n objp[:, :2] = np.mgrid[0:nx, 0:ny].T.reshape(-1, 2)\n\n # Arrays to store object points and image points from all the images.\n objpoints = [] # 3d points in real world space\n imgpoints = [] # 2d points in image plane.\n\n # Make a list of calibration images\n images = [\"camera_cal/calibration2.jpg\",\"camera_cal/calibration3.jpg\" ]\n\n # Step through the list and search for chessboard corners\n for idx, fname in enumerate(images):\n print(\"Processing file \" + fname)\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)\n\n # If found, add object points, image points\n if ret == True:\n objpoints.append(objp)\n imgpoints.append(corners)\n\n # Draw and display the corners\n cv2.drawChessboardCorners(img, (nx, ny), corners, ret)\n write_name = 'corners_found' + fname.split('/')[-1]\n cv2.imwrite('camera_cal/' + write_name, img)\n cv2.imshow(write_name, img)\n cv2.waitKey(500)\n else:\n print(\"Error: no chessboard corners found for \" + fname)\n assert (False)\n\n cv2.destroyAllWindows()\n\n img_size = (img.shape[1], img.shape[0])\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size, None, None)\n\n dist_pickle = {}\n dist_pickle[\"mtx\"] = mtx\n dist_pickle[\"dist\"] = dist\n pickle.dump( dist_pickle, open( \"camera_cal/wide_dist_pickle.p\", \"wb\" ) )\n\n self.mtx = mtx\n self.dist = dist\n return mtx,dist\n def load(self):\n with open('camera_cal/wide_dist_pickle.p', 'rb') as handle:\n calib = pickle.load(handle)\n self.mtx = calib[\"mtx\"]\n self.dist = calib[\"dist\"]\n","sub_path":"calibration.py","file_name":"calibration.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"384493081","text":"import pygame\n\nfrom morphs.morph import Morph\n\nfrom primitives.point import Point\n\nclass String(Morph):\n \"I am a single line of text\"\n\n def __init__(self,\n text,\n fontname=\"verdana\",\n fontsize=12,\n bold=False,\n italic=False):\n self.text = text\n self.fontname = fontname\n self.fontsize=fontsize\n self.bold = bold\n self.italic = italic\n self.is_editable = False\n super(String, self).__init__()\n self.color = pygame.Color(0,0,0)\n self.draw_new()\n\n def __repr__(self):\n return 'String(\"' + self.text + '\")'\n\n def draw_new(self):\n self.font = pygame.font.SysFont(\n self.fontname,\n self.fontsize,\n self.bold,\n self.italic)\n self.image = self.font.render(self.text, 1, self.color)\n self.image.set_alpha(self.alpha)\n corner = Point(self.image.get_width(),\n self.image.get_height())\n self.bounds.corner = self.bounds.origin + corner\n\n #String menu:\n\n def developers_menu(self):\n menu = super(String, self).developers_menu()\n menu.add_line()\n if not self.is_editable:\n menu.add_item(\"edit...\", 'edit')\n menu.add_item(\"font name...\", 'choose_font')\n menu.add_item(\"font size...\", 'choose_font_size')\n menu.add_line()\n if self.bold or self.italic:\n menu.add_item(\"normal\", 'set_to_normal')\n if not self.bold:\n menu.add_item(\"bold\", 'set_to_bold')\n if not self.italic:\n menu.add_item(\"italic\", 'set_to_italic')\n return menu\n\n def edit(self):\n world.edit(self)\n\n def choose_font(self):\n fontname = world.fontname_by_user()\n if fontname != None:\n self.fontname = fontname\n self.changed()\n self.draw_new()\n self.changed()\n\n def choose_font_size(self):\n fontsize = self.prompt(\"please enter\\n the font size\\nin points:\",\n str(self.fontsize),\n 50)\n if fontsize != None:\n self.fontsize = int(fontsize)\n self.changed()\n self.draw_new()\n self.changed()\n\n def set_to_normal(self):\n self.bold = False\n self.italic = False\n self.changed()\n self.draw_new()\n self.changed()\n\n def set_to_bold(self):\n self.bold = True\n self.changed()\n self.draw_new()\n self.changed()\n\n def set_to_italic(self):\n self.italic = True\n self.changed()\n self.draw_new()\n self.changed()\n\n #String events:\n\n def handles_mouse_click(self):\n return self.is_editable\n\n def mouse_click_left(self, pos):\n self.edit()\n world.text_cursor.goto_pos(pos)\n","sub_path":"morphs/string.py","file_name":"string.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"515453144","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nX = np.linspace(-np.pi, np.pi, 256)\nC = np.cos(X)\nS = np.sin(X)\n\nplt.figure(figsize=(8, 6), dpi=80)\nplt.plot(X, C, color='blue', linewidth=2.5, linestyle='-', label=\"cosine\")\nplt.plot(X, S, color='red', linewidth=2.5, linestyle='-', label=\"sine\")\nplt.legend(loc='upper left', frameon=False)\nax = plt.gca()\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\nax.xaxis.set_ticks_position('bottom')\nax.spines['bottom'].set_position(('data', 0))\nax.yaxis.set_ticks_position('left')\nax.spines['left'].set_position(('data', 0))\nplt.xlim(X.min() * 1.1, X.max() * 1.1)\nplt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],\n [r'$-\\pi$', r'$-\\pi/2$', r'$0$', r'$+\\pi/2$', r'$+\\pi$'])\nplt.ylim(C.min() * 1.3, C.max() * 1.3)\nplt.yticks([-1.0, 0, 1.0], ['$-1.0$', '0', '$+1.0$'])\n\n\n\n# The tick labels are now hardly visible because of the blue and red lines.\n# We can make them bigger and we can also adjust their properties such that\n# they'll be rendered on a semi-transparent white background. This will allow\n# us to see both the data and the labels.\n\nfor label in ax.get_xticklabels() + ax.get_yticklabels():\n label.set_fontsize(14)\n label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))\n\n\nt = 2 * np.pi / 3\nplt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle=\"--\")\nplt.scatter([t, ], [np.cos(t), ], 50, color='blue')\nplt.annotate(r'$\\sin(\\frac{2\\pi}{3})=\\frac{\\sqrt{3}}{2}$', xy=(t, np.sin(t)),\n xycoords='data', xytext=(+10, +30), textcoords='offset points',\n fontsize=16, arrowprops=dict(arrowstyle='->',\n connectionstyle=\"arc3,rad=.2\"))\nplt.plot([t, t], [0, np.sin(t)], color='red', linewidth=2.5, linestyle='--')\nplt.scatter([t, ], [np.sin(t), ], 50, color='red')\nplt.annotate(r'$\\cos(\\frac{2\\pi}{3})=\\frac{\\sqrt{3}}{2}$', xy=(t, np.cos(t)),\n xycoords='data', xytext=(-90, -50), textcoords='offset points',\n fontsize=16, arrowprops=dict(arrowstyle='->',\n connectionstyle=\"arc3, rad=.2\")\n )\n\nplt.show()","sub_path":"python/ML/00numpy&matplotlib/learn_matplotlib/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"299444580","text":"\"\"\"Definition of the primary parser for RepoBee.\n\n.. module:: mainparser\n :synopsis: The primary parser for RepoBee.\n\n.. moduleauthor:: Simon Larsén\n\"\"\"\n\nimport types\nimport argparse\nimport pathlib\n\nimport logging\nfrom typing import List, Optional\n\nimport daiquiri\n\nimport repobee_plug as plug\n\nimport _repobee\nfrom _repobee import plugin\nfrom _repobee import util\nfrom _repobee import config\nfrom _repobee import constants\nfrom _repobee.cli.preparser import PRE_PARSER_SHOW_ALL_OPTS\n\nLOGGER = daiquiri.getLogger(__file__)\n\nSUB = \"subparser\"\n\n# Any new subparser mus tbe added to the PARSER_NAMES tuple!\nSETUP_PARSER = \"setup\"\nUPDATE_PARSER = \"update\"\nCLONE_PARSER = \"clone\"\nCREATE_TEAMS_PARSER = \"create-teams\"\nMIGRATE_PARSER = \"migrate\"\nOPEN_ISSUE_PARSER = \"open-issues\"\nCLOSE_ISSUE_PARSER = \"close-issues\"\nLIST_ISSUES_PARSER = \"list-issues\"\nVERIFY_PARSER = \"verify-settings\"\nASSIGN_REVIEWS_PARSER = \"assign-reviews\"\nPURGE_REVIEW_TEAMS_PARSER = \"end-reviews\"\nCHECK_REVIEW_PROGRESS_PARSER = \"check-reviews\"\nSHOW_CONFIG_PARSER = \"show-config\"\n\nPARSER_NAMES = (\n SETUP_PARSER,\n UPDATE_PARSER,\n CLONE_PARSER,\n CREATE_TEAMS_PARSER,\n MIGRATE_PARSER,\n OPEN_ISSUE_PARSER,\n CLOSE_ISSUE_PARSER,\n LIST_ISSUES_PARSER,\n VERIFY_PARSER,\n ASSIGN_REVIEWS_PARSER,\n PURGE_REVIEW_TEAMS_PARSER,\n SHOW_CONFIG_PARSER,\n CHECK_REVIEW_PROGRESS_PARSER,\n)\n\n_HOOK_RESULTS_PARSER = argparse.ArgumentParser(add_help=False)\n_HOOK_RESULTS_PARSER.add_argument(\n \"--hook-results-file\",\n help=\"Path to a file to store results from plugin hooks in. The \"\n \"results are stored as JSON, regardless of file extension.\",\n type=str,\n default=None,\n)\n_REPO_NAME_PARSER = argparse.ArgumentParser(add_help=False)\n_REPO_NAME_PARSER.add_argument(\n \"--mn\",\n \"--master-repo-names\",\n help=\"One or more names of master repositories. Names must either \"\n \"refer to local directories, or to master repositories in the \"\n \"target organization.\",\n type=str,\n required=True,\n nargs=\"+\",\n dest=\"master_repo_names\",\n)\n_REPO_DISCOVERY_PARSER = argparse.ArgumentParser(add_help=False)\n_DISCOVERY_MUTEX_GRP = _REPO_DISCOVERY_PARSER.add_mutually_exclusive_group(\n required=True\n)\n_DISCOVERY_MUTEX_GRP.add_argument(\n \"--mn\",\n \"--master-repo-names\",\n help=\"One or more names of master repositories. Names must either \"\n \"refer to local directories, or to master repositories in the \"\n \"target organization.\",\n type=str,\n nargs=\"+\",\n dest=\"master_repo_names\",\n)\n_DISCOVERY_MUTEX_GRP.add_argument(\n \"--discover-repos\",\n help=\"Discover all repositories for the specified students. NOTE: This \"\n \"is expensive in terms of API requests, if you have a rate limit you \"\n \"may want to avoid this option.\",\n action=\"store_true\",\n)\n\n# add any diprecated parsers to this dict on the following form:\n#\n# ASSIGN_REVIEWS_PARSER_OLD: plug.Deprecation(\n# replacement=ASSIGN_REVIEWS_PARSER, remove_by_version=\"2.0.0\"\n# ),\nDEPRECATED_PARSERS = {\n \"purge-review-teams\": plug.Deprecation(\n replacement=PURGE_REVIEW_TEAMS_PARSER, remove_by_version=\"2.2.0\"\n )\n}\n\n\ndef create_parser_for_docs() -> argparse.ArgumentParser:\n \"\"\"Create a parser showing all options for the default CLI\n documentation.\n\n Returns:\n The primary parser, specifically for generating documentation.\n \"\"\"\n daiquiri.setup(level=logging.FATAL)\n # load default plugins\n plugin.initialize_default_plugins()\n ext_commands = plug.manager.hook.create_extension_command()\n return create_parser(\n show_all_opts=True,\n ext_commands=ext_commands,\n config_file=_repobee.constants.DEFAULT_CONFIG_FILE,\n )\n\n\ndef create_parser(\n show_all_opts: bool,\n ext_commands: Optional[List[plug.ExtensionCommand]],\n config_file: pathlib.Path,\n) -> argparse.ArgumentParser:\n \"\"\"Create the primary parser.\n\n Args:\n show_all_opts: If False, help sections for options with configured\n defaults are suppressed. Otherwise, all options are shown.\n ext_commands: A list of extension commands.\n config_file: Path to the config file.\n Returns:\n The primary parser.\n \"\"\"\n\n def _versioned_plugin_name(plugin_module: types.ModuleType) -> str:\n \"\"\"Return the name of the plugin, with version if available.\"\"\"\n name = plugin_module.__name__.split(\".\")[-1]\n ver = plugin.resolve_plugin_version(plugin_module)\n return \"{}-{}\".format(name, ver) if ver else name\n\n loaded_plugins = \", \".join(\n [\n _versioned_plugin_name(p)\n for p in plug.manager.get_plugins()\n if isinstance(p, types.ModuleType)\n and not plugin.is_default_plugin(p)\n ]\n )\n\n program_description = (\n \"A CLI tool for administrating large amounts of git repositories \"\n \"on GitHub and\\nGitLab instances. Read the docs at: \"\n \"https://repobee.readthedocs.io\\n\\n\"\n )\n\n if not show_all_opts and constants.DEFAULT_CONFIG_FILE.is_file():\n program_description += (\n \"CLI options that are set in the config file are suppressed in \"\n \"help sections,\\nrun with pre-parser option {all_opts_arg} to \"\n \"unsuppress.\\nExample: repobee {all_opts_arg} setup -h\\n\\n\".format(\n all_opts_arg=PRE_PARSER_SHOW_ALL_OPTS\n )\n )\n program_description += \"Loaded plugins: \" + loaded_plugins\n\n parser = argparse.ArgumentParser(\n prog=\"repobee\",\n description=program_description,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n )\n parser.add_argument(\n \"-v\",\n \"--version\",\n help=\"Display version info\",\n action=\"version\",\n version=\"{}\".format(_repobee.__version__),\n )\n _add_subparsers(parser, show_all_opts, ext_commands, config_file)\n\n return parser\n\n\ndef _add_peer_review_parsers(base_parsers, subparsers):\n assign_parser = subparsers.add_parser(\n ASSIGN_REVIEWS_PARSER,\n description=(\n \"For each student repo, create a review team with read access \"\n \"named -review and randomly assign \"\n \"other students to it. All students are assigned to the same \"\n \"amount of review teams, as specified by `--num-reviews`. Note \"\n \"that `--num-reviews` must be strictly less than the amount of \"\n \"students. Note that review allocation strategy may be altered \"\n \"by plugins.\"\n ),\n help=\"Assign students to peer review each others' repos.\",\n parents=base_parsers,\n formatter_class=_OrderedFormatter,\n )\n assign_parser.add_argument(\n \"-n\",\n \"--num-reviews\",\n metavar=\"N\",\n help=\"Assign each student to review n repos (consequently, each repo \"\n \"is reviewed by n students). n must be strictly smaller than the \"\n \"amount of students.\",\n type=int,\n default=1,\n )\n assign_parser.add_argument(\n \"-i\",\n \"--issue\",\n help=(\n \"Path to an issue to open in student repos. If specified, this \"\n \"issue will be opened in each student repo, and the body will be \"\n \"prepended with user mentions of all students assigned to review \"\n \"the repo. NOTE: The first line is assumed to be the title.\"\n ),\n type=str,\n )\n check_review_progress = subparsers.add_parser(\n CHECK_REVIEW_PROGRESS_PARSER,\n description=(\n \"Check which students have opened review review issues in their \"\n \"assigned repos. As it is possible for students to leave the peer \"\n \"review teams on their own, the command checks that each student \"\n \"is assigned to the expected amound of teams. There is currently \"\n \"no way to check if students have been swapped around, so using \"\n \"this command fow grading purposes is not recommended.\"\n ),\n help=\"Check which students have opened peer review issues.\",\n parents=base_parsers,\n formatter_class=_OrderedFormatter,\n )\n check_review_progress.add_argument(\n \"-r\",\n \"--title-regex\",\n help=(\n \"Regex to match against titles. Only issues matching this regex \"\n \"will count as review issues.\"\n ),\n required=True,\n )\n check_review_progress.add_argument(\n \"-n\",\n \"--num-reviews\",\n metavar=\"N\",\n help=(\n \"The expected amount of reviews each student should be assigned \"\n \"to perform. If a student is not assigned to `num_reviews` \"\n \"review teams, warnings will be displayed.\"\n ),\n type=int,\n required=True,\n )\n subparsers.add_parser(\n PURGE_REVIEW_TEAMS_PARSER,\n description=(\n \"Delete review allocations assigned with `assign-reviews`. \"\n \"This is a destructive action, as the allocations for reviews \"\n \"are irreversibly deleted. The purpose of this command is to \"\n \"revoke the reviewers' read access to reviewed repos, and to \"\n \"clean up the allocations (i.e. deleting the review teams when \"\n \"using GitHub, or groups when using GitLab). It will however not \"\n \"do anything with the review issues. You can NOT run \"\n \"`check-reviews` after `end-reviews`, as the former \"\n \"needs the allocations to function properly. Use this command \"\n \"only when reviews are done.\"\n ),\n help=(\n \"Delete review allocations created by `assign-reviews`. \"\n \"DESTRUCTIVE ACTION: read help section before using.\"\n ),\n parents=base_parsers,\n formatter_class=_OrderedFormatter,\n )\n\n\ndef _add_issue_parsers(base_parsers, subparsers):\n base_parser, base_student_parser, *_ = base_parsers\n\n open_parser = subparsers.add_parser(\n OPEN_ISSUE_PARSER,\n description=(\n \"Open issues in student repositories. For each master repository \"\n \"specified, the student list is traversed. For every student repo \"\n \"found, the issue specified by the `--issue` option is opened. \"\n \"NOTE: The first line of the issue file is assumed to be the \"\n \"issue title!\"\n ),\n help=\"Open issues in student repos.\",\n parents=base_parsers,\n formatter_class=_OrderedFormatter,\n )\n open_parser.add_argument(\n \"-i\",\n \"--issue\",\n help=\"Path to an issue. The first line is assumed to be the title.\",\n type=str,\n required=True,\n )\n\n close_parser = subparsers.add_parser(\n CLOSE_ISSUE_PARSER,\n description=(\n \"Close issues in student repos based on a regex. For each master \"\n \"repository specified, the student list is traversed. For every \"\n \"student repo found, any open issues matching the `--title-regex` \"\n \"are closed.\"\n ),\n help=\"Close issues in student repos.\",\n parents=[base_parser, base_student_parser, _REPO_DISCOVERY_PARSER],\n formatter_class=_OrderedFormatter,\n )\n close_parser.add_argument(\n \"-r\",\n \"--title-regex\",\n help=(\n \"Regex to match titles against. Any issue whose title matches the \"\n \"regex will be closed.\"\n ),\n type=str,\n required=True,\n )\n\n list_parser = subparsers.add_parser(\n LIST_ISSUES_PARSER,\n description=\"List issues in student repos.\",\n help=\"List issues in student repos.\",\n parents=[\n base_parser,\n base_student_parser,\n _REPO_DISCOVERY_PARSER,\n _HOOK_RESULTS_PARSER,\n ],\n formatter_class=_OrderedFormatter,\n )\n list_parser.add_argument(\n \"-r\",\n \"--title-regex\",\n help=(\n \"Regex to match against titles. Only issues matching this regex \"\n \"will be listed.\"\n ),\n )\n list_parser.add_argument(\n \"-b\",\n \"--show-body\",\n action=\"store_true\",\n help=\"Show the body of the issue, alongside the default info.\",\n )\n list_parser.add_argument(\n \"-a\",\n \"--author\",\n help=\"Only show issues by this author.\",\n type=str,\n default=None,\n )\n state = list_parser.add_mutually_exclusive_group()\n state.add_argument(\n \"--open\",\n help=\"List open issues (default).\",\n action=\"store_const\",\n dest=\"state\",\n const=plug.IssueState.OPEN,\n )\n state.add_argument(\n \"--closed\",\n help=\"List closed issues.\",\n action=\"store_const\",\n dest=\"state\",\n const=plug.IssueState.CLOSED,\n )\n state.add_argument(\n \"--all\",\n help=\"List all issues (open and closed).\",\n action=\"store_const\",\n dest=\"state\",\n const=plug.IssueState.ALL,\n )\n list_parser.set_defaults(state=plug.IssueState.OPEN)\n\n\nclass _OrderedFormatter(argparse.HelpFormatter):\n \"\"\"A formatter class for putting out the help section in a proper order.\n All of the arguments that are configurable in the configuration file\n should appear at the bottom (in arbitrary, but always the same, order).\n Any other arguments should appear in the order they are added.\n\n The internals of the formatter classes are technically not public,\n so this class is \"unsafe\" when it comes to new versions of Python. It may\n have to be disabled for future versions, but it works for 3.6, 3.7 and 3.8\n at the time of writing. If this turns troublesome, it may be time to\n switch to some other CLI library.\n \"\"\"\n\n def add_arguments(self, actions):\n \"\"\"Order actions by the name of the long argument, and then add them\n as arguments.\n\n The order is the following:\n\n [ NON-CONFIGURABLE | CONFIGURABLE | DEBUG ]\n\n Non-configurable arguments added without modification, which by\n default is the order they are added to the parser. Configurable\n arguments are added in the order defined by\n :py:const:`constants.ORDERED_CONFIGURABLE_ARGS`. Finally, debug\n commands (such as ``--traceback``) are added in arbitrary (but\n consistent) order.\n \"\"\"\n args_order = tuple(\n \"--\" + name.replace(\"_\", \"-\")\n for name in constants.ORDERED_CONFIGURABLE_ARGS\n ) + (\"--traceback\",)\n\n def key(action):\n if len(action.option_strings) < 2:\n return -1\n long_arg = action.option_strings[1]\n if long_arg in args_order:\n return args_order.index(long_arg)\n return -1\n\n actions = sorted(actions, key=key)\n super().add_arguments(actions)\n\n\ndef _add_extension_parsers(\n subparsers,\n ext_commands,\n base_parser,\n base_student_parser,\n master_org_parser,\n repo_name_parser,\n):\n \"\"\"Add extension parsers defined by plugins.\"\"\"\n if not ext_commands:\n return []\n for cmd in ext_commands:\n parents = []\n bp = plug.BaseParser\n req_parsers = cmd.requires_base_parsers or []\n if cmd.requires_api or bp.BASE in req_parsers:\n parents.append(base_parser)\n if bp.STUDENTS in req_parsers:\n parents.append(base_student_parser)\n if bp.MASTER_ORG in req_parsers:\n parents.append(master_org_parser)\n\n if bp.REPO_DISCOVERY in req_parsers:\n parents.append(_REPO_DISCOVERY_PARSER)\n elif bp.REPO_NAMES in req_parsers:\n parents.append(repo_name_parser)\n parents.append(cmd.parser)\n\n ext_parser = subparsers.add_parser(\n cmd.name,\n help=cmd.help,\n description=cmd.description,\n parents=parents,\n formatter_class=_OrderedFormatter,\n )\n try:\n _add_traceback_arg(ext_parser)\n except argparse.ArgumentError:\n # already added\n pass\n\n return ext_commands\n\n\ndef _add_subparsers(parser, show_all_opts, ext_commands, config_file):\n \"\"\"Add all of the subparsers to the parser. Note that the parsers prefixed\n with `base_` do not have any parent parsers, so any parser inheriting from\n them must also inherit from the required `base_parser` (unless it is a\n `base_` prefixed parser, of course).\n \"\"\"\n\n base_parser, base_student_parser, master_org_parser = _create_base_parsers(\n show_all_opts, config_file\n )\n\n subparsers = parser.add_subparsers(dest=SUB)\n subparsers.required = True\n\n subparsers.add_parser(\n SETUP_PARSER,\n help=\"Setup student repos.\",\n description=(\n \"Setup student repositories based on master repositories. \"\n \"This command performs three primary actions: sets up the \"\n \"student teams, creates one student repository for each \"\n \"master repository and finally pushes the master repo files to \"\n \"the corresponding student repos. It is perfectly safe to run \"\n \"this command several times, as any previously performed step \"\n \"will simply be skipped.\"\n ),\n parents=[\n base_parser,\n base_student_parser,\n master_org_parser,\n _REPO_NAME_PARSER,\n _HOOK_RESULTS_PARSER,\n ],\n formatter_class=_OrderedFormatter,\n )\n\n update = subparsers.add_parser(\n UPDATE_PARSER,\n help=\"Update existing student repos.\",\n description=(\n \"Push changes from master repos to student repos. If the \"\n \"`--issue` option is provided, the specified issue is opened in \"\n \"any repo to which pushes fail (because the students have pushed \"\n \"something already).\"\n ),\n parents=[\n base_parser,\n base_student_parser,\n master_org_parser,\n _REPO_NAME_PARSER,\n ],\n formatter_class=_OrderedFormatter,\n )\n update.add_argument(\n \"-i\",\n \"--issue\",\n help=(\n \"Path to issue to open in repos to which pushes fail. \"\n \"Assumes that the first line is the title of the issue.\"\n ),\n type=str,\n )\n\n clone = subparsers.add_parser(\n CLONE_PARSER,\n help=\"Clone student repos.\",\n description=\"Clone student repos asynchronously in bulk.\",\n parents=[\n base_parser,\n base_student_parser,\n _REPO_DISCOVERY_PARSER,\n _HOOK_RESULTS_PARSER,\n ],\n formatter_class=_OrderedFormatter,\n )\n\n for task in plug.manager.hook.clone_task():\n util.call_if_defined(task.add_option, clone)\n\n plug.manager.hook.clone_parser_hook(clone_parser=clone)\n\n subparsers.add_parser(\n CREATE_TEAMS_PARSER,\n help=\"Create student teams without creating repos.\",\n description=(\n \"Only create student teams. This is intended for when you want to \"\n \"use RepoBee for management, but don't want to dictate the names \"\n \"of your student's repositories. The `setup` command performs \"\n \"this step automatically, so there is never a need to run both \"\n \"this command AND `setup`.\"\n ),\n parents=[base_parser, base_student_parser],\n formatter_class=_OrderedFormatter,\n )\n\n subparsers.add_parser(\n MIGRATE_PARSER,\n help=\"Migrate repositories into the target organization.\",\n description=(\n \"Migrate repositories into the target organization. \"\n \"The repos must be local on disk to be migrated. Note that \"\n \"migrated repos will be private.\"\n ),\n parents=[_REPO_NAME_PARSER, base_parser],\n formatter_class=_OrderedFormatter,\n )\n\n _add_issue_parsers(\n [base_parser, base_student_parser, _REPO_NAME_PARSER], subparsers\n )\n _add_peer_review_parsers(\n [base_parser, base_student_parser, _REPO_NAME_PARSER], subparsers\n )\n\n show_config = subparsers.add_parser(\n SHOW_CONFIG_PARSER,\n help=\"Show the configuration file\",\n description=(\n \"Show the contents of the configuration file. If no configuration \"\n \"file can be found, show the path where repobee expectes to find \"\n \"it.\"\n ),\n formatter_class=_OrderedFormatter,\n )\n _add_traceback_arg(show_config)\n\n subparsers.add_parser(\n VERIFY_PARSER,\n help=\"Verify core settings.\",\n description=\"Verify core settings by trying various API requests.\",\n parents=[base_parser, master_org_parser],\n formatter_class=_OrderedFormatter,\n )\n\n return _add_extension_parsers(\n subparsers,\n ext_commands,\n base_parser,\n base_student_parser,\n master_org_parser,\n _REPO_NAME_PARSER,\n )\n\n\ndef _create_base_parsers(show_all_opts, config_file):\n \"\"\"Create the base parsers.\"\"\"\n configured_defaults = config.get_configured_defaults(config_file)\n\n def default(arg_name):\n return (\n configured_defaults[arg_name]\n if arg_name in configured_defaults\n else None\n )\n\n def configured(arg_name):\n return arg_name in configured_defaults\n\n def api_requires(arg_name):\n return arg_name in plug.manager.hook.api_init_requires()\n\n def hide_api_arg(arg_name):\n # note that API args that are not required should not be shown even\n # when show_all_opts is True, as they are not relevant.\n return not api_requires(arg_name) or (\n not show_all_opts and configured(arg_name)\n )\n\n def hide_configurable_arg(arg_name):\n return not show_all_opts and configured(arg_name)\n\n # API args help sections\n user_help = argparse.SUPPRESS if hide_api_arg(\"user\") else \"Your username.\"\n org_name_help = (\n argparse.SUPPRESS\n if hide_api_arg(\"org_name\")\n else \"Name of the target organization\"\n )\n base_url_help = (\n argparse.SUPPRESS\n if hide_api_arg(\"base_url\")\n else (\n \"Base url to a platform API. Must be HTTPS. For example, with \"\n \"github.com, the base url is https://api.github.com, and with \"\n \"GitHub enterprise, the url is https:///api/v3\"\n )\n )\n token_help = (\n argparse.SUPPRESS\n if hide_api_arg(\"token\")\n else (\n \"Access token for the platform instance. Can also be specified in \"\n \"the `{}` environment variable.\".format(constants.TOKEN_ENV)\n )\n )\n\n # other configurable args help sections\n # these should not be checked against the api_requires function\n students_file_help = (\n argparse.SUPPRESS\n if hide_configurable_arg(\"students_file\")\n else (\n \"Path to a list of student usernames. Put multiple usernames on \"\n \"each line to form groups.\"\n )\n )\n master_org_help = (\n argparse.SUPPRESS\n if hide_configurable_arg(\"master_org_name\")\n else (\n \"Name of the organization containing the master repos. \"\n \"Defaults to the same value as `-o|--org-name` if left \"\n \"unspecified. Note that config values take precedence \"\n \"over this default.\"\n )\n )\n\n base_parser = argparse.ArgumentParser(add_help=False)\n base_parser.add_argument(\n \"-u\",\n \"--user\",\n help=user_help,\n type=str,\n required=not configured(\"user\") and api_requires(\"user\"),\n default=default(\"user\"),\n )\n\n base_parser.add_argument(\n \"-o\",\n \"--org-name\",\n help=org_name_help,\n type=str,\n required=not configured(\"org_name\") and api_requires(\"org_name\"),\n default=default(\"org_name\"),\n )\n base_parser.add_argument(\n \"--bu\",\n \"--base-url\",\n help=base_url_help,\n type=str,\n required=not configured(\"base_url\") and api_requires(\"base_url\"),\n default=default(\"base_url\"),\n dest=\"base_url\",\n )\n base_parser.add_argument(\n \"-t\",\n \"--token\",\n help=token_help,\n type=str,\n required=not configured(\"token\") and api_requires(\"token\"),\n default=default(\"token\"),\n )\n\n _add_traceback_arg(base_parser)\n # base parser for when student lists are involved\n base_student_parser = argparse.ArgumentParser(add_help=False)\n students = base_student_parser.add_mutually_exclusive_group(\n required=not configured(\"students_file\")\n )\n students.add_argument(\n \"--sf\",\n \"--students-file\",\n help=students_file_help,\n type=str,\n default=default(\"students_file\"),\n dest=\"students_file\",\n )\n students.add_argument(\n \"-s\",\n \"--students\",\n help=\"One or more whitespace separated student usernames.\",\n type=str,\n nargs=\"+\",\n )\n\n master_org_parser = argparse.ArgumentParser(add_help=False)\n master_org_parser.add_argument(\n \"--mo\",\n \"--master-org-name\",\n help=master_org_help,\n default=default(\"master_org_name\"),\n dest=\"master_org_name\",\n )\n\n return (base_parser, base_student_parser, master_org_parser)\n\n\ndef _add_traceback_arg(parser):\n parser.add_argument(\n \"--tb\",\n \"--traceback\",\n help=\"Show the full traceback of critical exceptions.\",\n action=\"store_true\",\n dest=\"traceback\",\n )\n","sub_path":"src/_repobee/cli/mainparser.py","file_name":"mainparser.py","file_ext":"py","file_size_in_byte":25625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"481932526","text":"import pygame\nimport os\nfrom chess_game_project import Objects\nfrom chess_game_project import Threat_checking\nfrom chess_game_project import Block_threat\n\nos.environ['SDL_VIDEO_WINDOW_POS'] = \"%d,%d\" % (700, 70)\n# initialize pygame module\npygame.init()\n\n# set constant values\nWIDTH = 600\nE_WIDTH = 100\ngap = 75\nBLACK = (139, 69, 45)\nWHITE = (250, 235, 215)\nRED = (255, 0, 0)\nYELLOW = (255, 255, 0)\npiece_list = []\nwhite_move = True\nblack_move = False\nblack_check = False\nwhite_check = False\nrunning = True\ncheck_mate = False\nplayer = \"None\"\n\n# set the display screen\nscreen = pygame.display.set_mode((WIDTH, WIDTH + E_WIDTH))\n# set the screen caption\npygame.display.set_caption(\"Chess Game\")\n# load the icon image\nico = pygame.image.load(\"images/horse.png\")\n# set the icon image for screen\npygame.display.set_icon(ico)\nfont = pygame.font.Font(\"freesansbold.ttf\", 35)\nNum_font = pygame.font.Font(\"freesansbold.ttf\", 30)\nchk_font = pygame.font.Font(\"freesansbold.ttf\", 30)\nexit_font = pygame.font.Font(\"freesansbold.ttf\", 20)\nmove = \"white move\"\npis = \" \"\nblack_crown = pygame.image.load(\"images/black_crown.png\")\nwhite_crown = pygame.image.load(\"images/white_crown.png\")\n\n\n# class for box in chess board\nclass Box:\n def __init__(self, clr, row, col, width):\n self.clr = clr\n self.x = row * width\n self.y = col * width\n self.width = width\n self.piece = None\n\n # function to draw each box\n def draw_box(self):\n pygame.draw.rect(screen, self.clr, (self.x, self.y, self.width, self.width))\n\n\n# To create grid of box\ndef create_grid():\n grid = []\n for i in range(8):\n grid.append([])\n for j in range(8):\n box = Box(WHITE, j, i, gap)\n grid[i].append(box)\n return grid\n\n\n# To draw grid lines\ndef create_board():\n for i in range(9):\n pygame.draw.line(screen, BLACK, (0, i * gap), (WIDTH, i * gap), 3)\n pygame.draw.line(screen, BLACK, (i * gap, 0), (i * gap, WIDTH), 3)\n\n\n# To make a black and white pattern in the board\ndef make_box(grid):\n for i in range(8):\n for j in range(8):\n if (i % 2 != 0 and j % 2 == 0) or (i % 2 == 0 and j % 2 != 0):\n grid[i][j].clr = BLACK\n else:\n grid[i][j].clr = WHITE\n\n\n# To get row and col of specific position(tuple)\ndef get_row(position):\n x, y = position\n rows = y // gap\n cols = x // gap\n return rows, cols\n\n\n# call created grid function\ngrid = create_grid()\nmake_box(grid)\n\n\n# To eliminate emeny piece\ndef eliminate(row, col, grid):\n grid[row][col].piece.eliminated = True\n grid[row][col].piece = None\n\n\ndef king_escape(grid, piece):\n c = 0\n if piece == \"white\":\n BPAS = Objects.black_spot(grid)\n wkp = Objects.get_whk_king_pos(grid)\n for i in wkp:\n if i in BPAS:\n c += 1\n if c == len(wkp):\n return False\n else:\n return True\n if piece == \"black\":\n WPAS = Objects.white_spot(grid)\n bkp = Objects.get_blk_king_pos(grid)\n for i in bkp:\n if i in WPAS:\n c += 1\n if c == len(bkp):\n return False\n else:\n return True\n\n\ndef check_for_capturing(grid, pis):\n piece = piece_list[0]\n r, c = piece.row, piece.col\n if pis == \"white\":\n if grid[r][c] not in Objects.white_atk_spot(grid):\n return True\n else:\n return False\n if pis == \"black\":\n if grid[r][c] not in Objects.black_atk_spot(grid):\n return True\n else:\n return False\n\n\ndef block_threaten(grid, pis):\n piece = piece_list[0]\n c = 0\n if piece.piece_name == \"rook\" or piece.piece_name == \"bishop\" or piece.piece_name == \"queen\":\n if pis == \"white\":\n lis = Block_threat.block_threat(grid, piece, Objects.wkp)\n WPAS = Objects.whiteP_atk_spot(grid)\n for i in lis:\n if i not in WPAS:\n c += 1\n if c == len(lis):\n return True\n else:\n return False\n if pis == \"black\":\n lis = Block_threat.block_threat(grid, piece, Objects.bkp)\n BPAS = Objects.blackP_atk_spot(grid)\n for i in lis:\n if i not in BPAS:\n c += 1\n if c == len(lis):\n return True\n else:\n return False\n else:\n return True\n\n\n# check for piece to move\ndef check_piece_move(grid, row, col):\n global running, move, pis, check_mate, player\n global white_move, black_move, black_check, white_check\n if grid[row][col].piece is None and (grid[row][col].clr == BLACK or grid[row][col].clr == WHITE):\n make_box(grid)\n piece_list.clear()\n\n elif grid[row][col].piece is None and grid[row][col].clr == YELLOW:\n # function to move the piece\n Threat_checking.start_pos.clear()\n Threat_checking.final_pos.clear()\n Threat_checking.start_pos.append(\n [piece_list[0].row, piece_list[0].col, piece_list[0].first_move if piece_list[0].piece_name == \"pawn\"\n else piece_list[0].row, piece_list[0].col])\n piece_list[0].move(row, col, grid, collision=False)\n Threat_checking.final_pos.append([piece_list[0].row, piece_list[0].col, piece_list[0]])\n if white_move:\n if Threat_checking.check_for_threat(Objects.wkp.row, Objects.wkp.col, WHITE, grid):\n Threat_checking.take_back(grid)\n else:\n white_check = False\n pis = \" \"\n if not Threat_checking.back and Threat_checking.check_for_threat(Objects.bkp.row, Objects.bkp.col, BLACK,\n grid):\n black_check = True\n pis = \"black\"\n if not king_escape(grid, \"black\"):\n if check_for_capturing(grid, \"black\"):\n if block_threaten(grid, \"black\"):\n check_mate = True\n player = \"White\"\n else:\n if Threat_checking.check_for_threat(Objects.bkp.row, Objects.bkp.col, BLACK, grid):\n Threat_checking.take_back(grid)\n else:\n black_check = False\n pis = \" \"\n if not Threat_checking.back and Threat_checking.check_for_threat(Objects.wkp.row, Objects.wkp.col, WHITE,\n grid):\n white_check = True\n pis = \"white\"\n if not king_escape(grid, \"white\"):\n if check_for_capturing(grid, \"white\"):\n if block_threaten(grid, \"white\"):\n check_mate = True\n player = \"Black\"\n\n if piece_list[0].clor == WHITE and not Threat_checking.back:\n white_move = False\n black_move = True\n move = \"black move\"\n elif piece_list[0].clor == BLACK and not Threat_checking.back:\n white_move = True\n black_move = False\n move = \"white move\"\n else:\n Threat_checking.back = False\n\n elif (grid[row][col].piece.clor == WHITE and white_move) or (grid[row][col].piece.clor == BLACK and black_move):\n if grid[row][col].piece is not None and (grid[row][col].clr == BLACK or grid[row][col].clr == WHITE):\n if len(piece_list) == 0:\n grid[row][col].piece.check_move(row, col, grid)\n grid[row][col].piece.attacked_spot(grid)\n piece_list.append(grid[row][col].piece)\n else:\n piece_list.pop()\n make_box(grid)\n grid[row][col].piece.check_move(row, col, grid)\n grid[row][col].piece.attacked_spot(grid)\n piece_list.append(grid[row][col].piece)\n\n elif grid[row][col].piece is not None and grid[row][col].clr == RED:\n # function to move the piece and eliminate enemy piece\n Threat_checking.start_pos.clear()\n Threat_checking.final_pos.clear()\n last_piece = grid[row][col].piece\n Threat_checking.start_pos.append(\n [piece_list[0].row, piece_list[0].col, piece_list[0].first_move if piece_list[0].piece_name == \"pawn\"\n else piece_list[0].row, piece_list[0].col])\n piece_list[0].move(row, col, grid, collision=True)\n Threat_checking.final_pos.append([piece_list[0].row, piece_list[0].col, piece_list[0]])\n if white_move:\n if Threat_checking.check_for_threat(Objects.wkp.row, Objects.wkp.col, WHITE, grid):\n Threat_checking.take_back(grid)\n else:\n white_check = False\n pis = \" \"\n if not Threat_checking.back and Threat_checking.check_for_threat(Objects.bkp.row, Objects.bkp.col, BLACK,\n grid):\n black_check = True\n pis = \"black\"\n if not king_escape(grid, \"black\"):\n if check_for_capturing(grid, \"black\"):\n if block_threaten(grid, \"black\"):\n check_mate = True\n player = \"White\"\n else:\n if Threat_checking.check_for_threat(Objects.bkp.row, Objects.bkp.col, BLACK, grid):\n Threat_checking.take_back(grid)\n else:\n black_check = False\n pis = \" \"\n if not Threat_checking.back and Threat_checking.check_for_threat(Objects.wkp.row, Objects.wkp.col, WHITE,\n grid):\n white_check = True\n pis = \"white\"\n if not king_escape(grid, \"white\"):\n if check_for_capturing(grid, \"white\"):\n if block_threaten(grid, \"white\"):\n player = \"Black\"\n check_mate = True\n\n if piece_list[0].clor == WHITE and not Threat_checking.back:\n white_move = False\n black_move = True\n move = \"black move\"\n elif piece_list[0].clor == BLACK and not Threat_checking.back:\n white_move = True\n black_move = False\n move = \"white move\"\n\n else:\n last_piece.eliminated = False\n grid[row][col].piece = last_piece\n Threat_checking.back = False\n\n\n# initialize objects of all piece class\nObjects.obj_init(grid, screen)\n\n\ndef show_eliminated_piece():\n c = 0\n e = 0\n for obj in Objects.white_piece:\n if obj.eliminated:\n c += 1\n screen.blit(white_crown, (460, 610))\n ele_wp = Num_font.render(str(c), True, (0, 0, 0))\n screen.blit(ele_wp, (490, 610))\n for obj in Objects.black_piece:\n if obj.eliminated:\n e += 1\n screen.blit(black_crown, (530, 610))\n ele_bp = Num_font.render(str(e), True, (0, 0, 0))\n screen.blit(ele_bp, (560, 610))\n\n\ndef exit_btn():\n pygame.draw.rect(screen, (0, 150, 255), (510, 660, 70, 30))\n exit_bt = exit_font.render(\"Exit\", True, (0, 0, 0))\n screen.blit(exit_bt, (525, 667))\n\n\ndef restart_btn():\n pygame.draw.rect(screen, (0, 150, 255), (20, 660, 80, 30))\n exit_bt = exit_font.render(\"Restart\", True, (0, 0, 0))\n screen.blit(exit_bt, (25, 667))\n\n\ndef make_restart():\n global grid, check_mate, piece_list, white_move, black_move, black_check, white_check, running, pis, player, move\n # call created grid function\n grid = create_grid()\n make_box(grid)\n # initialize objects of all piece class\n Objects.obj_init(grid, screen)\n check_mate = False\n piece_list = []\n white_move = True\n black_move = False\n black_check = False\n white_check = False\n running = True\n pis = \" \"\n move = \"white move\"\n player = \"None\"\n\n\n# main game loop\nwhile running:\n # fill the screen with black colour\n screen.fill((255, 255, 255))\n\n # check for the event happen in pygame\n for event in pygame.event.get():\n # check if exit key is pressed\n if event.type == pygame.QUIT:\n running = False\n # check if mouse button is pressed\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n pos = pygame.mouse.get_pos()\n if not check_mate:\n if pos[1] < 600:\n row, col = get_row(pos)\n check_piece_move(grid, row, col)\n if 510 < pos[0] < 580 and 660 < pos[1] < 690:\n running = False\n if 20 < pos[0] < 100 and 660 < pos[1] < 690:\n make_restart()\n\n # To create a chess board\n for i in range(8):\n for j in range(8):\n grid[i][j].draw_box()\n\n for i in range(len(Objects.pawn_list)):\n Objects.pawn_list[i].show_pawn()\n\n for i in range(len(Objects.rook_list)):\n Objects.rook_list[i].show_rook()\n Objects.knight_list[i].show_knight()\n Objects.bishop_list[i].show_bishop()\n\n for i in range(len(Objects.king_list)):\n Objects.king_list[i].show_king()\n Objects.queen_list[i].show_queen()\n\n create_board()\n if check_mate:\n mv_font = font.render(\"Checkmate\", True, (125, 55, 200))\n else:\n mv_font = font.render(move, True, (125, 55, 200))\n screen.blit(mv_font, (200, 610))\n pygame.draw.line(screen, (0, 0, 0), (0, 650), (WIDTH, 650), 4)\n if check_mate:\n ck_font = chk_font.render(player + \" player won\", True, (255, 0, 0))\n else:\n ck_font = chk_font.render(\"check for \" + pis + \" king\", True, (255, 0, 0))\n if pis != \" \" or check_mate:\n screen.blit(ck_font, (160, 660))\n show_eliminated_piece()\n exit_btn()\n restart_btn()\n\n # update the display screen\n pygame.display.update()\n","sub_path":"chess_game_main.py","file_name":"chess_game_main.py","file_ext":"py","file_size_in_byte":14123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"375368348","text":"from os.path import splitext\nfrom os import listdir\nimport numpy as np\nfrom glob import glob\nimport torch\nfrom torch.utils.data import Dataset\nimport logging\nfrom PIL import Image\nfrom PIL import ImageFile\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\nclass BasicDataset(Dataset):\n def __init__(self, imgs_dir, masks_dir, scale=1):\n self.imgs_dir = imgs_dir\n self.masks_dir = masks_dir\n self.scale = scale\n self.ids = [splitext(file)[0] for file in listdir(imgs_dir)\n if not file.startswith('.')]\n logging.info(f'Creating dataset with {len(self.ids)} examples')\n\n def __len__(self):\n return len(self.ids)\n\n def preprocess(self, pil_img):\n w, h = pil_img.size\n newW, newH = int(self.scale * w), int(self.scale * h)\n pil_img = pil_img.resize((newW, newH))\n img_nd = np.array(pil_img)\n img_nd = np.expand_dims(img_nd, axis=0)\n return img_nd\n\n def __getitem__(self, i):\n idx = self.ids[i]\n print(idx)\n idy = idx.replace('frame', 'mask')\n mask_file = glob(self.masks_dir + idy + '.tiff')\n img_file = glob(self.imgs_dir + idx + '.tiff')\n mask = Image.open(mask_file[0])\n img = Image.open(img_file[0])\n\n img = self.preprocess(img).astype(float)\n mask = self.preprocess(mask).astype(int)\n binary_mask = mask.copy()\n binary_mask[binary_mask > 0] = 1\n return {'image': torch.from_numpy(img), 'mask': torch.from_numpy(mask),\n 'binary_mask': torch.from_numpy(binary_mask)}\n","sub_path":"code(U-net)/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"390233540","text":"# TODO:\n# -- Move calibration data out of source code\n# -- Add temperature records?\n\nimport sys\nimport collections\nimport pandas as pd\nimport numpy as np\nimport warnings\nimport scipy.interpolate\nfrom ..utils import *\n\n####################\n# Plate Reader IDs #\n####################\nplate_reader_ids = {\"268449\":'b1',\n \"271275\":'b2',\n \"1402031D\":'b3'}\n\n####################\n# Calibration Data #\n####################\ncalibration_data = dict()\ncalibration_data[\"GFP\"] = {'b3': {61:2261, 100:80850},\n 'b2': {61:1762, 100:62732},\n 'b1': {61:1517, 100:53258}}\ncalibration_data[\"Citrine\"] = {'b3': {61:2379, 100:82680},\n 'b2': {61:1849, 100:64985},\n 'b1': {61:1487, 100:51725}}\ncalibration_data[\"RFP\"] = {'b3': {61:70.38, 100:2541},\n 'b2': {61:67.64, 100:2392},\n 'b1': {61:47.96, 100:1689}}\ncalibration_data[\"CFP\"] = {'b3': {61:578, 100:20722},\n 'b2': {61:513, 100:18136},\n 'b1': {61:387, 100:13809}}\ncalibration_data[\"Venus\"] = {'b3': {61:2246, 100:79955},\n 'b2': {61:1742, 100:61130},\n 'b1': {61:1455, 100:50405}}\ncalibration_data[\"Cherry\"] = {'b3': {61:79.39, 100:2850},\n 'b2': {61:80.84, 100:2822},\n 'b1': {61:51.07, 100:1782}}\n\n############################################\n# Deal with Unicode problems with Python 2 #\n############################################\nif sys.version_info[0] == 2:\n import unicodecsv as csv\nelse:\n import csv\n\ndef standard_channel_name(fp_name, suppress_name_warning = False):\n upper_name = fp_name.upper()\n for std_name in [\"GFP\", \"Citrine\", \"RFP\", \"CFP\", \"Venus\", \"Cherry\"]:\n if std_name in upper_name:\n return std_name\n if not suppress_name_warning:\n warnings.warn((\"Unable to convert channel %s into standard channel \" + \\\n \"name. Are you sure this is the right name?\") % fp_name)\n return fp_name\n\n\ndef raw_to_uM(raw, protein, biotek, gain, volume):\n if not protein in calibration_data or \\\n not biotek in calibration_data[protein] or \\\n not gain in calibration_data[protein][biotek]:\n return None\n # Note that volume is in uL!\n if raw == \"OVRFLW\":\n raw = np.infty\n return float(raw) * 10.0 / calibration_data[protein][biotek][gain] / volume\n\nReadSet = collections.namedtuple('ReadSet', ['name', 'excitation', 'emission',\n 'gain'])\n\ndef read_supplementary_info(input_filename):\n info = dict()\n with mt_open(input_filename, 'rU') as infile:\n reader = csv.reader(infile)\n title_line = next(reader)\n for i in range(1, len(title_line)):\n info[title_line[i]] = dict()\n for line in reader:\n if line[0].strip() == \"\":\n continue\n for i in range(1, len(title_line)):\n info[title_line[i]][line[0]] = line[i]\n return info\n\n\ndef tidy_biotek_data(input_filename, supplementary_filename = None,\n volume = None):\n '''\n Convert the raw output from a Biotek plate reader into tidy data.\n Optionally, also adds columns of metadata specified by a \"supplementary\n file\", which is a CSV spreadsheet mapping well numbers to metadata.\n\n Arguments:\n --input_filename: Name of a Biotek output file. Data file should be\n standard excel output files, saved as a CSV.\n --supplementary_filename: Name of a supplementary file. Supplementary\n file must be a CSV wit a header, where the\n first column is the name of the well,\n additional columns define additional\n metadata, and each row after the header is a\n single well's metadata. Defaults to None\n (no metadata other than what can be mined\n from the data file).\n --volume: Volume of the TX-TL reactions. Note that default is 10 uL!\n Returns: None\n Side Effects: Creates a new CSV with the same name as the data file with\n \"_tidy\" appended to the end. This new file is in tidy\n format, with each row representing a single channel read\n from a single well at a single time.\n\n '''\n if volume == None:\n print(\"Assuming default volume 10 uL. Make sure this is what you want!\")\n volume = 10.0\n\n supplementary_data = dict()\n if supplementary_filename:\n supplementary_data = read_supplementary_info(supplementary_filename)\n filename_base = input_filename.rsplit('.', 1)[0]\n output_filename = filename_base + \"_tidy.csv\"\n\n with mt_open(input_filename, 'rU') as infile:\n with mt_open(output_filename, 'w') as outfile:\n reader = csv.reader(infile)\n writer = csv.writer(outfile, delimiter = ',')\n title_row = ['Channel', 'Gain', 'Time (sec)', 'Time (hr)', 'Well',\n 'AFU', 'uM', 'Excitation', 'Emission']\n for name in supplementary_data.keys():\n title_row.append(name)\n writer.writerow(title_row)\n\n # Read plate information\n read_sets = dict()\n for line in reader:\n if line[0].strip() == \"Reader Serial Number:\":\n if line[1] in plate_reader_ids:\n plate_reader_id = plate_reader_ids[line[1]]\n else:\n warnings.warn((\"Unknown plate reader id '%s'; will \" + \\\n \"not attempt to calculate molarity \" + \\\n \"concentrations.\") % line[1])\n plate_reader_id = None\n continue\n if line[0].strip() == \"Read\":\n if line[1].strip() == \"Fluorescence Endpoint\":\n read_name = \"\"\n else:\n read_name = line[1]\n entered_layout = False\n for line in reader:\n if line[0].strip() == \"Layout\":\n entered_layout = True\n break\n if line[0].strip() == \"Read\":\n if line[1].strip() == \"Fluorescence Endpoint\":\n read_name = \"\"\n else:\n read_name = line[1].strip()\n continue\n if line[1].startswith(\"Filter Set\"):\n line = next(reader)\n lineparts = line[1].split(\",\")\n excitation = int(lineparts[0].split(\":\")[-1].split(\"/\")[0].strip())\n # Sometimes excitation and emission get split to\n # different cells; check for this.\n if len(lineparts) == 1:\n emission_cell = line[2]\n else:\n emission_cell = lineparts[0]\n emission = int(emission_cell.split(\":\")[-1].split(\"/\")[0].strip())\n line = next(reader)\n gain = line[1].split(\",\")[-1].split(\":\")[-1].strip()\n if gain != \"AutoScale\":\n gain = int(gain)\n if not read_name in read_sets:\n read_sets[read_name] = []\n read_sets[read_name].append(ReadSet(read_name,\n excitation,\n emission, gain))\n if entered_layout:\n break\n # Read data blocks\n # Find a data block\n for line in reader:\n if line[0].strip() == \"\":\n continue\n info = line[0].strip()\n if info in [\"Layout\", \"Results\"]:\n continue\n if info.strip().upper().startswith(\"OD600\"):\n reading_OD = True\n else:\n reading_OD = False\n if reading_OD:\n read_name = \"OD600\"\n excitation = 600\n emission = -1\n gain = -1\n else:\n read_name = info.split(\":\")[0]\n if not info.endswith(']'):\n read_idx = 0\n else:\n read_idx = int(info.split('[')[-1][:-1]) - 1\n read_properties = read_sets[read_name][read_idx]\n gain = read_properties.gain\n excitation = read_properties.excitation\n emission = read_properties.emission\n\n line = next(reader) # Skip a line\n line = next(reader) # Chart title line\n well_names = line\n # Data lines\n for line in reader:\n if line[1] == \"\":\n break\n raw_time = line[1]\n time_parts = raw_time.split(':')\n time_secs = int(time_parts[2]) + 60*int(time_parts[1]) \\\n + 3600*int(time_parts[0])\n time_hrs = time_secs / 3600.0\n temp = line[2]\n for i in range(3,len(line)):\n if line[i].strip() == \"\":\n continue\n well_name = well_names[i]\n # Check to see if there's any supplementary information\n # on this well.\n if supplementary_filename and \\\n not well_name in list(supplementary_data.values())[0]:\n warnings.warn(\"No supplementary data for well \" + \\\n \"%s; throwing out data for that well.\"\\\n % well_name)\n continue\n afu = line[i]\n # Check for overflow\n if afu.upper() == \"OVRFLW\":\n afu = np.infty\n if reading_OD:\n uM_conc = afu\n else:\n uM_conc = raw_to_uM(line[i],\n standard_channel_name(read_name),\n plate_reader_id, gain, volume)\n if uM_conc == None:\n uM_conc = -1\n row = [read_name, gain, time_secs, time_hrs, well_name,\n afu, uM_conc, excitation, emission]\n for name in supplementary_data.keys():\n row.append(supplementary_data[name][well_name])\n try:\n writer.writerow(row)\n except TypeError as e:\n print(\"Error writing line: \" + str(row))\n raise e\n\n\ndef extract_trajectories_only(df):\n '''\n Given a DataFrame that has been read in from a tidied piece of BioTek data,\n return a DataFrame that collapses each channel's AFU value as a column in a\n new DataFrame whose only columns are WellID, Time, and each measured\n channel.\n\n Assumptions:\n - The time is in a channel called 'Time (hr)', which becomes Time\n - There is at least 1 measured channel\n\n Arguments:\n df -- DataFrame of Biotek data, pulled from a tidy dataset of the form\n produced by tidy_biotek_data.\n Returns: A new DataFrame with the only columns being Well, Time, and each\n measured channel.\n '''\n # Create dictionary to make new data-frame\n master_dict = {}\n master_dict['Time'] = []\n master_dict['Well'] = []\n\n # get all channel names and initialize columns\n all_channels = df.Channel.unique()\n for channel in all_channels:\n master_dict[channel] = []\n\n all_wells = df.Well.unique()\n\n # go through and build the trajectory for each well.\n for well in all_wells:\n well_df = df[df.Well == well]\n time_series = well_df[well_df.Channel == all_channels[0]]['Time (hr)']\n series_length = len(time_series)\n well_series = [well] * series_length\n\n master_dict['Time'].extend(time_series)\n master_dict['Well'].extend(well_series)\n for channel in all_channels:\n channel_series = well_df[well_df.Channel == channel].AFU\n assert (len(channel_series) == series_length)\n master_dict[channel].extend(channel_series)\n\n return_df = pd.DataFrame(master_dict)\n return return_df\n\n\ndef background_subtract(df, negative_control_wells):\n '''\n Create a new version of a dataframe with background removed. Background is\n inferred from one or more negative control wells. If more than one negative\n control is specified, the average of the wells is used as a background\n value.\n\n Note that this function assumes that every measurement has a corresponding\n negative control measurement in each of the negative control wells (same\n channel and gain).\n\n Arguments:\n df -- DataFrame of Biotek data, pulled from a tidy dataset of the form\n produced by tidy_biotek_data.\n negative_control_wells -- String or iterable of Strings specifying one\n or more negative control wells.\n Returns: A new DataFrame with background subtracted out.\n '''\n if type(negative_control_wells) == str:\n negative_control_wells = [negative_control_wells]\n return_df = pd.DataFrame()\n # Split the dataframe by channel and gain\n for channel in df.Channel.unique():\n channel_df = df[df.Channel == channel]\n for gain in channel_df.Gain.unique():\n condition_df = channel_df[channel_df.Gain == gain]\n neg_ctrl_df = pd.DataFrame()\n for well in negative_control_wells:\n well_df = condition_df[condition_df.Well == well]\n neg_ctrl_df = neg_ctrl_df.append(well_df)\n grouped_neg_ctrl = neg_ctrl_df.groupby([\"Time (sec)\"])\n avg_neg_ctrl = grouped_neg_ctrl.aggregate(np.average)\n avg_neg_ctrl.sort_index(inplace = True)\n avg_neg_ctrl.reset_index(inplace = True)\n # Easiest thing to do is to apply the background subtraction to each\n # well separately\n for well in condition_df.Well.unique():\n well_df = condition_df[condition_df.Well == well].copy()\n well_df.sort_values(\"Time (sec)\", inplace = True)\n well_df.reset_index(inplace = True)\n well_df.AFU = well_df.AFU - avg_neg_ctrl.AFU\n if channel in calibration_data and \\\n gain in calibration_data[channel]['b1']:\n well_df.uM = well_df.uM - avg_neg_ctrl.uM\n return_df = return_df.append(well_df)\n return return_df\n\n\ndef window_averages(df, start, end, units = \"seconds\",\n grouping_variables = None):\n '''\n Converts a dataframe of fluorescence data to a dataframe of average\n fluorescences from a specified time window. The time window can be specified\n in seconds, hours, or index.\n\n Args:\n df -- Dataframe of fluorescence data\n start -- First frame to be included (inclusively)\n end -- Last frame to be included (also inclusively)\n units -- Either \"seconds\" (default), \"hours\", or \"index\". If \"seconds\"\n or \"hours\", takes data within a time window (using the\n obvious columns). If \"index\", takes a slice using an index,\n where the first time is 0, etc.\n grouping_variables - Optional list of column names on which to group.\n Use this option primarily to separate multiple\n plates' worth of data with overlapping wells.\n '''\n group_cols = [\"Channel\", \"Gain\", \"Well\"]\n if grouping_variables:\n group_cols += grouping_variables\n\n # Start by screening out everything outside the desired time window.\n def pick_out_window(df):\n # Find times within the given window.\n if units.lower() == \"index\":\n all_times = df[\"Time (sec)\"].unique()\n all_times.sort()\n window_times = all_times[start:end+1]\n window_df = df[df[\"Time (sec)\"].isin(window_times)]\n else:\n if units.lower() == \"seconds\":\n col = \"Time (sec)\"\n elif units.lower() == \"hours\":\n col = \"Time (hr)\"\n else:\n raise ValueError(('Unknown unit \"{0}\"; units must be \"seconds\", ' \\\n +'\"hours\", or \"index\"').format(units))\n window_df = df[(df[col] >= start) & (df[col] <= end)]\n return window_df\n\n grouped_df = df.groupby(group_cols)\n window_df = grouped_df.apply(pick_out_window)\n\n # Figure out which columns are numeric and which have strings.\n column_names = window_df.columns.values.tolist()\n functions = dict()\n for col in column_names:\n if col in group_cols:\n continue\n # Check to see if the column is numerically typed\n if np.issubdtype(window_df[col].dtype, np.number):\n # Numbers get averaged\n functions[col] = np.average\n else:\n # Non-numbers get a copy of the last value\n functions[col] = lambda x:x.iloc[-1]\n\n # Calculate windowed average\n averages_df = window_df.groupby(group_cols).agg(functions)\n\n averages_df.reset_index(inplace = True)\n\n return averages_df\n\n\ndef endpoint_averages(df, window_size = 10, grouping_variables = None):\n '''\n Converts a dataframe of fluorescence data to a dataframe of endpoint\n average fluorescence.\n\n Params:\n window_size - Averages are taken over the last window_size points.\n grouping_variables - Optional list of column names on which to group.\n Use this option primarily to separate multiple\n plates' worth of data with overlapping wells.\n '''\n group_cols = [\"Channel\", \"Gain\", \"Well\"]\n if grouping_variables:\n group_cols += grouping_variables\n grouped_df = df.groupby(group_cols)\n last_time_dfs = []\n for name, group in grouped_df:\n all_times = group[\"Time (hr)\"].unique()\n first_last_time = np.sort(all_times)[-window_size]\n last_time_dfs.append(group[group[\"Time (hr)\"] >= first_last_time])\n end_time_dfs = pd.concat(last_time_dfs)\n return window_averages(end_time_dfs, 0, window_size, \"index\",\n grouping_variables)\n\n\ndef spline_fit(df, column = \"uM\", smoothing_factor = None):\n '''\n Adds a spline fit of the uM traces of a dataframe of the type made by\n tidy_biotek_data.\n\n Params:\n df - DataFrame of time traces, of the kind produced by tidy_biotek_data.\n column - Column to find spline fit over. Defaults to \"uM\".\n smoothing_factor - Parameter determining the tightness of the fit.\n Default is the number of time points. Smaller\n smoothing factor produces tighter fit; 0 smoothing\n factor interpolates every point. See parameter 's'\n in scipy.interpolate.UnivariateSpline.\n Returns:\n A DataFrame of df augmented with columns for a spline fit.\n '''\n # Fit 3rd order spline\n grouped_df = df.groupby([\"Channel\", \"Gain\", \"Well\"])\n splined_df = pd.DataFrame()\n for name, group in grouped_df:\n spline = scipy.interpolate.UnivariateSpline(group[\"Time (sec)\"],\n group[column],\n s = smoothing_factor)\n group[column + \" spline fit\"] = spline(group[\"Time (sec)\"])\n splined_df = splined_df.append(group)\n return splined_df\n\ndef smoothed_derivatives(df, column = \"uM\", smoothing_factor = None):\n '''\n Calculates a smoothed derivative of the time traces in a dataframe. First\n fits a spline, then adds the derivatives of the spline to a copy of the\n DataFrame, which is returned.\n\n Args:\n df - DataFrame of time traces, of the kind produced by tidy_biotek_data.\n column - Column to fit derivatives to. Defaults to \"uM\"\n smoothing_factor - Parameter determining the tightness of the spline\n fit made before derivative calculation.\n Default is the number of time points. Smaller\n smoothing factor produces tighter fit; 0 smoothing\n factor interpolates every point. See parameter 's'\n in scipy.interpolate.UnivariateSpline.\n Returns:\n A DataFrame of df augmented with columns for a spline fit and a\n derivative\n '''\n splined_df = spline_fit(df, column, smoothing_factor)\n grouped_df = splined_df.groupby([\"Channel\", \"Gain\", \"Well\"])\n deriv_df = pd.DataFrame()\n for name, group in grouped_df:\n group[column + \"/sec\"] = np.gradient(group[column + \" spline fit\"])\n deriv_df = deriv_df.append(group)\n return deriv_df\n\ndef normalize(df, norm_channel = \"OD600\", norm_channel_gain = -1):\n '''\n Normalize expression measurements by dividing each measurement by the value\n of a reference channel at that time (default OD600).\n\n Args:\n df - DataFrame of time traces, of the kind produced by tidy_biotek_data.\n norm_channel - Name of a channel to normalize by. Default \"OD600\"\n norm_channel_gain - Gain of the channel you want to normalize by.\n Default -1 (for OD600)\n Returns:\n A DataFrame of df augmented with columns for normalized AFU\n (\"AFU/\").\n '''\n # Do some kind of check to make sure the norm channel exists with the given\n # channel...\n if not norm_channel in df.Channel:\n raise ValueError(\"No data for channel '%s' in dataframe.\" % \\\n norm_channel)\n if not norm_channel_gain in df[df.Channel == norm_channel].Gain:\n raise ValueError(\"Channel %s does not use gain %d.\" % \\\n (norm_channel, norm_channel_gain))\n\n # Iterate over channels/gains, applying normalization\n grouped_df = df.groupby([\"Channel\", \"Gain\", \"Well\"])\n normalized_df = pd.DataFrame()\n for name, group in grouped_df:\n group[\"AFU/\" + norm_channel] = group[\"AFU\"] / group[norm_channel]\n normalized_df = normalized_df.append(group)\n return normalized_df\n\n","sub_path":"murraylab_tools/biotek/biotek.py","file_name":"biotek.py","file_ext":"py","file_size_in_byte":23513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"270397635","text":"import os\nimport sys\nimport json\nimport pymysql.cursors\nfrom collections import OrderedDict\nfrom time import sleep\nfrom selenium import webdriver\n\ndriver = webdriver.Chrome(\"/Users/gimda-eun/Downloads/chromedriver\")\nurl = 'https://m.lalavla.com/service/main/mainBrand.html'\ndata = OrderedDict()\n\ndriver.get(url)\ndriver.implicitly_wait(5)\n\ndef execute_sql(sqls):\n with open('sql_abc.txt', 'a') as f:\n f.writelines(sqls)\n\n\n # for sql in sqls:\n # print(sql)\n # cursors.execute(sql)\n # conn.commit()\n\n# DB 연동\nconn = pymysql.connect(\n host = 'localhost', # 로컬호스트\n user = 'root', # 유저\n password = '', # 비밀번호\n db = 'MEKI', # 데이터베이스\n charset = 'utf8' # 인코딩 캐릭터셋\n)\ncursors = conn.cursor()\nprint('DB 연동 완료')\n\n\n\n# 네비게이션 바에서 ㄱ~ㅎ, ABC까지 하나씩 탭하기\nbrand_btn_lists = driver.find_elements_by_class_name('nav-brdSrch > li') # ㄱ~ABC\ncount = 1 # 전체 브랜드 개수\nbrand_dict = dict()\n\n\n# ㄱ~ㅎ, ABC까지 버튼이 ch_btn에 들어감\nfor i in range(14,15):\n sqls = []\n \n brand_btn_lists[i].click() # 첨자 버튼 클릭\n sleep(0.3)\n driver.implicitly_wait(3)\n # 전체보기 버튼 밑의 브랜드 리스트들\n brand_lists = driver.find_elements_by_class_name('list-brdSrchResult > li a')\n ch_brand_count = len(brand_lists) # 해당 첨자의 브랜드 개수들\n\n for k in range(ch_brand_count):\n # staleElement 에러 때문에 매번 새로 찾아줘야 함\n brand_lists = driver.find_elements_by_class_name('list-brdSrchResult > li a')\n brand = brand_lists[k]\n driver.implicitly_wait(3)\n b_name = brand.text\n brand.click() # 각 브랜드를 클릭해 들어가기\n driver.implicitly_wait(3)\n\n try:\n # 브랜드 이미지 찾기\n brand_img = (driver.find_element_by_id(\"topvisual-image\")).get_attribute('src')\n if brand_img == 'http://mimg.lalavla.com/resources': # 이미지가 없을 경우 except 절로\n raise Exception \n brand_dict[b_name] = [count, str(brand_img)]\n except: # 이미지가 없을 경우\n brand_dict[b_name] = [count, \"X\"]\n\n # print(\"브랜드이름 :\"+ b_name)\n # print(\"src: \"+str(brand_dict[b_name][1]))\n \n count += 1 # 브랜드 1개 찾았으니 count 증가\n driver.back()\n driver.implicitly_wait(3)\n \n # insert sql\n sqls.append(\"insert into Brand(brand_name, brand_img) \\\n values ('%s', '%s'); \\n\" % (str(b_name), str(brand_dict[b_name][1])))\n \n # excute sql\n execute_sql(sqls)\n\n brand_btn_lists = driver.find_elements_by_class_name('nav-brdSrch > li') # ㄱ~ABC\n sleep(0.5)\n driver.implicitly_wait(3)\n\n\ndriver.quit()\n\n\n\n\n# try:\n# with open(\n# './data/brand.json', 'w', encoding='utf-8') as f:\n# json.dump(brand_dict, f, ensure_ascii=False, indent=\"\\t\")\n# except: # 디렉터리가 없을 때만 디렉터리를 만듦\n# os.makedirs('./data')\n\nprint('done!')","sub_path":"practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"641876021","text":"def mergeSort(mylist):\n if len(mylist)>1:\n i=0\n j=0\n k=0\n mid = len(mylist)//2\n left = mylist[:mid]\n right = mylist[mid:]\n mergeSort(left)\n mergeSort(right)\n while i