diff --git "a/2461.jsonl" "b/2461.jsonl" new file mode 100644--- /dev/null +++ "b/2461.jsonl" @@ -0,0 +1,753 @@ +{"seq_id":"413720745","text":"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n# vispy: gallery 2\n\n\"\"\"\nExample volume rendering\n\nControls:\n\n* 1 - toggle camera between first person (fly), regular 3D (turntable) and\n arcball\n* 2 - toggle between volume rendering methods\n* 3 - toggle between stent-CT / brain-MRI image\n* 4 - toggle between colormaps\n* 0 - reset cameras\n* [] - decrease/increase isosurface threshold\n\nWith fly camera:\n\n* WASD or arrow keys - move around\n* SPACE - brake\n* FC - move up-down\n* IJKL or mouse - look around\n\"\"\"\n\nfrom itertools import cycle\n\nimport numpy as np\n\nfrom vispy import app, scene, io\nfrom vispy.scene import visuals\nimport vispy.visuals as impl_visuals\nfrom vispy.color import get_colormaps, BaseColormap\n\n# Read volume\nvol1 = np.load(io.load_data_file('volume/stent.npz'))['arr_0']\nvol2 = np.load(io.load_data_file('brain/mri.npz'))['data']\nvol2 = np.flipud(np.rollaxis(vol2, 1))\n\n# Prepare canvas\ncanvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True)\ncanvas.measure_fps()\n\n# Set up a viewbox to display the image with interactive pan/zoom\nview = canvas.central_widget.add_view()\n\n# Set whether we are emulating a 3D texture\nemulate_texture = False\n\n# Create the volume visuals, only one is visible\nvolume1 = scene.visuals.Volume(vol1, parent=view.scene, threshold=0.225,\n emulate_texture=emulate_texture)\nvolume1.transform = scene.STTransform(translate=(64, 64, 0))\nvolume2 = scene.visuals.Volume(vol2, parent=view.scene, threshold=0.2,\n emulate_texture=emulate_texture)\nvolume2.visible = False\n\n# Create three cameras (Fly, Turntable and Arcball)\nfov = 60.\ncam1 = scene.cameras.FlyCamera(parent=view.scene, fov=fov, name='Fly')\ncam2 = scene.cameras.TurntableCamera(parent=view.scene, fov=fov,\n name='Turntable')\ncam3 = scene.cameras.ArcballCamera(parent=view.scene, fov=fov, name='Arcball')\nview.camera = cam2 # Select turntable at first\n\n# Add scatter plots here\ncanvas.unfreeze()\nn = 100\nP = np.random.rand(n, 3)\ns = vol1.shape\nX, Y, Z = P[:, 0], P[:, 1], P[:, 2]\nX = X*s[2]\nY = Y*s[1]\nZ = Z*s[0]\npos = np.zeros((n, 3), dtype=np.float32)\npos[:, 0], pos[:, 1], pos[:, 2] = X, Y, Z\n\n# xmin, xmax = \"%.4g\" % np.nanmin(vol1[])\nscatter = scene.visuals.Markers()\nscatter.set_data(pos, face_color=(0, 1, 0), scaling=False)\nindex = 1\n# scatter.symbol = 'star'\nscatter.symbol = impl_visuals.marker_types[index]\n\nscatter.transform = scene.STTransform(translate=(s[2]/2.0, s[1]/2.0, 0))\n\nview.add(scatter)\n\n# Add text visual here\ntext = visuals.Text(impl_visuals.marker_types[index],\n pos=(80, 15), font_size=14,\n color='white', parent=canvas.scene)\ncanvas.freeze()\n# canvas.update()\n\n# create colormaps that work well for translucent and additive volume rendering\nclass TransFire(BaseColormap):\n glsl_map = \"\"\"\n vec4 translucent_fire(float t) {\n return vec4(pow(t, 0.5), t, t*t, max(0, t*1.05 - 0.05));\n }\n \"\"\"\n\n\nclass TransGrays(BaseColormap):\n glsl_map = \"\"\"\n vec4 translucent_grays(float t) {\n return vec4(t, t, t, t*0.05);\n }\n \"\"\"\n\n# Setup colormap iterators\nopaque_cmaps = cycle(get_colormaps())\ntranslucent_cmaps = cycle([TransFire(), TransGrays()])\nopaque_cmap = next(opaque_cmaps)\ntranslucent_cmap = next(translucent_cmaps)\n\n\n# Implement key presses\n@canvas.events.key_press.connect\ndef on_key_press(event):\n global opaque_cmap, translucent_cmap\n if event.text == '1':\n cam_toggle = {cam1: cam2, cam2: cam3, cam3: cam1}\n view.camera = cam_toggle.get(view.camera, cam2)\n print(view.camera.name + ' camera')\n elif event.text == '2':\n methods = ['mip', 'translucent', 'iso', 'additive']\n method = methods[(methods.index(volume1.method) + 1) % 4]\n print(\"Volume render method: %s\" % method)\n cmap = opaque_cmap if method in ['mip', 'iso'] else translucent_cmap\n volume1.method = method\n volume1.cmap = cmap\n volume2.method = method\n volume2.cmap = cmap\n elif event.text == '3':\n volume1.visible = not volume1.visible\n volume2.visible = not volume1.visible\n elif event.text == '4':\n if volume1.method in ['mip', 'iso']:\n cmap = opaque_cmap = next(opaque_cmaps)\n else:\n cmap = translucent_cmap = next(translucent_cmaps)\n volume1.cmap = cmap\n volume2.cmap = cmap\n elif event.text == '0':\n cam1.set_range()\n cam3.set_range()\n elif event.text != '' and event.text in '[]':\n s = -0.025 if event.text == '[' else 0.025\n volume1.threshold += s\n volume2.threshold += s\n th = volume1.threshold if volume1.visible else volume2.threshold\n print(\"Isosurface threshold: %0.3f\" % th)\n\n\n# for testing performance\n# @canvas.connect\n# def on_draw(ev):\n# canvas.update()\n\nif __name__ == '__main__':\n print(__doc__)\n app.run()\n","sub_path":"vispy_examples/vol+scat.py","file_name":"vol+scat.py","file_ext":"py","file_size_in_byte":5239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"463218899","text":"import mxnet as mx\nimport mxnet.ndarray as nd\nimport numpy as np\n\nnp.random.seed(777)\n\n# 1. Prepare Data\nxy = np.loadtxt('data-01-test-score.csv', delimiter=',', dtype=np.float32)\nx_data = xy[:, 0:-1]\ny_data = xy[:, [-1]]\n\nprint(\"x_data\", x_data)\nprint(\"y_data\", y_data)\n\nsample_num = x_data.shape[0]\ndimension = x_data.shape[1]\nbatch_size = 25\ntrain_iter = mx.io.NDArrayIter(x_data, y_data, batch_size, shuffle=True, label_name='lin_reg_label')\n\n# 2. Build Linear Regression Model\ndata = mx.sym.Variable(\"data\")\ntarget = mx.sym.Variable(\"target\")\npred = mx.sym.FullyConnected(data=data, num_hidden=1, name='pred')\nloss = mx.sym.mean(mx.sym.square(target - pred))\nloss = mx.sym.make_loss(loss)\n\n\n# 3. Build the network\nnet = mx.mod.Module(symbol=loss,\n data_names=['data'],\n label_names=['target'],\n context=mx.gpu(0))\nnet.bind(data_shapes = [mx.io.DataDesc(name='data', shape=(batch_size, 3), layout='NC')],\n label_shapes= [mx.io.DataDesc(name='target', shape=(batch_size, 1), layout='NC')])\nnet.init_params(initializer=mx.init.Normal(sigma=0.01))\nnet.init_optimizer(optimizer='sgd', optimizer_params={'learning_rate': 1E-3, 'momentum':0.9})\n\ntest_net = mx.mod.Module(symbol=pred,\n data_names=['data'],\n label_names=None,\n context=mx.gpu(0))\ntest_net.bind(data_shapes=[mx.io.DataDesc(name='data', shape=(sample_num, 3), layout='NC')],\n label_shapes=None,\n shared_module=net)\n\n# 4. Train the model\ny_data_nd = nd.array(y_data, ctx=mx.gpu())\nfor idx in range(2000):\n total_batch_num = int(sample_num / batch_size)\n for batch_id in range(total_batch_num):\n x_batch = x_data[batch_id*batch_size:(batch_id+1)*batch_size , :]\n y_batch = y_data[batch_id*batch_size:(batch_id+1)*batch_size , :]\n data_batch = mx.io.DataBatch(data=[mx.nd.array(x_batch)],\n label=[mx.nd.array(y_batch)])\n net.forward_backward(data_batch)\n net.update()\n test_net.forward(mx.io.DataBatch(data=[mx.nd.array(x_data)], label=None), is_train=False)\n pred_nd = test_net.get_outputs()[0]\n mse = nd.mean(nd.square(pred_nd - y_data_nd)).asnumpy()[0]\n print(\"epoch: %d, mse = %g\" %(idx, mse))\n\ntest_net.reshape(data_shapes=[[\"data\", (1, 3)]])\ntest_net.forward(mx.io.DataBatch(data=[nd.array([[60, 70, 110]])], label=None))\nprint(\"input = [60, 70, 110], score =\", test_net.get_outputs()[0].asnumpy())\ntest_net.forward(mx.io.DataBatch(data=[nd.array([[90, 100, 80]])], label=None))\nprint(\"input = [90, 100, 80], score =\", test_net.get_outputs()[0].asnumpy())\n'''\ninput = [60, 70, 110], score = [[ 182.48858643]]\ninput = [90, 100, 80], score = [[ 175.24279785]]\n'''","sub_path":"mxnet/mxlab-04-3-file_input_linear_regression.py","file_name":"mxlab-04-3-file_input_linear_regression.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"543841554","text":"import numpy as np\nfrom sklearn.svm import SVR\nfrom multiprocessing.pool import ThreadPool\nimport copy\n\nimport base\n\n\ndef learn(learner, X, y):\n return learner.fit(X, y)\n\n\nclass LearnerPredictor:\n def __init__(self):\n self.svr_rbf = SVR(kernel='rbf')\n self.learner = None\n self.predictor = None\n self.learner_size, self.predictor_size = 0, 0\n self.pool = ThreadPool(processes=1)\n self.async_result = None\n\n def init_data(self, init_features, init_results):\n self.learner = self.svr_rbf.fit(init_features, init_results)\n self.predictor = self.svr_rbf.fit(init_features, init_results)\n\n def predict(self, X):\n return self.predictor.predict(X)\n\n def update_learner(self, new_size):\n if self.async_result is None or (self.async_result.ready()):\n if self.async_result is not None:\n self.predictor = copy.copy(self.async_result.get())\n self.predictor_size = self.learner_size\n\n if new_size > 1.1 * self.predictor_size:\n features, results = base.get_lists()\n self.async_result = self.pool.apply_async(learn, (self.learner, features, results))\n self.learner_size = len(results)\n","sub_path":"learn.py","file_name":"learn.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"409074135","text":"def valid(n):\n s = str(n**2)\n l = len(str(n))\n r = s[-l:]\n l = s[:-l] or '0'\n return sum(map(int,(l,r)))==n\n\na = int(input())\nb = int(input())\nl = [i for i in range(a,b+1) if valid(i)]\nif l:\n print(*l)\nelse:\n print(\"INVALID RANGE\")\n\n","sub_path":"06_smart_interviews_basic/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"355339422","text":"from django.conf.urls import url\nfrom hotel.master import views\n\nurlpatterns = [\n # # MASTER URLS\n url(r'^master/$', views.master_index, name='master_index'),\n url(r'^master/country/$',views.master_country,name='master_country'),\n url(r'^master/cities/$',views.master_cities,name='master_cities'),\n url(r'^master/airport/$',views.master_airport,name='master_airport'),\n url(r'^master/board/$',views.master_board,name='master_board'),\n url(r'^master/hotelgrp/$',views.master_hotelgrp,name='master_hotelgrp'),\n url(r'^master/pos/$',views.master_pos,name='master_pos'),\n url(r'^master/hotel/$',views.master_hotel,name='master_hotel'),\n url(r'^master/Hotel_master_upload_excel/$',views.Hotel_master_upload_excel,name='Hotel_master_upload_excel'),\n url(r'^master/Bind_Hotel_master_name/$',views.Bind_Hotel_master_name,name='Bind_Hotel_master_name'),\n url(r'^master/Bind_city_master_name/$',views.Bind_city_master_name,name='Bind_city_master_name'),\n url(r'^master/Delete_City_master_name/$',views.Delete_City_master_name,name='Delete_City_master_name'),\n url(r'^master/Delete_Country_master_name/$',views.Delete_Country_master_name,name='Delete_Country_master_name'),\n url(r'^master/Bind_Country_master_name/$',views.Bind_Country_master_name,name='Bind_Country_master_name'),\n url(r'^master/Bind_POS_master_name/$',views.Bind_POS_master_name,name='Bind_POS_master_name'),\n url(r'^master/Bind_board_master_name/$',views.Bind_board_master_name,name='Bind_board_master_name'),\n url(r'^master/Bind_airport_master_name/$',views.Bind_airport_master_name,name='Bind_airport_master_name'),\n url(r'^master/Delete_Airport_master_name/$',views.Delete_Airport_master_name,name='Delete_Airport_master_name'),\n url(r'^master/Delete_Board_master_name/$',views.Delete_Board_master_name,name='Delete_Board_master_name'),\n url(r'^master/Delete_POS_master_name/$',views.Delete_POS_master_name,name='Delete_POS_master_name'),\n\n\n url(r'^master/Bind_Hotel_master_country_name/$',views.Bind_Hotel_master_country_name,name='Bind_Hotel_master_country_name'),\n url(r'^master/Bind_Hotel_master_city_name/$',views.Bind_Hotel_master_city_name,name='Bind_Hotel_master_city_name'),\n url(r'^master/update_Hotel_master/$',views.update_Hotel_master,name='update_Hotel_master'),\n url(r'^master/Add_New_Hotel_master/$',views.Add_New_Hotel_master,name='Add_New_Hotel_master'),\n url(r'^master/Delete_Hotel_master_name/$',views.Delete_Hotel_master_name,name='Delete_Hotel_master_name'),\n url(r'^master/Pos_master_upload_excel/$',views.Pos_master_upload_excel,name='Pos_master_upload_excel'),\n url(r'^master/City_master_upload_excel/$',views.City_master_upload_excel,name='City_master_upload_excel'),\n url(r'^master/Country_master_upload_excel/$',views.Country_master_upload_excel,name='Country_master_upload_excel'),\n\n url(r'^master/Download_hotel/$', views.Download_hotel_master, name='Download_Hotel_master'),\n url(r'^master/Bind_sup_name_by_city/$', views.Bind_sup_name_by_city, name='Bind_sup_name_by_city'),\n ]\n\n\n","sub_path":"eCube_Hotel_2/eCube_UI_2/hotel/master/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"41065647","text":"'''отображает изображение с помощью стандартного объекта PhotoImage из библиотеки\ntkinter; данная реализация может работать с GIF-файлами, но не может\nобрабатывать изображения в формате JPEG; использует файл с изображением, имя\nкоторого указано в командной строке, или файл по умолчанию; используйте Canvas\nвместо Label, чтобы обеспечить возможность прокрутки, и т.д.'''\n\n\nimport os, sys\nfrom tkinter import * # использовать стандартный объект PhotoImage\n # работает с форматом GIF, а для работы с форматом JPEG\n # требуется пакет PIL\n\nfrom PIL.ImageTk import PhotoImage # <== использовать альтернативный класс из\n # PIL, остальной программн��й код\n # без изменений\n\nroot = Tk()\n\nimgpath = \"C:/Users/Ivar/Pictures/Скрины/index.jpg\"\nroot.title('...'+ imgpath[-10:])\n\nimgobj = PhotoImage(file=imgpath)\n\nLabel(root, image=imgobj).pack(side=LEFT)\n\ncan = Canvas(root)\ncan.pack(side=LEFT)\ncan.create_image(0, 0, image=imgobj, anchor=NW)\ncan.config(width=imgobj.width(), height=imgobj.height())\nprint(imgobj.width(), imgobj.height())\n\nroot.mainloop()\n","sub_path":"tk24.py","file_name":"tk24.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"514525729","text":"import numpy\n\ndef stack(images):\n # We must not iterate over the input twice to get mean *and* standard deviation, so we use:\n # http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Incremental_algorithm\n n = 0\n mean = None\n M2 = None\n\n for image in images:\n n = n + 1\n if mean is None:\n mean = image\n M2 = numpy.zeros(image.shape, dtype=image.dtype)\n continue\n \n delta = image - mean\n mean = mean + delta / n\n M2 = M2 + delta * (image - mean)\n print(\"Stacked image\")\n\n if M2 is None:\n stdev = None\n else:\n stdev = numpy.sqrt(M2 / n) # I don't like Bessel's correction.\n\n return mean, stdev\n","sub_path":"AstropressPy/Stack.py","file_name":"Stack.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"651904648","text":"import os, subprocess, time, signal\nimport gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\nfrom c_elegan.envs.elegan import Controller, Discrete\n\ntry:\n import matplotlib.pyplot as plt\nexcept ImportError as e:\n raise error.DependencyNotInstalled(\"{}. (HINT: see matplotlib documentation for installation https://matplotlib.org/faq/installing_faq.html#installation\".format(e))\n\nclass CEleganEnv(gym.Env):\n metadata = {'render.modes': ['human']}\n\n def __init__(self, grid_size=[15,15], unit_size=10, unit_gap=1, n_elegans=1, n_foods=1):\n self.grid_size = grid_size\n self.unit_size = unit_size\n self.unit_gap = unit_gap\n self.n_elegans = n_elegans\n self.n_foods = n_foods\n self.viewer = None\n self.action_space = Discrete(3)\n\n def step(self, action):\n return self.controller.step(action)\n\n def reset(self):\n self.controller = Controller(self.grid_size, self.unit_size, self.unit_gap, self.n_elegans, self.n_foods)\n return self.controller.get_obses()\n\n def render(self, mode='human', close=False):\n obs = self.controller.grid.draw_elegans(self.controller.elegans)\n if self.viewer is None:\n self.viewer = plt.imshow(obs)\n else:\n self.viewer.set_data(obs)\n plt.pause(0.1)\n plt.draw()\n\n def seed(self, x):\n pass\n","sub_path":"c_elegan/envs/c_elegan_env.py","file_name":"c_elegan_env.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"169683932","text":"from collections import defaultdict\nimport numpy as np\nimport random\nfrom objects import *\nimport pybullet as p\nfrom utils import *\nfrom init import load_urdf\n\n\ndef categorize(types, categories):\n objects = defaultdict(set)\n # Get mapping category -> ids in category\n for id, type in types.items():\n for category, category_objects in categories.items():\n if type in category_objects:\n objects[category].add(id)\n return objects\n\ndef all_actions():\n return [\n 'pour', 'toast', 'peel', 'activate', 'deactivate', 'pick+place',\n ]\n\ndef valid_action_sequence(types, episode_length):\n categories = {\n 'table': ['table'],\n 'food': FOOD,\n 'cookware': COOKWARE,\n 'containers': CONTAINERS,\n 'sinks': ['sink'],\n 'stoves': ['stove'],\n 'knives': KNIVES,\n 'toasters': ['toaster'],\n 'drying_racks': ['drying_rack'],\n 'filled_drinks': FILLED_DRINKS,\n 'recepticles': RECEPTICLES,\n 'kitchenware': KITCHENWARE,\n }\n\n objects = categorize(types, categories)\n\n table = random.sample(objects['table'], 1)[0]\n sink = random.sample(objects['sinks'], 1)[0]\n stove = random.sample(objects['stoves'], 1)[0]\n drying_rack = random.sample(objects['drying_racks'], 1)[0]\n\n actions = []\n\n # While there exist things to be washed, we get a coin flip, and there are still actions\n coin_flip = random.random() < 0.5\n while len(objects['kitchenware']) > 0 and coin_flip and len(actions) < episode_length:\n # Sample kitchenware item\n kitchenware = random.sample(objects['kitchenware'], 1)[0]\n objects['kitchenware'].remove(kitchenware)\n\n # Wash item\n actions.append(('pick+place', (kitchenware, sink)))\n actions.append(('activate', (sink,)))\n actions.append(('deactivate', (sink,)))\n actions.append(('pick+place', (kitchenware, drying_rack)))\n actions.append(('pick+place', (kitchenware, table)))\n\n coin_flip = random.random() < 0.5\n\n while len(actions) < episode_length:\n sample_type = random.choice(['pour', 'prepare food'])\n\n # Pour liquid\n if sample_type == 'pour':\n if len(objects['filled_drinks']) > 0 and len(objects['recepticles']) > 0:\n # Sample and remove drink\n drink = random.sample(objects['filled_drinks'], 1)[0]\n objects['filled_drinks'].remove(drink)\n\n # Sample and remove cup\n cup = random.sample(objects['recepticles'], 1)[0]\n objects['recepticles'].remove(cup)\n\n actions.append(('pour', (drink, cup)))\n\n # Prepare food item\n elif sample_type == 'prepare food':\n cookware = random.sample(objects['cookware'], 1)[0]\n container = random.sample(objects['containers'], 1)[0]\n\n food = random.sample(objects['food'], 1)[0]\n food_type = types[food]\n\n if food_type == 'bread' and len(objects['toasters']) > 0:\n toaster = random.sample(objects['toasters'], 1)[0]\n actions.append(('pick+place', (food, toaster)))\n actions.append(('activate', (toaster,)))\n actions.append(('deactivate', (toaster,)))\n actions.append(('pick+place', (food, container)))\n\n elif food_type in PRODUCE:\n peel = random.random() < 0.5\n if peel and (food_type in PEELABLE_FOOD) and len(objects['knives']) > 0:\n knife = random.sample(objects['knives'], 1)[0]\n actions.append(('pick+place', (food, knife)))\n actions.append(('eel', (food, knife)))\n\n wash = random.random() < 0.5\n if wash and not peel and (food_type in WASHABLE_FOOD):\n actions.append(('pick+place', (food, sink)))\n actions.append(('activate', (sink,)))\n actions.append(('deactivate', (sink,)))\n\n cook = random.random() < 0.5\n if cook and (food_type in COOKABLE_FOOD):\n actions.append(('pick+place', (cookware, stove)))\n actions.append(('pick+place', (food, cookware)))\n actions.append(('activate', (stove,)))\n actions.append(('deactivate', (stove,)))\n\n actions.append(('pick+place', (food, container)))\n\n if cook:\n actions.append(('pick+place', (cookware, list(objects['table'])[0])))\n\n objects['food'].remove(food)\n else:\n raise Exception('Should not happen... (1)')\n\n return actions\n\ndef execute_pick_and_place(subj, dest, world, planner, time_step=0.001):\n pb_subj = world['pybullet_ids'][subj]\n pb_dest = world['pybullet_ids'][dest]\n\n types = world['types']\n children = world['children']\n\n if len(children[subj]) > 0:\n object_type = types[subj]\n raise Exception('Trying to move object {} (type: {}) with the following children: {}'.format(subj, object_type, children[subj]))\n\n with world_saved():\n pick_plan, pick_pose = planner.plan('pick', (pb_subj,))\n pick_command = ('pick', (pb_subj, pick_pose), pick_plan)\n pick_plan.refine().execute(time_step=time_step)\n\n with world_saved():\n place_plan, place_pose = planner.plan('place', (pb_subj, pb_dest))\n place_command = ('place', (pb_subj, pb_dest, place_pose), place_plan)\n place_plan.refine().execute(time_step=time_step)\n\n for obj_i, children_i in children.items():\n count = 0\n if subj in children_i:\n children_i.remove(subj)\n count += 1\n if count > 1:\n # Means that object was a child to two parents?\n print('This shouldn\\'t happen... (0)')\n\n children[dest].append(subj)\n\ndef dfs(node, graph, f):\n def visit(node, graph, visited, f):\n visited.add(node)\n f(node)\n for child in graph[node]:\n if child not in visited:\n visit(child, graph, visited, f)\n visit(node, graph, set(), f)\n\ndef execute_activate(id, world, textures):\n types = world['types']\n children = world['children']\n object_type = types[id]\n\n if object_type == 'sink':\n # Wash immediate child\n update_texture(id, world, textures, 'SINK_ACTIVE_COLOR')\n for child in children[id]:\n update_texture(child, world, textures, 'WASHED_COLOR')\n\n elif object_type == 'stove':\n # DFS to find food and cook it\n def change_to_cooked(id):\n if types[id] in COOKABLE_FOOD:\n update_texture(id, world, textures, 'COOKED_COLOR')\n\n update_texture(id, world, textures, 'STOVE_ACTIVE_COLOR')\n dfs(id, children, change_to_cooked)\n\n elif object_type == 'toaster':\n # DFS to find food and cook it\n def change_to_cooked(id):\n if types[id] in ['bread']:\n update_texture(id, world, textures, 'TOASTED')\n\n update_texture(id, world, textures, 'STOVE_ACTIVE_COLOR')\n dfs(id, children, change_to_cooked)\n\n else:\n raise Exception('Cannot activate object with type {}'.format(object_type))\n\ndef execute_deactivate(id, world, textures):\n children = world['children']\n object_type = world['types'][id]\n\n if object_type == 'sink':\n update_texture(id, world, textures, 'SINK_INACTIVE_COLOR')\n elif object_type == 'stove':\n update_texture(id, world, textures, 'STOVE_INACTIVE_COLOR')\n elif object_type == 'toaster':\n update_texture(id, world, textures, 'STOVE_INACTIVE_COLOR')\n else:\n raise Exception('Cannot deactivate object with type {}'.format(object_type))\n\ndef update_texture(id, world, textures, texture_name):\n texture = textures[texture_name]\n if type(texture) == list:\n p.changeVisualShape(world['pybullet_ids'][id], -1, rgbaColor=texture)\n else:\n p.changeVisualShape(world['pybullet_ids'][id], -1, textureUniqueId=texture)\n world['textures'][id] = texture\n\ndef fill_recepticle(source, sink, world, textures):\n type_name = world['types'][source]\n if type_name == 'powerade':\n update_texture(sink, world, textures, 'POWERADE')\n elif type_name == 'wine_bottle':\n update_texture(sink, world, textures, 'WINE')\n elif 'coke' in type_name.lower():\n update_texture(sink, world, textures, 'COLA')\n else:\n update_texture(sink, world, textures, 'FILLED_COLOR')\n\ndef execute_pour(source, sink, world, textures):\n update_texture(source, world, textures, 'EMPTY_COLOR')\n fill_recepticle(source, sink, world, textures)\n\ndef execute_peel(obj, knife, world, textures):\n types = world['types']\n scales = world['scales']\n\n # Retrieve type and scale information\n type_name = types[obj]\n scale = scales[obj]\n\n # Save pose and remove object\n pose = p.getBasePositionAndOrientation(world['pybullet_ids'][obj], physicsClientId=CLIENT)\n p.removeBody(world['pybullet_ids'][obj], physicsClientId=CLIENT)\n\n # Create new object, set pose\n new_obj = load_urdf(type_name, globalScaling=0.7*scale)\n p.resetBasePositionAndOrientation(new_obj, pose[0], pose[1], physicsClientId=CLIENT)\n\n # Update world state to include new id\n world['pybullet_ids'][obj] = new_obj\n\n # Maps type to peel color\n def get_peel_texture(type_name, textures):\n if type_name == 'orange':\n return 'LIGHTORANGE'\n elif type_name == 'banana':\n return 'PEELED_BANANA'\n else:\n return 'LIGHTYELLOW'\n\n # Update texture to be lighter color, as if peeled\n new_texture = get_peel_texture(type_name, textures)\n update_texture(obj, world, textures, new_texture)\n\ndef execute_toast(bread, toaster, world, textures):\n # Changes obj color given toaster\n update_texture(bread, world, textures, 'TOASTED')\n\ndef execute_action(action_seq, action_index, world, planner, textures):\n action = action_seq[action_index]\n action_type, ids = action[0], action[1]\n if action_type == 'pick+place':\n execute_pick_and_place(ids[0], ids[1], world, planner)\n elif action_type == 'activate':\n execute_activate(ids[0], world, textures)\n elif action_type == 'deactivate':\n execute_deactivate(ids[0], world, textures)\n elif action_type == 'peel':\n execute_peel(ids[0], ids[1], world, textures)\n elif action_type == 'pour':\n execute_pour(ids[0], ids[1], world, textures)\n elif action_type == 'toast':\n execute_toast(ids[0], ids[1], world, textures)\n else:\n raise 'Invalid action.'\n","sub_path":"rpn/create_dataset/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":9761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"352583624","text":"import torch\nimport math\nimport cv2\n\ndef limitsize(img):\n rate = img.shape[0]/img.shape[1]\n y = img.shape[0]; x = img.shape[1]\n if y > x :\n flag = True\n maxlen = y\n else :\n flag = False\n maxlen = x\n\n if maxlen > 800:\n if flag:\n y = 800;\n x = int(y/rate)\n else :\n x= 800\n y = int(x*rate)\n\n dst = cv2.resize(img, dsize=(x,y), interpolation=cv2.INTER_AREA)\n return dst\n\n\n\ndef expand16_9(ratelen,maxlen,src,dst):\n # main instance가 9비율의 y축 보다 작은경우 넓힌다.\n midlen = int((src+dst)/2);\n len = dst-src;\n if len < ratelen:\n src = midlen - int(ratelen / 2);\n dst = midlen + int(ratelen / 2)\n # 넒히는 범위가 삐져나갈경우,\n if src < 0:\n dst += abs(src);\n src = 0;\n elif dst > maxlen:\n src -= dst - maxlen;\n dst = maxlen;\n\n # main instance가 9비율 y축보다 클 경우 줄인다.\n elif len > ratelen:\n src = max(0, src - int(len / 17))\n dst = src + ratelen;\n\n return src,dst;\n\n\n\ndef rate16_9(img,y_s,y_d,x_s,x_d,ratex=16,ratey=9):\n y_s,y_d,x_s,x_d = int(y_s),int(y_d),int(x_s),int(x_d)\n\n maxy = img.shape[0]-1; maxx = img.shape[1]-1\n maxx_16len = int(maxy*ratex/ratey); maxy_9len = int(maxx*ratey/ratex);\n\n # x축 비율이 짧음\n if maxx_16len > maxx:\n # x축을 풀로 잡고, y축을 맞춤\n x_s= 0; x_d = maxx;\n y_s,y_d = expand16_9(maxy_9len,maxy,y_s,y_d)\n\n # y축 비율이 짧음\n elif maxy_9len > maxy:\n # y축을 풀로 잡고, x축을 맞춤\n y_s = 0; y_d = maxx;\n x_s,x_d = expand16_9(maxx_16len, maxx, x_s, x_d)\n else:\n #이미 16:9비율\n return img;\n\n return fitsize(img,y_s,y_d,x_s,x_d)\n\n\ndef get_weight(outputs,im,print_weight_info_flag = False):\n boxes = outputs[\"instances\"].pred_boxes.tensor\n pred = outputs['instances'].pred_classes\n scores = outputs[\"instances\"].scores\n\n weightlist = []\n midpos = torch.tensor([int(im.shape[0]/2),int(im.shape[1]/2)])\n linsize = im.shape[0] * im.shape[1]\n for i in range(scores.shape[0]):\n\n #중심에서 가까울수록 점수\n instancePos = torch.tensor([ int((boxes[i][3] + boxes[i][1]) / 2), int((boxes[i][2] + boxes[i][0])/2) ]);\n dist = torch.sum((midpos-instancePos) ** 2)\n center = int(linsize/dist+1)\n\n pred_Kind = math.log(pred[i]*2+1)+10\n if pred[i] == 0 : pred_Kind = math.log(pred[i]*2+1)+5\n\n #weight = 박스크기 * 점수^2 / 종류*2+10,,(사람 = 0) * log(center 점수)\n\n box_size = abs(boxes[i][2] - boxes[i][0])*abs(boxes[i][3]-boxes[i][1])\n\n weight = box_size*(scores[i]**1.5)*(math.log(center)+5)/(pred_Kind)\n\n # print weight 정보\n if print_weight_info_flag:\n print(i,\": weight:\",weight, \" boxsize:\",box_size,\"score\",scores[i]**1.5,\"center\",math.log(center)+5,\"pred\",pred_Kind,\"pos:\",instancePos,midpos)\n weightlist.append(int(weight))\n\n if weightlist != []:\n idx = weightlist.index(max(weightlist))\n else : idx = -1\n weightlist = torch.tensor(weightlist)\n return idx, weightlist\n\n#x,y축을 찾아내서 이미지 slice\ndef fitsize(im,y_s,y_d,x_s,x_d):\n y_s,y_d,x_s,x_d = int(y_s),int(y_d),int(x_s),int(x_d)\n return im[y_s:y_d,x_s:x_d]\n\n\n#직선 축이 겹치는지 확인\ndef checklinear(x1,x2,y1,y2):\n #더 앞에 있는 직선을 골라냄.\n if x1 <= y1:\n front = [x1,x2]; back = [y1,y2]\n else:\n front = [y1,y2]; back = [x1,x2]\n\n #더 뒤에 있는 직선의 앞부분이 앞의 직선 끝보다 앞에있다면 둘은 겹침.\n if back[0] < front[1]: return True\n\n return False\n\n#가까운 정도 ( 겹치거나, 이미지의 1/10 만큼 가깝다면 True )큰\ndef closelinear(m1, m2, add1, add2, maxline):\n if checklinear(m1, m2, add1, add2) : return True\n if (m1 > add2 and abs(m1-add2) * 10 < maxline) or (add1 > m2 and abs(add1 - m2)*10 < maxline) : return True\n else: return False\n\n\n#weight가 너무 차이나면 바로 무시슬\n#겹치는 Box크기가 작은 이미지의 1/5만큼 겹치면 return\n# 축 하나가 lab_lin_lr 비율만큼 겹치고, 충분히 가깝다면 1 return\ndef getLapBox(main, add, m_w, a_w, lap_wide_lr=5, lap_lin_lr=0.7):\n #weight가 7배 이상 차이나면 바로 캔슬\n if 7*a_w <= m_w :\n return -1\n\n x_s = max(main[0],add[0]); x_d = min(main[2],add[2])\n y_s = max(main[1],add[1]); y_d = min(main[3],add[3])\n\n if not checklinear(main[0], main[2], add[0], add[2]):\n x_d = 0; x_s=0\n if not checklinear(main[1], main[3], add[1], add[3]):\n y_d = 0; y_s = 0\n\n main_wide = (main[2] - main[0])*(main[3]-main[1])\n add_wide = (add[2] - add[0])*(add[3]-add[1])\n overLab_wide = (x_d - x_s)*(y_d - y_s)\n\n shortY = min(main[3]-main[1],add[3]-add[1])\n shortX = min(main[2]-main[0],add[2]-add[0])\n\n longY = max(main[3] - main[1], add[3] - add[1])\n longX = max(main[2] - main[0], add[2] - add[0])\n\n\n if lap_wide_lr*overLab_wide > min(main_wide, add_wide) :\n return int(overLab_wide)\n elif (y_d-y_s) >= shortY*lap_lin_lr and closelinear(main[0], main[2], add[0], add[2], longX) :\n return 1\n elif (x_d-x_s) >= shortX*lap_lin_lr and closelinear(main[1], main[3], add[1], add[3], longY) :\n return 1\n\n else : return -1\n\n#main을 기준으로 getLapBox기준에 알맞는 instance들의 index를 tensor 형태로 반환\ndef getconInstances(boxes,idx,weightlist,lab_wide_lr=6,lab_lin_lr=0.7):\n BOX_index = []\n for i in range(boxes.shape[0]):\n # print(i,\"번째 시작\")\n if getLapBox(boxes[idx],boxes[i],weightlist[idx],weightlist[i],lab_wide_lr,lab_lin_lr) != -1 :\n BOX_index.append(i)\n BOX_index = torch.tensor(BOX_index)\n return BOX_index\n\n#\ndef edgeSearch(mask_line,flag):\n maskArry = torch.where(mask_line == True)[0]\n if maskArry.size() == torch.Size([0]):\n return -1\n if flag :\n src = maskArry[0]+1\n else : src = maskArry[-1]-1\n return src\n\n\ndef expandMask(masks, size, y_s, y_d, x_s, x_d):\n if size == 0 : return masks;\n mask = masks.clone()\n masktemp = masks.clone()\n y_s,y_d,x_s,x_d = int(y_s),int(y_d),int(x_s),int(x_d)\n for i in range(y_s,y_d):\n leftx = edgeSearch(masktemp[i],True)\n rightx = edgeSearch(masktemp[i],False)\n if leftx == -1 :\n continue\n mleft = max(leftx-size,0)\n mright = min(rightx+size,mask.shape[1])\n mask[i][mleft:leftx] = True #왼쪽으로 쭉\n mask[i][rightx:mright] = True #오른쪽으로 쭉\n\n masktemp = masks.clone()\n for i in range(x_s,x_d):\n upy = edgeSearch(masktemp.T[i],True)\n downy = edgeSearch(masktemp.T[i],False)\n\n if upy == -1 :\n continue\n mup = max(upy-size,0)\n mdown = min(downy+size,mask.shape[0])\n mask.T[i][mup:upy] = True #위로 쭉\n mask.T[i][downy:mdown] = True #아래로 쭉\n\n return mask\n\ndef combinde_img_box(conlist_boxes):\n tmps = torch.min(conlist_boxes.T[0:2], axis=1)\n tmpd = torch.max(conlist_boxes.T[2:], axis=1)\n\n X_S, Y_S = tmps.values\n X_D, Y_D = tmpd.values\n\n return int(Y_S),int(Y_D),int(X_S),int(X_D)\n\ndef combine_img_mask(conlist_masks):\n combineMask = conlist_masks[0].clone()\n conlist_mask_index = torch.where(conlist_masks == True)\n combineMask[conlist_mask_index[1:]] = True\n\n return combineMask\n\ndef rmBg(im,mask,size,y_s,y_d,x_s,x_d):\n rmbgIm = torch.from_numpy(im.copy())\n emask = expandMask(mask,size, y_s, y_d, x_s, x_d)\n ebe = torch.where(emask != True)\n rmbgIm[ebe] = 224\n rmbgIm = rmbgIm.numpy()\n\n return rmbgIm\n","sub_path":"Detectron2-python-code/imageTools/imageTool.py","file_name":"imageTool.py","file_ext":"py","file_size_in_byte":7774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"268318762","text":"n = int(input())\ncounter = 0\ntotal = 0\n\nwhile counter < n:\n deposit = float(input())\n if deposit < 0:\n print('Invalid operation!')\n break\n print(f'Increase: {deposit:.2f}')\n total += deposit\n counter += 1\n\nprint(f'Total: {total:.2f}')","sub_path":"while-loop/account_balance.py","file_name":"account_balance.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"118685246","text":"\nimport json\nimport urllib\nimport logging\n\nfrom .models import Annotation, Queue, Tags\nfrom datetime import datetime\nfrom django.http import JsonResponse, HttpResponse\nfrom django.shortcuts import redirect, render\nfrom django.core.paginator import Paginator\n\n# Create your views here.\n\n# 主入口\ndef index(request):\n hints = get_hints()\n return render(request, 'search.html', hints)\n\n# Updae dropdown options\ndef update_opts(request):\n hints = get_hints(list(request.POST.items()))\n return JsonResponse(hints, safe=False)\n\n# Show available options in dropdown list\ndef get_hints(cond=None):\n # Apply condition if given\n objects = Annotation.objects.all();\n if cond:\n objects = select(objects, cond)\n\n scenes = objects.values('project_scene').distinct()\n scenes = [x['project_scene'] for x in scenes]\n scenes.insert(0, '*')\n projects = objects.values('project').distinct()\n projects = [x['project'] for x in projects]\n projects.insert(0, '*')\n types = objects.values('project_type').distinct()\n types = [x['project_type'] for x in types]\n types.insert(0, '*')\n # annotation 表中 tags 存储为 int[],需要从 Tags 表中取出 int 对应的 tag_en 提高可读性\n # tags = [i['tag_en'] for i in Tags.objects.filter(\n # tag_id__in=rows.tags).values('tag_en') if i['tag_en'] != 'default'] \n tag_distinct = set()\n for tag_lst in [x['tags'] for x in objects.values('tags').distinct()]:\n for tag in tag_lst:\n tag_distinct.add(tag)\n tag_distinct = [i['tag_en'] for i in Tags.objects.filter(\n tag_id__in=tag_distinct).values('tag_en') if i['tag_en'] != 'default'] \n tag_distinct.sort()\n tag_distinct.insert(0, '*')\n earliest = objects.earliest('time_add').time_add.strftime(\"%m/%d/%Y\")\n latest = objects.latest('time_add').time_add.strftime(\"%m/%d/%Y\")\n\n return {'scenes':scenes, 'projects':projects, 'types':types, 'tags':tag_distinct, 'from':earliest, 'to': latest}\n\n# Select entries with condition\ndef select(data, cond):\n\n for k, v in cond:\n if not v or v == '*':\n continue\n if k == 'scene': \n data = data.filter(project_scene=v) \n elif k == 'project':\n data = data.filter(project=v)\n elif k == 'type':\n data = data.filter(project_type=v)\n elif k == 'daterange': # 在时间范围内搜索(包括前后时间)\n earlier = v.split('-')[0].strip()\n later = v.split('-')[1].strip()\n data = data.filter(\n time_add__gte=datetime.strptime(earlier, '%m/%d/%Y')).filter(\n time_add__lte=datetime.strptime(later, '%m/%d/%Y'))\n elif k == 'tags': # 逗号分隔的 tag_en 必须要存在于 Tags 表中\n tags_en = json.loads(v)\n tags_num = [Tags.objects.filter(tag_en=tag).values('tag_id')[0]['tag_id'] for tag in tags_en]\n data = data.filter(tags__contains=tags_num)\n else:\n print(f\"INFO: Undefined parameter: {k}, value: {v}\")\n continue\n return data\n\n# 主类 用于request处理函数之间互用缓存 ps: 在这里没有问题,download 使用类做缓存就会报错,暂时无解\nclass Query():\n def __init__(self):\n self.cache = Annotation.objects.all() # 缓存\n self.q = '' # 查询条件缓存\n self.req = []\n\n # 搜索条件过滤以及查找\n def search(self, request):\n CACHE = self.cache\n search_dict = {}\n q = request.POST['q']\n if q != '':\n query = q.split(' ')\n query = list(\n map(lambda x: {x.split(':')[0].strip(): x.split(\":\")[1].strip()}, query)) # 以冒号分隔关键词和 value,并存入 search_dict\n for b in query:\n search_dict.update(b) \n else:\n return redirect('/search')\n for k, v in search_dict.items(): # 根据关键词搜索\n if k == 'scene': \n CACHE = CACHE.filter(project_scene=v) \n elif k == 'project':\n CACHE = CACHE.filter(project=v)\n elif k == 'type':\n CACHE = CACHE.filter(project_type=v)\n elif k == 'time': # time 形如 2019-08-01\n CACHE = CACHE.filter(\n time_add__date=datetime.strptime(v, '%Y-%m-%d'))\n elif k == 'time_year': # 只搜索年份\n CACHE = CACHE.filter(\n time_add__year=v)\n elif k == 'time_and_after': # 搜索当前时间后(包括当前时间)\n CACHE = CACHE.filter(\n time_add__gte=datetime.strptime(v, '%Y-%m-%d'))\n elif k == 'time_after': # 搜索当前时间前(不包括当前时间)\n CACHE = CACHE.filter(\n time_add__gt=datetime.strptime(v, '%Y-%m-%d'))\n elif k == 'time_and_before': # 同上\n CACHE = CACHE.filter(\n time_add__lte=datetime.strptime(v, '%Y-%m-%d'))\n elif k == 'time_before': # 同上\n CACHE = CACHE.filter(\n time_add__lt=datetime.strptime(v, '%Y-%m-%d'))\n elif k == 'tags': # 逗号分隔的 tag_en 必须要存在于 Tags 表中\n t = v.split(',')\n ids = [i.id for i in Tags.objects.filter(tag_en=k) if k in t]\n CACHE = CACHE.filter(tags__contains=list(ids)) \n else:\n return redirect('/search')\n self.cache = CACHE\n q_encode = urllib.parse.urlencode({'q': q}) # 解码搜索条件,方便之后发送文本格式的邮件\n self.q = q_encode\n return redirect(f'/search/show') # 跳转结果展示页面\n\n # 展示查询结果(分页)\n def search_with_cond(self, request):\n CACHE = Annotation.objects.all()\n req_lst = list(request.POST.items())\n self.req = ' '.join([f\"{req[0]}:{req[1]}\" for req in req_lst][1:])\n self.cache = select(CACHE, req_lst)\n return redirect(f'/search/show_page?page=1')\n\n # 展示查询结果(分页)\n def show_res(self, request):\n CACHE = self.cache\n res = CACHE.filter(ano_type='pascal_voc').order_by('id') # 取出搜索结果\n pag = Paginator(res, 10) # 分页展示,每页取10个结果,可调整\n page = request.GET.get('page')\n data = pag.get_page(page) # 获取每一页的结果\n context = {'total': res.count(), 'data': data} \n return render(request, 'show_search_res.html', context)\n\n # 按页展示查询结果\n # data field example: [{}, {}, {}]\n def show_page(self, request):\n CACHE = self.cache\n res = CACHE.filter(ano_type='pascal_voc').order_by('id') # 取出��索结果\n n_res = res.count()\n pag = Paginator(res, 10) # 分页展示,每页取10个结果,可调整\n page = request.GET.get('page')\n # Construct data field\n if int(page) > pag.num_pages:\n page = pag.num_pages\n data = pag.get_page(page) # 获取每一页的结果\n data = self.page_to_dict(data)\n context = {'total': n_res, 'data': data, 'page': page}\n return JsonResponse(context, safe=False)\n\n # 将pagenator数据转化为dict\n def page_to_dict(self, data):\n # Construct data field if there's data\n if len(data) == 0:\n return {}\n fields = [f.name for f in data[0]._meta.fields]\n data_l = []\n for row in range(min(10, len(data))):\n row_d = {}\n for attr in fields:\n row_d[attr] = getattr(data[row], attr)\n data_l.append(row_d)\n return data_l\n\n # 跳转打包路径\n def red_download(self, request):\n if self.q:\n q = self.q\n CACHE = self.cache\n caches = CACHE.filter(ano_type='pascal_voc') # 限制打包的标注格式只能式pascal_voc\n ids = [str(i.id) for i in caches] # 取出待打包的 id 列表\n Queue.objects.create(mail=request.GET['mail'], task_list=list(ids)) # 把 id 列表存入队列\n\n return redirect(f'/download?mail={request.GET[\"mail\"]}&{q}')\n else:\n print('q is null')\n\n # 下载\n def dl(self, request):\n if self.req:\n mail = request.POST.get('mail')\n unchecked = request.POST.get('unchecked')\n CACHE = self.cache\n # CACHE = CACHE.filter(ano_type='pascal_voc') # 限制打包的标注格式只能式pascal_voc\n ids = [str(i.id) for i in CACHE]\n ids = list(set(ids) - set(unchecked))\n Queue.objects.create(mail=mail, task_list=ids) # 把 id 列表存入队列\n req_dict = \"req=\"+self.req\n return redirect(f'/download?mail={mail}&{req_dict}')\n else:\n return HttpResponse(content='To use the download function, you must make a search query first!', status=400)\n \n","sub_path":"src/Search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"424638802","text":"''' \n LRU\n\n Copyright (C) 2011 Richard Marshall\n This software may be used and distributed according to the terms of the \n Apache 2.0 Licence.\n http://www.apache.org/licenses/LICENSE-2.0.html\n'''\n\n\nimport threading\nfrom apiframework.limiteddict import LimitedDict\n\nclass LRU(LimitedDict):\n ''' Adds LRU mechanics to OrderedDict.\n WARNING: Not all thread unsafe operations have been wrapped!\n '''\n\n def __init__(self, maxsize=100, *args, **kwargs):\n ''' Setup maxsize and threading lock '''\n self.lock = threading.RLock()\n self.refresh_lock = threading.Lock()\n super(LRU, self).__init__(*args, **kwargs)\n self.maxsize = maxsize\n \n def clear(self):\n ''' Thread \"safe\" clear '''\n with self.lock:\n self.clear()\n\n def refresh(self, key):\n ''' Move a key to the beginning of the LRU '''\n if self.refresh_lock.acquire(0):\n try:\n val = super(LRU, self).__getitem__(key)\n del self[key]\n super(LRU, self).__setitem__(key, val)\n finally:\n self.refresh_lock.release()\n\n def __getitem__(self, key):\n ''' Get item and update placement in cache '''\n with self.lock:\n try:\n result = super(LRU, self).__getitem__(key)\n self.refresh(key)\n return result\n except KeyError:\n raise\n\n def __setitem__(self, key, value):\n ''' Set item and pop out old items if needed '''\n with self.lock:\n super(LRU, self).__setitem__(key, value)\n \n","sub_path":"apiframework/lru.py","file_name":"lru.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"257474411","text":"\"\"\"\n If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these\n multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number\n passed in.\n\n Note: If the number is a multiple of both 3 and 5, only count it once. Also, if a number is negative, return 0(for\n languages that do have them)\n\n\"\"\"\n\n\ndef solution(number):\n count = 0\n\n for num in range(number):\n if not num % 5 or not num % 3:\n count = count + num\n\n print(count)\n\n\nsolution(10)","sub_path":"python_code/kata1.py","file_name":"kata1.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"416087415","text":"import os\nimport sys\nimport copy\nfrom abc import abstractmethod, ABCMeta\n\nfile_path_dir = os.path.abspath('.')\nif file_path_dir not in sys.path:\n sys.path.append(file_path_dir)\n\nfrom generator.physical_network import PhysicalNetwork\n\n\nclass Environment(metaclass=ABCMeta):\n def __init__(self):\n super(Environment, self).__init__()\n # physical network\n self.pn = PhysicalNetwork()\n self.pn_backup = copy.deepcopy(self.pn)\n # record\n self.total_revenue = 0\n self.total_cost = 0\n self.success = 0\n self.inservice = 0\n\n def reset(self):\n \"\"\"reset the environment\"\"\"\n self.pn = PhysicalNetwork()\n self.pn_backup = copy.deepcopy(self.pn)\n self.total_revenue = 0\n self.total_cost = 0\n self.success = 0\n self.inservice = 0\n return True\n\n def ready(self):\n \"\"\"ready to embace a new sfc\"\"\"\n self.pn_backup = copy.deepcopy(self.pn)\n\n @abstractmethod\n def step(self, vn):\n \"\"\"Agent interacts with Environment\n \n An abstract method which must be implemented\n\n Exmple:\n SUCCESS:\n self.pn_backup = copy.deepcopy(self.pn)\n self.inservice += 1\n self.success += 1\n self.total_revenue += vn.revenue\n self.total_cost += vn.cost\n FAILURE:\n self.pn = copy.deepcopy(self.pn_backup)\n return False\n \"\"\"\n pass\n \n def release_resources(self, vn):\n \"\"\"release its resources when a vn leaves \"\"\"\n if len(vn.slots) == 0:\n return True\n for vid, pid in vn.slots.items():\n self.pn.update_node(pid, 'cpu_free', vn.cpu_data[vid])\n self.pn.update_node(pid, 'ram_free', vn.ram_data[vid])\n self.pn.update_node(pid, 'rom_free', vn.rom_data[vid])\n for eid, path in vn.paths.items():\n if len(path)==1:\n continue\n bw_req = vn.graph.edges[eid]['bw']\n self.pn.update_bw_with_path(path, bw_req) # (path, bw_req)\n self.pn_backup = copy.deepcopy(self.pn)\n self.inservice -= 1\n return True\n\n\nif __name__ == '__main__':\n pass\n \n\n","sub_path":"generator/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"638440349","text":"from config import *\nimport state\nimport globals\nimport pygame\n\nbgtile = pygame.Surface((TWIDTH, THEIGHT))\nbgtile.fill((0, 0, 0, 0))\n\nclass GameObject(pygame.sprite.Sprite):\n def __init__(self, x, y):\n pygame.sprite.Sprite.__init__(self)\n self.x = x\n self.y = y\n self.image = \"\"\n self.load_picture()\n self.rect = self.image.get_rect()\n self.rect.topleft = (self.x*TWIDTH, self.y*THEIGHT)\n self.triggers = []\n self.triggered = []\n self.t = \"NONE\"\n self.drawn = False\n self.moving_dir = (0, 0)\n self.saved_pos = (0, 0)\n\n self.to_blit = []\n\n def collide_with(self, go):\n return True\n\n def collided_by(self, go):\n return True\n\n def load_picture(self):\n self.image = pygame.image.load(self.pp)\n self.image = pygame.transform.scale(self.image, (TWIDTH, THEIGHT))\n\n def render(self):\n x = (self.x - state.view_center[0] + (WIDTH / 2))*TWIDTH\n y = (self.y - state.view_center[1] + (HEIGHT / 2))*THEIGHT\n if not (x == self.saved_pos[0] and y == self.saved_pos[1]):\n globals.scr.blit(bgtile, self.saved_pos)\n globals.scr.blit(self.image, (x, y))\n self.saved_pos = (x, y)\n self.drawn = True\n \n def delete(self):\n globals.scr.blit(bgtile, self.saved_pos)\n drawn = False\n\n def destroy(self):\n global golist\n newlist = list()\n\n # handle self.on_destroy trigger here\n pass\n\n self.delete()\n for go in state.gos:\n if go != self:\n newlist.append(go)\n state.gos = newlist\n \n def move(self, x, y):\n self.moving_dir = (x, y)\n leaving = None\n passable = True\n for go in state.gos:\n if (go.x == self.x + x) and (go.y == self.y + y):\n ccheck_a = self.collide_with(go)\n ccheck_b = go.collided_by(self)\n passable = ccheck_a and ccheck_b\n if passable:\n # handle go.on_enter trigger here\n pass\n elif (go.x == self.x) and (go.y == self.y):\n leaving = go\n\n if passable:\n if leaving:\n # handle leaving.on_leave trigger here\n pass\n self.to_blit.append((bgtile, (self.x, self.y)))\n self.x += x\n self.y += y\n\n if isinstance(self, GOPlayer):\n state.current_moves += 1\n return True\n return False\n\nclass GOPlayer(GameObject):\n def __init__(self, x, y):\n self.pp = \"gos/player.png\"\n GameObject.__init__(self, x, y)\n\nclass GOWall(GameObject):\n def __init__(self, x, y):\n self.pp = \"gos/wall.png\"\n GameObject.__init__(self, x, y)\n\n def collided_by(self, go):\n return False\n\nclass GOBoulder(GameObject):\n def __init__(self, x, y):\n self.pp = \"gos/boulder.png\"\n GameObject.__init__(self, x, y)\n\n def collided_by(self, go):\n if isinstance(go, GOPlayer):\n if self.move(go.moving_dir[0], go.moving_dir[1]):\n return True\n return False\n\nclass GOFinish(GameObject):\n def __init__(self, x, y):\n self.pp = \"gos/finish.png\"\n GameObject.__init__(self, x, y)\n\n def collided_by(self, go):\n if isinstance(go, GOPlayer):\n state.finished = 1\n return True\n return False\n\nclass GOKey(GameObject):\n def __init__(self, x, y):\n self.pp = \"gos/key.png\"\n GameObject.__init__(self, x, y)\n\n def collided_by(self, go):\n if isinstance(go, GOPlayer):\n globals.sound_channel.play(globals.snd_obtained_key)\n state.keys += 1\n self.destroy()\n return True\n return False\n\nclass GODoor(GameObject):\n def __init__(self, x, y):\n self.pp = \"gos/door.png\"\n GameObject.__init__(self, x, y)\n\n def collided_by(self, go):\n if isinstance(go, GOPlayer):\n if state.keys > 0:\n globals.sound_channel.play(globals.snd_open_door)\n state.keys -= 1\n self.destroy()\n return True\n return False\n\nclass GOLightBonus(GameObject):\n def __init__(self, x, y):\n self.pp = \"gos/light_bonus.png\"\n GameObject.__init__(self, x, y)\n\n def collided_by(self, go):\n if isinstance(go, GOPlayer):\n state.lradius += 6\n self.destroy()\n return True\n\nclass GOWarpA(GameObject):\n def __init__(self, x, y):\n self.pp = \"gos/warp_a.png\"\n GameObject.__init__(self, x, y)\n\n def collided_by(self, go):\n if isinstance(go, GOPlayer):\n for g in state.gos:\n if isinstance(g, GOWarpB):\n state.player.x = g.x\n state.player.y = g.y\n break\n return False\n\nclass GOWarpB(GameObject):\n def __init__(self, x, y):\n self.pp = \"gos/warp_b.png\"\n GameObject.__init__(self, x, y)\n\n def collided_by(self, go):\n if isinstance(go, GOPlayer):\n for g in state.gos:\n if isinstance(g, GOWarpA):\n state.player.x = g.x\n state.player.y = g.y\n break\n return False\n","sub_path":"gameobject.py","file_name":"gameobject.py","file_ext":"py","file_size_in_byte":5338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"252343293","text":"#!/usr/bin/env python3\n\n''' trigrams '''\nimport string\nimport random\n\nfile_name = 'sherlock.txt'\nwith open (file_name) as f_handle:\n# find the real content we need from the file\n line_useful = ''\n bool_flag = False\n while True:\n line = f_handle.readline()\n bool_flag = bool_flag or (line == 'To Sherlock Holmes she is always THE woman. I have seldom heard\\n')\n if bool_flag:\n line_useful += line\n if line == 'Walsall, where I believe that she has met with considerable success.\\n':\n break\n\n# deltet the punctuation\n\ntable = str.maketrans(dict.fromkeys(list(string.punctuation)))\nline_useful = line_useful.strip().translate(table)\n\nwords = line_useful.split()\ndatas = {}\nfor i in range(len(words)-2):\n key = (words[i], words[i+1])\n datas.setdefault(key,[]).append(words[i+2])\n\ndef new_text():\n k1 = input('Enter the first word>>')\n k2 = input('Enter the second word>>')\n k = (k1,k2)\n new = ''\n while True:\n if k in datas:\n new_word = str(random.choice(datas.get(k)))\n new += ' ' + new_word\n k = (k[1],new_word)\n else:\n break\n return new\n","sub_path":"students/Ruohan/lesson04/kata.py","file_name":"kata.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"323394712","text":"\"\"\"\nTests scikit-onehotencoder converter.\n\"\"\"\nimport unittest\nfrom sklearn.preprocessing import OneHotEncoder\nfrom onnxmltools import convert_sklearn\nfrom onnxmltools.convert.common.data_types import FloatTensorType, Int64TensorType\n\nclass TestSklearnOneHotEncoderConverter(unittest.TestCase):\n\n def test_model_one_hot_encoder(self):\n model = OneHotEncoder()\n model.fit([[1, 2, 3], [4, 3, 0], [0, 1, 4], [0, 5, 6]])\n model_onnx = convert_sklearn(model, 'scikit-learn one-hot encoder', [('input', Int64TensorType([1, 3]))])\n self.assertTrue(model_onnx is not None)\n\n def test_one_hot_encoder_mixed_float_int(self):\n model = OneHotEncoder()\n model.fit([[0.4, 0.2, 3], [1.4, 1.2, 0], [0.2, 2.2, 1]])\n model_onnx = convert_sklearn(model, 'one-hot encoder mixed-type inputs',\n [('input1', FloatTensorType([1, 2])), ('input2', Int64TensorType([1, 1]))])\n self.assertTrue(model_onnx is not None)\n","sub_path":"tests/sklearn/test_OneHotEncoderConverter.py","file_name":"test_OneHotEncoderConverter.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"221029145","text":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# 랜덤시드 고정시키기\nnp.random.seed(3)\n\n# 1. 데이터 생성하기\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n rotation_range=10,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.7,\n zoom_range=[0.9, 2.2],\n horizontal_flip=True,\n vertical_flip=True,\n fill_mode='nearest')\ntrain_generator = train_datagen.flow_from_directory(\n 'yagun',\n target_size=(224, 224),\n batch_size=3,\n class_mode='categorical')\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_datagen.flow_from_directory(\n 'yagun2',\n target_size=(224, 224),\n batch_size=3,\n class_mode='categorical')\nprint (\"debug3\")\n# 2. 모델 구성하기\ndef makeModel():\n model=Sequential()\n model.add(Conv2D(16, kernel_size=(3, 3),\n activation='relu',\n input_shape=(224, 224, 3)))\n model.add(MaxPooling2D(pool_size=(3, 3)))\n model.add(Conv2D(32, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(3, 3)))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(3, 3)))\n model.add(Flatten())\n model.add(Dense(1048, activation='relu'))\n model.add(Dense(4, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\nmodel=makeModel()\nprint(\"debug4\")\n# 3. 모델 학습과정 설정하기\nprint (\"debug2\")\n# 4. 모델 학습시키기\nhist=model.fit_generator(\n train_generator,\n steps_per_epoch=1500,\n epochs=3,\n validation_data=test_generator,\n validation_steps=8)\n\n# 5. 모델 평가하기\nprint(\"-- Evaluate --\")\nscores = model.evaluate_generator(test_generator, steps=5)\nprint(\"%s: %.2f%%\" %(model.metrics_names[1], scores[1]*100))\n\n\n\n\nmodel_json = model.to_json()\nwith open(\"m.json\", \"w\") as json_file:\n json_file.write(model_json)\n model.save_weights('wallModelWeight.h5')\n\n\n# 6. 모델 사용하기\nprint(\"-- Predict --\")\noutput = model.predict_generator(test_generator, steps=2)\nnp.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)})\nprint(test_generator.class_indices)\nprint(output)\n\nimport matplotlib.pyplot as plt\nprint (\"debug1\")\nfig, loss_ax = plt.subplots()\n\nacc_ax = loss_ax.twinx()\n\nloss_ax.plot(hist.history['loss'], 'y', label='train loss')\nloss_ax.plot(hist.history['val_loss'], 'r', label='val loss')\n\nacc_ax.plot(hist.history['acc'], 'b', label='train acc')\nacc_ax.plot(hist.history['val_acc'], 'g', label='val acc')\n\nloss_ax.set_xlabel('epoch')\nloss_ax.set_ylabel('loss')\nacc_ax.set_ylabel('accuray')\n\nloss_ax.legend(loc='upper left')\nacc_ax.legend(loc='lower left')\n\nplt.show()\n","sub_path":"MakeModel.py","file_name":"MakeModel.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"340825726","text":"import sys\nimport atexit\nfrom zmq import PULL\nfrom django.core.management.base import BaseCommand\nfrom ...models import Task\nfrom ...conf import settings, get_logger\nfrom ...context import shared_context as context\n\n\nclass Command(BaseCommand):\n\n args = 'NAME'\n help = (\n 'Start a worker instance.\\n\\n'\n 'NAME is the name of the worker, which is necessary to differentiate \\n'\n 'correctly between them.\\n\\n'\n 'Example: manage.py workerd worker1'\n )\n\n def handle(self, *args, **options): # pylint: disable=W0613\n if len(args) < 1:\n sys.stderr.write(\n \"You must specify a name for this worker! See '%s -h'\\n\" % (\n \" \".join(sys.argv[:2]),\n )\n )\n sys.stderr.flush()\n sys.exit(-1)\n try:\n name = args[0]\n logger = get_logger(name)\n logger.info(\n \"Worker listening on %s.\" % (settings.ZTASK_WORKER_URL,))\n socket = context.socket(PULL)\n def _shutdown():\n logger.debug('Shutting down nicely')\n socket.close()\n atexit.register(_shutdown)\n socket.connect(settings.ZTASK_WORKER_URL)\n while True:\n task_id, = socket.recv_pyobj()\n logger.info('Worker received task (%s)' % (str(task_id),))\n task = Task.objects.get(pk=task_id)\n task.run(logger)\n except KeyboardInterrupt:\n raise sys.exit(0)\n","sub_path":"django_ztaskq/management/commands/workerd.py","file_name":"workerd.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"328935004","text":"import graphene\nfrom graphene_django_extras import DjangoObjectType, DjangoObjectField, DjangoFilterListField\nfrom django.contrib.auth.models import Group\n\nfrom apps.utils import STRING_FILTERS, NUM_FILTERS\nfrom .models import Rank, Role, Certification, Division, DiscordRoleConfig\n\n\nclass DiscordRoleConfigType(DjangoObjectType):\n class Meta:\n model = DiscordRoleConfig\n\n\nclass RankType(DjangoObjectType):\n class Meta:\n model = Rank\n filter_fields = {\n 'name': STRING_FILTERS,\n 'order': NUM_FILTERS,\n 'discord_role_configs__enabled': ['exact'],\n }\n\n\nclass CertificationType(DjangoObjectType):\n class Meta:\n model = Certification\n filter_fields = {\n 'title': STRING_FILTERS,\n 'prerequisites__title': STRING_FILTERS,\n 'prerequisites__id': NUM_FILTERS,\n 'division__name': STRING_FILTERS,\n 'discord_role_configs__enabled': ['exact'],\n }\n\n @staticmethod\n def resolve_icon(instance, info, **kwargs):\n if instance.icon:\n return info.context.build_absolute_uri(instance.icon.url)\n return ''\n\n\nclass RoleType(DjangoObjectType):\n division = graphene.Field('apps.sc.org.schema.DivisionType')\n display = graphene.String()\n\n class Meta:\n model = Role\n\n filter_fields = {\n 'title': STRING_FILTERS,\n 'division': ['isnull'],\n 'division__name': STRING_FILTERS,\n 'division__id': NUM_FILTERS,\n 'discord_role_configs__enabled': ['exact'],\n }\n\n @staticmethod\n def resolve_display(instance, info, **kwargs):\n return str(instance)\n\n\nclass DivisionType(DjangoObjectType):\n certifications = DjangoFilterListField(CertificationType)\n roles = DjangoFilterListField(RoleType)\n\n class Meta:\n model = Division\n\n exclude_fields = [\n # Not sure why these shows up, but this hides it\n 'user',\n 'certification'\n ]\n\n filter_fields = {\n 'name': STRING_FILTERS,\n 'discord_role_configs__enabled': ['exact'],\n }\n\n\nclass Query(object):\n rank = DjangoObjectField(RankType)\n ranks = DjangoFilterListField(RankType)\n\n role = DjangoObjectField(RoleType)\n roles = DjangoFilterListField(RoleType)\n\n division = DjangoObjectField(DivisionType)\n divisions = DjangoFilterListField(DivisionType)\n\n certification = DjangoObjectField(CertificationType)\n certifications = DjangoFilterListField(CertificationType)\n\n","sub_path":"backend/apps/sc/org/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"111701083","text":"#!/usr/bin/python\n\n# Uses 'fractions' module to perform fraction calculations\nfrom fractions import Fraction\n\n# Validates user input based on specified 'type', 'min' and 'max' values, or 'range'\n#\n# Examples: number = validate.input_validation(\"Please enter a number between 1 and 10: \", int, 1, 10) yesno = validate.input_validation(\"Would you like to try again (y/n)? \", str.lower, ('y', 'n'))\nimport validate\n\n\n# Dictionaries for storing denominator and numerator values\ndenominators = {}\nnumerators = {}\n\n# Maximum values for numerators, denominators, and number of fractions\nmax_numerator_value = 1000000\nmax_denominator_value = 1000000\nmax_fractions = 1000000\n\n# Performs the specified operation on numerators and denominators arrays\ndef perform_operation(operation):\n if operation == '+':\n counter = 1\n result = Fraction(numerators[str(counter)], denominators[str(counter)])\n while counter < number_of_fractions:\n result = Fraction(result) + Fraction(numerators[str(counter + 1)], denominators[str(counter + 1)])\n counter = counter + 1\n return result\n\n elif operation == '-':\n counter = 1\n result = Fraction(numerators[str(counter)], denominators[str(counter)])\n while counter < number_of_fractions:\n result = Fraction(result) - Fraction(numerators[str(counter + 1)], denominators[str(counter + 1)])\n counter = counter + 1\n return result\n\n elif operation == '*':\n counter = 1\n result = Fraction(numerators[str(counter)], denominators[str(counter)])\n while counter < number_of_fractions:\n result = Fraction(result) * Fraction(numerators[str(counter + 1)], denominators[str(counter + 1)])\n counter = counter + 1\n return result\n\n elif operation == '/':\n counter = 1\n result = Fraction(numerators[str(counter)], denominators[str(counter)])\n while counter < number_of_fractions:\n result = Fraction(result) / Fraction(numerators[str(counter + 1)], denominators[str(counter + 1)])\n counter = counter + 1\n return result\n\n# Populates numerators and denominators arrays by calling 'request_numerator' and 'request_denominator' functions\ndef populate_fractions(fractions):\n counter = 1\n while counter < (fractions + 1):\n numerators[str(counter)] = request_numerator(counter)\n denominators[str(counter)] = request_denominator(counter)\n counter = counter + 1\n\n# Requests total number of fractions to work with\ndef request_fractions():\n print()\n fractions = validate.input_validation(\"Enter the number of fractions would you like to work with: \", int, 1, max_fractions)\n print()\n confirm = validate.input_validation(\"Thank you. Just to confirm, you would like to work with %s fractions (y/n)? \" % (str(fractions)), str.lower, range_ = ('y', 'n'))\n if confirm == 'y':\n return fractions\n else:\n request_fractions()\n\n# Requests value for a numerator\ndef request_numerator(current_numerator):\n print()\n numerator = validate.input_validation(\"Enter the value for numerator number %s :\" % (current_numerator), int, 1, max_numerator_value)\n return numerator\n\n# Requests value for a denominator\ndef request_denominator(current_denominator):\n print()\n denominator = validate.input_validation(\"Enter the value for denominator number %s :\" % (current_denominator), int, 1, max_denominator_value)\n return denominator\n\n# Requests the type of operation to be performed\ndef request_operation():\n print()\n operation = validate.input_validation(\"Input the type of operation you would like to perform (+-*/): \", str, range_ = ('+', '-', '*', '/'))\n return operation\n\n# Asks user if they would like to perform another operation\ndef another_operation():\n print()\n again = validate.input_validation(\"Would you like to perform another calculation (y/n)? \", str.lower, range_ = ('y', 'n'))\n return again\n\n# Program code: 0 - Welcome message 1 - Request number of fractions and create arrays 2 - Request values and populate arrays 3 - Request and perform operation 4 - Return result 5 - Return to step 1 or break 0 - Welcome message\nprint()\nprint(\"Welcome to Fraction Calculator v1.0\")\n\nwhile True:\n # 1 - Requests number of fractions and arrays\n number_of_fractions = request_fractions()\n # 2 - Request values and populate arrays\n populate_fractions(number_of_fractions)\n # 3 - Request and perform operation, then returns result\n result = perform_operation(request_operation())\n # 4 - Return result\n print()\n print(\"The result of your input is: \")\n print()\n print(result)\n # 5 - Return to step 1 or break\n again = another_operation()\n if again == 'y':\n continue\n else:\n print()\n break\n","sub_path":"numbers/01-fractions.py","file_name":"01-fractions.py","file_ext":"py","file_size_in_byte":4828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"521314731","text":"#== mimiced from JKJ vid 2018_12_05 by tt ===\nclass Inkay:\n def __init__(self, whob_name):\n self.name=whob_name\n def get_whob_name(self):\n return self.name\nyoub=Inkay(\"SayWhat\")\nprint (\"who be me\", youb.get_whob_name())\n \n \nclass CurrentAccount:\n def __init__(self, customer_name):\n self.name=customer_name\n def get_customer_name(self):\n return self.name\nchevrolet_car=CurrentAccount(\"Django_Jingo\")\nprint(\"automobile\", chevrolet_car.get_customer_name())\naccount_holder=CurrentAccount(\"Ringo_Bingo\")\nprint(\"customer\", account_holder.get_customer_name())\naccount_holder=CurrentAccount(\"Obligato_Delgatto\")\nprint(\"hello world\", account_holder.get_customer_name())\naccount_holder=CurrentAccount(\"Alien Creature\")\nprint(\"OuterSpace\", account_holder.get_customer_name())\nx2=CurrentAccount(\"SlimeDog\")\nprint(\"Barks out Loud\", x2.get_customer_name())\n\n","sub_path":"jkj2018_12_05.py","file_name":"jkj2018_12_05.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"537061619","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# open files\ntrainFile = open('hw2p2r.txt', 'r')\ntestFile = open('hw2p2t.txt', 'r')\n\n# load to fields\ntrainData = np.array(np.loadtxt(trainFile))\ntestData = np.array(np.loadtxt(testFile))\n\n\nw = []#[[0] for i in range(1, 5+1)]\nerror = np.array([])\n\nfor i in range(5):\n # use polyfit (the result is high power first)\n w.append([])\n w[i].append(np.polyfit(trainData[:, 0], trainData[:, 1], i+1))\n\n # calculate the error\n error.append([])\n\n err = []\n for j in trainData[:, 0]:\n err.append( (j - np.polyval(w[i], j))**2 )\n\n error[i].append(err)\n print(error[i].shape)\n # plot mse\n plt.figure(i+1)\n #plt.plot(trainData[:, 0], error[i])\n plt.show()\n#for i in range(1, 5+1):\n #plt.plot(trainData[:, 0], (trainData[:, 1] - )**2)\n\n\n#print(testData)","sub_path":"Assignment/hw02/HW2_2/HW2_2.py","file_name":"HW2_2.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"191129201","text":"import pygame\nimport math\nfrom Engine.geometry import Vec2d\nfrom Game.Character import YTGBasePlayer\nfrom Engine.character import WeaponInv\nfrom Objects.MechPlayer import Creature as Body\nfrom Components.LegsPlayer import Engine as Legs\nfrom Engine.config import ROLE\n# from Weapons.plasma_repeater import Weapon as DefaultW\n# from Weapons.pulson import Weapon as Pulson\nfrom Weapons.net_cannon import Weapon as Net\nfrom Weapons.mini_launcher import Weapon as Launcher\n\n\nclass Character(YTGBasePlayer, Body):\n\n def pregenerate(self):\n self.max_health = 500\n self.health = self.max_health\n self.w_inv = WeaponInv(self, gui=self.gui.inventory if self.gui else None)\n l = Legs()\n l.max_vel = 400\n l.add(*self.groups())\n self.mount(l, key='engine')\n # for _ in range(2):\n # self.w_inv.add(DefaultW())\n # for _ in range(2):\n # self.w_inv.add(Pulson())\n self.w_inv.add(Net())\n self.w_inv.add(Launcher())\n\n def update(self):\n add = self.step_time * self.max_health * .001 / 1000\n if self.health + add <= self.max_health:\n self.health += add\n\n def effect(self, obj, arbiter, first=True):\n if obj.is_own_body() and obj.role == ROLE.WEAPON:\n self.w_inv.add(obj)\n\n def send_event(self, event):\n super().send_event(event)\n if event.type == pygame.KEYDOWN and event.key == pygame.K_j:\n ind = self.w_inv.index\n for n in range(len(self.w_inv[ind])):\n w = self.w_inv.drop(ind)\n ang = math.radians(self.angle)\n vector = Vec2d(math.cos(ang), math.sin(ang))\n mv = 1000000 / w.mass\n vel = w.velocity_for_distance((self.level.mouse_world - self.position).length)\n if vel > mv:\n vel = mv\n w.position += vector * 75\n w.velocity = vector * vel\n","sub_path":"Characters/player_survival.py","file_name":"player_survival.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"651062393","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 14 11:02:42 2016\n\n@author: manasmudbari\n\"\"\"\n\nimport quandl\nimport pandas as pd\nimport pickle\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('fivethirtyeight')\n\n\ndef state_list():\n fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')\n return fiddy_states[0][0][1:]\n \ndef grab_initial_state_data():\n states = state_list()\n main_df = pd.DataFrame()\n \n for abbv in states:\n #print(abbv)\n query = \"FMAC/HPI_\"+str(abbv)\n df = quandl.get(query, authtoken=\"Auth_key_here\")\n df.rename(columns={'Value':str(abbv)}, inplace=True)\n df[abbv] = (df[abbv]-df[abbv][0])/df[abbv][0]*100.0\n if main_df.empty:\n main_df = df\n else:\n main_df = main_df.join(df)\n \n print(main_df.head())\n \n pickle_out = open('fiddy_states3.pickle','wb')\n pickle.dump(main_df, pickle_out)\n pickle_out.close()\n \ndef HPI_Benchmark():\n df = quandl.get(\"FMAC/HPI_USA\", authtoken=\"Auth_key_here\")\n df[\"Value\"] = (df[\"Value\"] - df[\"Value\"][0])/df[\"Value\"][0]*100.0\n return df \n \n#fig = plt.figure()\n#ax1 = plt.subplot2grid((1,1),(0,0))\n#grab_initial_state_data()\n\nHPI_data=pd.read_pickle('fiddy_states3.pickle')\n#benchmark = HPI_Benchmark()\n#\n#HPI_data.plot(ax = ax1)\n#benchmark.plot(ax = ax1, color='k', linewidth=10)\n#plt.legend().remove()\n#plt.show()\n\nHPI_State_Correlation = HPI_data.corr()\nprint(HPI_State_Correlation)\n\nprint(HPI_State_Correlation.describe())","sub_path":"correlation_data.py","file_name":"correlation_data.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"35493158","text":"##\n# The selectionSort function sorts a list using the selection sort algorithm.\n#\n\n## Sorts a list, using selection sort.\n# @param values the list to sort\n#\ndef selectionSort(values) :\n for i in range(len(values)) :\n minPos = minimumPosition(values, i)\n temp = values[minPos] # swap the two elements\n values[minPos] = values[i]\n values[i] = temp\n\n## Finds the smallest element in a tail range of the list.\n# @param values the list to sort\n# @param start the first position in values to compare\n# @return the position of the smallest element in the\n# range values[start] . . . values[len(values) - 1]\n#\ndef minimumPosition(values, start) :\n minPos = start\n for i in range(start + 1, len(values)) :\n if values[i] < values[minPos] :\n minPos = i\n \n return minPos\n","sub_path":"Ch12/selectionsort.py","file_name":"selectionsort.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"571385840","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='UserExtraEmail',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('email', models.EmailField(unique=True, max_length=100)),\n ('confirmed', models.BooleanField(default=False)),\n ('token', models.CharField(max_length=100, blank=True)),\n ('tokensent', models.DateTimeField()),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ('user', 'email'),\n },\n ),\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('selectedemail', models.ForeignKey(verbose_name=b'Sender email', blank=True, to='userprofile.UserExtraEmail', null=True)),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.AlterUniqueTogether(\n name='userextraemail',\n unique_together=set([('user', 'email')]),\n ),\n ]\n","sub_path":"pgcommitfest/userprofile/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"378717629","text":"import os\n\n\nclass OSHelper:\n\n # 根节点\n def __init__(self, s_path='r_path'):\n self.root = None\n self.s_path = s_path\n\n # 输入一个路径,获取目录下的所有文件名\n @staticmethod\n def img_getter(path):\n fin = list()\n if os.path.exists(path) is False:\n os.makedirs(path)\n return []\n for root, dirs, files in os.walk(path):\n for i in files:\n fin.append(path + '/' + i)\n return fin\n\n # 输入img对象,保存为指定目录指定名字位置\n def img_saver(self, img, name):\n img.save(self.s_path + '/' + name + '.png')\n\n\ndef main():\n oser = OSHelper()\n oser.img_getter('w_path')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"os_finder.py","file_name":"os_finder.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"357445081","text":"# https://www.geeksforgeeks.org/print-all-pairs-with-given-sum/\n\n\ndef pairedElements(arr, sum):\n arr.sort()\n results = set()\n low, high = 0, len(arr) - 1\n\n while low < high:\n current_sum = arr[low] + arr[high]\n if current_sum == sum:\n results.add((arr[low], arr[high]))\n if current_sum > sum:\n high -= 1\n else:\n low += 1\n\n return results\n\n\n# Invoke function\narr = [2, 3, 4, -2, 6, 8, 9, 11, 8, -2, 8]\nsum = 6\npairedElements(arr, sum)\n","sub_path":"Problems/SRE/23_AllPairsWithGivenSum.py","file_name":"23_AllPairsWithGivenSum.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"214188763","text":"from app.data import utils as mutils, settings as msettings, models as mmodels\nimport datetime\n\n\ndef return_common_info():\n return msettings.get_test_server()\n\n\ndef formiodate_to_datetime(formio_date):\n date = datetime.datetime.strptime(':'.join(formio_date.split(':')[:2]), '%Y-%m-%dT%H:%M')\n return date\n\n\ndef datetime_to_formiodate(date):\n delta_utc = datetime.datetime.now().astimezone().utcoffset().seconds//3600\n string = f\"{datetime.datetime.strftime(date, '%Y-%m-%dT%H:%M')}:00+{delta_utc:02d}:00\"\n return string\n\ndef datetime_to_string(date):\n string = date.strftime('%d/%m/%Y %H:%M')\n return string\n\n\ndef raise_error(message, details=None):\n error = Exception(f'm({message}), d({details}), td({type(details).__name__})')\n raise error\n\n\ndef datetime_to_dutch_datetime_string(date):\n return mutils.datetime_to_dutch_datetime_string(date)\n\n\ndef deepcopy(table):\n if type(table) == dict:\n out = {}\n for k, v in table.items():\n if type(v) == list or type(v) == dict:\n out[k] = deepcopy(v)\n else:\n out[k] = v\n elif type(table) == list:\n out = []\n for i in table:\n if type(i) == list or type(i) == dict:\n out.append(deepcopy(i))\n else:\n out.append(i)\n else:\n out = table\n return out\n\n\ndef deepupdate(dst, src):\n for k, v in src.items():\n if type(v) == dict:\n deepupdate(dst[k], v)\n elif type(v) == list:\n dst[k] = deepcopy(v)\n else:\n dst[k] = v\n return dst\n\n\n","sub_path":"app/application/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"97869969","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: XuMing \n@description:\n\"\"\"\n\nimport functools\nimport sys\nimport abc\nimport warnings\n\nfrom ..exception import UnexpectedResponseException, JSONDecodeError, TokenError, UnimplementedException\nfrom .utils import build_obj_from_dict\n\n\nclass BaseGenerator:\n def __init__(self, url, session, **default_params):\n self._url = url\n self._session = session\n self._index = 0\n self._data = []\n self._up = 0\n self._next_url = self._url\n self._need_sleep = 0.5\n self._default_params = dict(default_params if default_params else {})\n self._extra_params = {}\n\n def _fetch_more(self):\n \"\"\"\n Get next page info\n :return: \n \"\"\"\n params = dict(self._default_params)\n params.update(self._extra_params)\n\n if self._next_url != self._url and 'offset' in params:\n del params['offset']\n res = self._session.get(self._next_url, params=params)\n try:\n json_dict = res.json()\n if not json_dict:\n self._next_url = None\n return\n if 'error' in json_dict:\n error = json_dict['error']\n if 'name' in error:\n if error['name'] == 'ERR_CONVERSATION_NOT_FOUND':\n self._next_url = None\n return\n if 'code' in error:\n if error['code'] == 100:\n raise TokenError(error['message'])\n raise UnexpectedResponseException(\n self._next_url,\n res,\n 'It is a json string, has data and paging'\n )\n self._up += len(json_dict['data'])\n self._data.extend(json_dict['data'])\n if json_dict['paging']['is_end']:\n self._next_url = None\n else:\n self._next_url = json_dict['paging']['next']\n except (JSONDecodeError, AttributeError):\n raise UnexpectedResponseException(\n self._next_url,\n res,\n 'It is a json string, has data and paging'\n )\n\n @abc.abstractmethod\n def _build_obj(self, data):\n return None\n\n def __getitem__(self, item):\n \"\"\"\n Override int\n :param item: \n :return: \n \"\"\"\n if not isinstance(item, int):\n raise TypeError(f'Need an int as index, not {type(item)}')\n if item < 0:\n raise ValueError(f'Index must >=0, {item} provided.')\n while item >= self._up:\n if self._next_url is not None:\n self._fetch_more()\n else:\n raise IndexError('list index out of range')\n return self._build_obj(self._data[item])\n\n def __iter__(self):\n self._reset()\n return self\n\n def __next__(self):\n obj = None\n while obj is None:\n try:\n obj = self[self._index]\n except IndexError:\n self._index = 0\n raise StopIteration\n self._index += 1\n return obj\n\n next = __next__\n","sub_path":"12Auth/auth/core/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"635327186","text":"#!/usr/bin/python\n\n# Write it as a python script for portability\nimport glob\nimport os\nfrom subprocess import check_call\n\nversion = os.environ['ISTIO_VERSION']\nopj = os.path.join\n\n# We don't care about the platform as we only use yaml files\ncheck_call(\n [\n \"curl\",\n \"-o\",\n \"istio.tar.gz\",\n \"-L\",\n \"https://github.com/istio/istio/releases/download/{version}/istio-{version}-linux.tar.gz\".format(\n version=version\n ),\n ]\n)\ncheck_call([\"tar\", \"xf\", \"istio.tar.gz\"])\n\ncheck_call([\"kubectl\", \"create\", \"ns\", \"istio-system\"])\ncheck_call([\"kubectl\", \"label\", \"namespace\", \"default\", \"istio-injection=enabled\"])\n\nistio = \"istio-{}\".format(version)\n\nfor f in glob.glob(opj(istio, \"install\", \"kubernetes\", \"helm\", \"istio-init\", \"files\", \"crd*.yaml\")):\n check_call([\"kubectl\", \"apply\", \"-f\", f])\n\ncheck_call([\"kubectl\", \"apply\", \"-f\", opj(istio, \"install\", \"kubernetes\", \"istio-demo-auth.yaml\")])\ncheck_call(\n [\"kubectl\", \"wait\", \"deployments\", \"--all\", \"--for=condition=Available\", \"-n\", \"istio-system\", \"--timeout=300s\"]\n)\n\ncheck_call([\"kubectl\", \"apply\", \"-f\", opj(istio, \"samples\", \"bookinfo\", \"platform\", \"kube\", \"bookinfo.yaml\")])\ncheck_call([\"kubectl\", \"wait\", \"pods\", \"--all\", \"--for=condition=Ready\", \"--timeout=300s\"])\n\ncheck_call([\"kubectl\", \"apply\", \"-f\", opj(istio, \"samples\", \"bookinfo\", \"networking\", \"bookinfo-gateway.yaml\")])\ncheck_call([\"kubectl\", \"wait\", \"pods\", \"--all\", \"--for=condition=Ready\", \"--timeout=300s\"])\n","sub_path":"istio/tests/terraform/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"373802785","text":"import time\nfrom selenium import webdriver\nfrom flask import Flask, request\nfrom flask_restful import Resource, Api\n\n\napp = Flask(__name__)\napi = Api(app)\n\nitems = []\n\nclass Item(Resource):\n def get(self, name):\n item = next(filter(lambda x: x['name'] == name, items), None) #Returns first item matched by the filter function or none\n\n return {'item': item}, 200 if item else 404\n\n def post(self, name):\n if next(filter(lambda x: x['name'] == name, items), None):\n return {'message' : \"An item with name '{}' already exists.\".format(name)}, 400\n\n data = request.get_json()\n item = {'name' : name, 'price': data['price'] }\n items.append(item)\n return item, 201\n\n\nclass ItemList(Resource):\n def get(self):\n return{'items' : items}\n\nclass ReturnTracking(Resource):\n def get(self):\n driver = webdriver.Chrome()\n driver.get(\"http://www.dhl.co.uk/en/express/tracking.html\")\n txtArea = driver.find_element_by_id('AWB')\n button = driver.find_element_by_class_name('tracking-button')\n\n txtArea.clear()\n txtArea.send_keys('6746486014')\n button.click()\n\n time.sleep(3)\n\n elements = driver.find_element_by_css_selector(\".result-checkpoints.show.result-has-pieces\")\n th = elements.find_elements_by_tag_name(\"tbody\")\n tr = elements.find_elements_by_tag_name(\"tr\")\n # driver.quit()\n size = len(tr)\n\n if \"Delivered\" in tr[1].text:\n return(\"Your parcel was delivered\"), 200\n else:\n return(\"Not delivered\"), 200\n\n\napi.add_resource(Item,'/item/')\napi.add_resource(ItemList, '/items') #Return all tracking steps??\napi.add_resource(ReturnTracking, '/track')\napp.run(debug=True)\n\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"35358438","text":"#!/Users/spoll/Virtualenvs/automate/bin/python3\n\ndef collatz(number):\n if number % 2 == 0:\n number = number // 2\n else:\n number = 3 * number + 1\n print(number)\n return number\n\nwhile True:\n try:\n print('Enter an integer: ', end = '')\n num = int(input())\n\n while num != 1:\n num = collatz(num)\n break\n except:\n print(\"That's not an integer!\")\n","sub_path":"Python/Automate the Boring Stuff/ch03/collatz.py","file_name":"collatz.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"368396248","text":"import pytest\n\nfrom api import queries\nfrom tests.factories import (\n GPSReadingF,\n)\n\n\ndef test_gps_reading_has_results(session):\n gr = GPSReadingF()\n gr1 = GPSReadingF(sensor=gr.sensor, sensor_unit=gr.sensor_unit, timestamp=gr.timestamp + 1)\n gr2 = GPSReadingF(sensor=gr.sensor, sensor_unit=gr.sensor_unit, timestamp=gr.timestamp + 2)\n gr3 = GPSReadingF(sensor=gr.sensor, sensor_unit=gr.sensor_unit, timestamp=gr.timestamp + 3)\n GPSReadingF(sensor=gr.sensor, sensor_unit=gr.sensor_unit, timestamp=gr.timestamp + 4)\n\n qr = queries.get_gps_reading_qr(gr.sensor.uid, gr.sensor_unit.uid, gr.timestamp + 1, gr.timestamp + 3)\n\n assert qr == [\n (float(gr1.latitude), float(gr1.longitude), gr1.timestamp),\n (float(gr2.latitude), float(gr2.longitude), gr2.timestamp),\n (float(gr3.latitude), float(gr3.longitude), gr3.timestamp),\n ]\n\n\ndef test_gps_reading_has_no_results(session):\n g = GPSReadingF()\n\n qr = queries.get_gps_reading_qr(g.sensor_uuid, g.sensor_unit_uuid, g.timestamp + 1, g.timestamp + 2)\n\n assert qr == []\n\n\n@pytest.mark.skip('STUB TEST')\ndef test_get_alerts(session):\n qr = queries.get_alerts(None, None, None)\n\n assert qr\n\n\n@pytest.mark.skip('STUB TEST')\ndef test_get_alert_categories(session):\n qr = queries.get_alert_categories_qr()\n\n assert qr\n\n\n@pytest.mark.skip('STUB TEST')\ndef test_gross_counts(session):\n qr = queries.get_gross_counts_qr(None, None, None, None)\n\n assert qr\n\n\n@pytest.mark.skip('STUB TEST')\ndef test_investigations(session):\n qr = queries.get_investigations_qr(None, None)\n\n assert qr\n\n\n@pytest.mark.skip('STUB TEST')\ndef test_users(session):\n qr = queries.get_users_qr()\n\n assert qr\n\n\n@pytest.mark.skip('STUB TEST')\ndef test_missions(session):\n qr = queries.get_missions_qr()\n\n assert qr\n","sub_path":"kegflask/tests/api/test_queries.py","file_name":"test_queries.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"373393629","text":"\"\"\"Hermes MQTT service for Rhasspy wakeword with snowboy\"\"\"\nimport argparse\nimport asyncio\nimport dataclasses\nimport itertools\nimport json\nimport logging\nimport os\nimport sys\nimport typing\nfrom pathlib import Path\n\nimport paho.mqtt.client as mqtt\nimport rhasspyhermes.cli as hermes_cli\n\nfrom . import SnowboyModel, WakeHermesMqtt\n\n_DIR = Path(__file__).parent\n_LOGGER = logging.getLogger(\"rhasspywake_snowboy_hermes\")\n\n# -----------------------------------------------------------------------------\n\n\ndef main():\n \"\"\"Main method.\"\"\"\n parser = argparse.ArgumentParser(prog=\"rhasspy-wake-snowboy-hermes\")\n parser.add_argument(\n \"--model\",\n required=True,\n action=\"append\",\n nargs=\"+\",\n help=\"Snowboy model settings (model, sensitivity, audio_gain, apply_frontend)\",\n )\n parser.add_argument(\n \"--model-dir\",\n action=\"append\",\n default=[],\n help=\"Directories with snowboy models\",\n )\n parser.add_argument(\n \"--wakeword-id\",\n action=\"append\",\n help=\"Wakeword IDs of each keyword (default: use file name)\",\n )\n parser.add_argument(\n \"--stdin-audio\", action=\"store_true\", help=\"Read WAV audio from stdin\"\n )\n parser.add_argument(\n \"--udp-audio\",\n nargs=3,\n action=\"append\",\n help=\"Host/port/siteId for UDP audio input\",\n )\n parser.add_argument(\n \"--udp-raw-audio\",\n action=\"append\",\n help=\"Site id(s) where UDP audio is raw 16Khz 16-bit mono PCM instead of WAV chunks\",\n )\n parser.add_argument(\n \"--udp-forward-mqtt\",\n action=\"append\",\n help=\"Site id(s) to forward audio to MQTT after detection\",\n )\n parser.add_argument(\"--lang\", help=\"Set lang in hotword detected message\")\n\n hermes_cli.add_hermes_args(parser)\n args = parser.parse_args()\n\n # logging.basicConfig wouldn't work if a handler already existed.\n # snowboy must mess with logging, so this resets it.\n logging.getLogger().handlers = []\n\n hermes_cli.setup_logging(args)\n\n _LOGGER.debug(args)\n\n if args.model_dir:\n args.model_dir = [Path(d) for d in args.model_dir]\n\n # Use embedded models too\n args.model_dir.append(_DIR / \"models\")\n\n # Load model settings\n models: typing.List[SnowboyModel] = []\n\n for model_settings in args.model:\n model_path = Path(model_settings[0])\n\n if not model_path.is_file():\n # Resolve relative to model directories\n for model_dir in args.model_dir:\n maybe_path = model_dir / model_path.name\n if maybe_path.is_file():\n model_path = maybe_path\n break\n\n _LOGGER.debug(\"Loading model from %s\", str(model_path))\n model = SnowboyModel(model_path=model_path)\n\n if len(model_settings) > 1:\n model.sensitivity = model_settings[1]\n\n if len(model_settings) > 2:\n model.audio_gain = float(model_settings[2])\n\n if len(model_settings) > 3:\n model.apply_frontend = model_settings[3].strip().lower() == \"true\"\n\n models.append(model)\n\n wakeword_ids = [\n kn[1]\n for kn in itertools.zip_longest(\n args.model, args.wakeword_id or [], fillvalue=\"\"\n )\n ]\n\n if args.stdin_audio:\n # Read WAV from stdin, detect, and exit\n client = None\n hermes = WakeHermesMqtt(client, models, wakeword_ids)\n\n for site_id in args.site_id:\n hermes.load_detectors(site_id)\n\n if os.isatty(sys.stdin.fileno()):\n print(\"Reading WAV data from stdin...\", file=sys.stderr)\n\n wav_bytes = sys.stdin.buffer.read()\n\n # Print results as JSON\n for result in hermes.handle_audio_frame(wav_bytes):\n result_dict = dataclasses.asdict(result)\n json.dump(result_dict, sys.stdout, ensure_ascii=False)\n\n return\n\n udp_audio = []\n if args.udp_audio:\n udp_audio = [\n (host, int(port), site_id) for host, port, site_id in args.udp_audio\n ]\n\n # Listen for messages\n client = mqtt.Client()\n hermes = WakeHermesMqtt(\n client,\n models,\n wakeword_ids,\n model_dirs=args.model_dir,\n udp_audio=udp_audio,\n udp_raw_audio=args.udp_raw_audio,\n udp_forward_mqtt=args.udp_forward_mqtt,\n site_ids=args.site_id,\n lang=args.lang,\n )\n\n hermes_cli.connect(client, args)\n\n client.loop_start()\n\n try:\n # Run event loop\n asyncio.run(hermes.handle_messages_async())\n except KeyboardInterrupt:\n pass\n finally:\n _LOGGER.debug(\"Shutting down\")\n hermes.stop()\n client.loop_stop()\n\n\n# -----------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rhasspywake_snowboy_hermes/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"527633198","text":"from cito.core.math import find_subranges, overlap_region, speed_in1d_continous\n\n__author__ = 'tunnell'\n\nimport unittest\nimport numpy as np\n\n\nclass CoreMathTestCase(unittest.TestCase):\n def test_subrange(self):\n self.assertEqual(find_subranges([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]),\n [[0, 3], [4, 9], [10, 10]])\n\n\n def test_overlap_region(self):\n f = overlap_region\n\n offset = 1000\n\n indices = np.arange(offset, offset + 10)\n\n a = (offset, offset + 2)\n\n self.assertEqual(f(a, (offset+4, offset+6)),\n (None, None))\n\n\n\nclass CoreMathTestCase(unittest.TestCase):\n def setUp(self):\n self.testcases = []\n max = 10\n\n for a in range(max):\n for b in range(max):\n for x in range(max):\n for y in range(max):\n if b < a:\n continue\n elif y < x:\n continue\n else:\n self.testcases.append([a, b, x, y])\n \n def in1d_helper(self, a, b, x, y):\n array1 = np.arange(a, b)\n array2 = np.arange(x, y)\n\n answer = np.in1d(array1, array2)\n my_answer = speed_in1d_continous(a, b, x, y)\n if not (my_answer == answer).all():\n print('fail.')\n print('answer:', answer)\n print('my answer:', my_answer)\n self.assertEqual(my_answer.size, answer.size)\n self.assertTrue((my_answer == answer).all())\n\n def test_all_before(self):\n self.in1d_helper(0, 10, 100, 200)\n \n def test_all_after(self):\n self.in1d_helper(100, 200, 0, 10)\n\n def test_equal(self):\n self.in1d_helper(3, 15, 3, 15)\n\n def test_test_all(self):\n \"\"\"Test all permutations\"\"\"\n for a,b,x,y in self.testcases:\n self.in1d_helper(a, b, x, y)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/TestCoreMath.py","file_name":"TestCoreMath.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"471390312","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nweb = urlopen('http://nhaczingmp3.com/bang-xep-hang/bai-hat-Viet-Nam/IWZ9Z08I.html')\ncontent = web.read().decode('utf8')\nweb.close()\nsoup = BeautifulSoup(content, 'html.parser')\nul_chart = soup.find('ul', 'box-song')\nli_chart_list = ul_chart.find_all('li')\nfor li in li_chart_list:\n a = li.a\n print(a['title'])\n","sub_path":"Session 2/HW/zing_chart.py","file_name":"zing_chart.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"251607712","text":"import socket\nimport threading\nimport os\nimport time\nver=\"1.0.0\"\nprint(str(\"\\nJames Forty's Remote terminal\\nBETA TEST VERSION \"+ver+\"\\n\"))\ntarget_port=\"\"\nhosting_can_start=\"0\"\nab_unc=[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\",\"A\",\"B\",\n\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\",\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\n\"6\",\"7\",\"8\",\"9\",\"-\",\"=\",\"`\",\"!\",\"\\\"\",\"£\",\"$\",\"%\",\"^\",\"&\",\"*\",\"(\",\")\",\"_\",\"+\",\"-\",\"=\",\"[\",\"]\",\"{\",\"}\",\";\",\"'\",\"#\",\":\",\"@\",\n\"~\",\"\\'\",\",\",\".\",\"/\",\"|\",\"<\",\">\",\"?\",\" \",\"\\\\\",\"\\n\"] # unencrypted alphabet\nab_enc=[\"W(\",\"M.\",\".7\",\"{=\",\"!g\",\";a\",\"c^\",\"=d\",\"cg\",\"og\",\"(>\",\"VL\",\"FT\",\"Ce\",\"}O\",\":b\",\"|8\",\"eE\",\"(d\",\"l.\",\"q'\",\"?<\",\"%x\",\">:\",\"r \",\"~w\",\"Y]\",\"~(\",\"!.\",\"9o\",\"OO\",\"}9\",\"Nq\",\"F5\",\"8N\",\"t&\",\"LF\",\"?y\",\"/1\",\"Z=\",\"=u\",\"=\",\"4L\",\"=n\",\"7b\",\"F)\",\"9B\",\"4z\",\"7L\",\":s\",\"PE\",\"N+\",\"ng\",\"kq\",\"Ss\",\"=`\",\"a7\",\"dP\",\"?_\",\"{#\",\"-6\"]\n# encrypted alphabet\nwhile target_port==\"\":\n print(\"\\nPlease type the port you want to host the Remote Terminal Server from.\\nValues must be between 0 and 65535.\")\n target_port=input(\"\\n> \")\n try:\n target_port=int(target_port)\n if not 0<=target_port<=65535:\n target_port=\"\"\n else:\n hosting_can_start=\"1\"\n except:\n target_port=\"\"\n print(\"\\nInvalid input\\n\")\n\n\nclass Server:\n sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n connections=[]\n def __init__(self):\n global target_port\n self.sock.bind((\"0.0.0.0\",target_port))\n self.sock.listen(1)\n def handler(self,c,a):\n while True:\n data=str(c.recv(4096))[2:-1]\n data_decrypt=[]\n data_can_be_returned=\"1\"\n temp=[]\n for i in range(len(data)):\n if data[i]!=\"\\\\\":\n temp.append(data[i])\n data=\"%s\"%\"\".join(temp[0:])\n for i in range(int(len(str(data))/2)):\n try:\n data_decrypt.append(ab_unc[ab_enc.index(data[(i*2):(i*2)+2])])\n except:\n data_can_be_returned=\"0\"\n print(\"bad data\")\n if len(Server.connections)==1 and data_can_be_returned==\"1\":\n \n\n data_decrypt=str(\"%s\"%\"\".join(data_decrypt[0:]))\n print(\"\\n\")\n print(str(\"decrypted data \"+data_decrypt))\n data_terminal=str(os.system(str(data_decrypt)))\n data_encrypt=[]\n for i in range(len(data_terminal)):\n try:\n data_encrypt.append(ab_enc[ab_unc.index(data_terminal[i])])\n except:\n pass\n\n data_encrypt=str(\"%s\"%\"\".join(data_encrypt[0:]))\n for connection in Server.connections:\n connection.send(bytes(data_encrypt,\"utf-8\"))\n def run(self):\n while True:\n c,a=Server.sock.accept()\n cThread=threading.Thread(target=self.handler,args=(c,a))\n cThread.daemon=True\n cThread.start()\n if len(Server.connections)==0:\n Server.connections.append(c)\n print(Server.connections[-1])\nserver=Server()\nserver.run()\n","sub_path":"Remote Terminal Server - 1.0.0.00001.pyw","file_name":"Remote Terminal Server - 1.0.0.00001.pyw","file_ext":"pyw","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"584074544","text":"import time\r\nimport tifffile as tif\r\nimport napari\r\nfrom ht_sols_microscope import DataPreview, DataRoi, DataNative, DataTraditional\r\n\r\ndef imread(filename): # re-define imread to keep 5D axes\r\n with tif.TiffFile(filename) as t:\r\n axes = t.series[0].axes\r\n hyperstack = t.series[0].asarray()\r\n return tif.transpose_axes(hyperstack, axes, 'TZCYX')\r\n\r\ndef imwrite(filename, data):\r\n return tif.imwrite(filename, data, imagej=True)\r\n\r\ndef view_in_napari(data_preview,\r\n data_native=None,\r\n voxel_aspect_ratio=None, # Needed for data_native\r\n data_traditional=None):\r\n print('\\nViewing in napari')\r\n with napari.gui_qt():\r\n preview = napari.Viewer()\r\n preview.add_image(data_preview, name='data_preview')\r\n if data_native is not None:\r\n native = napari.Viewer()\r\n for channel in range(data_native.shape[2]):\r\n native.add_image(data_native[:, :, channel, :, :],\r\n name='data_native',\r\n scale=(1, voxel_aspect_ratio, 1, 1))\r\n if data_traditional is not None: \r\n traditional = napari.Viewer()\r\n for channel in range(data_traditional.shape[2]):\r\n traditional.add_image(data_traditional[:, :, channel, :, :],\r\n name='data_traditional')\r\n\r\n# Get processsing tools:\r\ndatapreview = DataPreview()\r\ndataroi = DataRoi()\r\ndatanative = DataNative()\r\ndatatraditional = DataTraditional()\r\n\r\n# Get data and metadata:\r\nt0 = time.perf_counter()\r\nprint('\\nGetting: data', end=' ')\r\ndata = imread('data.tif')\r\nt1 = time.perf_counter()\r\nprint('(%0.2fs)'%(t1 - t0))\r\nprint('-> data.shape =', data.shape)\r\nprint('-> format = 5D \"tzcyx\" (volumes, slices, channels, height_px, width_px)')\r\nscan_step_size_px = 1\r\npreview_line_px = 10\r\npreview_crop_px = 3\r\ntimestamp_mode = \"off\"\r\nvoxel_aspect_ratio = 1.19175359259421\r\n\r\n# Get preview:\r\nprint('\\nGetting: preview', end=' ')\r\npreview = datapreview.get(\r\n data, scan_step_size_px, preview_line_px, preview_crop_px, timestamp_mode)\r\nt2 = time.perf_counter()\r\nprint('(%0.2fs)'%(t2 - t1))\r\nprint('-> saving: data_preview.tif')\r\nimwrite('data_preview.tif', preview)\r\n\r\n# Get native data:\r\nprint('\\nGetting: native view', end=' ')\r\nnative = datanative.get(data, scan_step_size_px)\r\nt3 = time.perf_counter()\r\nprint('(%0.2fs)'%(t3 - t2))\r\nprint('-> saving: data_native.tif')\r\nimwrite('data_native.tif', native)\r\n\r\n# Get traditional data for roi: -> this is very slow (adds about ~30s)\r\nprint('\\nGetting: traditional view', end=' ')\r\nnative_subset = native[0:1, : , 0:1, :, :] # -> picking 1 volume, but keep 5D!\r\ntraditional = datatraditional.get(native_subset, scan_step_size_px)\r\nt4 = time.perf_counter()\r\nprint('(%0.2fs)'%(t4 - t3))\r\nprint('-> saving: data_traditional.tif')\r\nimwrite('data_traditional.tif', traditional)\r\n\r\n# View in napari (or checked saved data with ImageJ or similar):\r\nview_in_napari(preview, native, voxel_aspect_ratio, traditional)\r\n","sub_path":"figures/data/water_objective/beads/ht_sols_microscope_data_processing.py","file_name":"ht_sols_microscope_data_processing.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"85651305","text":"# app/app.py\n\n# Common python package imports.\nfrom flask import Flask, jsonify, request, render_template\nimport pickle\nimport numpy as np\n\n# Import from model_api/app/features.py.\nfrom features import FEATURES\n\n\n# Initialize the app and set a secret_key.\napp = Flask(__name__)\napp.secret_key = 'something_secret'\n\n# Load the pickled model.\n#MODEL = pickle.load(open('model.pkl', 'rb'))\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n#prediction function\ndef ValuePredictor(to_predict_list):\n to_predict = np.array(to_predict_list).reshape(1,6)\n loaded_model = pickle.load(open(\"model.pkl\",\"rb\"))\n result = loaded_model.predict(to_predict)\n return result[0]\n\n\n@app.route('/result',methods = ['POST'])\ndef result():\n if request.method == 'POST':\n to_predict_list = request.form.to_dict()\n to_predict_list=list(to_predict_list.values())\n to_predict_list = list(map(int, to_predict_list))\n result = ValuePredictor(to_predict_list)\n \n if int(result)==0:\n prediction='Worthless house'\n else:\n prediction='Predicted value of the house (*1000) is $'+str(round(result, 2))\n \n return render_template(\"result.html\",prediction=prediction)\n\n\n#@app.route('/api', methods=['GET'])\n#def api():\n# \"\"\"Handle request and output model score in json format.\"\"\"\n# # Handle empty requests.\n# if not request.json:\n# return jsonify({'error': 'no request received'})\n#\n# # Parse request args into feature array for prediction.\n# x_list, missing_data = parse_args(request.json)\n# x_array = np.array([x_list])\n#\n# # Predict on x_array and return JSON response.\n# estimate = int(MODEL.predict(x_array)[0])\n# response = estimate\n#\n# return jsonify(response)\n\n\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=True)","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"567450678","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 23 14:25:50 2014\n\nThis script predicts the FE response of a set of microstructures designated by\na specific set-ID using a previously calibrated MKS\n\n@author: nhpnp3\n\"\"\"\n\nimport time\nimport numpy as np\nimport functions as rr\n#import matplotlib.pyplot as plt\n\n\n\ndef validation(el,ns_cal,ns_val,H,set_id_cal,set_id_val,wrt_file):\n\n start = time.time()\n\n ## perform the prediction procedure \n specinfc = np.load('specinfc_%s%s.npy' %(ns_cal,set_id_cal)).reshape(H,el,el,el) \n \n M = np.load('M_%s%s.npy' %(ns_val,set_id_val))\n tmp = np.sum(np.conjugate(specinfc) * M,1) \n mks_R = np.fft.ifftn(tmp,[el,el,el],[1,2,3]).real\n \n np.save('mksR_%s%s' %(ns_val,set_id_val), mks_R)\n\n end = time.time()\n timeE = np.round((end - start),3)\n\n msg = 'validation performed: %s seconds' %timeE\n rr.WP(msg,wrt_file)\n\n","sub_path":"fip_collab/2014_12_18_equiaxed_delta_random/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"477675575","text":"def sum(m, n):\n if n < 0:\n for i in range(abs(n)):\n m -= 1\n else:\n for i in range(0, n):\n m += 1\n return m\n\n\ndef subtract(m, n):\n return sum(m, -n)\n\n\ndef divide(m, n):\n result = 0\n negativeResult = m > 0 and n < 0 or m < 0 and n > 0\n mAbs = abs(m)\n nAbs = abs(n)\n if n != 0:\n while (mAbs >= nAbs):\n mAbs -= nAbs\n result += 1\n if negativeResult:\n result = -result\n else:\n raise ZeroDivisionError()\n return result\n\n\ndef multiply(m, n):\n result = 0\n negativeResult = m > 0 and n < 0 or m < 0 and n > 0\n for i in range(abs(n)):\n result += abs(m)\n if negativeResult:\n result = -result\n return result\n\n\ndef MCD(m, n):\n mAbs = abs(m)\n nAbs = abs(n)\n while nAbs != 0:\n mAbs, nAbs = nAbs, mAbs % nAbs\n return mAbs\n","sub_path":"Lecture01/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"112733443","text":"import os\nimport yaml\nfrom pathlib import Path\nfrom flask import Flask, send_from_directory\nfrom dynaconf import FlaskDynaconf\nimport logging\nimport logging.config\n\n\ndef create_app():\n \"\"\"Initialize the Flask app instance\"\"\"\n\n # create the flask app instance\n app = Flask(__name__)\n dynaconf = FlaskDynaconf(extensions_list=True)\n\n with app.app_context():\n\n # create a route to the favicon.ico file\n @app.route('/favicon.ico')\n def favicon():\n return send_from_directory(\n os.path.join(app.root_path, 'static'),\n 'favicon.ico',\n mimetype=\"image/vnd.microsoft.icon\"\n )\n\n # initialize plugins\n os.environ[\"ROOT_PATH_FOR_DYNACONF\"] = app.root_path\n dynaconf.init_app(app)\n\n # turn the secret key into a bytearray\n app.config[\"SECRET_KEY\"] = bytearray(app.config[\"SECRET_KEY\"], \"UTF-8\")\n\n _configure_logging(app, dynaconf)\n\n # import the routes\n from . import intro\n\n # register the blueprints\n app.register_blueprint(intro.intro_bp)\n\n return app\n\n\ndef _configure_logging(app, dynaconf):\n # configure logging\n logging_config_path = Path(app.root_path).parent / \"logging_config.yaml\"\n with open(logging_config_path, \"r\") as fh:\n logging_config = yaml.safe_load(fh.read())\n env_logging_level = dynaconf.settings.get(\"logging_level\", \"INFO\").upper()\n logging_level = logging.INFO if env_logging_level == \"INFO\" else logging.DEBUG\n logging_config[\"handlers\"][\"console\"][\"level\"] = logging_level\n logging_config[\"loggers\"][\"\"][\"level\"] = logging_level\n logging.config.dictConfig(logging_config)\n","sub_path":"examples/CH_08/examples/07/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"488382651","text":"from datetime import time\nimport os\nimport random\nimport shutil\nimport yaml\nfrom yaml.loader import SafeLoader\nfrom Backend.app.config import settings\nfrom Backend.app.helpers.project_helper import merge_project_path, get_raw_data_path, get_project_type\nfrom Backend.app.helpers.allhelpers import CurrentIDs, serialiseDict\n\ndef generate_random_id():\n \"\"\"\n Generates a 5 digit random number from 10000 to 99999\n \"\"\"\n return random.randint(10000,99999)\n\ndef generate_project_folder(projectName,trainFileStream):\n \"\"\"\n Generates a project folder with the name projectName_16digitrandomnumber\n ...\n Parameters\n ----------\n projectName: str\n trainFileStream: UploadFile type\n Returns\n -------\n dict: Success, RawDataPath, ProjectFolderPath\n or Success, Error\n \"\"\"\n try:\n newpath=os.path.join(os.getcwd(),\"Database\",merge_project_path(projectName),'raw_data')\n if(not os.path.exists(newpath)):\n os.makedirs(newpath)\n with open(os.path.join(newpath,\"raw_data.csv\"),\"wb\") as buffer:\n shutil.copyfileobj(trainFileStream.file,buffer)\n return {\"Success\":True, \"RawDataPath\":os.path.abspath(os.path.join(newpath,\"raw_data.csv\")),\"ProjectFolderPath\":os.path.abspath(os.path.join(newpath,os.pardir))}\n except:\n return {\"Success\":False,\"Error\": \"File could not be saved. Folder creation unsuccessful\"}\n\n\ndef generate_project_auto_config_file(projectID,currentIDs,formData,Project21Database):\n \"\"\"\n Returns the auto config file generated for the project\n ...\n Parameters\n ----------\n projectID: int\n currentIDs: obj\n formData: obj\n Project21Databse: obj\n \n Returns\n -------\n tuple: path, randomID, problemType\n \"\"\"\n user_yaml=yaml.load(open(settings.CONFIG_AUTO_YAML_FILE),Loader=SafeLoader)\n random_id=generate_random_id()\n user_yaml[\"id\"]=random_id\n user_yaml[\"raw_data_address\"]=get_raw_data_path(projectID,Project21Database)\n user_yaml[\"target_col_name\"]=formData[\"target\"]\n user_yaml[\"na_value\"]=formData[\"nulltype\"]\n user_yaml[\"n\"]=formData[\"modelnumber\"]\n user_yaml[\"problem_type\"]=get_project_type(projectID,Project21Database)\n if(user_yaml[\"problem_type\"]=='clustering'):\n user_yaml[\"clusteringType\"]=formData[\"clusteringType\"]\n # try:\n # result_model=Project21Database.find_one(settings.DB_COLLECTION_MODEL,{\"modelID\":currentIDs.get_current_model_id()})\n # result_model=serialiseDict(result_model)\n # if result_model is not None:\n # user_yaml[\"problem_type\"]=result_model[\"modelType\"]\n # else:\n # user_yaml[\"problem_type\"]='default'\n # except:\n # print(\"Unable to Update User's Project's AutoConfig File\")\n\n try:\n result_project=Project21Database.find_one(settings.DB_COLLECTION_PROJECT,{\"projectID\":projectID})\n result_project=serialiseDict(result_project)\n if result_project is not None:\n user_yaml[\"location\"]=os.path.join(result_project[\"projectFolderPath\"],'run'+str(random_id))\n user_yaml[\"experimentname\"]=result_project[\"projectName\"]\n else:\n user_yaml[\"location\"]='/'\n user_yaml[\"experimentname\"]='default'\n except:\n print(\"Unable to Update User's Project's Config File\")\n if(not os.path.exists(user_yaml[\"location\"])):\n os.makedirs(user_yaml[\"location\"])\n with open(os.path.join(user_yaml[\"location\"],\"autoConfig.yaml\"), \"w\") as f:\n yaml.dump(user_yaml,f)\n f.close()\n \n return os.path.join(user_yaml[\"location\"],'autoConfig.yaml'), random_id , user_yaml[\"problem_type\"]\n\n\n\n\ndef generate_project_manual_config_file(projectID,preprocessJSONFormData,Project21Database):\n \"\"\"\n \n \"\"\"\n # user_yaml=yaml.load(open(settings.CONFIG_PREPROCESS_YAML_FILE),Loader=SafeLoader)\n \n random_id=generate_random_id()\n preprocessJSONFormData[\"id\"]=random_id\n preprocessJSONFormData[\"raw_data_address\"]=get_raw_data_path(projectID,Project21Database)\n \n location=\"/\"\n random_id=generate_random_id()\n try:\n result_project=Project21Database.find_one(settings.DB_COLLECTION_PROJECT,{\"projectID\":projectID})\n result_project=serialiseDict(result_project)\n if result_project is not None:\n location=os.path.join(result_project[\"projectFolderPath\"],'run'+str(random_id))\n except:\n print(\"Unable to Update User's Project's Config File\")\n if(not os.path.exists(location)):\n os.makedirs(location)\n\n preprocessJSONFormData[\"location\"]=location\n with open(os.path.join(location,\"preprocess_config.yaml\"), \"w\") as f:\n yaml.dump(preprocessJSONFormData,f)\n f.close()\n \n return os.path.join(location,'preprocess_config.yaml'), random_id , result_project[\"projectType\"], location\n\ndef generate_project_timeseries_config_file(projectID,currentIDs,timeseriesFormData,Project21Database):\n user_yaml=yaml.load(open(settings.CONFIG_PREPROCESS_YAML_FILE),Loader=SafeLoader)\n\n random_id=generate_random_id()\n user_yaml[\"id\"]=random_id\n user_yaml[\"raw_data_address\"]=get_raw_data_path(projectID,Project21Database)\n user_yaml[\"target_column_name\"]=timeseriesFormData[\"target\"]\n user_yaml[\"date_index\"]=timeseriesFormData[\"dateColumn\"]\n user_yaml[\"frequency\"]=timeseriesFormData[\"frequency\"]\n \n try:\n result_project=Project21Database.find_one(settings.DB_COLLECTION_PROJECT,{\"projectID\":projectID})\n result_project=serialiseDict(result_project)\n if result_project is not None:\n user_yaml[\"location\"]=os.path.join(result_project[\"projectFolderPath\"],'run'+str(random_id))\n user_yaml[\"experimentname\"]=result_project[\"projectName\"]\n else:\n user_yaml[\"location\"]='/'\n user_yaml[\"experimentname\"]='default'\n except Exception as e:\n print(\"Unable to Update User's Project's Config File. An Error Occured: \",e)\n \n if(not os.path.exists(user_yaml[\"location\"])):\n os.makedirs(user_yaml[\"location\"])\n with open(os.path.join(user_yaml[\"location\"],\"preprocess_config.yaml\"), \"w\") as f:\n yaml.dump(user_yaml,f)\n f.close()\n \n return os.path.join(user_yaml[\"location\"],'preprocess_config.yaml'), user_yaml[\"location\"],random_id, result_project[\"projectType\"]","sub_path":"Backend/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"151313785","text":"from unittest2 import TestCase\nfrom describe import expect\n\nfrom exam.objects import noop\n\n\nclass TestNoOp(TestCase):\n\n def test_can_be_called_with_anything(self):\n noop()\n noop(1)\n noop(key='val')\n noop(1, key='val')\n noop(1, 2, 3, key='val')\n noop(1, 2, 3, key='val', another='thing')\n\n def test_returns_none(self):\n expect(noop()).to == None\n","sub_path":"tests/test_objects.py","file_name":"test_objects.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"507891780","text":"import time\nfrom typing import Tuple, List, Union, Dict, Counter\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch import optim, nn\nfrom torch.utils.data import DataLoader\n\nfrom classifiers.BaseClassifier import BaseClassifier, ClassificationResult, compute_classification_result\nfrom classifiers.config import Config\nfrom model.ProjectClassifier import ProjectClassifier\nfrom preprocessing.context_split import ContextSplit\nfrom util import ProcessedFolder\n\n\nclass NNClassifier(BaseClassifier):\n \"\"\"\n An implementation of PbNN classifier. For the code of the neural network part please see authorship_pipeline.model\n \"\"\"\n def __init__(self, config: Config, project_folder: ProcessedFolder, change_entities: pd.Series,\n change_to_time_bucket: Dict, min_max_count: Tuple[int, int], author_occurrences: Counter,\n context_splits: List[ContextSplit]):\n super(NNClassifier, self).__init__(config, project_folder, change_entities, change_to_time_bucket,\n min_max_count, author_occurrences, context_splits)\n\n def __sample_loaders(self, fold_ind: Union[int, Tuple[int, int]] = 0) -> Tuple[DataLoader, DataLoader]:\n \"\"\"\n Define training and testing data loaders for a given testing fold.\n \"\"\"\n train_dataset, test_dataset = self._split_train_test(self._loader, fold_ind, pad=True)\n train_loader = DataLoader(train_dataset, self.config.batch_size(), shuffle=True)\n test_loader = DataLoader(test_dataset, self.config.batch_size())\n return train_loader, test_loader\n\n def __train(self, train_loader, test_loaders, model, optimizer, loss_function, n_epochs, log_batches, batch_size,\n fold_ind, should_train):\n \"\"\"\n Train the model and report metrics for each of the testing datasets defined by test_loaders.\n \"\"\"\n print(\"Start training\")\n accuracies = [ClassificationResult(0, 0, 0, 0) for _ in range(len(test_loaders))]\n if not should_train:\n n_epochs = 1\n\n for epoch in range(n_epochs):\n print(\"Epoch #{}\".format(epoch + 1))\n model.train()\n if should_train:\n current_loss = 0\n start_time = time.time()\n for n_batch, sample in enumerate(train_loader):\n starts, paths, ends, labels = sample['starts'], sample['paths'], sample['ends'], sample['labels']\n optimizer.zero_grad()\n\n predictions = model((starts, paths, ends))\n loss = loss_function(predictions, labels)\n loss.backward()\n optimizer.step()\n\n current_loss += loss.item()\n if (n_batch + 1) % log_batches == 0:\n print(\"After {} batches: average loss {}\".format(n_batch + 1, current_loss / log_batches))\n print(f\"Throughput {int(log_batches * batch_size / (time.time() - start_time))} examples / sec\")\n current_loss = 0\n start_time = time.time()\n\n model.eval()\n with torch.no_grad():\n for i, test_loader in enumerate(test_loaders):\n total = len(test_loader.dataset)\n predictions = np.zeros(total)\n targets = np.zeros(total)\n cur = 0\n test_loss = 0.\n n_batches = 0\n for sample in test_loader:\n starts, paths, ends, labels = sample['starts'], sample['paths'], sample['ends'], sample[\n 'labels']\n batched_predictions = model((starts, paths, ends))\n\n test_loss += loss_function(batched_predictions, labels)\n n_batches += 1\n\n batched_predictions = np.argmax(batched_predictions, axis=1)\n batched_targets = labels\n predictions[cur:cur + len(batched_predictions)] = batched_predictions\n targets[cur:cur + len(batched_targets)] = batched_targets\n cur += len(batched_predictions)\n\n # print(predictions)\n # print(targets)\n print(\"average loss {}\".format(test_loss / n_batches))\n classification_result = compute_classification_result(targets, predictions, fold_ind)\n print(f\"classification results: {classification_result}\")\n accuracies[i] = max(accuracies[i], classification_result, key=lambda cl: cl.accuracy)\n # values, counts = np.unique(predictions, return_counts=True)\n # vc = [(c, v) for v, c in zip(values, counts)]\n # for cnt, val in sorted(vc):\n # print(cnt, val)\n\n print(\"Training completed\")\n return accuracies\n\n def __run_classifier(self, train_loader: DataLoader, test_loaders: Union[DataLoader, List[DataLoader]], fold_ind) \\\n -> Union[float, List[float]]:\n if isinstance(fold_ind, int) or isinstance(fold_ind, np.int64) or fold_ind[0] not in self.models:\n model = ProjectClassifier(self._loader.tokens().size,\n self._loader.paths().size,\n dim=self.config.hidden_dim(),\n n_classes=self._loader.n_classes())\n should_train = True\n else:\n model = self.models[fold_ind[0]]\n should_train = False\n\n optimizer = optim.Adam(model.parameters(), lr=self.config.learning_rate())\n loss_function = nn.CrossEntropyLoss()\n if type(test_loaders) is DataLoader:\n test_loaders = [test_loaders]\n # test_loaders.append(train_loader)\n accuracies = self.__train(train_loader, test_loaders, model, optimizer, loss_function,\n n_epochs=self.config.epochs(),\n log_batches=self.config.log_batches(),\n batch_size=self.config.batch_size(),\n fold_ind=fold_ind, should_train=should_train)\n\n if not isinstance(fold_ind, int) and not isinstance(fold_ind, np.int64) and fold_ind[0] not in self.models:\n self.models[fold_ind[0]] = model\n\n if len(test_loaders) == 1:\n return max(accuracies, key=lambda cl: cl.accuracy)\n else:\n return accuracies\n\n def run(self, fold_indices: Union[List[int], List[Tuple[int, int]]]) \\\n -> Tuple[float, float, List[ClassificationResult]]:\n \"\"\"\n Run experiments for all the testing datasets defined by fold_indices.\n \"\"\"\n print(\"Begin cross validation\")\n scores = []\n for fold_ind in fold_indices:\n # print(fold_ind)\n train_loader, test_loader = self.__sample_loaders(fold_ind)\n scores.append(self.__run_classifier(train_loader, test_loader, fold_ind))\n print(scores[-1])\n print(scores)\n mean = float(np.mean([score.accuracy for score in scores]))\n std = float(np.std([score.accuracy for score in scores]))\n return mean, std, scores\n","sub_path":"attribution/authorship_pipeline/classifiers/NNClassifier.py","file_name":"NNClassifier.py","file_ext":"py","file_size_in_byte":7387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"638111996","text":"#!/usr/bin/python\n\n# Copyright 2017 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\nimport logging\nimport unittest\nimport urlparse\nfrom retrying import retry\n\nimport google.cloud.logging\n\nimport test_util\n\n\nclass TestLogging(unittest.TestCase):\n\n def __init__(self, url, methodName='runTest'):\n self._url = urlparse.urljoin(url, test_util.LOGGING_ENDPOINT)\n unittest.TestCase.__init__(self)\n\n def runTest(self):\n logging.debug('Posting to endpoint: {0}'.format(self._url))\n\n payload = test_util.generate_logging_payload()\n if test_util.post(self._url, payload) != 0:\n return self.fail('Error encountered inside sample application!')\n\n client = google.cloud.logging.Client()\n log_name = payload.get('log_name')\n token = payload.get('token')\n\n logging.info('log name is {0}, '\n 'token is {1}'.format(log_name, token))\n\n project_id = test_util._project_id()\n FILTER = 'logName = projects/{0}/logs/' \\\n 'appengine.googleapis.com%2Fstdout'.format(project_id)\n\n self.assertTrue(self._read_log(client, log_name, token, FILTER),\n 'Log entry not found for posted token!')\n\n @retry(wait_fixed=4000, stop_max_attempt_number=8)\n def _read_log(self, client, log_name, token, filter):\n for entry in client.list_entries(filter_=filter):\n if token in entry.payload:\n logging.info('Token {0} found in '\n 'Stackdriver logs!'.format(token))\n return True\n raise Exception('Log entry not found for posted token!')\n","sub_path":"integration_tests/testsuite/test_logging.py","file_name":"test_logging.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"341080480","text":"# -*-coding:utf-8 -*-\nimport io\nimport sys\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options as ChromeOptions\nfrom selenium.webdriver.firefox.options import Options as FirefoxOptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n\nclass HttpHelper:\n # 自动化测试核心脚本\n def __init__(self, options, browser_type, path):\n options = self.get_default_options(options)\n\n if browser_type == 'chrome':\n chrome_options = ChromeOptions()\n if(options['hidden_ui']):\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n self.browser = webdriver.Chrome(chrome_options=chrome_options)\n elif browser_type == 'firefox':\n firefox_options = FirefoxOptions()\n if(options['hidden_ui']):\n firefox_options.set_headless()\n self.browser = webdriver.Firefox(firefox_options=firefox_options)\n elif browser_type == 'chrome360':\n chrome_options = ChromeOptions()\n chrome_options.binary_location = path['360']\n if(options['hidden_ui']):\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n self.browser = webdriver.Chrome(chrome_options=chrome_options)\n elif browser_type == 'ie':\n self.browser = webdriver.Ie()\n\n self.wait = WebDriverWait(self.browser, options['timeout'])\n\n # 获取默认配置\n def get_default_options(self, options):\n default_options = {\n 'hidden_ui': True, # 该值指示是否显示ui界面,默认不显示\n 'timeout': 100 # 该值指示超时时间,默认100毫秒\n }\n return dict(default_options, **options)\n\n # 访问页面\n def get(self, url):\n self.browser.get(url)\n\n # 获取dom元素\n def get_dom(self, xpath):\n return self.wait.until(EC.presence_of_element_located((By.XPATH, xpath)))\n\n # 获取浏览器\n def get_browser(self):\n return self.browser\n\n # 退出浏览器\n def quit(self):\n self.browser.quit()\n","sub_path":"lib/HttpHelper.py","file_name":"HttpHelper.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"190560693","text":"\n\"\"\"\nThis is a special file. It contains many script functions which\ndo not fit the normal work-flow of this package.\n\"\"\"\n\nimport pathlib\nimport numpy as np\n\nimport IfA_Smeargle.core as core\n\ndef script_special_create_tutorial_configuration_file(config):\n \"\"\" This function copies a tutorial configuration file into\n the current working directory. It serves to initiate the \n tutorials provided.\n\n Parameters\n ----------\n config : ConfigObj\n The configuration object that is to be used for this \n function.\n\n Returns\n -------\n None \n \"\"\"\n # There are no configuration parameters needed for this function.\n\n # In order to copy the configuration into the current working\n # directory, the directory path must be known.\n current_directory = pathlib.Path().absolute()\n\n # Copy the tutorial configuration into the current directory.\n config_path = core.config.copy_configuration_file(\n config_type='tutorial', destination=current_directory, \n file_name=None)\n\n # All done.\n return None\n\ndef script_special_list_scripts(config):\n \"\"\" This lists all of the scripts in alphabetical order in \n two columns.\n \n Parameters\n ----------\n config : ConfigObj\n The configuration object that is to be used for this \n function.\n\n Returns\n -------\n None \n \"\"\"\n\n # There are no real configuration parameters needed.\n pass\n\n # Obtain the list of all scripts.\n script_functions = core.runtime.get_script_functions()\n # Only the keys are needed.\n script_keys = list(script_functions.keys())\n # Sorting them as the script printing should be in alphabetical \n # order.\n sorted_script_keys = sorted(script_keys)\n n_keys = len(sorted_script_keys)\n max_length = len(max(sorted_script_keys, key=len))\n \n # Format the key list in the two columns, going across first\n # so the alphabetical list is spread across the two.\n printed_lines = []\n for evendex, odddex in zip(np.arange(0, n_keys, 2), \n np.arange(1, n_keys, 2)):\n temp_line = ' '.join([sorted_script_keys[evendex].ljust(max_length),\n sorted_script_keys[odddex].ljust(max_length)])\n printed_lines.append(temp_line)\n\n # Display the information as normal information. (Some fancy \n # formatting to help the eyes.)\n core.error.ifas_info(\"The list of all callable scripts are: \\n\"\n \"{hline} \\n\"\n \"{script_print}\"\n \"\\n\"\n .format(hline=''.join(['-' for __ in range(49)]),\n script_print='\\n'.join(printed_lines)))\n \n # All done.\n return None","sub_path":"special.py","file_name":"special.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"188308145","text":"#!/practice/Study_Test python\n# -*- coding: utf-8 -*-\n# @Time : 2019/1/9 21:18\n# @Author : yb.w\n# @File : douyu.py\nimport json\n\nimport requests\n\n\ndef get_json(url):\n response = requests.get(url)\n if response.status_code ==200:\n json_data = json.loads(response.text)\n return json_data\n return None\n\ndef parse_json(json_data):\n print(json_data)\n for i in json_data['data']['rl']:\n image_name = \"图片\\\\\"+ i['nn'] +\".jpg\"\n image_src = i['rs1']\n content = requests.get(image_src).content\n # print(\"正在抓取第 \"+i+\"张图片: \"+i['nn'])\n print(content)\n with open(image_name,'wb') as f:\n f.write(content)\n\n\n\n\n\nif __name__ == '__main__':\n url = 'https://www.douyu.com/gapi/rkc/directory/2_201/0'\n json_data = get_json(url)\n # print(json_data)\n parse_json(json_data)","sub_path":"StudyPacticePython/WebCrawler/斗鱼主播信息/douyu.py","file_name":"douyu.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"123979386","text":"from cv_utilities import Utilities as utils\r\nimport cv2\r\nimport os\r\nfrom PIL import Image\r\nimport pandas as pd\r\n\r\n\r\nclass ComputerVision:\r\n def __init__(self):\r\n self.utils = utils()\r\n\r\n def measure_object_dimension(self, image, scale = None, reference_scale = None, unit = 'um', save = False, path = None, resize_width=0, rotate_angle=0, blur=(1, 9), cannyMin=50, cannyMax=0, edge_iterations=1):\r\n firstImage = 0\r\n utils = self.utils\r\n\r\n\r\n #load the image, convert it to grayscale, and blur it slightly - review\r\n resized, blurred, area, filename, contours = utils.optimize_image(image, resize_width, rotate_angle, blur)\r\n\r\n # step I.2: perform edge detection, then perform a dilation + erotion to close gaps in between object edges\r\n edge = utils.detect_edge(blurred, cannyMin, cannyMax)\r\n\r\n # step I.3: find and sort objects (sort from left-to-right)\r\n # objs = utils.detect_and_sort_objects(edge)\r\n objs = contours\r\n\r\n # II. LOOP OVER THE OBJECTS IDENTIFIED\r\n data = []\r\n\r\n for idx, obj in enumerate(objs):\r\n # step II.1: compute the bounding box of the object and draw the box (rectangle)\r\n box, resized = utils.create_bounding_box(resized, obj)\r\n\r\n # step II.2: mark the corners of the box\r\n utils.mark_corners(box, resized)\r\n\r\n # step II.3: compute the midpoints and mark them\r\n tltrX, tltrY, blbrX, blbrY, tlblX, tlblY, trbrX, trbrY = utils.get_midpoints(box, resized)\r\n\r\n # step II.4: compute the Euclidean distance between the midpoints\r\n dA, dB = utils.get_distances(\r\n tltrX, tltrY, blbrX, blbrY, tlblX, tlblY, trbrX, trbrY)\r\n\r\n # step II.5: perform the calibration pixel to millimeters if the pixels per metric has not been initialized\r\n if scale is None: scale = reference_scale / dB # metric / pixel\r\n \r\n if dA * scale > 50 and dB * scale > 50:\r\n diamA, diamB = utils.get_dimensions(dA, dB, scale, resized, unit, tltrX, tltrY, trbrX, trbrY)\r\n \r\n # Get the filename only from the initial file path.\r\n file = os.path.basename(filename)\r\n # split text to get filename and ext separated\r\n (file, ext) = os.path.splitext(file) \r\n \r\n if save:\r\n name = file + \".png\"\r\n if path is None: \r\n cv2.imwrite(name, resized)\r\n else:\r\n n = path + name\r\n cv2.imwrite(n, resized)\r\n \r\n \r\n \r\n #name = file + \".png\"\r\n #cv2.imwrite(name, resized)\r\n\r\n data.append({'filename': file, 'diamA': diamA, 'diamB': diamB, 'area': area[idx]})\r\n\r\n\r\n df = pd.DataFrame(data)\r\n df.area = df.area * (scale ** 2)\r\n return df\r\n \r\n","sub_path":"inst/python/measure_dim.py","file_name":"measure_dim.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"606312260","text":"\"\"\" Read a plain text located in a Blob Container (Azure) \"\"\"\nimport json\nfrom azure.storage.blob import BlockBlobService\n\nclass ReadFile():\n \"\"\" Read a plain text located in a Blob Container (Azure) \"\"\"\n def __init__(cls):\n \"\"\" Constructor \"\"\"\n with open(\"config/config.json\",\"r\") as file:\n cls.config = json.load(file)\n print(cls.config['connection_string'])\n cls.block_blob_service = BlockBlobService(connection_string=cls.config['connection_string'])\n\nif __name__ == \"__main__\":\n ReadFile()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"564051267","text":"from sardana.macroserver.macro import Macro, Type, Hookable\nimport taurus\nFEAUTO_ATTR = \"BL13/CT/EPS-PLC-01/FE_AUTO\"\nFE_PSS_PERMIT = \"alba03:10000/expchan/id13ivu_machine_attributes/8/value\"\n\nclass feauto(Macro):\n \"\"\"This macro enables or disables the Front End Automatic opening mode\"\"\"\n\n param_def = [\n ['state', Type.String, '', '1/0 Yes/No' ]\n ]\n\n def run(self,state):\n _attr = taurus.Attribute(FEAUTO_ATTR)\n if state == '':\n self.output(\"FE Automatic mode is %d.\" % _attr.read().value)\n elif state == '1' or state.upper() == \"YES\":\n _attr.write(1)\n self.output(\"FE Automatic mode is set to %d.\" % _attr.read().value)\n elif state == '0' or state.upper() == \"NO\":\n _attr.write(0)\n self.output(\"FE Automatic mode is set to %d.\" % _attr.read().value)\n else:\n self.output(\"Error. FE state not valid. disabling\")\n _attr.write(0)\n\nclass fepss(Macro):\n\n \"\"\"This macro checks the permits of the PSS from the Machine to open the FE\"\"\"\n\n def run(self):\n _attr = taurus.Attribute(FE_PSS_PERMIT)\n self.output(\"FE PERMIT FROM THE PSS is %d.\" % _attr.read().value)\n\n\n","sub_path":"ALBA_BL13_XALOC_USER_MACROS/stdlocal.py","file_name":"stdlocal.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"453664268","text":"import time \nfrom opcua import Client \n\n\nurl = \"opc.tcp://anencounter.iptime.org:48400\" \n#url = \"opc.tcp://111.171.52.6:4840\"\n#url = \"opc.tcp://localhost:4840\"\n\nclient= Client(url) \nclient.connect() \nprint(\"Client Connected\") \n\ntry:\n while True:\n Temp = client.get_node(\"ns=2;i=2\")\n Temperature = Temp.get_value()\n print(Temperature)\n # Press = client.get_node(\"ns=2;i=3\")\n #Pressure = Press.get_value()\n #print(Pressure)\n # TIME = client.get_node(\"ns=2;i=4\")\n # Time = TIME.get_value()\n # print(Time)\n time.sleep(2)\n\nfinally:\n client.disconnect()\n","sub_path":"clienttest.py","file_name":"clienttest.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"437051663","text":"#coding: UTF-8\nfrom django.http import HttpResponseRedirect\nfrom abc import ABCMeta, abstractmethod, abstractproperty\nfrom django.forms.models import modelformset_factory\nfrom django.shortcuts import render\nfrom django.views.generic import ListView, DetailView\nfrom django.views.generic.edit import FormMixin\nfrom .models import Host, Group, Service\nfrom .forms import HostFormSet, GroupFormSet, ServiceFormSet, LoginShhForm\nfrom functions.functionsDb import *\nfrom functions.functionsSsh import *\nfrom functions.functionsWrite import *\nfrom functions.functionsRead import *\n\nhost_file = 'host_generated.cfg'\ngroups_file = 'hostgroups_generated.cfg'\nsergroups_file = 'hostgroups_service_generated.cfg'\nservices_file = 'service_generated.cfg'\n\n\ndef index(request):\n return render(request, 'index.html', {})\n\n\nclass ObjectListView(FormMixin, ListView):\n object_formset_name = 'objects_formset'\n\n def get_context_data(self, **kwargs):\n context = super(ObjectListView, self).get_context_data(**kwargs)\n context[self.object_formset_name] = self.get_formset()\n return context\n\n def post(self, request, *args, **kwargs):\n formset = self.get_formset(request.POST)\n if formset.is_valid():\n return self.form_valid(formset)\n else:\n return self.form_invalid(formset)\n\n def form_valid(self, formset):\n formset.save()\n return super(ObjectListView, self).form_valid(formset)\n\n def form_invalid(self, formset):\n self.object_list = self.get_queryset()\n context = super(ObjectListView, self).get_context_data()\n context['objects_formset'] = formset\n return self.render_to_response(context)\n\n\nclass HostListView(ObjectListView):\n model = Host\n context_object_name = 'hosts'\n template_name = 'hosts.html'\n success_url = '/hosts/'\n get_formset = HostFormSet\n\n\nclass GroupListView(ObjectListView):\n model = Group\n context_object_name = 'groups'\n template_name = 'groups.html'\n success_url = '/groups/'\n get_formset = GroupFormSet\n\nclass ServiceListView(ObjectListView):\n model = Service\n context_object_name = 'services'\n template_name = 'services.html'\n success_url = '/services/'\n get_formset = ServiceFormSet\n\n\ndef deleteHost(request, host_name):\n try:\n if host_name != \"\":\n Host.objects.get(name=host_name).delete();\n except:\n pass\n return render(request, \"base.html\")\n\n\ndef deleteGroup(request, group_name):\n try:\n if group_name != \"\":\n Group.objects.get(name=group_name).delete();\n except:\n pass\n return render(request, \"base.html\")\n\n\ndef deleteService(request, service_name):\n try:\n if service_name != \"\":\n Service.objects.get(name=service_name).delete();\n except:\n pass\n return render(request, \"base.html\")\n\n\ndef apply(request):\n log = {'stages': [], 'errors': []}\n if request.method == 'POST':\n if request.POST['login'] == \"\":\n return render(request, 'apply.json', {\n 'errorForm': 'Логин забыли вы'\n })\n if request.POST['secret'] == \"\":\n return render(request, 'apply.json', {\n 'errorForm': 'Пароль забыли вы'\n })\n user = {\n 'name': request.POST['login'],\n 'secret': request.POST['secret']\n }\n hosts = Host.objects.all()\n lines = getLinesHosts(hosts)\n log['stages'].append(\"Хосты\")\n log['errors'].append(\" \")\n if createFile(lines, host_file, log):\n cpConfigFiles(user, host_file, False, log)\n deleteFileConfig(host_file)\n groups = Group.objects.all()\n lines = getLinesGroups(groups)\n log['stages'].append(\"Группы\")\n log['errors'].append(\" \")\n if createFile(lines, groups_file, log):\n cpConfigFiles(user, groups_file, False, log)\n deleteFileConfig(groups_file)\n services = Service.objects.all()\n lines = getLinesServicesGroups(services)\n log['stages'].append(\"Сервис-Группы\")\n log['errors'].append(\" \")\n if createFile(lines, sergroups_file, log):\n cpConfigFiles(user, sergroups_file, False, log)\n deleteFileConfig(sergroups_file)\n lines = getLinesServices(services)\n log['stages'].append(\"Сервисы\")\n log['errors'].append(\" \")\n if createFile(lines, services_file, log):\n cpConfigFiles(user, services_file, False, log)\n deleteFileConfig(services_file)\n status, res = restartServerNagios(user, log)\n return render(request, 'apply.json', {'log': log})\n else:\n return render(request, 'apply.json', {\n 'errorConnection': 'Откуда в�� к нам зашли то?'\n })\n return render(request, 'apply.json')\n\n\ndef read(request):\n return render(request, 'read.html', {})\n\n\ndef readListFile(request):\n if request.method == 'POST':\n if request.POST['login'] == \"\":\n return render(request, 'read.json', {\n 'errorForm': 'Логин забыли вы'\n })\n if request.POST['secret'] == \"\":\n return render(request, 'read.json', {\n 'errorForm': 'Пароль забыли вы'\n })\n user = {\n 'name': request.POST['login'],\n 'secret': request.POST['secret']\n }\n log = {'stages': [], 'errors': []}\n log['stages'].append(\"Список файлов\")\n log['errors'].append(\" \")\n flag, data = lsConfigFiles(user, log)\n if(flag):\n filename_list = parceListOfFile(data)\n return render(request, \"list_file.json\", {\n \"data\": filename_list, \"log\": log\n })\n else:\n return render(request, \"list_file.json\", {\n \"error\": True, \"log\": log\n })\n else:\n return render(request, 'read.json', {\n 'errorConnection': 'Откуда вы к нам зашли то?'\n })\n return render(request, 'read.json')\n\n\n\ndef readConfs(request):\n if request.method == 'POST':\n if request.POST['login'] == \"\":\n return render(request, 'read.json', {\n 'errorForm': 'Логин забыли вы'\n })\n if request.POST['secret'] == \"\":\n return render(request, 'read.json', {\n 'errorForm': 'Пароль забыли вы'\n })\n user = {\n 'name': request.POST['login'],\n 'secret': request.POST['secret']\n }\n log = {'stages': [], 'errors': []}\n log['stages'].append(\"Парсинг файлов\")\n log['errors'].append(\" \")\n files = request.POST['filename'].split(\",\")\n data = []\n for filename in files:\n log['stages'].append(\"Парсинг \" + filename.encode(\"UTF-8\"))\n log['errors'].append(\"\")\n flag, res = catConfigFiles(user, filename, log)\n if(backupConfigFiles(user, filename, log)):\n removeConfigFiles(user, filename, log)\n if flag:\n data.extend(res)\n result, mass = parceData(data, log)\n if not result:\n return render(request, 'read.json', {\"log\": log})\n for concr in mass:\n if(concr[\"type\"] == \"host\"):\n addHostToBase(concr)\n elif(concr[\"type\"] == \"group\"):\n addGroupToBase(concr)\n elif(concr[\"type\"] == \"service\"):\n addServiceToBase(concr)\n for concr in mass:\n if(concr[\"type\"] == \"host\"):\n addParentHost(concr)\n elif(concr[\"type\"] == \"group\"):\n addMembersToGroup(concr)\n elif(concr[\"type\"] == \"service\"):\n addMembersToService(concr)\n return render(request, 'read.json', {\"log\": log})\n else:\n return render(request, 'read.json', {\n 'errorConnection': 'Откуда вы к нам зашли то?'\n })\n return render(request, 'read.json')\n","sub_path":"nagios_configurator/nagios_configurator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"254286340","text":"#!/usr/bin/env python3\n\n#\n# This file is part of LiteX-Boards.\n#\n# Copyright (c) 2021 Franck Jullien \n# SPDX-License-Identifier: BSD-2-Clause\n\nimport argparse\n\nfrom migen import *\nfrom migen.genlib.resetsync import AsyncResetSynchronizer\n\nfrom litex_boards.platforms import efinix_titanium_ti60_f225_dev_kit\n\nfrom litex.build.generic_platform import *\n\nfrom litex.soc.cores.clock import *\nfrom litex.soc.integration.soc_core import *\nfrom litex.soc.integration.builder import *\nfrom litex.soc.integration.soc import SoCRegion\n\nfrom litehyperbus.core.hyperbus import HyperRAM\n\n# CRG ----------------------------------------------------------------------------------------------\n\nclass _CRG(Module):\n def __init__(self, platform, sys_clk_freq):\n self.clock_domains.cd_sys = ClockDomain()\n\n # # #\n\n clk25 = platform.request(\"clk25\")\n rst_n = platform.request(\"user_btn\", 0)\n\n # PLL\n self.submodules.pll = pll = TITANIUMPLL(platform)\n self.comb += pll.reset.eq(~rst_n)\n pll.register_clkin(clk25, 25e6)\n # You can use CLKOUT0 only for clocks with a maximum frequency of 4x\n # (integer) of the reference clock. If all your system clocks do not fall within\n # this range, you should dedicate one unused clock for CLKOUT0.\n pll.create_clkout(None, 25e6)\n\n pll.create_clkout(self.cd_sys, sys_clk_freq, with_reset=True)\n\n# BaseSoC ------------------------------------------------------------------------------------------\n\nclass BaseSoC(SoCCore):\n def __init__(self, sys_clk_freq=int(200e6), with_spi_flash=False, with_hyperram=False, **kwargs):\n platform = efinix_titanium_ti60_f225_dev_kit.Platform()\n\n # SoCCore ----------------------------------------------------------------------------------\n SoCCore.__init__(self, platform, sys_clk_freq,\n ident = \"LiteX SoC on Efinix Titanium Ti60 F225 Dev Kit\",\n ident_version = True,\n **kwargs\n )\n\n # CRG --------------------------------------------------------------------------------------\n self.submodules.crg = _CRG(platform, sys_clk_freq)\n\n # SPI Flash --------------------------------------------------------------------------------\n if with_spi_flash:\n from litespi.modules import W25Q64JW\n from litespi.opcodes import SpiNorFlashOpCodes as Codes\n self.add_spi_flash(mode=\"1x\", module=W25Q64JW(Codes.READ_1_1_1), with_master=True)\n\n # HyperRAM ---------------------------------------------------------------------------------\n if with_hyperram:\n self.submodules.hyperram = HyperRAM(platform.request(\"hyperram\"), latency=7)\n self.bus.add_slave(\"main_ram\", slave=self.hyperram.bus, region=SoCRegion(origin=0x40000000, size=32*1024*1024))\n\n# Build --------------------------------------------------------------------------------------------\n\ndef main():\n parser = argparse.ArgumentParser(description=\"LiteX SoC on Efinix Titanium Ti60 F225 Dev Kit\")\n parser.add_argument(\"--build\", action=\"store_true\", help=\"Build bitstream.\")\n parser.add_argument(\"--load\", action=\"store_true\", help=\"Load bitstream.\")\n parser.add_argument(\"--flash\", action=\"store_true\", help=\"Flash bitstream.\")\n parser.add_argument(\"--sys-clk-freq\", default=200e6, help=\"System clock frequency.\")\n parser.add_argument(\"--with-spi-flash\", action=\"store_true\", help=\"Enable SPI Flash (MMAPed).\")\n parser.add_argument(\"--with-hyperram\", action=\"store_true\", help=\"Enable HyperRAM.\")\n builder_args(parser)\n soc_core_args(parser)\n args = parser.parse_args()\n\n soc = BaseSoC(\n sys_clk_freq = int(float(args.sys_clk_freq)),\n with_spi_flash = args.with_spi_flash,\n with_hyperram = args.with_hyperram,\n **soc_core_argdict(args))\n builder = Builder(soc, **builder_argdict(args))\n builder.build(run=args.build)\n\n if args.load:\n prog = soc.platform.create_programmer()\n prog.load_bitstream(os.path.join(builder.gateware_dir, f\"{soc.build_name}.bit\"))\n\n if args.flash:\n from litex.build.openfpgaloader import OpenFPGALoader\n prog = OpenFPGALoader(\"titanium_ti60_f225\")\n prog.flash(0, os.path.join(builder.gateware_dir, f\"{soc.build_name}.hex\"))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"litex_boards/targets/efinix_titanium_ti60_f225_dev_kit.py","file_name":"efinix_titanium_ti60_f225_dev_kit.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"207134322","text":"import pymongo\nfrom pymongo import MongoClient\nimport csv\nimport json\nimport pandas as pd\nimport sys\nfrom config import FilesConfig\n\nclient = MongoClient(\"localhost\", 27017, username=\"Ganesh\", password=\"Siren@123\",)\ndb = client[\"Siren\"]\n# collection_name = \"Information_Security\"\ndb_cm = db[\"Information_Security\"]\nurls = []\n\n\ndef insertion():\n csvfile = open(FilesConfig.csv_file_name + \"Urls.csv\", \"r\")\n data = pd.read_csv(csvfile)\n data_json = json.loads(data.to_json(orient=\"records\"))\n db_cm.insert_many(data_json)\n\n\ndef update_hash():\n with open(\"Urls.csv\") as csv_file:\n csv_data = csv.reader(csv_file)\n for row in csv_data:\n url = row[2]\n url = str(url)\n hash_x = row[5]\n myquery = {\"URLs\": url}\n newvalues = {\"$set\": {\"Flag\": 1, \"Hash Value\": hash_x}}\n db_cm.update_one(myquery, newvalues)\n\n\ndef sno():\n sno = db_cm.find().sort(\"Sno\", -1).limit(1)\n for x in sno:\n first, second, *_ = x.values()\n return second\n\n\ndef sorting_ip():\n flag = {\"Flag\": 0}\n mydoc = db_cm.find(flag, sort=[(\"IP Address\", -1)])\n for x in mydoc:\n id_val, sno, pid, url, *_ = x.values()\n urls.append(url)\n return urls\n\n\ndef seed_url_fetch():\n flag = {\"Flag\": 0}\n mydoc = db_cm.find_one(flag, sort=[(\"IP Address\", -1)])\n if mydoc is None:\n return None\n else:\n id_val, sno, pid, url, *_ = mydoc.values()\n return URL\n\n","sub_path":"mongo_db.py","file_name":"mongo_db.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"146297572","text":"#coding: utf-8\n\n# 処理概要 「着順の分類分析」\n# 機能名 「着順の分類(4割以内かどうか分析」\n# 変更日 2017/10/21\n'''\nランダムフォレストの実行python\n\n'''\n\n##---------------------------\n## ディープラーニングの雛形\n##---------------------------\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets\nimport numpy as np\nimport tensorflow as tf\nimport os\nimport sys\nimport configparser\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\nimport sklearn.cross_validation as crv\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.datasets import load_iris\n\n\n# main処理\ndef main():\n # 環境変数を取得する。\n homeDir = os.environ[\"APPMONEYTRADE\"]\n\n # log用の文字列準備\n pid = os.path.basename(__file__)[0:4] # 機能IDの取得\n\n # 1時的に環境変数を追加する。\n sys.path.append(homeDir)\n from util import Util\n from util import JsonParse\n from bitflyer import BitflyerApi_STRE\n from dataBaseAccess import Dao\n from service import DTMDataMining\n from service import MASSMailSendService\n from service import TradeDecision\n\n # utilクラスのオブジェクト取得\n utilClass = Util.Util(pid)\n\n # daoクラスのオブジェクトを取得する。\n dao = Dao.Dao(pid)\n # utilクラス、propatiesファイル、DBアクセスクラスまでのpathを取得する。\n condigPath = homeDir + 'conf'\n\n # configファイルから情報を抜き出す.\n inifile = configparser.ConfigParser()\n inifile.read(condigPath + '/config.ini', 'UTF-8')\n\n # path用の辞書を取得\n pathdict = getpath('')\n\n # ハイパーパラメータ\n data_num = 10000\n result_column = 142\n kensho_num = 10000\n n_in = 0\n n_out = 0\n \n # DBより学習データを取得する。\n where = [\"WHERE DATA_MINING_RESULT_T.DATA_TIME >= '201704010000' AND DATA_MINING_RESULT_T.DATA_TIME < '2017070100000'\"]\n dataList = dao.selectQuery(where,'machinelearn')\n\n # 各パラメータをの配列を初期化する.\n x_predate = []\n y_predate = []\n\n # dict\n dataDict = {}\n\n # レースID毎に処理をする。\n for datainfo in dataList:\n\n # 格納しない番号を列強する。\n ifList = [0,1,11,41,42,43,44,45,55,56,57,58,59,60,75,90,105]\n # 格納する番号\n inlist = [10,12,13,14,15,16,17,21,22,23,28,29,30,40,52,53,54,61,62,63,64,65,66,74,76,77,78,79,80,81,82,88,89,91,92,93,94,95,96,103,104,106,107,108,109,110,111,112,118]\n\n # デバッグ\n input_num = 0\n\n # 初期化\n paramlist = []\n resultlist = []\n\n # skipFlg\n skipFlg = 0\n\n # テストデータを格納する。\n for i in range(len(datainfo)):\n\n # 答えデータを取得する。ただし、答えデータが 9 の場合は格納しない\n if result_column == i and datainfo[result_column] == 9:\n skipFlg = 1\n continue\n elif result_column == i:\n resultlist.append(datainfo[result_column])\n \n # 学習データ格納\n if i not in ifList and i <= 119 and i in inlist:\n dataDict[len(paramlist) + 1] = i\n paramlist.append(datainfo[i])\n \n\n if skipFlg == 1:\n continue\n \n x_predate.append(paramlist)\n y_predate.append(resultlist[0])\n\n input_num = len(paramlist) \n\n # デバッグ\n\n\n # DNNで読み取れるデータに変換\n X_train = np.array(x_predate)\n Y_train = np.array(y_predate)\n \n\n # RFTで予想\n clf = RandomForestClassifier(n_estimators=350, random_state=0)\n clf.fit(X_train, Y_train)\n \n#########################################################################################################\n#########################################################################################################\n#########################################################################################################\n where = [\"WHERE DATA_MINING_RESULT_T.DATA_TIME >= '201707010000' AND DATA_MINING_RESULT_T.DATA_TIME < '2017080100000'\"]\n dataList = dao.selectQuery(where,'machinelearn')\n\n # 各パラメータをの配列を初期化する.\n x_predate = []\n y_predate = []\n\n # デバッグ用\n countA = 0\n countB = 0\n\n # レースID毎に処理をする。\n for datainfo in dataList:\n\n # 格納しない番号を列強する。\n ifList = [0,1,11,41,42,43,44,45,55,56,57,58,59,60,75,90,105]\n # デバッグ\n input_num = 0\n\n # 初期化\n paramlist = []\n resultlist = []\n\n # skipFlg\n skipFlg = 0\n\n # テストデータを格納する。\n for i in range(len(datainfo)):\n\n # 答えデータを取得する。ただし、答えデータが 9 の場合は格納しない\n if result_column == i and datainfo[result_column] == 9:\n skipFlg = 1\n continue\n elif result_column == i:\n if datainfo[result_column] == 1:\n countA = countA + 1\n countB = countB + 1\n resultlist.append(datainfo[result_column])\n\n # 学習データ格納\n if i not in ifList and i <= 119 and i in inlist:\n paramlist.append(datainfo[i])\n\n\n if skipFlg == 1:\n continue\n\n x_predate.append(paramlist)\n y_predate.append(resultlist[0])\n\n input_num = len(paramlist)\n\n\n # DNNで読み取れるデータに変換\n X_test = np.array(x_predate)\n Y_test = np.array(y_predate)\n\n y_predict = clf.predict(X_test)\n print(accuracy_score(Y_test, y_predict))\n\n # 特徴量の重要度\n feature = clf.feature_importances_ \n \n # デバッグ\n print('countA:' + str(countA))\n print('countB:' + str(countB))\n\n # \n for i in range(len(feature)):\n if feature[i] > 0.009:\n print(str(dataDict[i]) + '/' + pathdict[dataDict[i]] + ':' + str(feature[i]))\n\n print(feature)\n\n\n\ndef getpath(oath):\n dict = {}\n dict[0] = 'DATA_TIME'\n dict[1] = 'WHAT_DAY'\n dict[2] = 'DAY_MONDAY'\n dict[3] = 'DAY_TUESDAY'\n dict[4] = 'DAY_WEDNESDAY'\n dict[5] = 'DAY_THURSDAY'\n dict[6] = 'DAY_FRIDAY'\n dict[7] = 'DAY_SATURDAY'\n dict[8] = 'DAY_SUNDAY'\n dict[9] = 'WEEK_DAY'\n dict[10] = 'DAY_OF_TIME'\n dict[11] = 'FINAL_TRANS_PRICE'\n dict[12] = 'FTP_DIS_1MINUTE'\n dict[13] = 'FTP_DIS_2MINUTES'\n dict[14] = 'FTP_DIS_3MINUTES'\n dict[15] = 'FTP_DIS_4MINUTES'\n dict[16] = 'FTP_DIS_5MINUTES'\n dict[17] = 'FTP_DIS_6MINUTES'\n dict[18] = 'FTP_DIS_7MINUTES'\n dict[19] = 'FTP_DIS_8MINUTES'\n dict[20] = 'FTP_DIS_9MINUTES'\n dict[21] = 'FTP_DIS_10MINUTES'\n dict[22] = 'FTP_DIS_30MINUTES'\n dict[23] = 'FTP_DIS_60MINUTES'\n dict[24] = 'FTP_DIS_2HOURS'\n dict[25] = 'FTP_DIS_3HOURS'\n dict[26] = 'FTP_DIS_4HOURS'\n dict[27] = 'FTP_DIS_5HOURS'\n dict[28] = 'FTP_DIS_6HOURS'\n dict[29] = 'FTP_DIS_12HOURS'\n dict[30] = 'FTP_DIS_18HOURS'\n dict[31] = 'FTP_DIS_24HOURS'\n dict[32] = 'FTP_DIS_10M_HIGH'\n dict[33] = 'FTP_DIS_1H_HIGH'\n dict[34] = 'FTP_DIS_2H_HIGH'\n dict[35] = 'FTP_DIS_3H_HIGH'\n dict[36] = 'FTP_DIS_4H_HIGH'\n dict[37] = 'FTP_DIS_5H_HIGH'\n dict[38] = 'FTP_DIS_6H_HIGH'\n dict[39] = 'FTP_DIS_12H_HIGH'\n dict[40] = 'FTP_DIS_24H_HIGH'\n dict[41] = 'FTP_DIS_2D_HIGH'\n dict[42] = 'FTP_DIS_4D_HIGH'\n dict[43] = 'FTP_DIS_7D_HIGH'\n dict[44] = 'FTP_DIS_14D_HIGH'\n dict[45] = 'FTP_DIS_28D_HIGH'\n dict[46] = 'FTP_DIS_10M_LOW'\n dict[47] = 'FTP_DIS_1H_LOW'\n dict[48] = 'FTP_DIS_2H_LOW'\n dict[49] = 'FTP_DIS_3H_LOW'\n dict[50] = 'FTP_DIS_4H_LOW'\n dict[51] = 'FTP_DIS_5H_LOW'\n dict[52] = 'FTP_DIS_6H_LOW'\n dict[53] = 'FTP_DIS_12H_LOW'\n dict[54] = 'FTP_DIS_24H_LOW'\n dict[55] = 'FTP_DIS_2D_LOW'\n dict[56] = 'FTP_DIS_4D_LOW'\n dict[57] = 'FTP_DIS_7D_LOW'\n dict[58] = 'FTP_DIS_14D_LOW'\n dict[59] = 'FTP_DIS_28D_LOW'\n dict[60] = 'FINAL_SELL_COUNT'\n dict[61] = 'FSC_SUMIN_1MINUTE'\n dict[62] = 'FSC_SUMIN_2MINUTES'\n dict[63] = 'FSC_SUMIN_3MINUTES'\n dict[64] = 'FSC_SUMIN_4MINUTES'\n dict[65] = 'FSC_SUMIN_5MINUTES'\n dict[66] = 'FSC_SUMIN_10MINUTES'\n dict[67] = 'FSC_SUMIN_60MINUTES'\n dict[68] = 'FSC_SUMIN_2HOURS'\n dict[69] = 'FSC_SUMIN_3HOURS'\n dict[70] = 'FSC_SUMIN_4HOURS'\n dict[71] = 'FSC_SUMIN_5HOURS'\n dict[72] = 'FSC_SUMIN_6HOURS'\n dict[73] = 'FSC_SUMIN_12HOURS'\n dict[74] = 'FSC_SUMIN_24HOURS'\n dict[75] = 'FINAL_SELL_AMMOUNT'\n dict[76] = 'FSA_SUMIN_1MINUTE'\n dict[77] = 'FSA_SUMIN_2MINUTES'\n dict[78] = 'FSA_SUMIN_3MINUTES'\n dict[79] = 'FSA_SUMIN_4MINUTES'\n dict[80] = 'FSA_SUMIN_5MINUTES'\n dict[81] = 'FSA_SUMIN_10MINUTES'\n dict[82] = 'FSA_SUMIN_60MINUTES'\n dict[83] = 'FSA_SUMIN_2HOURS'\n dict[84] = 'FSA_SUMIN_3HOURS'\n dict[85] = 'FSA_SUMIN_4HOURS'\n dict[86] = 'FSA_SUMIN_5HOURS'\n dict[87] = 'FSA_SUMIN_6HOURS'\n dict[88] = 'FSA_SUMIN_12HOURS'\n dict[89] = 'FSA_SUMIN_24HOURS'\n dict[90] = 'FINAL_BUY_COUNT'\n dict[91] = 'FBC_SUMIN_1MINUTE'\n dict[92] = 'FBC_SUMIN_2MINUTES'\n dict[93] = 'FBC_SUMIN_3MINUTES'\n dict[94] = 'FBC_SUMIN_4MINUTES'\n dict[95] = 'FBC_SUMIN_5MINUTES'\n dict[96] = 'FBC_SUMIN_10MINUTES'\n dict[97] = 'FBC_SUMIN_60MINUTES'\n dict[98] = 'FBC_SUMIN_2HOURS'\n dict[99] = 'FBC_SUMIN_3HOURS'\n dict[100] = 'FBC_SUMIN_4HOURS'\n dict[101] = 'FBC_SUMIN_5HOURS'\n dict[102] = 'FBC_SUMIN_6HOURS'\n dict[103] = 'FBC_SUMIN_12HOURS'\n dict[104] = 'FBC_SUMIN_24HOURS'\n dict[105] = 'FINAL_BUY_AMMOUNT'\n dict[106] = 'FBA_SUMIN_1MINUTE'\n dict[107] = 'FBA_SUMIN_2MINUTES'\n dict[108] = 'FBA_SUMIN_3MINUTES'\n dict[109] = 'FBA_SUMIN_4MINUTES'\n dict[110] = 'FBA_SUMIN_5MINUTES'\n dict[111] = 'FBA_SUMIN_10MINUTES'\n dict[112] = 'FBA_SUMIN_60MINUTES'\n dict[113] = 'FBA_SUMIN_2HOURS'\n dict[114] = 'FBA_SUMIN_3HOURS'\n dict[115] = 'FBA_SUMIN_4HOURS'\n dict[116] = 'FBA_SUMIN_5HOURS'\n dict[117] = 'FBA_SUMIN_6HOURS'\n dict[118] = 'FBA_SUMIN_12HOURS'\n dict[119] = 'FBA_SUMIN_24HOURS'\n dict[120] = 'FTP_DIS_1MINUTE'\n dict[121] = 'FTP_DIS_2MINUTE'\n dict[122] = 'FTP_DIS_3MINUTE'\n dict[123] = 'FTP_DIS_4MINUTE'\n dict[124] = 'FTP_DIS_5MINUTE'\n dict[125] = 'FTP_DIS_6MINUTE'\n dict[126] = 'FTP_DIS_7MINUTE'\n dict[127] = 'FTP_DIS_8MINUTE'\n dict[128] = 'FTP_DIS_9MINUTE'\n dict[129] = 'FTP_DIS_10MINUTE'\n dict[130] = 'FTP_DIS_15MINUTE'\n dict[131] = 'FTP_DIS_20MINUTE'\n dict[132] = 'FTP_DIS_30MINUTE'\n dict[133] = 'FTP_DIS_60MINUTE'\n dict[134] = 'FTP_DIS_2HOUR'\n dict[135] = 'FTP_DIS_3HOUR'\n dict[136] = 'FTP_DIS_4HOUR'\n dict[137] = 'FTP_DIS_5HOUR'\n dict[138] = 'FTP_DIS_6HOUR'\n dict[139] = 'FTP_DIS_12HOUR'\n dict[140] = 'FTP_DIS_18HOUR'\n dict[141] = 'FTP_DIS_24HOUR'\n dict[142] = 'FLG_UPDOWN_1MINUTE'\n dict[143] = 'FLG_UPDOWN_2MINUTE'\n dict[144] = 'FLG_UPDOWN_3MINUTE'\n dict[145] = 'FLG_UPDOWN_4MINUTE'\n dict[146] = 'FLG_UPDOWN_5MINUTE'\n dict[147] = 'FLG_UPDOWN_6MINUTE'\n dict[148] = 'FLG_UPDOWN_7MINUTE'\n dict[149] = 'FLG_UPDOWN_8MINUTE'\n dict[150] = 'FLG_UPDOWN_9MINUTE'\n dict[151] = 'FLG_UPDOWN_10MINUTE'\n dict[152] = 'FLG_UPDOWN_15MINUTE'\n dict[153] = 'FLG_UPDOWN_20MINUTE'\n dict[154] = 'FLG_UPDOWN_30MINUTE'\n dict[155] = 'FLG_UPDOWN_60MINUTE'\n dict[156] = 'FLG_UPDOWN_2HOUR'\n dict[157] = 'FLG_UPDOWN_3HOUR'\n dict[158] = 'FLG_UPDOWN_4HOUR'\n dict[159] = 'FLG_UPDOWN_5HOUR'\n dict[160] = 'FLG_UPDOWN_6HOUR'\n dict[161] = 'FLG_UPDOWN_12HOUR'\n dict[162] = 'FLG_UPDOWN_18HOUR'\n dict[163] = 'FLG_UPDOWN_24HOUR'\n dict[164] = 'LOW_5MINUTE'\n dict[165] = 'LOW_10MINUTE'\n dict[166] = 'LOW_15MINUTE'\n dict[167] = 'LOW_20MINUTE'\n dict[168] = 'LOW_30MINUTE'\n dict[169] = 'LOW_60MINUTE'\n dict[170] = 'LOW_2HOUR'\n dict[171] = 'LOW_3HOUR'\n dict[172] = 'LOW_4HOUR'\n dict[173] = 'LOW_5HOUR'\n dict[174] = 'LOW_6HOUR'\n dict[175] = 'LOW_12HOUR'\n dict[176] = 'LOW_18HOUR'\n dict[177] = 'LOW_24HOUR'\n dict[178] = 'HIGH_5MINUTE'\n dict[179] = 'HIGH_10MINUTE'\n dict[180] = 'HIGH_15MINUTE'\n dict[181] = 'HIGH_20MINUTE'\n dict[182] = 'HIGH_30MINUTE'\n dict[183] = 'HIGH_60MINUTE'\n dict[184] = 'HIGH_2HOUR'\n dict[185] = 'HIGH_3HOUR'\n dict[186] = 'HIGH_4HOUR'\n dict[187] = 'HIGH_5HOUR'\n dict[188] = 'HIGH_6HOUR'\n dict[189] = 'HIGH_12HOUR'\n dict[190] = 'HIGH_18HOUR'\n dict[191] = 'HIGH_24HOUR'\n return dict\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"source/batch/machinelearn/sigmoid_RFT/calc_sigmoid.py","file_name":"calc_sigmoid.py","file_ext":"py","file_size_in_byte":12732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"187073630","text":"\n\ndef get_interfaces_dict(self):\n ' get interfaces attributes dict.'\n intfs_info = dict()\n conf_str = CE_NC_GET_INTFS\n recv_xml = get_nc_config(self.module, conf_str)\n if ('' in recv_xml):\n return intfs_info\n xml_str = recv_xml.replace('\\r', '').replace('\\n', '').replace('xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"', '').replace('xmlns=\"http://www.huawei.com/netconf/vrp\"', '')\n root = ElementTree.fromstring(xml_str)\n intfs = root.findall('ifm/interfaces/')\n if intfs:\n for intf in intfs:\n intf_type = intf.find('ifPhyType').text.lower()\n if intf_type:\n if (not intfs_info.get(intf_type)):\n intfs_info[intf_type] = list()\n intf_info = dict()\n for tmp in intf:\n intf_info[tmp.tag] = tmp.text\n intfs_info[intf_type].append(intf_info)\n return intfs_info\n","sub_path":"Data Set/bug-fixing-2/07a598089a454cc3fa040849ae04559bc52c144e--bug.py","file_name":"07a598089a454cc3fa040849ae04559bc52c144e--bug.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"437698060","text":"import tcod as libtcod\r\nfrom random_utils import roll_dice, dnd_bonus_calc\r\nfrom game_messages import Message\r\nfrom math import floor\r\n\r\n\r\nclass Fighter:\r\n def __init__(self, current_hp, max_hp, damage_dice, damage_sides, strength, dexterity, vitality, intellect,\r\n perception, armour, xp=0, level=1, dodges=False):\r\n self.base_max_hp = max_hp\r\n self.current_hp = current_hp\r\n self.damage_dice = damage_dice\r\n self.damage_sides = damage_sides\r\n self.base_strength = strength\r\n self.base_dexterity = dexterity\r\n self.base_vitality = vitality\r\n self.base_intellect = intellect\r\n self.base_perception = perception\r\n self.base_armour = armour\r\n self.xp = xp\r\n self.level = level\r\n self.dodges = dodges\r\n\r\n @property\r\n def max_hp(self):\r\n bonus = 0\r\n\r\n return self.base_max_hp + bonus\r\n\r\n @property\r\n def damage(self):\r\n if self.owner and self.owner.equipment:\r\n damage = roll_dice(self.owner.equipment.damage_dice, self.owner.equipment.damage_sides)\r\n else:\r\n damage = roll_dice(self.damage_dice, self.damage_sides)\r\n\r\n return damage\r\n\r\n @property\r\n def crit_damage(self):\r\n if self.owner and self.owner.equipment:\r\n damage = roll_dice(2*self.owner.equipment.damage_dice, self.owner.equipment.damage_sides)\r\n else:\r\n damage = roll_dice(2*self.damage_dice, self.damage_sides)\r\n\r\n return damage\r\n\r\n @property\r\n def strength_modifier(self):\r\n bonus = 0\r\n if self.owner and self.owner.equipment:\r\n bonus += self.owner.equipment.strength_bonus\r\n\r\n strength_bonus = dnd_bonus_calc(self.base_strength)\r\n\r\n return strength_bonus + bonus\r\n\r\n @property\r\n def dexterity_modifier(self):\r\n bonus = 0\r\n if self.owner and self.owner.equipment:\r\n bonus += self.owner.equipment.dexterity_bonus\r\n\r\n dexterity_bonus = dnd_bonus_calc(self.base_dexterity)\r\n\r\n return dexterity_bonus + bonus\r\n\r\n @property\r\n def vitality_modifier(self):\r\n bonus = 0\r\n if self.owner and self.owner.equipment:\r\n bonus += self.owner.equipment.vitality_bonus\r\n\r\n vitality_bonus = dnd_bonus_calc(self.base_vitality)\r\n\r\n return vitality_bonus + bonus\r\n\r\n @property\r\n def intellect_modifier(self):\r\n bonus = 0\r\n if self.owner and self.owner.equipment:\r\n bonus += self.owner.equipment.intellect_bonus\r\n\r\n intellect_bonus = dnd_bonus_calc(self.base_intellect)\r\n\r\n return intellect_bonus + bonus\r\n\r\n @property\r\n def perception_modifier(self):\r\n bonus = 0\r\n if self.owner and self.owner.equipment:\r\n bonus += self.owner.equipment.perception_bonus\r\n\r\n perception_bonus = dnd_bonus_calc(self.base_perception)\r\n\r\n return perception_bonus + bonus\r\n\r\n @property\r\n def armour_total(self):\r\n bonus = 0\r\n if self.owner and self.owner.equipment:\r\n bonus += self.owner.equipment.armour_bonus\r\n\r\n return self.base_armour + bonus\r\n\r\n def take_damage(self, amount):\r\n results = []\r\n\r\n self.current_hp -= amount\r\n if self.current_hp <= 0:\r\n self.current_hp = 0\r\n results.append({'dead': self.owner, 'xp': self.xp})\r\n return results\r\n\r\n def heal(self, amount):\r\n self.current_hp += amount\r\n if self.current_hp > self.max_hp:\r\n self.current_hp = self.max_hp\r\n\r\n def attack(self, target):\r\n results = []\r\n damage = None\r\n crit = False\r\n crit_chance = 0.05 # Critical hit chance in %\r\n max_crit_chance = 0.25 # Define max chance to stop overflows!\r\n\r\n # Roll to see if hit\r\n attack_roll = roll_dice(1, 20) + self.dexterity_modifier\r\n if target.fighter.dodges:\r\n dodge_roll = roll_dice(1, 20) + target.fighter.dexterity_modifier\r\n else:\r\n dodge_roll = 0\r\n\r\n if attack_roll > dodge_roll: # Attack hits\r\n # Calculate strength-weighted damage roll\r\n damage_roll = self.damage + self.strength_modifier\r\n if target.fighter.armour_total > 0:\r\n defence_roll = roll_dice(1, target.fighter.armour_total)\r\n else:\r\n defence_roll = 0\r\n\r\n # Check if entity penetrates target's armour\r\n penetration_int = abs(damage_roll - defence_roll)\r\n if (damage_roll - defence_roll) > 0:\r\n\r\n # Calculate modified (positive) crit chance\r\n while penetration_int > 0 and crit_chance <= max_crit_chance:\r\n crit_chance += 0.01\r\n penetration_int -= 1\r\n\r\n # Check if crit\r\n if roll_dice(1, floor(1/crit_chance)) == floor(1/crit_chance):\r\n crit = True\r\n damage = self.crit_damage - defence_roll\r\n else:\r\n damage = self.damage - defence_roll\r\n\r\n # Crits can penetrate otherwise impervious armour!\r\n elif (damage_roll - defence_roll) <= 0:\r\n\r\n # Calculate modified (negative) crit chance\r\n while penetration_int > 0 and crit_chance > 0:\r\n crit_chance -= 0.01\r\n penetration_int -= 1\r\n\r\n # Check if crit\r\n if crit_chance <= 0:\r\n damage = 0\r\n else:\r\n if roll_dice(1, floor(1 / crit_chance)) == floor(1 / crit_chance):\r\n crit = True\r\n damage = self.crit_damage - defence_roll\r\n else:\r\n damage = 0\r\n\r\n # Check for damage and display chat messages\r\n if damage > 0:\r\n if crit:\r\n results.append({'message': Message('{0} crits {1} for {2} damage.'.\r\n format(self.owner.name.capitalize(), target.name,\r\n str(damage)), libtcod.light_red)})\r\n results.extend(target.fighter.take_damage(damage))\r\n else:\r\n results.append({'message': Message('{0} attacks {1} for {2} damage.'.\r\n format(self.owner.name.capitalize(), target.name, str(damage)), libtcod.white)})\r\n results.extend(target.fighter.take_damage(damage))\r\n # Debug to see enemy HP\r\n # if target.name == 'Risen Sacrifice':\r\n # results.append({'message': Message('{0} has hit {1} points left.'.format(\r\n # target.name.capitalize(), target.fighter.current_hp), libtcod.orange)})\r\n else:\r\n results.append({'message': Message('{0} attacks {1} but does no damage.'.\r\n format(self.owner.name.capitalize(), target.name),\r\n libtcod.grey)})\r\n else:\r\n results.append({'message': Message('{0} attacks {1} and misses. ([{2} vs. {3}])'.format(\r\n self.owner.name.capitalize(), target.name, attack_roll, dodge_roll), libtcod.grey)})\r\n\r\n return results\r\n","sub_path":"fighter.py","file_name":"fighter.py","file_ext":"py","file_size_in_byte":7398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"249734640","text":"from queue import Queue\n\n\nclass Node:\n def __init__(self, data=None):\n self.data = data\n self.left = None\n self.right = None\n\n\ndef inorder(node, result):\n if not node:\n return\n inorder(node.left, result)\n result.append(node.data)\n inorder(node.right, result)\n\n\ndef preorder(node, result):\n if not node:\n return\n result.append(node.data)\n preorder(node.left, result)\n preorder(node.right, result)\n\n\ndef postorder(node, result):\n if not node:\n return\n postorder(node.left, result)\n postorder(node.right, result)\n result.append(node.data)\n\n\ndef level_order(node, result):\n if not node:\n return\n q = Queue()\n q.put(node)\n while not q.empty():\n temp_node = q.get()\n result.append(temp_node.data)\n if temp_node.left:\n q.put(temp_node.left)\n if temp_node.right:\n q.put(temp_node.right)\n\n\ndef reverse_level_order(node):\n if not node:\n return False\n q = Queue()\n s = []\n q.put(node)\n while not q.empty():\n temp_node = q.get()\n if temp_node.left:\n q.put(temp_node.left)\n if temp_node.right:\n q.put(temp_node.right)\n s.insert(0, temp_node)\n while len(s) > 0:\n print(s.pop(0).data)\n\n\ndef find_max_node(node):\n max_data = float(\"-infinity\")\n if not node:\n return max_data\n if node.data > max_data:\n max_data = node.data\n find_max_node(node.left)\n find_max_node(node.right)\n return max_data\n\n\ndef find(node, val):\n if not node:\n return False\n if node.data == val:\n return True\n else:\n temp = find(node.left, val)\n if temp:\n return temp\n else:\n return find(node.right, val)\n\n\ndef find_size(node):\n if not node:\n return 0\n return find_size(node.left) + find_size(node.right) + 1\n\n\ndef find_depth(node):\n if not node:\n return 0\n return max(find_depth(node.left), find_depth(node.right)) + 1\n\n\ndef find_deepest_node(node):\n if not node:\n return\n q = Queue()\n q.put(node)\n temp_node = None\n while not q.empty():\n temp_node = q.get()\n if temp_node.left:\n q.put(temp_node.left)\n if temp_node.right:\n q.put(temp_node.right)\n return temp_node.data\n\n\nif __name__ == \"__main__\":\n n1 = Node(1)\n n2 = Node(2)\n n3 = Node(3)\n n4 = Node(4)\n n5 = Node(5)\n n6 = Node(6)\n n7 = Node(7)\n n1.left(n2)\n n1.right(n3)\n n1.right.left(n4)\n n1.right.right(n5)\n n1.left.left(n6)\n n1.left.right(n7)\n","sub_path":"BinaryTree.py","file_name":"BinaryTree.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"454509413","text":"from django.db import models\r\nfrom django.utils.text import slugify\r\nfrom tinymce.models import HTMLField\r\nfrom taggit.managers import TaggableManager\r\n\r\n# Create your models here.\r\nclass Pembicara(models.Model):\r\n Nama = models.CharField(max_length=100)\r\n panggilan = models.CharField(max_length=30, blank=True)\r\n Slug = models.SlugField(default='', editable=False, max_length=140)\r\n Pekerjaan = models.CharField(max_length=100)\r\n Perusahaan = models.CharField(max_length=100)\r\n Deskripsi_singkat = models.TextField(blank=True)\r\n Foto = models.ImageField(upload_to='web/')\r\n Email = models.EmailField(blank=True)\r\n Facebook = models.URLField(blank=True)\r\n Twitter = models.URLField(blank=True)\r\n Linkedin = models.URLField(blank=True)\r\n Instagram = models.URLField(blank=True)\r\n Keterangan = models.TextField(blank=True)\r\n keynote = models.BooleanField(default=True)\r\n\r\n def __str__(self):\r\n return self.Nama\r\n\r\n class Meta:\r\n verbose_name = (\"Pembicara\")\r\n verbose_name_plural = (\"Pembicara\")\r\n\r\n def save(self, *args, **kwargs):\r\n value = self.Nama\r\n self.Slug = slugify(value, allow_unicode=True)\r\n super().save(*args, **kwargs)\r\n\r\nclass Event(models.Model):\r\n Judul = models.CharField(max_length=100)\r\n Slug = models.SlugField(default='', editable=False, max_length=140)\r\n Mulai = models.DateTimeField()\r\n Selesai = models.DateTimeField(blank=True)\r\n Pembicara = models.ForeignKey(Pembicara, on_delete=models.PROTECT ,null=True)\r\n Lokasi = models.TextField(blank=True)\r\n Link = models.URLField(blank=True)\r\n Keterangan = models.TextField(blank=True)\r\n\r\n def __str__(self):\r\n return self.Judul\r\n\r\n class Meta:\r\n verbose_name = (\"Acara\")\r\n verbose_name_plural = (\"Acara\")\r\n\r\n def save(self, *args, **kwargs):\r\n value = self.Judul\r\n self.Slug = slugify(value, allow_unicode=True)\r\n super().save(*args, **kwargs)\r\n\r\n @property\r\n def waktu(self):\r\n return self.Mulai.strftime('%d-%B-%Y')\r\n def jammulai(self):\r\n return self.Mulai.strftime('%H:%M')\r\n def jamselesai(self):\r\n return self.Selesai.strftime('%H:%M')\r\n\r\n\r\nclass Artikel(models.Model):\r\n Judul = models.CharField(max_length=150)\r\n Slug = models.SlugField(default='', editable=False, max_length=140)\r\n Tanggal = models.DateField(null=True)\r\n Isi = HTMLField()\r\n tags = TaggableManager()\r\n\r\n def __str__(self):\r\n return self.Judul\r\n\r\n class Meta:\r\n verbose_name = (\"Artikel\")\r\n verbose_name_plural = (\"Artikel\")\r\n\r\n def save(self, *args, **kwargs):\r\n value = self.Judul\r\n self.Slug = slugify(value, allow_unicode=True)\r\n super().save(*args, **kwargs)\r\n\r\n\r\nclass Sponsor(models.Model):\r\n UNIVERSITY = '0'\r\n CORPORATE = '1'\r\n MEDIA = '2'\r\n\r\n KATEGORI_CHOICES = (\r\n (UNIVERSITY, 'University Sponsors'),\r\n (CORPORATE, 'Corporate Sponsors'),\r\n (MEDIA, 'Media Sponsors'),\r\n )\r\n\r\n nama = models.CharField(max_length=100)\r\n logo = models.ImageField(upload_to='web/logosponsor')\r\n kategori = models.CharField(max_length=1, choices=KATEGORI_CHOICES, default=0)\r\n keterangan = models.TextField(blank=True)\r\n\r\n def __str__(self):\r\n return self.nama\r\n\r\nclass team(models.Model):\r\n nama = models.CharField(max_length=100)\r\n panggilan = models.CharField(max_length=30, blank=True)\r\n jabatan = models.CharField(max_length=150, blank=True)\r\n foto = models.ImageField(upload_to='web/teams/', blank=True)\r\n keterangan = models.TextField(blank=True)\r\n no_urut = models.PositiveIntegerField(blank=True)\r\n scientific_coord = models.BooleanField(default=False)\r\n\r\n def __str__(self):\r\n return self.nama\r\n\r\n class Meta:\r\n verbose_name = (\"team\")\r\n verbose_name_plural = (\"teams\")\r\n\r\nclass importantdates(models.Model):\r\n Judul =models.CharField(max_length=150)\r\n Tanggal = models.CharField(max_length=50)\r\n urutan =models.PositiveIntegerField(blank=True)\r\n\r\n def __str__(self):\r\n return self.Judul\r\n\r\n class Meta:\r\n verbose_name = (\"tanggal penting\")\r\n verbose_name_plural = (\"tanggal penting\")","sub_path":"web/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"398568073","text":"import pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\n\n\ndef iplot_line(self, y, x='TIME', marginal_x=None, marginal_y='histogram', color='DEPTH',\n range_y='auto', line_shape='lineard', rangeslider_visible=True, **kwds):\n \"\"\"\n It uses plotly.express.line.\n Each data point is represented as a marker point, whose location is given by the x and y columns\n of self.data.\n\n Parameters\n ----------\n y: str\n Y axes, column or index of data.\n x: str\n X axes, column or index of data.\n color: str\n Name of a column or index of data. Values from this column are used to assign color to\n marks. If color = 'auto', color = QC column of y.\n range_y: list\n [min value, max value] of y axes. If range_y = 'auto', range is generated between the\n mina nd max values of y axes +- 5%.\n line_shape: str\n Line options: 'linear' 'spline', 'vhv', 'hvh', 'vh', 'hv'\n rangeslider_visible: bool\n Show a time range slide on the bottom x axes.\n **kwds: keywords\n plotly express scatter keywords.\n\n Returns\n -------\n fig: plotly.graph_objects.Figure\n \"\"\"\n df = pd.DataFrame()\n _df = self.data.reset_index()\n\n df[y] = _df[y]\n df[f'{y}_QC'] = _df[f'{y}_QC']\n df[x] = _df[x]\n\n if 'DEPTH' in _df.keys():\n df['DEPTH'] = _df['DEPTH']\n\n # Range Y calculation\n y_min = min(df[y].values)\n y_max = max(df[y].values)\n y_percent = (y_max - y_min) / 100\n\n if range_y == 'auto':\n range_y = [y_min - 5* y_percent, y_max + 5* y_percent]\n\n # Save memory\n del _df\n\n # Dropna\n df.dropna(inplace=True)\n\n if 'DEPTH' in df.keys() and 'TIME' in df.keys():\n # Sort by TIME AND DEPTH\n df.sort_values(['DEPTH', 'TIME'], inplace=True)\n elif 'TIME' in df.keys():\n df.sort_values(['TIME'], inplace=True)\n\n if color == 'DEPTH':\n df[color] = df[color].astype('str')\n elif color:\n df[color] = df[color]\n\n # # Set index TIME\n # df.set_index('TIME', inplace=True)\n # df.sort_index(inplace=True)\n # df.reset_index(inplace=True)\n\n fig = px.line(df, x=x, y=y, color=color,\n range_y=range_y,\n line_shape=line_shape,\n labels={\n y: self.vocabulary[y].get('units', y)},\n **kwds)\n\n fig.update_xaxes(rangeslider_visible=rangeslider_visible)\n fig.update_layout(margin=dict(l=30, r=0, t=30, b=0))\n\n if 'QC' in color:\n fig.for_each_trace(\n lambda trace: trace.update(\n visible='legendonly',\n mode='markers',\n marker_color='red') if trace.name == 'Bad data' else (),\n )\n fig.for_each_trace(\n lambda trace: trace.update(\n mode='lines+markers',\n marker_color='blue',\n line_color='blue') if trace.name == 'Good data' else (),\n )\n elif 'DEPTH' in color:\n fig.for_each_trace(\n lambda trace: trace.update(mode='lines+markers'))\n\n return fig\n","sub_path":"mooda/waterframe/iplot/iplot_line.py","file_name":"iplot_line.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"551577287","text":"import os\n\nmodel_mark = \"latest.pth\"\n\nmodel_dirs = [\n \"work_dirs/deeplabv3_m-v2-d8_512x1024_80k_cityscapes\",\n \"work_dirs/apcnet_r50-d8_512x1024_40k_cityscapes\"\n]\nimage_dir = \"img/city_scape\"\n\nfor idx, model_dir in enumerate(model_dirs):\n cmds = []\n print(\"--------------------------Visualizing model {}------------------------------\".format(idx))\n # model_dir_path = os.path.join(model_root, model_dir)\n out_dir = \"img/result\"\n os.makedirs(out_dir, exist_ok=True)\n for file in os.listdir(model_dir):\n file_path = os.path.join(model_dir, file)\n if \".py\" in file:\n config = file_path\n elif model_mark in file:\n chkp = file_path\n else:\n pass\n\n img_result_dir = os.path.join(out_dir, model_dir.split(\"/\")[-1] + \"-\" + image_dir.split(\"/\")[-1])\n os.makedirs(img_result_dir, exist_ok=True)\n for img_name in os.listdir(image_dir):\n img_path = os.path.join(image_dir, img_name)\n out_file = os.path.join(img_result_dir, img_name)\n if not os.path.exists(out_file):\n cmds.append(\"python demo/image_demo.py {} {} {} --out {}\".format(img_path, config, chkp, out_file))\n\n for cmd in cmds:\n print(cmd)\n os.system(cmd)\n","sub_path":"auto_visualize.py","file_name":"auto_visualize.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"126107522","text":"from flask import Flask, flash, render_template, request, redirect, session\nimport random\napp = Flask(__name__)\napp.secret_key = \"NumberGame101\"\n@app.route('/')\ndef num_game():\n try:\n session['random']\n except:\n session['random'] = random.randint(1, 101)\n return render_template('greatnumbergame.html')\n\n@app.route('/check', methods=['POST'])\ndef check():\n guess = int(request.form['guess'])\n if guess > session['random']:\n flash(\"Too high\", 'error')\n elif guess < session ['random']:\n flash(\"Too low\", 'error')\n else:\n flash(\"You guessed correct\", 'success')\n return redirect('/')\n\n@app.route('/reset')\ndef reset():\n session.clear()\n return redirect('/')\n\napp.run(debug=True)\n","sub_path":"greatNumberGame.py","file_name":"greatNumberGame.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"521261589","text":"#encode: UTF-8\r\n#Autor: Leonardo Castillejos Vite\r\n#Descripción: programa que lee los lados de 2 rectángulos y entrega el perimetro y el área.\r\n\r\nimport turtle\r\n\r\n\r\ndef main():\r\n largo1 = int(input(\"Teclea el largo del rectángulo 1: \"))\r\n ancho1 = int(input(\"Teclea el ancho del rectángulo 1: \"))\r\n perimetro1 = calcularPerimetro(largo1, ancho1)\r\n area1 = calcularArea (largo1, ancho1)\r\n print(\"El perimetro del rectángulo 1 es %d cm\" % (perimetro1))\r\n print(\"El área del rectángulo 1 es %d cm**2\" % (area1))\r\n largo2 = int(input(\"Teclea el largo del rectángulo 2: \"))\r\n ancho2 = int(input(\"Teclea el ancho del rectángulo 2: \"))\r\n perimetro2 = calcularPerimetro(largo2, ancho2)\r\n area2 = calcularArea(largo2, ancho2)\r\n print(\"El perimetro del rectángulo 2 es %d cm\"% (perimetro2))\r\n print(\"El área del rectángulo 2 es %d cm**2\"% (area2))\r\n mayor = compararArea(area1, area2)\r\n print(mayor)\r\n dibujarRectangulos(largo1, ancho1, largo2, ancho2)\r\n\r\n\r\n\r\n# Calcula el perimetro de un rectángulo\r\ndef calcularPerimetro(largo, ancho):\r\n perimetro = (largo * 2)+(ancho * 2)\r\n return perimetro\r\n\r\n# Calcula el área de un rectángulo\r\ndef calcularArea(largo, ancho):\r\n area = largo * ancho\r\n return area\r\n\r\n# Compara el área de 2 rectángulos\r\ndef compararArea (area1, area2):\r\n if area1 > area2:\r\n return \"El área del rectángulo 1 es mayor\"\r\n elif area1 == area2:\r\n return \"Los rectángulos tienen la misma área \"\r\n else:\r\n return \"El área del rectángulo 2 es mayor\"\r\n\r\n\r\n# Dibuja dos rectángulos de 2 colores diferentes\r\ndef dibujarRectangulos(largo1, ancho1, largo2, ancho2):\r\n turtle.pencolor(\"blue\")\r\n turtle.forward(largo1)\r\n turtle.left(90)\r\n turtle.forward(ancho1)\r\n turtle.left(90)\r\n turtle.forward(largo1)\r\n turtle.left(90)\r\n turtle.forward(ancho1)\r\n turtle.pencolor(\"red\")\r\n turtle.left(90)\r\n turtle.forward(largo2)\r\n turtle.left(90)\r\n turtle.forward(ancho2)\r\n turtle.left(90)\r\n turtle.forward(largo2)\r\n turtle.left(90)\r\n turtle.forward(ancho2)\r\n turtle.exitonclick()\r\n\r\nmain()","sub_path":"Áreas de rectángulos.py","file_name":"Áreas de rectángulos.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"97671125","text":"# coding: Utf-8\n\nfrom pyspark import SparkConf, SparkContext\n\nif __name__ == '__main__':\n conf = SparkConf().setAppName(\"rdd\").setMaster(\"local[*]\")\n sc = SparkContext(conf=conf)\n\n a = [\"a\", \"a\", \"c\", \"d\", \"d\", \"c\", \"e\"]\n b = [1, 2, 3, 4, 1, 3, 7]\n data = list(zip(a, b))\n disData = sc.parallelize(data)\n d = disData.reduceByKey(lambda x, y: x + y)\n print(d.collect())\n","sub_path":"PyProject/sparkproject/rdd/pairRdd/transformations/reduceByKey.py","file_name":"reduceByKey.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"384702765","text":"import requests\nimport six.moves.urllib.parse as urlparse\nimport json\nimport os\nimport gym\nimport numpy as np\nfrom gym import spaces\n\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\nclass Client(object):\n \"\"\"\n Gym client to interface with gym_http_server\n \"\"\"\n def __init__(self, remote_base):\n self.remote_base = remote_base\n self.session = requests.Session()\n self.session.headers.update({'Content-type': 'application/json'})\n\n def _parse_server_error_or_raise_for_status(self, resp):\n j = {}\n try:\n j = resp.json()\n except Exception:\n # Most likely json parse failed because of network error, not server error (server\n # sends its errors in json). Don't let parse exception go up, but rather raise default\n # error.\n resp.raise_for_status()\n if resp.status_code != 200 and \"message\" in j: # descriptive message from server side\n raise ServerError(message=j[\"message\"], status_code=resp.status_code)\n resp.raise_for_status()\n return j\n\n def _post_request(self, route, data):\n url = urlparse.urljoin(self.remote_base, route)\n logger.info(\"POST {}\\n{}\".format(url, json.dumps(data)))\n resp = self.session.post(urlparse.urljoin(self.remote_base, route),\n data=json.dumps(data))\n return self._parse_server_error_or_raise_for_status(resp)\n\n def _get_request(self, route):\n url = urlparse.urljoin(self.remote_base, route)\n logger.info(\"GET {}\".format(url))\n resp = self.session.get(url)\n return self._parse_server_error_or_raise_for_status(resp)\n\n def env_create(self, env_id):\n route = '/v1/envs/'\n data = {'env_id': env_id}\n resp = self._post_request(route, data)\n instance_id = resp['instance_id']\n return instance_id\n\n def env_list_all(self):\n route = '/v1/envs/'\n resp = self._get_request(route)\n all_envs = resp['all_envs']\n return all_envs\n\n def env_getattr(self, instance_id, attr):\n route = f'/v1/envs/{instance_id}/getattr/{attr}'\n resp = self._get_request(route)\n val = resp[attr]\n return val\n\n def env_reset(self, instance_id):\n route = '/v1/envs/{}/reset/'.format(instance_id)\n resp = self._post_request(route, None)\n observation = resp['observation']\n return observation\n\n def env_step(self, instance_id, action, render=False):\n route = '/v1/envs/{}/step/'.format(instance_id)\n data = {'action': action, 'render': render}\n resp = self._post_request(route, data)\n observation = resp['observation']\n reward = resp['reward']\n done = resp['done']\n info = resp['info']\n return [observation, reward, done, info]\n\n def env_action_space_info(self, instance_id):\n route = '/v1/envs/{}/action_space/'.format(instance_id)\n resp = self._get_request(route)\n info = resp['info']\n return info\n\n def env_action_space_sample(self, instance_id):\n route = '/v1/envs/{}/action_space/sample'.format(instance_id)\n resp = self._get_request(route)\n action = resp['action']\n return action\n\n def env_action_space_contains(self, instance_id, x):\n route = '/v1/envs/{}/action_space/contains/{}'.format(instance_id, x)\n resp = self._get_request(route)\n member = resp['member']\n return member\n\n def env_observation_space_info(self, instance_id):\n route = '/v1/envs/{}/observation_space/'.format(instance_id)\n resp = self._get_request(route)\n info = resp['info']\n return info\n\n def env_observation_space_contains(self, instance_id, params):\n route = '/v1/envs/{}/observation_space/contains'.format(instance_id)\n resp = self._post_request(route, params)\n member = resp['member']\n return member\n\n def env_monitor_start(self, instance_id, directory,\n force=False, resume=False, video_callable=False):\n route = '/v1/envs/{}/monitor/start/'.format(instance_id)\n data = {'directory': directory,\n 'force': force,\n 'resume': resume,\n 'video_callable': video_callable}\n self._post_request(route, data)\n\n def env_monitor_close(self, instance_id):\n route = '/v1/envs/{}/monitor/close/'.format(instance_id)\n self._post_request(route, None)\n\n def env_close(self, instance_id):\n route = '/v1/envs/{}/close/'.format(instance_id)\n self._post_request(route, None)\n\n def upload(self, training_dir, algorithm_id=None, api_key=None):\n raise NotImplementedError(\"upload is hard-deprecated because viraj doesn't know why you would ever want this\")\n if not api_key:\n api_key = os.environ.get('OPENAI_GYM_API_KEY')\n\n route = '/v1/upload/'\n data = {'training_dir': training_dir,\n 'algorithm_id': algorithm_id,\n 'api_key': api_key}\n self._post_request(route, data)\n\n def shutdown_server(self):\n route = '/v1/shutdown/'\n self._post_request(route, None)\n\n\nclass ClientWrapperEnv(gym.Env):\n '''\n A wrapper around the client that allows you to treat an environement\n running on the other side of one of these servers as a gym environment.\n\n remote_base: a string pointing to the base URL for the api server.\n env_id: a string that gets passed into gym.make() on the server side to\n access the desired environment. Will throw an exception if it doesn't\n exist on server side.\n '''\n def __init__(self, remote_base, env_id):\n self.client = Client(remote_base)\n self.instance_id = self.client.env_create(env_id)\n action_info = self.client.env_action_space_info(self.instance_id)\n obs_info = self.client.env_observation_space_info(self.instance_id)\n self.action_space = self._process_space_info(action_info)\n self.observation_space = self._process_space_info(obs_info)\n\n def reset(self):\n obs = self.client.env_reset(self.instance_id)\n return np.array(obs)\n\n def step(self, action):\n if type(action) is not int:\n action = action.tolist()\n obs, rew, done, info = self.client.env_step(self.instance_id, action)\n return np.array(obs), rew, done, info\n\n def _process_space_info(self, info):\n if info['name'] == 'Discrete':\n n = info['n']\n return spaces.Discrete(n)\n elif info['name'] == 'Box':\n low = np.array(info['low'])\n high = np.array(info['high'])\n return spaces.Box(low, high, dtype=np.float32)\n else:\n raise NotImplementedError(f\"Info name {info['name']} not supported\")\n\n def get_remote_attr(self, attr):\n return self.client.env_getattr(self.instance_id, attr)\n\n\nclass ServerError(Exception):\n def __init__(self, message, status_code=None):\n Exception.__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n\n\nif __name__ == '__main__':\n remote_base = 'http://127.0.0.1:5000'\n client = Client(remote_base)\n\n # Create environment\n env_id = 'CartPole-v0'\n instance_id = client.env_create(env_id)\n\n # Check properties\n all_envs = client.env_list_all()\n action_info = client.env_action_space_info(instance_id)\n obs_info = client.env_observation_space_info(instance_id)\n\n # Run a single step\n client.env_monitor_start(instance_id, directory='tmp', force=True)\n init_obs = client.env_reset(instance_id)\n [observation, reward, done, info] = client.env_step(instance_id, 1, True)\n client.env_monitor_close(instance_id)\n # client.upload(training_dir='tmp')\n\n # test the ClientWrapperEnv\n env = ClientWrapperEnv(remote_base, env_id)\n\n # reset\n obs = env.reset()\n\n # run a single step\n obs, rew, done, info = env.step(env.action_space.sample())\n","sub_path":"helpers/gym_http_client.py","file_name":"gym_http_client.py","file_ext":"py","file_size_in_byte":8089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"78731636","text":"import pandas as pd\nimport networkx as nx\nfrom spectral_machinery import WaveletMachine\nfrom parser import parameter_parser\n\ndef read_graph(path):\n \"\"\"\n Reading the edge list from the path and returning the networkx graph object.\n :param path: Path to the edge list.\n :return graph: Graph from edge list.\n \"\"\"\n edge_list = pd.read_csv(path).values.tolist()\n graph = nx.from_edgelist(edge_list)\n return graph\n\nif __name__ == \"__main__\":\n settings = parameter_parser()\n G = read_graph(settings.input)\n machine = WaveletMachine(G,settings)\n machine.create_embedding()\n machine.transform_and_save_embedding()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"247120318","text":"import os\r\nfrom Gui import GUI\r\n#from capture import capture, capture2\r\n#from templateMatching import Match\r\n\r\nclass PhysInput_deprecated:\r\n\r\n class Diff:\r\n\r\n #State changes s:\r\n # a) W->E\r\n # b) B->E\r\n # c) E->W\r\n # d) E->B\r\n # e) B->W\r\n # f) W->B\r\n \r\n def __init__(self, diffStr):\r\n assert type(diffStr) == str and len(diffStr) == 3\r\n self.F = diffStr[0] #File A-H\r\n self.R = diffStr[1] #Rank 1-8\r\n self.s = diffStr[2] #state change a-f\r\n self.space = self.F + self.R\r\n self.state = diffStr\r\n \r\n class Move:\r\n def __init__(self, diffList):\r\n self.diffList = diffList\r\n self.diffList.sort(key = lambda diff: diff.s)\r\n self.stateList = []\r\n for diff in diffList:\r\n self.stateList.append(diff.state)\r\n\r\n def getMoveType(self):\r\n mTypeStr = ''\r\n for diff in self.diffList:\r\n mTypeStr += diff.s\r\n return mTypeStr #should be in alphabetical order\r\n \r\n def getDiffFromS(self, s): #can't be used with castle\r\n for diff in self.diffList:\r\n if diff.s == s:\r\n return diff\r\n return '[changed space not found]'\r\n \r\n def getRegMove(self, moveType, colorWhite):\r\n space_i = self.diffList[0].space\r\n space_f = self.diffList[1].space\r\n return space_i + space_f\r\n \r\n def getCastle(self, colorWhite):\r\n if colorWhite:\r\n kSideList = ['E1a', 'G1c', 'H1a', 'F1c']\r\n qSideList = ['E1a', 'C1c', 'A1a', 'D1c']\r\n else:\r\n kSideList = ['E8b', 'G8d', 'H8b', 'F8d']\r\n qSideList = ['E8b', 'C8d', 'A8b', 'D8d']\r\n \r\n if set(kSideList) == set(self.stateList):\r\n return 'o-o'\r\n elif set(qSideList) == set(self.stateList):\r\n return 'o-o-o'\r\n else:\r\n return 'invalid castle'\r\n\r\n def getPassant(self, moveType, colorWhite):\r\n fileStr = 'ABCDEFGH'\r\n \r\n pawnDest = self.diffList[2].space\r\n destF = pawnDest[0]\r\n destR = pawnDest[1]\r\n\r\n if colorWhite:\r\n plPawn = self.diffList[0].space\r\n aiPawn = self.diffList[1].space\r\n delta = 1 #rank movement for en passant\r\n correctRank = '5'\r\n else:\r\n plPawn = self.diffList[1].space\r\n aiPawn = self.diffList[0].space\r\n delta = -1\r\n correctRank = '4'\r\n plF = plPawn[0]\r\n aiF = aiPawn[0]\r\n plR = plPawn[1]\r\n aiR = plPawn[1]\r\n \r\n fileDiff = fileStr.index(plF) - fileStr.index(aiF)\r\n sameRank = (plR == aiR == correctRank)\r\n adjacent = (abs(fileDiff) == 1)\r\n correctDest = (destF == aiF and int(destR) == int(aiR) + delta)\r\n \r\n if sameRank and adjacent and correctDest:\r\n return plPawn + pawnDest + 'EP'\r\n else:\r\n return 'invalid EP'\r\n \r\n def __init__(self, playerColor):\r\n moveDir = os.path.dirname(os.path.realpath(__file__)) + '/../phys/'\r\n self.filename = moveDir + 'playerMove.txt'\r\n self.playerColor = playerColor\r\n \r\n def promptCamera(self):\r\n return 0\r\n #TODO: wait for player to finish turn, call camera prog to generate playerMove.txt\r\n\r\n def getPlayerMove(self):\r\n self.promptCamera()\r\n plFile = open(self.filename, \"r\")\r\n diffList = []\r\n for line in plFile:\r\n diffList.append(self.Diff(line.strip()))\r\n plFile.close()\r\n \r\n move = self.Move(diffList)\r\n regMoves = ['ac', 'ae', 'bd', 'bf']\r\n castles = ['aacc', 'bbdd']\r\n passants = ['abc', 'abd']\r\n \r\n moveType = move.getMoveType()\r\n if moveType in regMoves:\r\n return move.getRegMove(moveType, self.playerColor)\r\n elif moveType in castles:\r\n return move.getCastle(self.playerColor)\r\n elif moveType in passants:\r\n return move.getPassant(moveType, self.playerColor)\r\n else:\r\n return 'invalid move type ' + moveType #will register as invalid move\r\n #TODO: Implement pawn promotion\r\n\r\nclass PhysInput:\r\n\r\n kingIDs = [1, 17]\r\n queenIDs = [2, 18]\r\n bishopIDs = [3, 4, 19, 20]\r\n knightIDs = [5, 6, 21, 22]\r\n rookIDs = [7, 8, 23, 24]\r\n pawnIDs = [9, 10, 11, 12, 13, 14, 15, 16,\r\n 25, 26, 27, 28, 29, 30, 31, 32]\r\n\r\n pieces = dict.fromkeys(kingIDs, 'K')\r\n pieces.update(dict.fromkeys(queenIDs, 'Q'))\r\n pieces.update(dict.fromkeys(bishopIDs, 'B'))\r\n pieces.update(dict.fromkeys(knightIDs, 'N'))\r\n pieces.update(dict.fromkeys(rookIDs, 'R'))\r\n pieces.update(dict.fromkeys(pawnIDs, 'P'))\r\n\r\n WHITE = True\r\n BLACK = False\r\n\r\n class Diff:\r\n def __init__(self, diff):\r\n assert self.isValid(diff)\r\n self.ID = int(diff[0])\r\n self.i = diff[1]\r\n self.f = diff[2]\r\n \r\n def __str__(self):\r\n diffStr = ''\r\n if self.taken():\r\n diffStr = self.i + ' taken'\r\n elif self.newPiece():\r\n diffStr = 'New piece at ' + self.f\r\n else:\r\n diffStr = self.i + ' to ' + self.f\r\n return diffStr\r\n \r\n def isValid(self, diff):\r\n def isSquare(sq):\r\n if len(sq) != 2:\r\n return False\r\n elif sq == '__':\r\n return True\r\n elif sq[0] in 'ABCDEFGH' and sq[1] in '12345678':\r\n return True\r\n else:\r\n return False\r\n \r\n if len(diff) != 3:\r\n return False\r\n\r\n diffID = diff[0]\r\n if not diffID.isdigit():\r\n return False\r\n elif int(diffID) < 0 or int(diffID) > 32:\r\n return False\r\n \r\n init = diff[1]\r\n finl = diff[2]\r\n if not (isSquare(init) and isSquare(finl)):\r\n return False\r\n \r\n return True\r\n \r\n def taken(self):\r\n return self.f == '__'\r\n \r\n def newPiece(self):\r\n return self.i == '__'\r\n \r\n def getColor(self):\r\n return self.ID < 17\r\n \r\n def getMoveStr(self):\r\n return self.i + self.f\r\n #if self.taken() or self.newPiece():\r\n # return None\r\n #else:\r\n # return self.i + self.f\r\n \r\n\r\n def __init__(self, playerColor):\r\n moveDir = os.path.dirname(os.path.realpath(__file__)) + '/../phys/'\r\n self.filename = moveDir + 'playerMove.txt'\r\n self.playerColor = playerColor\r\n #self.matcher = Match()\r\n \r\n def promptCamera(self, capt1):\r\n if capt1:\r\n #capture()\r\n return\r\n else:\r\n #capture2()\r\n #self.matcher.genDiffs()\r\n return\r\n \r\n def promptMove(self):\r\n temp = GUI(self)\r\n temp.promptMove()\r\n \r\n def regMove(self, diffA, diffB):\r\n if not diffB:\r\n if diffA.taken():\r\n return 'Piece illegally removed: ' + diffA.i\r\n else:\r\n return diffA.getMoveStr()\r\n \r\n #diffList has two diffs\r\n if diffB.taken() and diffA.f == diffB.i:\r\n return diffA.getMoveStr()\r\n elif diffA.taken() and diffB.f == diffA.i:\r\n return diffB.getMoveStr()\r\n else:\r\n return 'Player and opponent pieces moved,\\nor taken piece still on board.'\r\n \r\n\r\n def castleMove(self, kingDiff, rookDiff):\r\n color = kingDiff.getColor()\r\n if color != self.playerColor:\r\n return 'Invalid castle'\r\n elif color == self.WHITE:\r\n if str(kingDiff) == 'E1 to G1' and str(rookDiff) == 'H1 to F1':\r\n return 'O-O'\r\n elif str(kingDiff) == 'E1 to C1' and str(rookDiff) == 'A1 to D1':\r\n return 'O-O-O'\r\n else:\r\n return 'Invalid castle'\r\n else:\r\n if str(kingDiff) == 'E8 to G8' and str(rookDiff) == 'H8 to F8':\r\n return 'O-O'\r\n elif str(kingDiff) == 'E8 to C8' and str(rookDiff) == 'A8 to D8':\r\n return 'O-O-O'\r\n else:\r\n return 'Invalid castle'\r\n\r\n\r\n def passantMove(self, pMoved, pTaken):\r\n fileList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\r\n\r\n color = pMoved.getColor()\r\n if color != self.playerColor:\r\n return 'Invalid EP'\r\n moveRf = '6'\r\n takenRi = '5'\r\n if color == self.BLACK:\r\n moveRf = '3'\r\n takenRi = '4'\r\n fileDelta = abs(fileList.index(pMoved.i[0]) - fileList.index(pTaken.i[0]))\r\n\r\n if not (pMoved.i[1] == pTaken.i[1] == takenRi):\r\n return 'En passant: Invalid initial rank'\r\n if pMoved.f[1] != moveRf:\r\n return 'En passant: Invalid final rank'\r\n if fileDelta > 1:\r\n return 'En passant: Invalid initial file'\r\n if pMoved.f[0] != pTaken.i[0]:\r\n return 'En passant: Invalid final file'\r\n return pMoved.getMoveStr() + 'EP'\r\n\r\n\r\n def promotionMove(self, diffList):\r\n fileList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\r\n\r\n pawnDiff = None\r\n newDiff = None\r\n takenDiff = None\r\n \r\n for diff in diffList:\r\n if self.pieces[diff.ID] == 'P':\r\n pawnDiff = diff\r\n elif diff.newPiece():\r\n newDiff = diff\r\n else:\r\n takenDiff = diff\r\n\r\n if not pawnDiff:\r\n moveStr = 'Too many pieces moved:'\r\n for diff in diffList:\r\n moveStr += '\\n' + str(diff)\r\n return moveStr\r\n\r\n pawnColor = pawnDiff.getColor()\r\n \r\n pawnRi = '7'\r\n newRf = '8'\r\n if pawnColor == self.BLACK:\r\n pawnRi = '2'\r\n newRf = '1'\r\n\r\n pawnFi = pawnDiff.i[1]\r\n newFf = newDiff.f[1]\r\n fileDelta = abs(fileList.index(pawnFi) - fileList.index(newFf))\r\n\r\n if pawnDiff.i[0] != pawnRi:\r\n return 'Pawn ineligible for promotion.'\r\n elif newDiff.f[0] != newRf or fileDelta > 1:\r\n return 'Promoted pice at incorrect spot.'\r\n \r\n if takenDiff:\r\n if takenDiff.i != newDiff.f:\r\n return 'Piece illegally removed.'\r\n\r\n newPieceType = self.pieces[newDiff.ID]\r\n return pawnDiff.i + newDiff.f + '=' + newPieceType\r\n\r\n\r\n def hasNewPiece(self, diffList):\r\n for diff in diffList:\r\n if diff.newPiece():\r\n return True\r\n return False\r\n\r\n def processDiffs(self, diffList):\r\n if len(diffList) == 1:\r\n return self.regMove(diffList[0], None)\r\n \r\n diffA = diffList[0]\r\n diffB = diffList[1]\r\n opposed = (diffA.getColor() != diffB.getColor()) #pieces are opposite colors\r\n\r\n if not opposed:\r\n if self.pieces[diffA.ID] == 'K' and self.pieces[diffB.ID] == 'R':\r\n return self.castleMove(diffA, diffB)\r\n elif self.pieces[diffB.ID] == 'R' and self.pieces[diffB.ID] == 'K':\r\n return self.castleMove(diffB, diffA)\r\n else:\r\n return 'Two pieces of the same color moved.'\r\n \r\n #pieces are opposite colors\r\n if self.hasNewPiece(diffList):\r\n return self.promotionMove(diffList)\r\n \r\n if self.pieces[diffA.ID] == self.pieces[diffB.ID] == 'P':\r\n if diffB.taken():\r\n if diffB.i != diffA.f:\r\n return self.passantMove(diffA, diffB) \r\n elif diffA.taken():\r\n if diffA.i != diffB.f:\r\n return self.passantMove(diffB, diffA)\r\n\r\n return self.regMove(diffA, diffB)\r\n \r\n\r\n def getPlayerMove(self, cam=True):\r\n if cam:\r\n self.promptCamera(False)\r\n else:\r\n self.promptMove()\r\n plFile = open(self.filename, \"r\")\r\n diffList = []\r\n for line in plFile:\r\n cleanDiff = line.strip().split()\r\n newDiff = self.Diff(cleanDiff)\r\n if not newDiff:\r\n return 'Invalid input'\r\n diffList.append(newDiff)\r\n plFile.close()\r\n\r\n moveStr = ''\r\n numDiffs = len(diffList)\r\n if numDiffs < 1:\r\n moveStr = 'No move made'\r\n elif numDiffs > 2:\r\n if numDiffs == 3 and self.hasNewPiece(diffList):\r\n moveStr = self.promotionMove(diffList)\r\n else:\r\n moveStr = 'Too many pieces moved:'\r\n for diff in diffList:\r\n moveStr += '\\n' + str(diff)\r\n else:\r\n moveStr = self.processDiffs(diffList)\r\n return moveStr\r\n\r\n\r\n\r\nclass PhysOutput:\r\n \r\n def __init__(self):\r\n self.a = 5\r\n\r\n\r\n\r\nclass VirtualBoard:\r\n class VirtualPiece:\r\n def __init__(self, color, x, y):\r\n self.color = color\r\n self.x = x\r\n self.y = y\r\n\r\n fileStr = 'ABCDEFGH'\r\n def __init__(self):\r\n self.grid = [\r\n ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'],\r\n ['-', '-', '-', '-', '-', '-', '-', '-'],\r\n ['-', '-', '-', '-', '-', '-', '-', '-'],\r\n ['-', '-', '-', '-', '-', '-', '-', '-'],\r\n ['-', '-', '-', '-', '-', '-', '-', '-'],\r\n ['-', '-', '-', '-', '-', '-', '-', '-'],\r\n ['p', 'p', 'P', 'P', 'P', 'P', 'P', 'P'],\r\n ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']]\r\n \r\n def __str__(self):\r\n gridStr = ''\r\n for rank in reversed(self.grid):\r\n for space in rank:\r\n gridStr += space\r\n gridStr += '\\r\\n'\r\n return gridStr\r\n","sub_path":"src/PhysIO.py","file_name":"PhysIO.py","file_ext":"py","file_size_in_byte":14249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"546315504","text":"# coding:utf-8\n\nimport asyncio, logging\nimport aiomysql\n\nasync def create_pool(loop, **kw):\n '''\n 创建互数据库连接池\n :param loop: 事件循环处理程序\n :param kw: 数据库配置参数集合\n :return:无\n '''\n logging.info('创建数据库连接池。。。')\n #创建全局变量\n global __pool\n #初始化连接池参数 ,通过aiohttp方法创建连接池\n #kw.get()从字典里面 取值,如果不存在可以设置默认值,普通的kw[key]取不存在的值会报错\n __pool = await aiohttp.create_pool(\n host = kw.get('host', 'localhost'),\n port = kw.get('port', 3306),\n user = kw['user'],\n password = kw['password'],\n db = kw['db'],\n charset = kw.get('charset', 'utf-8'),\n autocommit = ke.get('autocommit', True),\n maxsize = kw.get('maxsize', 10),\n minsize = kw.get('minsize',1),\n loop = loop\n )\n\nasync def select(sql, args, size = None):\n '''\n 数据库查询函数\n :param sql:sql语句\n :param args: sql语句里面的参数\n :param size: 要查询的数量\n :return: 查询结果\n\n '''\n logging.log(sql, args)\n global __pool\n async with __pool.get() as conn:\n # 创建一个结果为字典的游标\n async with conn.cursor(aiomysql.DictCursor) as cur:\n #执行sql语句,将sql语句中的‘?’换成 “%s\"\n await cur.execute(sql.repalce('?', '%s'), args or ())\n #如果指定了数量,就返回指定数量的记录,否则, 就返回所有的记录\n if size:\n rs = await cur.fetchmany(size)\n else:\n rs = await cur.fetchall()\n logging.info(\"返回的记录数:%s\" %len(rs))\n\nasync def execute(sql, args, autocommit = True):\n '''\n Insert, Update, Delete操作的公共执行函数,因为他们有共同的特征\n :param sql: sql语句\n :param args: sql参数\n :param autocommit: 自动提交事务\n :return:\n '''\n #logging.log(sql, args)\n async with __pool.get() as coon:\n if not autocommit:\n await conn.begin()\n try:\n #创建游标\n async with conn.cursor(aiomysql.DictCursor) as cur:\n #执行sql语句\n await cur.execute(sql.replace('?', '%s'), args or ())\n #获取操作的记录数\n affected = cur.rowcount\n if not autocommit:\n await conn.commit()\n except BaseException as e:\n if not autocommit:\n await conn.rollback()\n raise\n return affected\n\nclass ModelMetaclass(type): #继承自tpye元类\n def __new__(cls, name, bases, attrs): #实例化的时候最先被调用 cls是类参数\n '''\n 创建模型与表映射的基类\n :param name: 类名\n :param bases: 父名\n :param attrs: 类的属性列表\n :return: 返回模型元类\n '''\n #排除Model类本身\n if name == 'Model':\n return type.__new__(cls, name, base, atttrs)\n #获取表名,如果没有表明就将类名作为表名\n tableName = attrs.get('__table__', None ) or name\n logging.info('模型:%s (表名 %s)' %(name, tableName))\n #获取所有的类属性和主键名\n mappings = dict() #存储属性名和字段信息的映射关系,是一个字典类型\n fields =[] #存储所有非主键的属性\n primaryKey = None #存储主键属性\n for k,v in attrs.items(): #attrs.items()把字典变成列表里面是元组的形式,遍历attrs(类的属性名),k为属性名,v为该属性对应的字段信息\n if isinstance(v, Field): #如果v是自己定义的字段类型\n logging.info('映射关系:%s ==> %s' %(k, v))\n mappings[k] = v #存储映射关系\n if v.primary_key: #如果v是主键\n if primaryKey: #若primaryKey已经有数据,即已经找到了主键,说明主键重复\n raise RuntimeError('主键重复,在%s中的%s' %(name,k))\n primaryKey = k #把k置为主键\n else: #如果不是主键,就加入到fields里面去\n fields.append(k)\n if not primaryKey: #主键不存在,即主键没有定义\n raise RuntimeError('主键未定义:%s', name)\n for k in mappings.keys(): #拿出mappings字典里面的keys,组成列表\n attrs.pop(k) #清空attrs\n\n #将fields中属性名以 ^属性名^ 的方式装饰器起来\n escaped_fields = list(map(lambda f: '%s' %f, fields)) #语法map(func,可迭代类型)\n #重新设置attrs\n attrs['__mappings__'] = mappings #保存属性和字段信息的映射关系\n attrs['__table__'] = tableName #保存表名\n attrs['__primary_key__'] = primaryKey #主键属性名\n attrs['__fields__'] = fields #主键之外的属性名\n #构造默认的Select, insert, update, delete语句\n #','.join(a)是字符串连接作用,无论a是字典,列表还是元组,字符串,返回的都是一个字符串\n #反引号``作用同repr() 格式化成解释器可读的形式, 而str()格式化成人可读的形式\n #在mysql中,反引号用于区分mysql的保留字 比如select `select` from 。。中的后一个select就是字段名称,和保留字就区分了\n\n attrs['__select__'] = 'select `%s` , %s from `%s`' %(primaryKey, ','.join(escaped_fields),tableName) #.join()即逗号分隔\n attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' %(\n tableName, ','.join(escaped_fields), primaryKey, create_args_string(len(escaped_fields) + 1) )\n attrs['__update__'] = 'update `%s` set %s where `%s`=? ' %(\n tableName, ','.join(map(lambda f: '`%s`=?' %(mappings.get(f).name or f),fields)), primaryKey)\n attrs['__delete__'] = 'delete from `%s` where `%s`=? ' %(tableName, primaryKey)\n\n return type.__new__(cls, name, bases, attrs)\n\ndef create_args_string(num):\n '''\n 计算需要拼多少个占位符\n :param num:\n :return:\n '''\n L = []\n for n in range(num):\n L.append('?')\n return ','.join(L)\n\nclass Field(object):\n def __init__(self, name, column_type, primary_key, default):\n self.name = name\n self.column_type = column_type\n self.primary_key = primary_key\n self.default = default\n\n def __str__(self):\n return '<%s, %s:%s>' %(self.__class__.__name__, self.column_type, self.name)\n\nclass StringField(Field):\n def __init__(self, name=None, primary_key= False, default=None, ddl='varchar(100)'):\n super().__init__(name, ddl, primary_key, default)\n\nclass BooleanField(Field):\n def __init__(self, name=None, default=False):\n super().__init__(name,'boolean', False, default )\n\nclass IntegerField(Field):\n def __init__(self,name=None, primary_key=Flase, default=0):\n super().__init__(name, 'real', primary_key,default)\n\nclass FloatField(Field):\n def __init__(self, name=None, default=None):\n super().__init__(name, 'text', False, default)\n\n#定义orm所有映射的基类,Model\n#Model类的任意子类可以映射一个数据库表\n#Model类可以看做是对所有的数据库操作的基本定义的映射\n\n#基于字典的查询方式\n#Model从dict类继承,拥有字典的所有功能,同时实现特殊的方法,__getattr__ 和__setatr__可以实现属性的操作\n#实现数据库操作的所有方法,定义为class方法, 所有的继承都具有数据库操作的方法\n\nclass Model(dict, metaclass=ModelMetacalss):\n def __init__(self, **kw):\n super(Model, self).__init__(**kw)\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError(r\"'Model'对象没有属性'%s'\" %key)\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def getValue(self, key):\n #内建函数getattr()处理\n return getattr(self, key, None)\n\n def getValueDefault(self,key):\n value = getattr(self, key, None)\n if vlaue is None:\n field = self.__mappings__[key]\n value = field.default() if callback(field.default) else field.default\n logging.debug(self,key, value)\n setattr(self, key,vlaue)\n return value\n\n @classmethod\n #类方法有类变量cls传入,可以使用cls做一些处理,并且有子类继承时,调用该方法时,传入的时类变量时子类,而不是父类\n async def findAll(cls, where = None, args = None, **kw):\n '''\n 通过where查找多条记录\n :param cls:\n :param where: 查询条件\n :param args: sql参数\n :param kw: 查询条件列表\n :return: 返回多条记录的集合\n '''\n sql = [cls.__select__]\n #如果where查询条件存在\n if where:\n sql.append('where')\n sql.append(where)\n if args is None:\n args = []\n\n orderBy= kw.get('orderBy', None)\n if orderBy:\n sql.append('orderBy')\n sql.append(orderBy)\n\n limit = kw.get('limit', None)\n if limit is not None:\n sql.append('limit')\n if isinstance(limit, int):\n sql.append('?')\n args.append(limit)\n elif isinstance(limit, tuple) and len(limit) ==2:\n sql.append('?,?')\n args.extend(limit)\n else:\n raise ValueError('limit参数无效:%s' %str(limit))\n rs = await select(''.join(sql), args)\n return [cls(**r) for r in rs]\n\n @classmethod #类方法,区别于默认的实例方法,可以不实例化,通过类.方法调用\n async def findNumber(cls, selectField, where = None, args = None):\n '''\n 查询某个字段的数量\n :param selectField: 要查询的字段\n :param where: where 查询条件\n :param args: 参数列表\n :return: 数量\n '''\n sql = ['select count(%s) _num_ from `%s`' %(selectField, cls.__table__) ]\n if where:\n sql.append('where')\n sql.append(where)\n rs = await select (''.join(sql), args, 1)\n return rs[0]['_num_']\n\n @classmethod\n async def findByID(cls, pk):\n '''\n 通过id查询\n :param pk:id\n :return: 一条记录\n '''\n fi = None\n for field in cls.__fields__:\n if f==field:\n fi = field\n break\n if fi is None:\n raise AttributeError('在%s中没有找到该字段:' %cls.__table__)\n\n rs = await select('%s where `%s`= ?' %(cls.__select__,fi), [cl], 1)\n if len(rs) ==0:\n return None\n return cls(**rs[0])\n\n async def save(self):\n #将__fields__保存的除主键外所有有的属性一次传递到getValueOrDefault函数中获取值\n args = list(map(self.getValueOrDefault, self.__fields__))\n #获取主键值\n args.append(self.getValueOrDefault(self.__fields__))\n #执行insert语句\n rows = await execute(self.__insert__, args)\n if rows !=1:\n logging.warning('插入记录失败:受影响的行数:%s' %rows)\n\n async def update(self):\n args = list(map(self.getValue, self.__fields__))\n args.append(self.getVaule(self.__primary_key__))\n rows = await execute(self.__update__, args)\n if rows !=1:\n logging.warning('更新记录失败:受影响的行数:%s' %rows)\n\n async def delete(self):\n args = [self.getValue(self.__primary_key__)]\n rows = await execute(self.__delete__, args)\n if rows != 1:\n logging.warning('删除记录失败:受影响的行数:%s' %rows)\n\n\n\nif __name__ ==\"__main__\":\n\n class User(Model):\n #定义类的属性到列的映射\n id = IntegerField('id', primary_key = True)\n name = StringField('username')\n email = StringField('email')\n password = StringField('password')\n\n #创建一个实例\n u = User(id= 1234, name= \"kaikai\", email=\"123@qq.com\", password= \"password\")\n print(u)\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\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\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"www/orm.py","file_name":"orm.py","file_ext":"py","file_size_in_byte":12888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"337234133","text":"# BinarySearchTree: A binary search tree.\n# Implement as many operations as possible with recursion.\n# If you can't figure it out recursively, use a loop. (But then refactor\n# your implementation into a recursive one!)\n# Your implementation should pass the tests in test_bst.py.\n# Nikita Rubocki\n\nclass BinarySearchTree:\n\n def __init__(self, key=None, left=None, right=None, parent=None):\n self.left = left\n self.right = right\n self.key = key\n\n def insert(self, child):\n if child.key <= self.key:\n if not self.has_left_child():\n self.left = child\n return\n return self.left.insert(child)\n elif child.key > self.key:\n if not self.has_right_child():\n self.right = child\n return\n return self.right.insert(child)\n elif self.is_leaf():\n if child.key <= self.key:\n self.left = child\n return \n if child.key > self.key:\n self.right = child\n return\n\n def delete(self, key):\n if key < self.key and self.has_left_child():\n self.left = self.left.delete(key)\n return self\n elif key > self.key and self.has_right_child():\n self.right = self.right.delete(key)\n return self\n elif self.key == key:\n # node with only one/no children\n if self.has_children() is False:\n self = None\n return self\n elif self.left is None:\n tempNode = self.right\n self = None\n return tempNode\n elif self.right is None:\n tempNode = self.left\n self = None\n return tempNode\n # node with two children\n minNode = self.right.minimum()\n self.delete(minNode.key)\n minNode.left = self.left\n minNode.right = self.right \n return minNode\n elif self.is_leaf() and self.maximum() is self:\n return self\n \n def search(self, key):\n if self.key == key:\n return self\n elif self.is_leaf() and self.maximum() is self:\n return None\n elif key <= self.key:\n return self.left.search(key)\n return self.right.search(key)\n\n def keys(self, value):\n keys = []\n if value == 'pre':\n keys.append(self.key)\n if not self.is_leaf():\n keys.extend(self.left.keys(value))\n keys.extend(self.right.keys(value))\n return keys\n elif value == 'in':\n if not self.is_leaf():\n keys.extend(self.left.keys(value))\n keys.append(self.key)\n if not self.is_leaf():\n keys.extend(self.right.keys(value))\n return keys\n elif value == 'post':\n if not self.is_leaf():\n keys.extend(self.left.keys(value))\n keys.extend(self.right.keys(value))\n keys.append(self.key)\n return keys\n elif self.is_leaf():\n return self.key\n\n def is_leaf(self):\n return not (self.left or self.right)\n\n def minimum(self):\n if self.left is None:\n return self\n return self.left.minimum()\n\n def maximum(self):\n if self.right is None:\n return self\n return self.right.maximum()\n\n def has_children(self):\n return self.has_left_child() or self.has_right_child()\n \n def has_left_child(self):\n return not (self.left == None)\n\n def has_right_child(self):\n return not (self.right == None)\n\n","sub_path":"bst.py","file_name":"bst.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"238060131","text":"from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter\n\n\nclass Command(BaseXpressDemocracyClubCsvImporter):\n council_id = \"HNS\"\n addresses_name = (\n \"2021-04-01T10:43:33.063903/Democracy_Club__06May2021 - Hounslow.CSV\"\n )\n stations_name = (\n \"2021-04-01T10:43:33.063903/Democracy_Club__06May2021 - Hounslow.CSV\"\n )\n elections = [\"2021-05-06\"]\n csv_delimiter = \",\"\n csv_encoding = \"windows-1252\"\n\n def address_record_to_dict(self, record):\n uprn = record.property_urn.strip().lstrip(\"0\")\n\n if uprn in [\n \"100021554382\", # 104 MARTINDALE ROAD, HOUNSLOW\n \"100021539525\", # 208B BATH ROAD, HOUNSLOW\n \"10090801431\", # FLAT 5 95 MASWELL PARK ROAD, HOUNSLOW\n \"10090801430\", # FLAT 4 95 MASWELL PARK ROAD, HOUNSLOW\n \"100021580780\", # FLAT 2 392 CHISWICK HIGH ROAD, CHISWICK, LONDON\n \"100021514552\", # FLAT 1 36 HAMILTON ROAD, BRENTFORD\n ]:\n return None\n\n if record.addressline6 in [\n \"TW4 6DH\",\n \"TW3 3DW\",\n \"TW3 3TU\",\n \"TW13 5JE\",\n \"W4 4EU\",\n \"TW13 6AB\",\n ]:\n return None\n\n return super().address_record_to_dict(record)\n","sub_path":"polling_stations/apps/data_importers/management/commands/import_hounslow.py","file_name":"import_hounslow.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"330867020","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/12/17 16:24\n# @Author : Zhangyp\n# @File : readini.py\n# @Software: PyCharm\n# @license : Copyright(C), eWord Technology Co., Ltd.\n# @Contact : yeahcheung213@163.com\nimport configparser\nimport logging\n\nlogging.basicConfig(level = logging.DEBUG, filemode = 'a',filename = 'run.log' ,format = ('''[时间]:%(asctime)s\n[线程]:%(thread)s\n[级别]:%(levelname)s\n[路径]:%(pathname)s\n[函数]:%(funcName)s\n[行号]:%(lineno)d\n[信息]:%(message)s\n------------------\n'''))\n#日志启用开关,注释掉即开启日志\n# logging.disable(logging.DEBUG)\n\n# 处理BOM字符(当配置文件被记事本编辑过后,会插入一个bom头)\nBOM = b'\\xef\\xbb\\xbf'\nwith open('config.ini','r+b') as f:\n if BOM == f.read(3):\n content = f.read()\n f.seek(0)\n f.write(content)\n f.truncate()\n\ncf = configparser.ConfigParser()\ncf.read('config.ini',encoding='utf-8')\n# 获取配置节点列表\nsection = cf.sections()\n\n'''将获取到的各节点的key-value放入字典,便于读取'''\ns = {}\nfor i in range(len(section)):\n\tkv = cf.items(section[i])\n\tfor j in range(len(kv)):\n\t\ts[kv[j][0]] = kv[j][1]\n\n# print(s)","sub_path":"dist/readini.py","file_name":"readini.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"517732160","text":"from PIL import Image\nimport os\nfrom os import listdir\nfrom os.path import isfile, join, splitext\n\n\nh_q_size = (640, 480)\nm_q_size = (480, 360)\nl_q_size = (280, 210)\nxh_q_size = (960, 720)\nhd_q_size = (1280, 960)\nfhd_q_size = (1920, 1440)\n\noutput_sizes = [m_q_size, xh_q_size]\n\n_path = \"C:/Users/Lukasz/Python/ErroresBuenos/assets/\\\nphotos/resizing/resize_queue/\"\n\nfiles = [f for f in listdir(_path) if isfile(join(_path, f))]\n\nfor f in files:\n file_name, _ext = splitext(f)\n if _ext == \".png\":\n path_file = _path + f\n\n for size in output_sizes:\n i = Image.open(path_file)\n i.thumbnail(size)\n path_out = f\"C:/Users/Lukasz/Python/ErroresBuenos/assets/photos/resizing/resize_output/png/\"\n i.save(path_out+file_name+f\"-{size[0]}px\"+_ext, optimize=True)\n","sub_path":"lalang/auxil/resize_images_png.py","file_name":"resize_images_png.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"648049245","text":"class Buffer:\n def __init__(self,input):\n self.input=input\n self.p=-1\n def next(self):\n self.p+=1\n if self.p >= len(self.input):\n return None\n else:\n return self.input[self.p]\n def peek(self):\n return self.input[self.p]\nbuffer=Buffer(\"hello\")\ndef ise(ch):\n return ch == 'e'\nfor x in iter(buffer.next,'e'):\n print(x)\nprint(buffer.peek())\nfor x in iter(buffer.next,None):\n print(x)\n","sub_path":"parsing/example/buffer.py","file_name":"buffer.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"346719453","text":"import requests\nfrom bs4 import BeautifulSoup\nimport datetime\nimport string\nimport re\nimport sys\nimport psycopg2\n\nconn = psycopg2.connect(\"dbname='cpa' user='postgres' host='localhost' password='1234'\")\ncur = conn.cursor()\n\nclass Dados():\n\tdef __init__(self, mercadoria, data, vencimento, ajusteAtual, ajusteAnterior, contratosAbertos, volume, abertura, minimo, maximo):\n\t\tself.mercadoria = mercadoria\n\t\tself.data = data\n\t\tself.vencimento = vencimento\n\t\tself.ajusteAtual = ajusteAtual.replace('.', '').replace(',', '.')\n\t\tself.ajusteAnterior = ajusteAnterior.replace('.', '').replace(',', '.')\n\t\tself.contratosAbertos = contratosAbertos.replace('.', '').replace(',', '.')\n\t\tself.volume = volume.replace('.', '').replace(',', '.')\n\t\tself.abertura = abertura.replace('.', '').replace(',', '.')\n\t\tself.minimo = minimo.replace('.', '').replace(',', '.')\n\t\tself.maximo = maximo.replace('.', '').replace(',', '.')\n\nclass DadosFuturo():\n\tdef __init__(self, contratosAbertos, volume, abertura, minimo, maximo):\n\t\tself.contratosAbertos = contratosAbertos\n\t\tself.volume = volume\n\t\tself.abertura = abertura\n\t\tself.minimo = minimo\n\t\tself.maximo = maximo\n\nclass DadosAjuste():\n\tdef __init__(self, mercadoria, data, vencimento, ajusteAtual, ajusteAnterior):\n\t\tself.mercadoria = mercadoria\n\t\tself.data = data\n\t\tself.vencimento = vencimento\n\t\tself.ajusteAtual = ajusteAtual\n\t\tself.ajusteAnterior = ajusteAnterior\n\ndef requestAjuste(data):\n\trAjuste = requests.post('http://www2.bmf.com.br/pages/portal/bmfbovespa/lumis/lum-ajustes-do-pregao-ptBR.asp', data = {'dData1': data})\n\tsoupAjuste = BeautifulSoup(rAjuste.text, 'html.parser')\n\ttable = soupAjuste.find('table', attrs={'id':'tblDadosAjustes'})\n\ttable_body = table.find('tbody')\n\n\treturn table_body\n\t\ndef parseAjuste(data):\n\ttry:\n\t\ttable = requestAjuste(data)\n\texcept:\n\t\treturn -1;\n\tajuste = []\n\ttr = table.find_all('tr')\n\tfor rows in tr:\n\t\ttd = rows.find_all('td')\n\t\trow = [i.text for i in td]\n\t\tif (len(row[0])):\n\t\t\tmercadoria = row[0]\n\t\tvencimento = row[1]\n\t\tprecoAnterior = row[2]\n\t\tprecoAtual = row[3]\n\t\tif mercadoria[:3] == 'BGI' or mercadoria[:3] == 'SFI' or mercadoria[:3] == 'ICF' or mercadoria[:3] == 'CCM':\t\t\t\n\t\t\tajuste.append(DadosAjuste(mercadoria[:3], data, vencimento, precoAtual, precoAnterior))\n\n\treturn ajuste\n\ndef requestFuturo(data, mercadoria):\n\n\trFuturo = requests.post('http://www2.bmf.com.br/pages/portal/bmfbovespa/boletim1/SistemaPregao1.asp', data = {'txtData': data, 'cboMercadoria': mercadoria})\n\tsoupFuturo = BeautifulSoup(rFuturo.text, 'html.parser')\n\ttable = soupFuturo.findAll('script', attrs={'language':'JavaScript'})\n\tmatchObj = re.findall(r'>([0-9]|[0-9][0-9,.]+|[A-Z]\\d\\d )<', str(table[6]))\n\n\treturn matchObj\n\ndef parseFuturo(table, vencimento):\n\n\ttry:\n\t\ti = table.index(vencimento)\n\t\tcontratosAbertos = table[i + 1]\n\t\tvolume = table[i + 5]\n\t\tabertura = table[i + 6]\n\t\tminimo = table[i + 7]\n\t\tmaximo = table[i + 8]\n\texcept:\n\t\tprint(\"vencimento nao encontrado!\")\n\n\treturn DadosFuturo(contratosAbertos, volume, abertura, minimo, maximo)\n\ndef update(start, end):\t\n\n\tstep = datetime.timedelta(days=1)\n\tdados = []\n\n\n\tstart = datetime.datetime.strftime(start, '%Y-%m-%d')\n\tend = datetime.datetime.strftime(end, '%Y-%m-%d')\n\tstart = datetime.datetime.strptime(start, '%Y-%m-%d')\n\tend = datetime.datetime.strptime(end, '%Y-%m-%d')\n\n\tstart += step\n\tmax_date = start\n\twhile start <= end:\n\n\t\tdadosAjuste = parseAjuste(str(start.day).zfill(2) + \"/\" + str(start.month).zfill(2) + \"/\" + str(start.year))\n\n\t\tif (dadosAjuste != -1):\n\n\t\t\tdataFormat = str(start.year).zfill(2) + \"-\" + str(start.month).zfill(2) + \"-\" + str(start.day).zfill(2) \n\n\t\t\tprint(\"Starting request day \" + dataFormat) \n\n\t\t\tmercadoria = dadosAjuste[0].mercadoria\n\t\t\tdata = dadosAjuste[0].data\n\t\t\t\n\t\t\ttable = requestFuturo(data, mercadoria)\n\n\t\t\tfor d in dadosAjuste:\t\n\n\t\t\t\tif (d.mercadoria != mercadoria):\n\t\t\t\t\tmercadoria = d.mercadoria\n\t\t\t\t\ttable = requestFuturo(d.data, mercadoria)\n\n\t\t\t\tf = parseFuturo(table, d.vencimento) \n\t\t\t\tdados.append(Dados(d.mercadoria, dataFormat, d.vencimento.strip(' '), d.ajusteAtual, d.ajusteAnterior, f.contratosAbertos, f.volume, f.abertura, f.minimo, f.maximo))\n\n\t\t\t\tprint(d.data)\n\n\t\t\t\tif datetime.datetime.strptime(d.data, '%d/%m/%Y') > max_date:\n\t\t\t\t\tmax_date = datetime.datetime.strptime(d.data, '%d/%m/%Y')\n\n\t\t\t\tprint(datetime.datetime.strptime(d.data, '%d/%m/%Y'))\n\n\t\tstart += step\n\t\n\tfor d in dados:\n\t\tif (d.mercadoria == 'BGI'):\n\t\t\tcur.execute(\"INSERT INTO boi VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (d.data, d.mercadoria, d.vencimento, d.volume, d.contratosAbertos, d.abertura, d.minimo, d.maximo, d.ajusteAtual, d.ajusteAnterior)) \n\t\telif (d.mercadoria == 'ICF'):\n\t\t\tcur.execute(\"INSERT INTO cafe VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (d.data, d.mercadoria, d.vencimento, d.volume, d.contratosAbertos, d.abertura, d.minimo, d.maximo, d.ajusteAtual, d.ajusteAnterior)) \n\t\telif d.mercadoria == 'CCM':\n\t\t\tcur.execute(\"INSERT INTO milho VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (d.data, d.mercadoria, d.vencimento, d.volume, d.contratosAbertos, d.abertura, d.minimo, d.maximo, d.ajusteAtual, d.ajusteAnterior)) \n\t\telse:\t\t\t\n\t\t\tcur.execute(\"INSERT INTO soja VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (d.data, d.mercadoria, d.vencimento, d.volume, d.contratosAbertos, d.abertura, d.minimo, d.maximo, d.ajusteAtual, d.ajusteAnterior)) \n\t\n\tif len(dados):\n\t\tmax_date = str(max_date.day).zfill(2) + \"/\" + str(max_date.month).zfill(2) + \"/\" + str(max_date.year)\n\t\tcur.execute(\"UPDATE info_geral SET ultima_atualizacao = %s WHERE cpf='00000000000';\", (max_date, ))\n\t\tconn.commit()\n","sub_path":"flask/app/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":5579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"137233937","text":"# coding: utf-8\n\nimport sys\n\nimport sqlalchemy as sa\n\nfrom . import msg\nfrom . import tabelas\nfrom . import varredura\nfrom . import alchemy_utils\n\n\ndef run():\n\n #engine = alchemy_utils.cria_engine('postgresql', 'localhost', 'cauelt',\n # '', 'cep')\n\n engine = alchemy_utils.cria_engine('mysql', 'localhost', 'root',\n '', 'cep2')\n\n msg.exibe('Testando conexao com o banco...', end='')\n if not alchemy_utils.testa_conexao(engine):\n print('FALHOU\\n')\n sys.exit(1)\n\n # conexao estabelecida com sucesso\n print('OK')\n\n msg.exibe('Procurando diretorios com o e-DNE...', end='')\n dirs_encontrados = varredura.busca_recursiva('./edne2db')\n print('PRONTO\\n')\n\n if dirs_encontrados['basico']:\n print('Diretorio com e-DNE basico:')\n\n msg.identacao += 2\n msg.exibe(dirs_encontrados['basico']['caminho'])\n msg.identacao -= 2\n print('')\n\n else:\n print(\"Nenhum diretorio com e-DNE basico encontrado\\n\")\n\n if dirs_encontrados['delta']:\n print('Diretorios com e-DNE delta:')\n msg.identacao += 2\n for dir in dirs_encontrados['delta']:\n msg.exibe(dir['caminho'])\n msg.identacao -= 2\n\n else:\n print('Nenhum e-DNE delta encontrado.')\n if not dirs_encontrados['basico']:\n print('')\n sys.exit(2)\n\n print('')\n\n # cria as tabelas para a população dos dados\n tabelas.Base.metadata.create_all(engine)\n\n # cria a sessão que se comunicará com o BD\n sessao = sa.orm.sessionmaker(bind=engine)()\n\n if dirs_encontrados['basico']:\n # cria os leitores e dados, que lerão as linhas dos arquivos\n mapa_leitores = varredura.cria_leitores_dados(\n dirs_encontrados['basico'])\n\n print('Processando diretorio {}...'\n .format(dirs_encontrados['basico']['caminho']))\n\n msg.identacao += 2\n alchemy_utils.processa_tabelas(mapa_leitores, sessao, envia_a_cada=2000)\n msg.identacao -= 2\n\n if dirs_encontrados['delta']:\n for dir in dirs_encontrados['delta']:\n print('Processando diretorio {}...'.format(dir['caminho']))\n\n mapa_leitores = varredura.cria_leitores_dados(dir)\n\n msg.identacao += 2\n alchemy_utils.processa_tabelas(mapa_leitores, sessao, envia_a_cada=100)\n msg.identacao -= 2\n\nif __name__ == '__main__':\n run()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"335299909","text":"import datetime\r\nimport os\r\nimport tkinter.messagebox\r\nimport cv2\r\n\r\nfrom aip import AipOcr, AipImageClassify\r\nfrom flask import Flask, render_template, request\r\nfrom MyDB import MyDBHelper\r\n\r\ndb = MyDBHelper()\r\n\r\n\r\napp = Flask(__name__)\r\n\r\n#管理员登录方法\r\n@app.route('/login')\r\ndef login():\r\n return render_template('login.html', error=\"false\")\r\n\r\n#管理员注册方法\r\n@app.route('/register')\r\ndef register():\r\n return render_template('register.html')\r\n\r\n#路段查询页面\r\n@app.route('/index')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n\r\n# 首页\r\n@app.route('/')\r\ndef shouye():\r\n return render_template('shouye.html')\r\n\r\n\r\n# 车主登录页面\r\n@app.route('/login01')\r\ndef login01():\r\n return render_template('login01.html')\r\n\r\n\r\n# 交警功能选择页面\r\n@app.route('/policefunction')\r\ndef policefunction():\r\n return render_template('policefunction.html')\r\n\r\n\r\n# 车主功能选择页面\r\n@app.route('/caruserfunction')\r\ndef caruserfunction():\r\n return render_template('caruserfunction.html')\r\n\r\n\r\n# 注册界面\r\n@app.route(\"/doregister\")\r\ndef doregister():\r\n Name = request.args.get(\"Name\")\r\n Password = request.args.get(\"Password\")\r\n print(Name, Password)\r\n args = [Name, Password]\r\n db.add(args)\r\n return render_template(\"login.html\", error1=\"false\")\r\n\r\n# 管理员通过用户名和密码登录 不匹配将显示登录失败\r\n@app.route(\"/dologin\")\r\ndef dologin():\r\n Name = request.args.get('Name')\r\n Password = request.args.get('Password')\r\n args = [Name, Password]\r\n result = db.login(args)\r\n if result == '登录成功':\r\n return render_template(\"policefunction.html\")\r\n else:\r\n # tkinter.messagebox.showwarning(\"系统提示\", \"该用户未注册!请先注册后登陆\")\r\n return render_template(\"login.html\", error=\"true\")\r\n\r\n# 车主通过用户名和密码登录 不匹配将显示登录失败\r\n@app.route(\"/dologin1\")\r\ndef dologin1():\r\n carNum = request.args.get('carNum')\r\n engineNum = request.args.get('engineNum')\r\n args = [carNum, engineNum]\r\n result = db.login01(args)\r\n if result == '登录成功':\r\n return render_template(\"caruserfunction.html\")\r\n else:\r\n return render_template(\"login01.html\")\r\n\r\n# 进入路段查询功能 按路段查询违章数据\r\n@app.route('/infoshow')\r\ndef infoshow():\r\n result = db.showAllUser('学院路')\r\n if result != ():\r\n return render_template('infoshow.html', u=result)\r\n else:\r\n return render_template('infoshowNone.html')\r\n\r\n# 实时监控功能\r\n@app.route('/monitor')\r\ndef monitor():\r\n return render_template(\"monitor.html\")\r\n\r\n# 调用车辆检测功能 将视频流截取成图片 识别公交车与非公交车 并将识别的私家车违章信息记录到数据库\r\n@app.route('/carcheck') # 按钮调用\"车辆检测.py\"\r\ndef carcheck():\r\n # 要提取的视频路径\r\n video_path = os.path.join('./static/video.MOV')\r\n\r\n times = 0\r\n\r\n # 提取视频的频率,每15帧提取一个\r\n frameFrequency = 15\r\n\r\n # 输出图片存放路径\r\n outPutDirName = 'static/pic/'\r\n\r\n if not os.path.exists(outPutDirName):\r\n # 如果文件目录不存在则创建目录\r\n os.makedirs(outPutDirName)\r\n\r\n camera = cv2.VideoCapture(video_path)\r\n\r\n while True:\r\n times += 1\r\n res, image = camera.read()\r\n\r\n if not res:\r\n print('not res , not image')\r\n break\r\n\r\n if times % frameFrequency == 0:\r\n cv2.imwrite(outPutDirName + str(times) + '.jpg', image)\r\n print(outPutDirName + str(times) + '.jpg')\r\n\r\n print(\"图片提取结束,下面开始识别\")\r\n\r\n camera.release()\r\n\r\n # -------------------------- 你的 车牌识别 APPID AK SK --------------------------\r\n APP_ID1 = 'xxxxxxxxxx'\r\n API_KEY1 = 'xxxxxxxxxxxxxxxxxxxxxxx'\r\n SECRET_KEY1 = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'\r\n\r\n client1 = AipOcr(APP_ID1, API_KEY1, SECRET_KEY1)\r\n # -------------------------------------------------------------------------------\r\n\r\n # -------------------------- 你的 车型识别 APPID AK SK --------------------------\r\n APP_ID2 = 'xxxxxxxxxx'\r\n API_KEY2 = 'xxxxxxxxxxxxxxxxxxxxxx'\r\n SECRET_KEY2 = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'\r\n\r\n client2 = AipImageClassify(APP_ID2, API_KEY2, SECRET_KEY2)\r\n\r\n # -------------------------------------------------------------------------------\r\n\r\n # 读取图片\r\n def get_file_content(filePath):\r\n with open(filePath, 'rb') as fp:\r\n return fp.read()\r\n\r\n for pic_num in range(15, 1485, 15):\r\n\r\n image = get_file_content('./static/pic/' + str(pic_num) + '.jpg')\r\n\r\n # 将图片路径以字符串的形式存入变量path\r\n path = '../static/pic/' + str(pic_num) + '.jpg'\r\n\r\n result1 = client1.licensePlate(image) # 调用车牌识别结果\r\n result2 = client2.carDetect(image) # 调用车型识别结果\r\n\r\n # 将公交车和无法识别的图片排除\r\n if 'error_code' in result1.keys() or \"非车类\" == result2['result'][0]['name'] or \"日产贵士\" == result2['result'][0][\r\n 'name'] or \"路虎DC100\" == result2['result'][0]['name']:\r\n print(\"无法识别\")\r\n else:\r\n car_license = (result1['words_result']['number']) # 车牌识别结果\r\n car_shape = (result2['result'][0]['name']) # 车型识别结果\r\n now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 识别时间\r\n\r\n args = [car_license, car_shape, now_time, path]\r\n print(args)\r\n\r\n row = db.add1(args)\r\n print(\"影响的行数\", row)\r\n\r\n return render_template('checkVideoDone.html')\r\n\r\n# 对各个路段的违章记录进行统计 并按降序排序\r\n@app.route('/arr')\r\ndef arrange():\r\n row1 = db.checkplace(\"海淀区--成府路\")\r\n row2 = db.checkplace(\"海淀区--学院路\")\r\n row3 = db.checkplace(\"海淀区--中关村\")\r\n row4 = db.checkplace(\"海淀区--清华东路\")\r\n row5 = db.checkplace(\"海淀区--颐和园路\")\r\n row6 = db.checkplace(\"海淀区--学清路\")\r\n db.placeaddsta(\"海淀区--成府路\", row1)\r\n db.placeaddsta(\"海淀区--学院路\", row2)\r\n db.placeaddsta(\"海淀区--中关村\", row3)\r\n db.placeaddsta(\"海淀区--清华东路\", row4)\r\n db.placeaddsta(\"海淀区--颐和园路\", row5)\r\n db.placeaddsta(\"海淀区--学清路\", row6)\r\n result = db.arrange()\r\n return render_template(\"roadStatistics.html\", u6=result)\r\n\r\n# 车主按照车牌查询\r\n@app.route('/userinfoshow')\r\ndef userinfoshow():\r\n user_result = db.searchUser(\"京FL0278\")\r\n return render_template('userinfoshow.html', u2=user_result)\r\n\r\n# 车主的待审核记录页面\r\n@app.route('/pending')\r\ndef pending():\r\n pending_result = db.searchPending()\r\n if pending_result == None:\r\n return render_template('pendingNone.html')\r\n else:\r\n return render_template('pending.html', u4=pending_result)\r\n\r\n# 车主的已审核记录页面\r\n@app.route('/solved')\r\ndef solved():\r\n solved_result = db.searchSolved()\r\n if solved_result == None:\r\n return render_template('solvedNone.html')\r\n else:\r\n return render_template('solved.html', u5=solved_result)\r\n\r\n# 车主提交申请重新审核\r\n@app.route('/apply')\r\ndef apply():\r\n db.updatecarnumber(\"京FL0278\")\r\n return render_template('applyResponse.html')\r\n\r\n# 交警管理员对提交的记录进行重新审核\r\n@app.route('/policeexamine')\r\ndef policeexamine():\r\n examine_result = db.searchMoreUser()\r\n if examine_result == ():\r\n return render_template('examineNone.html')\r\n else:\r\n return render_template('policeexamine.html', u3=examine_result)\r\n\r\n# 交警判定没有违章\r\n@app.route('/approve')\r\ndef approve():\r\n db.updatecheckIf()\r\n return render_template('checkOK.html')\r\n\r\n# 交警判定车主已违章\r\n@app.route('/disapprove')\r\ndef disapprove():\r\n db.updatecheckIf()\r\n return render_template('checkOK.html')\r\n\r\n# 车主缴费\r\n@app.route('/pay')\r\ndef pay():\r\n return render_template('pay.html')\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"380318102","text":"import random\n\nclass Queue():\n def __init__(self):\n self.queue = []\n\n def enqueue(self, value):\n self.queue.append(value)\n\n def dequeue(self):\n if self.size() > 0:\n return self.queue.pop(0)\n else:\n return None\n\n def size(self):\n return len(self.queue)\n\ndef find_unexplored(room):\n # for direction in room:\n # if room[direction] == '?':\n # return direction\n # return None\n\n unexplored = [dir for dir in room if room[dir] == '?']\n # print (\"unexplored\", unexplored)\n if len(unexplored) == 0:\n return None\n direction = unexplored[random.randint(0, len(unexplored) - 1)]\n return direction\n\ndef find_direction(current_room, target_room_id):\n for direction in current_room:\n if current_room[direction] == target_room_id:\n return direction\n return None\n\ndef traverse_map(player):\n path = []\n starting_room = player.current_room.id\n graph = {}\n unexplored_paths = 0\n\n graph[starting_room] = {}\n for e in player.current_room.get_exits():\n graph[starting_room][e] = '?'\n unexplored_paths += 1\n\n reverse_directions = {'n': 's', 's': 'n', 'e': 'w', 'w': 'e'}\n\n # while there are unexplored paths in graph\n while unexplored_paths > 0:\n current_room = player.current_room.id\n # print (\"current room\", current_room)\n # check if current room has unexplored paths\n if '?' in graph[current_room].values():\n # if so\n # find an unexplored direction from current room\n direction = find_unexplored(graph[current_room])\n # travel in that direction\n player.travel(direction)\n next_room = player.current_room.id\n # add direction to path\n path.append(direction)\n # add directions to graph (replace '?'s)\n graph[current_room][direction] = player.current_room.id\n if not next_room in graph:\n graph[next_room] = {}\n for e in player.current_room.get_exits():\n graph[next_room][e] = '?'\n unexplored_paths += 1\n graph[next_room][reverse_directions[direction]] = current_room\n unexplored_paths -= 2\n\n else:\n # if no paths left\n # perform a bfs to find nearest rom with unexplored path ('?)\n # create empty queue\n q = Queue()\n # enqueue path to current room\n q.enqueue([current_room])\n # create empty visited set\n visited = set()\n\n # while the queue is not empty..\n while q.size() > 0:\n # dequeue path\n p = q.dequeue()\n # grab last room from path\n room = p[-1]\n\n direction = find_unexplored(graph[room])\n\n # check if room has any unexplored exits\n if direction is not None:\n # if so\n # convert room ids in path to usable direction\n for i in range(len(p) - 1):\n d = find_direction(graph[p[i]], p[i + 1])\n # add direction to traversal path\n path.append(d)\n # move player to room using direction\n player.travel(d)\n # break loop\n break\n \n # check if room has been visited \n if room not in visited:\n # if not\n # mark as visited\n visited.add(room)\n # enqueue paths to neighboring rooms\n for e in graph[room]:\n p_copy = p.copy()\n p_copy.append(graph[room][e])\n q.enqueue(p_copy)\n\n return path\n","sub_path":"traverse.py","file_name":"traverse.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"308849622","text":"from bs4 import BeautifulSoup\nimport requests\nimport urllib.request\nfrom time import sleep\nfrom random import randint\nimport os\nimport numpy as np\nfrom refine_image import refine_image\n# 남성화 페이지 갯수는 이렇습니다..\n\n#pages = [str(1)]\n\n\n\n\n\ndef men():\n if not os.path.exists('imageDescente/'):\n os.mkdir('imageDescente/')\n else:\n print(\"you may delete the contents in the image file\")\n pages = [str(i) for i in range(1,17)]\n basicURL = \"\"\"https://shop.descentekorea.co.kr/product/list.do?cate=1140000\\\n&cateList=1140000&brandList=&meterialList=&playerList=&clothesSizeList=&suppliesSizeList=&\\\nshoesSizeList=&priceList=100000%7C300000&etcList=&brandIdList=&meterialIdList=&playerIdList=&\\\nclothesSizeIdList=&suppliesSizeIdList=&shoesSizeIdList=&priceIdList=checkbox_price_1&etcIdList=&schColorList=&\\\nlistsize=20&sort=new&dcRate=&page=\"\"\"\n result = []\n univNum = 0\n for page in pages:\n URL = basicURL + page\n\n # 이거 해야지만 html 형식을 쉽게 다룰 수 있음\n _html = \"\"\n resp = requests.get(URL)\n # 반드시 필요합니다.\n sleep(randint(5,12))\n if resp.status_code == 200:\n _html = resp.text\n # HTML 형식을 쉽게 다루게 해줌\n soup = BeautifulSoup(_html, 'html.parser')\n # 태그가 div이고 class이름이 ly-img인것을 모두 가져와요\n img = soup.find_all(\"div\", class_= \"goods-list__items-img\")\n\n webPrice = soup.find_all(\"div\", class_= \"goods-list__items-price\")\n for num in range(len(webPrice)):\n univNum += 1\n imgLink = img[num].img['src']\n fullLink = 'https:' + imgLink\n textPrice = webPrice[num].get_text('')\n # print(fullLink, textPrice)\n textPrice = textPrice.strip()\n price = int(''.join(textPrice[:-1].split(',')))\n dirIm = \"imageDescente/\"+ \"{:06d}\".format(univNum)+ \".jpg\"\n refine_image(fullLink, dirIm)\n result.append((dirIm, price))\n dtype = [('dir','U24'),('price',int)]\n result = np.array(result, dtype=dtype)\n np.save(\"train_dataDescente.npy\", result)\n print('done!')\n\nif __name__ == '__main__':\n men()\n \n","sub_path":"crawling/crawling_descente.py","file_name":"crawling_descente.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"116362011","text":"import urllib.request\nimport urllib.parse\nfrom bs4 import BeautifulSoup\nimport csv\nimport examine_data as exm\n\nheader = \"https://www.worldcat.org/\"\n\nedition_tail = 'editions?sd=asc&start_edition=1&referer=di&se=yr&qt=sort_yr_asc&editionsView=true&fq='\n\nog_header = ['id', 'Original Title', 'Original Author']\n\nbrief_header = ['Title', 'Author', 'Publisher', 'Series', 'Edition/Format', 'Rating', 'Publication',\n 'Dissertation', 'Summary', 'Subjects', 'More like this', 'Other Databases']\n\ndetail_header = ['Document Type', 'All Authors / Contributors', 'OCLC Number', 'Responsibility', 'Genre/Form',\n 'ISBN', 'ISSN', 'BL Shelfmark', 'Accession No', 'Unique Identifier', 'In', 'Series Title', 'Other Titles',\n 'Description', 'Contents', 'Awards', 'Details', 'Material Type', 'Additional Physical Format',\n 'Notes', 'Language Note', 'Reproduction Notes', 'More information', 'Named Person', 'Performer(s)',\n 'Credits', 'Cartographic Mathematical Data', 'Target Audience', 'Event notes', 'Number of Edition']\n\nlabel_index = {'Title': 0, 'Author': 1, 'Publisher': 2, 'Series': 3, 'Edition/Format': 4, 'Rating': 5, 'Publication': 6,\n 'Dissertation': 7, 'Summary': 8, 'Subjects': 9, 'More like this': 10, 'Other Databases': 11,\n 'Document Type': 12, 'All Authors / Contributors': 13, 'OCLC Number': 14, 'Responsibility': 15,\n 'Genre/Form': 16, 'ISBN': 17, 'ISSN': 18, 'BL Shelfmark': 19, 'Accession No': 20, 'Unique Identifier': 21,\n 'In': 22, 'Series Title': 23, 'Other Titles': 24, 'Description': 25, 'Contents': 26, 'Awards': 27,\n 'Details': 28, 'Material Type': 29, 'Additional Physical Format': 30, 'Notes': 31, 'Language Note': 32,\n 'Reproduction Notes': 33, 'More information': 34, 'Named Person': 35, 'Performer(s)': 36, 'Credits': 37,\n 'Cartographic Mathematical Data': 38, 'Target Audience': 39, 'Event notes': 40, 'Music Type': 41,\n 'Number of Edition': 42}\n\n\nTOTAL_NUM = 43\n\n\n# TODO: methods for reading and writing files\n\ndef read_from_file(in_path, read_header=True):\n res = []\n with open(in_path, 'r') as csvfile:\n file_reader = csv.reader(csvfile)\n if read_header is False:\n next(file_reader, None)\n for row in file_reader:\n res.append(row)\n return res\n\n\n# helper function to write to file\ndef write_to_file(out_path, data, print_lines=False):\n counter = 0\n with open(out_path, 'w') as csvfile:\n s_writer = csv.writer(csvfile)\n for row in data:\n counter += 1\n s_writer.writerow(row)\n if print_lines is True:\n print(row)\n print(\"------------\")\n print(counter)\n\n# TODO: methods for accessing WorldCat via url manipulation and making a beautiful soup\n\n\n# get original url from given author, book name and year published\n# au and yr are flags to indicate whether author name and year to be included in search\ndef get_advanced_search_url(specifiers, au=True, yr=True, ln=True):\n # 1. get author name, book name and year from specifiers\n author_name = specifiers[0]\n book_name = specifiers[1]\n year = specifiers[2]\n language = specifiers[3]\n\n # 2. clean and obtain author name for search\n # NOTE: we only take one word from author's name. we leave searching to the website itself\n author_word = author_name.split(',')[0]\n encoded_author = urllib.parse.quote(author_word).replace(' ', '')\n\n # 3. clean and obtain book name for search\n # first tokenize by '[' and ']'\n first_tokens = book_name.split('[')\n tokens = first_tokens[0].split(' ')\n # encode everything in ascii for url use\n encoded_book_name = ''\n counter = 0\n for each in tokens:\n new_word = urllib.parse.quote(each)\n if counter == 0:\n encoded_book_name += new_word\n else:\n encoded_book_name += '+'\n encoded_book_name += new_word\n counter += 1\n\n # 4. make link and return link, depending on parameters\n link = header + 'search?q=ti%3A' + encoded_book_name\n if au is True:\n link += '+au%3A' + encoded_author\n if ln is True:\n link += '+ln%3A' + language\n if yr is True:\n link += '&fq=yr%3A' + year\n\n link += '+%3E' + \"&qt=advanced&dblist=638\"\n return link\n\n\n# TODO: need error checking for all soup getting and html finding\n\n# get html of the folklore we want and turn into soup\ndef get_soup(raw_link):\n page = urllib.request.urlopen(raw_link)\n raw_soup = BeautifulSoup(page, 'html.parser')\n return raw_soup\n\n\n# get the link to the document that we want\ndef get_result_link(raw_soup):\n\n material = raw_soup.find('tr', {'class': 'menuElem'})\n # print(material)\n detail = material.find('td', {'class': 'result details'})\n # print(detail)\n link_prev = detail.find('div',{'class': 'name'})\n real_link = link_prev.find('a', {'id': 'result-1'}, href=True, text=True)\n link_str = real_link['href']\n real_link = header + link_str\n\n return real_link\n\n\n# TODO: scraping methods for the RESULTS section\n# method to scrape \"Result\" section on the result page\n# input: soup from [author, book name, year published]\n# output: List of tuples containing result key to result value\ndef scrape_results_section(soup):\n to_return = []\n raw_material = soup.find('div', {'id': 'bibdata'})\n\n title = raw_material.find('h1', {'class': 'title'}).getText()\n\n title_tuple = tuple(['Title', title])\n to_return.append(title_tuple)\n\n res_list = raw_material.find_all({'tr'})\n\n for res in res_list:\n text = res.getText()\n res_tuple = clean_result(text)\n if res_tuple is not None:\n to_return.append(res_tuple)\n return to_return\n\n\ndef clean_result(text):\n tokens = [x for x in text.split('\\n') if x is not '' and x is not '\\r']\n key = tokens[0]\n value = ''.join(tokens[1:]).replace('\\xa0', '')\n if 'Publication:' in key:\n key_token = key.split(':')\n key = key_token[0]\n value = key_token[1]\n if key == 'Rating:':\n value = 'not yet rated'\n if key == 'Edition/Format:':\n value = value.split('View all editions and formats')[0]\n\n to_return = None\n if key != 'Search this publication for other articles with the following words:':\n to_return = tuple([key.replace(':', ''), value])\n\n return to_return\n\n\n# TODO: scraping methods for the DETAILS section\n\n# method to scrape \"Details\" section on the result page\ndef scrape_detail_section(soup):\n to_return = []\n raw_material = soup.find('div', {'id': 'details'})\n details_list = raw_material.find_all('tr')\n\n for detail in details_list:\n text = detail.getText()\n res_tuple = clean_detail(text)\n to_return.append(res_tuple)\n return to_return\n\n\n# method to tokenize and clean details into a key value pair\ndef clean_detail(text):\n tokens = text.split(':')\n key = tokens[0].replace('\\n', '')\n value = ''.join(tokens[1:]).replace('\\n', '')\n value = value.replace('\\xa0', '')\n to_return = [key, value]\n return tuple(to_return)\n\n\n# TODO: scraping methods for the EDITION section (also getting oldest link)\n\ndef scrape_edition_section(soup, get_oldest=True):\n edition_count = '-1'\n oldest_edition_url = ''\n try:\n raw_material = soup.find('span', {'id': 'editionFormatType'})\n raw_url = raw_material.find('a')['href']\n\n url_token = raw_url.split('editions?')\n edition_url = header + url_token[0] + edition_tail\n\n edition_soup = get_soup(edition_url)\n\n edition_count = get_edition_count(edition_soup)\n\n if get_oldest is True:\n oldest_edition_url = get_oldest_url(edition_soup)\n\n except (TypeError, AttributeError):\n pass\n\n return edition_count, oldest_edition_url\n\n\ndef get_oldest_url(edition_soup):\n raw_material = edition_soup.find('table', {'class': 'table-results'})\n raw_string = raw_material.find('div', {'class': 'name'})\n url = header + raw_string.find('a')['href']\n return url\n\n\ndef get_edition_count(edition_soup):\n raw_material = edition_soup.find('div', {'id': 'fial-numresults'})\n raw_string = raw_material.find('td')\n raw_text = raw_string.getText()\n text = raw_text.split('out of ')\n return text[1]\n\n\n# TODO: scraping methods for the SIMILAR ITEMS section in place of 'MORE LIKE THIS'\ndef scrape_similar_items(soup):\n to_return = ''\n try:\n raw_material = soup.find('ul', {'id': 'subject-terms-detailed'})\n raw_row = raw_material.getText()\n to_return = clean_similar_items(raw_row)\n except (TypeError, AttributeError):\n pass\n return to_return\n\n\ndef clean_similar_items(text):\n to_return = []\n tokens = text.split('\\n')\n for token in tokens:\n if token != '':\n to_return.append(token)\n\n to_return = '; '.join(to_return)\n return to_return\n\n\n# TODO: scraping methods for the LIBRARY section [Require a different set of packages]\n\n\n# TODO: wrapper method for getting information from a folklore\n# input: the result link generated from advance search generated from [author, book name, year published]\n# output: 1. a List composed of values fitting to the formal\n# 2. (optional) when get_oldest=True, a string for the url of oldest edition\ndef get_info(result_link, get_oldest=True):\n # build row as default\n row = ['No info' for i in range(TOTAL_NUM)]\n # get result of advance research for folklore in html format\n result_soup = get_soup(result_link)\n\n # get brief result and detail for this folklore\n result = scrape_results_section(result_soup)\n detail = scrape_detail_section(result_soup)\n\n # get information from the similar items section\n similar_items = scrape_similar_items(result_soup)\n\n # create a holder for oldest link and edition info\n if get_oldest is True:\n edition_count, oldest_link = scrape_edition_section(result_soup, get_oldest=True)\n else:\n edition_count, oldest_link = scrape_edition_section(result_soup, get_oldest=True)\n\n # modify row\n raw_row = result + detail\n for each in raw_row:\n key = each[0]\n value = each[1]\n index = label_index[key]\n row[index] = value\n\n if similar_items != '':\n row[label_index['More like this']] = similar_items\n else:\n row[label_index['More like this']] = 'No Info'\n\n if edition_count != '-1':\n row[label_index['Number of Edition']] = edition_count\n else:\n row[label_index['Number of Edition']] = 'No Info'\n return row, oldest_link\n\n\n# TODO: helper method to make a dictionary out of brief_result header and details header\n# TODO: Uncomment only when need to change header. Used to generate {label:index}\ndef generate_label_index():\n total_header = brief_header + detail_header\n label_index = {}\n for i, value in enumerate(total_header):\n print(i)\n label_index[value] = i\n print(label_index)\n return label_index\n\n\nif __name__ == \"__main__\":\n # generate_label_index()\n name = 'b0_b1_error_2'\n\n # data = read_from_file('data/real_' + name + '.csv')\n data = read_from_file('data/errors/' + name + '.csv')\n\n result_file = []\n error_file = []\n real_header = og_header + list(label_index.keys())\n result_file.append(real_header)\n\n # generate id_counter\n id_counter = 6256\n print(real_header)\n for folklore in data:\n id_counter += 1\n basic_info = [str(id_counter), folklore[1], folklore[0]]\n try:\n # get info for current version info by doing search with less constraints\n new_folklore, tmp_link = exm.do_search_with_less_constraints(folklore)\n if new_folklore != 'missing' and new_folklore != 'error':\n search_link = tmp_link\n basic_info = [str(id_counter), new_folklore[1], new_folklore[0]]\n else:\n print('*** MISSING ***')\n id_counter -= 1\n print(basic_info[2] + '; ' + basic_info[1])\n error_file.append(folklore)\n print(\"------------------------------------------\")\n continue\n # get to the result page\n soup = get_soup(search_link)\n result_link = get_result_link(soup)\n # get information from result page\n temp_row, old_link = get_info(result_link, get_oldest=True)\n row = basic_info + temp_row\n print(row)\n # print(id_counter)\n result_file.append(row)\n except (TypeError, AttributeError, UnicodeEncodeError) as err:\n print('*** ERROR ***')\n id_counter -= 1\n print(basic_info[2] + '; ' + basic_info[1])\n error_file.append(folklore)\n print(\"------------------------------------------\")\n continue\n except urllib.error.HTTPError as err:\n if str(err).split(':')[0] == 'HTTP Error 403':\n print('quota exceeded at ')\n print(' ' + str(folklore))\n break\n else:\n print('*** NETWORK ERROR ***')\n id_counter -= 1\n print(basic_info[2] + '; ' + basic_info[1])\n error_file.append(folklore)\n print(\"------------------------------------------\")\n continue\n\n try:\n # get info for oldest version info\n if old_link != '':\n basic_info = [str(id_counter) + '_F', folklore[1] + ' (oldest version)', folklore[0]]\n # print(old_link)\n temp_row, _ = get_info(old_link, get_oldest=False)\n row = basic_info + temp_row\n print(row)\n # print(id_counter)\n result_file.append(row)\n except urllib.error.HTTPError as err:\n if str(err).split(':')[0] == 'HTTP Error 403':\n print('quota exceeded at ')\n print(' ' + str(folklore))\n break\n else:\n print('*** NETWORK ERROR ***')\n id_counter -= 1\n print(basic_info[2] + '; ' + basic_info[1])\n error_file.append(folklore)\n print(\"------------------------------------------\")\n continue\n # break\n except (TypeError, AttributeError, UnicodeEncodeError):\n print(\"**********\")\n print('failed to obtain oldest info for ' + folklore[1])\n print(\"**********\")\n print(\"------------------------------------------\")\n print(id_counter)\n\n write_to_file('data/errors/r/' + name + '_result.csv', result_file)\n write_to_file('data/errors/e/' + name + '_error.csv', error_file)\n","sub_path":"retrieve_info.py","file_name":"retrieve_info.py","file_ext":"py","file_size_in_byte":14877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"536716902","text":"#successful experiment!\n\n\nl = 52\nnot_number = \"Error message: not a number\"\nweeks_vacation_clarification = \"Sorry, please enter a number between 0 and 52 for the number of weeks you were on vacation or leave this year: \"\ndef NumberTest(i):\n try:\n val = float(i)\n return True\n except ValueError:\n return False\n\nk = \"\"\nwhile True:\n print(\"How many weeks were you on vacation or leave this year? \")\n k = input()\n if NumberTest(k) is False:\n print(\"Error message: not a number\")\n print(weeks_vacation_clarification)\n continue\n if float(k) < 0:\n continue\n if float(k) >= l:\n continue\n else:\n break\nprint(k, \"is a valid number of weeks\") #return k\n\n#seems to work from a logical standpoint (not thoroughly tested)\n# but my error messages aren't printed\n\n# I'm an idiot - the error messages that aren't printed aren't in this version\n\n\n\n#while True:\n# print('Who are you?')\n# name = input()\n# if name != 'Joe': #(1)\n# continue #(2)\n# print('Hello, Joe. What is the password? (It is a fish.)')\n# password = input() #(3)\n# if password == 'swordfish':\n# break #(4)\n#print('Access granted.') #(5)\n","sub_path":"original_code/experiments/continue_break.py","file_name":"continue_break.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"552984742","text":"\"\"\"\n8-13. User Profile: Start with a copy of user_profile.py from page 153.\nBuild a profile of yourself by calling build_profile(), using your first\nand last names and three other key-value pairs that describe you.\n\"\"\"\n\ndef build_profile(first, last, **user_info):\n \"\"\"Build a dictionary containing everything we know about a user.\"\"\"\n profile = {} # create empty dictionary\n profile['first_name'] = first # add first name to dictionary\n profile['last_name'] = last # add last name to dictionary\n for key, value in user_info.items():\n profile[key] = value # store values in dictionary\n return profile\n\n# butild my profile\nuser_profile = build_profile('Angelica', 'Rodriguez',\n country = 'Mexico',\n field = 'Computer Science',\n age = '20 years')\nprint(user_profile) # print profile\n","sub_path":"Ene-Jun-2019/Angelica Rodriguez/Practica 1/user_profile_8_13.py","file_name":"user_profile_8_13.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"282993458","text":"def f(n):\n width_raw = len(\"{0:b}\".format(n))\n dict_nums = []\n for i in range(1, n + 1):\n dec_num = format(i, \"d\")\n octal_num = format(i, \"o\")\n hex_num = format(i, \"x\").upper()\n bin_num = format(i, \"b\")\n print(\"{0:^{width}} {1:^{width}} {2:^{width}} {3:{width}}\"\n .format(dec_num, octal_num, hex_num, bin_num, width=width_raw))\n dict_nums.append([dec_num, octal_num, hex_num, bin_num])\n return dict_nums\n\n\nif __name__ == \"__main__\":\n n = int(input(\"Please enter n:\"))\n while 1 > n or n > 99:\n n = int(input(\"Please enter n in a range 1 <= n <= 99:\"))\n f(n)\n print(f(17)[16][0])\n","sub_path":"homework6/task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"87534889","text":"from django.contrib import messages\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\n\nfrom overtime.models import OvertimeApplication\nfrom overtime.selectors import get_overtime_application, get_ceo_pending_overtime_applications\nfrom overtime.services import ceo_reject_overtime_application, ceo_approve_overtime_application, \\\n approve_overtime_application_finally\n\n\ndef ceo_role_page(request):\n context = {\n \"dashboard_page\": \"active\",\n }\n return render(request, \"role/ceo/dashboard.html\", context)\n\n\ndef ceo_overtime_page(request):\n # Get the pending overtime applications\n pending_applications = get_ceo_pending_overtime_applications()\n context = {\n \"overtime_page\": \"active\",\n \"pending_applications\": pending_applications\n }\n return render(request, \"role/ceo/overtime.html\", context)\n\n\ndef ceo_overtime_approved_page(request):\n # Get the approved overtime applications\n approved_applications = OvertimeApplication.objects.filter(status=\"Approved\")\n context = {\n \"overtime_page\": \"active\",\n \"approved_applications\": approved_applications\n }\n return render(request, \"role/ceo/approved_applications_page.html\", context)\n\n\ndef ceo_amend_overtime_page(request, id):\n overtime_application = get_overtime_application(id)\n context = {\n \"overtime_page\": \"active\",\n \"overtime_application\": overtime_application\n }\n return render(request, \"role/ceo/amend_overtime.html\", context)\n\n\n# Process\ndef ceo_reject_overtime(request, id):\n ceo_reject_overtime_application(id)\n messages.success(request, \"The overtime application was rejected\")\n context = {\n \"overtime_page\": \"active\"\n }\n return HttpResponseRedirect(reverse(ceo_overtime_page))\n\n\ndef ceo_approve_overtime(request, id):\n ceo_approve_overtime_application(id)\n approve_overtime_application_finally(id)\n messages.success(request, \"The overtime application was approved\")\n context = {\n \"overtime\": \"active\"\n }\n return HttpResponseRedirect(reverse(ceo_overtime_page))\n","sub_path":"role/views/ceo_views.py","file_name":"ceo_views.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"596322223","text":"# Library to automate Libra client\n\n##########\n# Logger #\n##########\nimport logging\nlogger = logging.getLogger(__name__)\n\n###########\n# Imports #\n###########\nimport os\nimport re\nimport sys\nfrom datetime import datetime\nfrom subprocess import Popen, PIPE\nfrom time import sleep\n\n\n#########\n# Funcs #\n#########\ndef start_client_instance(client_path = '', account_file = ''):\n c_path = os.path.expanduser(client_path + \"target/debug/client\")\n args = [c_path, \"--host\", \"ac.testnet.libra.org\", \"--port\", \"80\",\n \"-s\", \"./scripts/cli/trusted_peers.config.toml\"]\n logger.info(' '.join(args))\n p = Popen(args, cwd=os.path.expanduser(client_path),\n shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True, bufsize=0, universal_newlines=True)\n sleep(5)\n p.stdout.flush()\n logger.info(os.read(p.stdout.fileno(), 10000).decode('unicode_escape'))\n logger.info('loading account {}: {}'.format(account_file, do_cmd(\"a r \" + account_file, p = p)))\n sys.stdout.flush()\n\n return p\n\n\ndef do_cmd(cmd, delay=0.5, bufsize=50000, decode=True, p=None):\n p.stdin.write(cmd+'\\n')\n p.stdin.flush()\n sleep(delay)\n p.stdout.flush()\n if decode:\n return os.read(p.stdout.fileno(), bufsize).decode('utf-8')\n else:\n return os.read(p.stdout.fileno(), bufsize)\n\n\ndef get_version_from_raw(s):\n return next(re.finditer(r'(\\d+)\\s+$', s)).group(1)\n\n\ndef get_acct_info(raw_account_status):\n try:\n account = next(re.finditer(r'Account: ([a-z0-9]+)', raw_account_status)).group(1)\n balance = str(int(next(re.finditer(r'balance: (\\d+),', raw_account_status)).group(1)) / 1000000)\n sq_num = next(re.finditer(r'sequence_number: (\\d+),', raw_account_status)).group(1)\n sent_events = next(re.finditer(r'sent_events_count: (\\d+),', raw_account_status)).group(1)\n recv_events = next(re.finditer(r'received_events_count: (\\d+),', raw_account_status)).group(1)\n except:\n logger.exception('Error in getting account info')\n\n return account, balance, sq_num, sent_events, recv_events\n\n\ndef parse_raw_tx(raw):\n ver = int(next(re.finditer(r'Transaction at version (\\d+):', raw)).group(1))\n expiration_num = int(next(re.finditer(r'expiration_time: (\\d+)s', raw)).group(1))\n expiration_num = min(expiration_num, 2147485547) # handle values above max unixtime\n expiration = str(datetime.fromtimestamp(expiration_num))\n sender = next(re.finditer(r'sender: ([a-z0-9]+),', raw)).group(1)\n target = next(re.finditer(r'ADDRESS: ([a-z0-9]+)', raw)).group(1)\n t_type = next(re.finditer(r'transaction: ([a-z_-]+),', raw)).group(1)\n amount = str(int(next(re.finditer(r'U64: (\\d+)', raw)).group(1)) / 1000000)\n gas_price = str(int(next(re.finditer(r'gas_unit_price: (\\d+),', raw)).group(1)) / 1000000)\n gas_max = str(int(next(re.finditer(r'max_gas_amount: (\\d+),', raw)).group(1)) / 1000000)\n sq_num = next(re.finditer(r'sequence_number: (\\d+),', raw)).group(1)\n pubkey = next(re.finditer(r'public_key: ([a-z0-9]+),', raw)).group(1)\n\n return ver, expiration, sender, target, t_type, amount, gas_price, gas_max, sq_num, pubkey, expiration_num\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"269932333","text":"# Convert xml to tags format and save the pothole crops\nimport xml.etree.ElementTree as ET\nimport os\nimport sys\nimport cv2\n\ninputFolderName = '/home/mcw/ML_NAS/Rubicon/SOW2/pothole-retag-data/train/new_tag/front-facing-rubicon_xml/'\n#outputPath = '/home/mcw/ML_NAS/Rubicon/SOW2/pothole-retag-data/val/new_tag/2class/tags/'\nimageDir = '/home/mcw/ML_NAS/Rubicon/SOW2/pothole-retag-data/train/front-facing-rubicon/img/'\nmodimageDir = '/home/mcw/ML_NAS/Rubicon/SOW2/pothole-retag-data/train/img_crops/'\n\n#new tagging lt project\nclasses = {'pothole': 101,\n 'manhole': 102}\n'''\n 'bin_other': 1,\n 'bin_pos': 2,\n 'bus': 3,\n 'car': 4,\n 'person': 5,\n 'trash_object': 6,\n 'truck': 7,\n 'waste_container': 8,\n 'traffic_sign_crosswalk': 9,\n 'traffic_sign_school_crosswalk': 10,\n 'traffic_sign_speed_limit_25': 11,\n 'traffic_sign_speed_limit_35': 12,\n 'traffic_sign_stop': 13,\n 'traffic_sign_stop_ahead': 14,\n }'''\n#res_file = open('img_res.txt', 'w')\nfor path, subdirs, files in os.walk(inputFolderName):\n if len(files) > 0:\n for dirFile in files:\n #print \"dirfile \" + dirFile\n filename = os.path.join(path,dirFile)\n if os.stat(os.path.join(path,dirFile)) == 0:\n continue\n print (\" filename \" + filename)\n if filename.endswith(\".xml\"):\n outputFilename = dirFile.replace('.xml','')\n #print \"outputfilename \" + outputFilename\n tag_count = 0\n pot_count = 0\n Taglist = []\n tree = ET.parse(filename)\n root = tree.getroot()\n for LabelingTool in root.iter('LabelingTool'):\n creator = LabelingTool.find('creator').text # creator\n version = LabelingTool.get('version') # version\n for project in LabelingTool.findall('project'):\n name = project.get('name') # project_name\n for clas in project.findall('class'):\n class_id = clas.get('id')\n for box in clas.findall('boundingbox'): # B_box values\n invisible = \"False\"\n atrList = None\n attr = None\n x1 = box.find('x1').text\n x2 = box.find('x2').text\n y1 = box.find('y1').text\n y2 = box.find('y2').text\n angle = 0\n w = str(int(x2) - int(x1)) # width\n h = str(int(y2) - int(y1)) # height # can be used if needed \n if class_id == \"101\" or class_id == \"102\":\n tag_count = tag_count + 1\n Taglist.append((x1,y1,w,h,angle,int(class_id)))\n if class_id == \"101\":\n if os.path.exists(imageDir + outputFilename):\n img = cv2.imread(imageDir + outputFilename )\n crop = img[int(y1):int(y2), int(x1):int(x2)]\n new_name = modimageDir + \"ffr_\" + outputFilename.split('.jpg')[0] + \"_\" + str(pot_count) + '.jpg' \n cv2.imwrite(new_name, crop)\n pot_count = pot_count + 1\n\n #print( x1 , y1 , w , h , angle , classes[cls])\n '''print(imageDir + outputFilename )\n if os.path.exists(imageDir + outputFilename):\n img = cv2.imread(imageDir + outputFilename )\n new_name = modimageDir + \"ad_\" + outputFilename \n cv2.imwrite(new_name, img)'''\n '''if tag_count > 0:\n fileId = open(outputPath+ \"ad_\" + outputFilename+\".tags\", \"w+\")\n fileId.write(str(tag_count))\n for tag in Taglist:\n x1,y1,w,h,angle,class_id = tag\n fileId.write('\\t' + str(x1) +\" \"+str(y1)+\" \"+str(w)+\" \"+str(h)+\" \"+str(angle)+\" \"+str(class_id))\n fileId.close()'''\n\n","sub_path":"darknet_based/convert_xml_to_tags_save_img.py","file_name":"convert_xml_to_tags_save_img.py","file_ext":"py","file_size_in_byte":4496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"322872394","text":"def mult():\r\n a = float(input(\"Vá inserindo números para serem multiplicados\\\r\n(o número um interromperá o processo): \"))\r\n mul = 1*a\r\n while a!=1:\r\n a = float(input(\"Continue a multiplicação!(1 interrompe o processo): \"))\r\n mul*=a\r\n print (mul)\r\n\r\n\r\nmult()\r\n \r\n","sub_path":"produto com função.py","file_name":"produto com função.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"57451828","text":"from django.contrib import admin\nfrom django.utils.html import format_html\n\nfrom imageboard.models.captcha import Captcha\nfrom imageboard.utils.captchamaker import bytes_to_base64, CAPTCHA_WIDTH, CAPTCHA_HEIGHT\n\n\n@admin.register(Captcha)\nclass CaptchaAdmin(admin.ModelAdmin):\n list_display = ('id', 'board', 'thread', 'ip_address', 'solution', 'thumbnail')\n readonly_fields = ('id', 'board', 'thread', 'ip_address', 'solution', 'thumbnail')\n fields = ('id', 'board', 'thread', 'ip_address', 'solution', 'thumbnail')\n\n def thumbnail(self, obj):\n return format_html(\n '\"{}\"',\n bytes_to_base64(obj.image),\n obj.solution,\n CAPTCHA_WIDTH,\n CAPTCHA_HEIGHT\n )\n thumbnail.short_description = 'Thumbnail'\n","sub_path":"src/imageboard/admin/captcha.py","file_name":"captcha.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"377319628","text":"import json\nimport sys\nimport Board as brd\nimport time as tm\n\n\ndef stream_read(width, height):\n print(\"HELLO-2\")\n for line in sys.stdin:\n print(\"HELLO\")\n sys.stdout.flush()\n sys.stderr.write(line)\n sys.stderr.flush()\n parse = json.loads(line)\n board_array = parse['grid']\n board = brd.Board(board_array)\n return board\n print(\"HELLO-3\")\n\n\n\"\"\"\ndef stream_read(width, height):\n gotBoard = False\n if sys.stdin:\n sys.stderr.write(\"GOT EM\\n\")\n else:\n sys.stderr.write(\"NOTHING\\n\")\n\n readin = sys.stdin\n readin = readin.read()\n \n while gotBoard is False:\n readin = sys.stdin\n readin = readin.read()\n\n if len(readin) == 0:\n tm.sleep(0.5)\n continue\n else:\n gotBoard = True\n\n sys.stderr.write(\"\\\"\" + readin + \"\\\"\" + '\\n')\n sys.stderr.write(str(type(readin)) + '\\n' + str(len(readin)))\n parse = json.loads(readin)\n\n board_array = parse['grid']\n board = brd.Board(board_array)\n return board\n\"\"\"\n\n","sub_path":"src/examples/groupx/Reader.py","file_name":"Reader.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"652734722","text":"#!/IPush/System\r\n#主要是用来登录系统和相关的操作方法'\r\nfrom Html.ReadHtml import *\r\nimport data\r\nfrom urllib import request,parse\r\nimport re\r\ndef loginSystem():#此方法创建一个ReadHtml类型的参数,这个参数所对应的实例未登录到系统,执行此方法后将返回这个参数,但是是已经登录的参数\r\n data1={'agreeProtocol':'1','password':'yjcl6666','rememberMe':'0','userName':'18812345678'}\r\n rep=ReadHtml(url=data.systemUrl,data=data1,contentLength='application/x-www-form-urlencoded')\r\n print(rep.connection())\r\n print(rep.connection())#已登陆系统\r\n return rep\r\n#传入关键参数进行查询并返回查询结果\r\ndef getResault(rep,taskid=\"\",batchNum=\"\",wechatMicro=\"\",logDescribe=\"\",logType=\"\",footName=\"\",deviceNumber=\"\",deviceAsset=\"\",date=\"\"):#得到加粉数\r\n '''\r\n :param rep: 表示一个网页解析器\r\n :param taskid: 任务id\r\n :param batchNum: 任务批号\r\n :param wechatTag: #标签\r\n :param wechatMicro: 微信小号\r\n :param logDescribe: 日志内容\r\n :param logType: 日志类型\r\n :param footName: 脚本类型\r\n :param deviceNumber: 设备编号\r\n :param deviceAsset: 资产编号\r\n :param date: 日期\r\n :param rows:\r\n :return: 限制行数\r\n '''\r\n rep = ReadHtml(url=data.systemUrl)\r\n data1={\r\n \"ftaskid\":taskid, #任务idi\r\n \"fbatch_num\":batchNum, #任务批号i\r\n \"fmicro\":wechatMicro, #微信小号i\r\n \"fdescribe\":logDescribe, #日志内容i\r\n \"flogtype\":logType, #日志类型i\r\n \"script_name\":footName, #脚本类型i\r\n \"fdevice\":deviceNumber, #设备编号i\r\n \"fdevice_asset\":deviceAsset, #资产编号i\r\n \"calc_date_start\":date, #日期i\r\n }#构建查询数据\r\n #tUrl=data.reportUrl+'?'+'act=do_search&report_id=16&action=&refund_id='\r\n res=rep.connection(url=data.reportUrl,contentType=data.contentType,data=data1,xRequestedWith=True)\r\n #对数据解析获取结果\r\n matcher=re.search('(?<=total\\\">)[0-9]+',res)\r\n if(matcher):\r\n return matcher.group()#返回查询网页\r\n else:\r\n return None","sub_path":"python/company/IPush - 副本/System/LoginSystem.py","file_name":"LoginSystem.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"128068979","text":"#!/anaconda3/bin/python3.7\n# -*- coding: utf-8 -*-\n# Plots.py\n# Bernard Schroffenegger\n# 6th of October, 2019\nimport statistics\n\nfrom Tools.BullingerData import *\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom config import *\nplt.rcdefaults()\n\n# colors ('black'/'b', 'white'/'w')\ncb0, cb1, cb2, cb3 = 'royalblue', 'cornflowerblue', 'dodgerblue', 'navy' # 'b'\ncg0, cg1, cg2, cg3 = 'forestgreen', 'darkgreen', 'yellowgreen', 'olivedrab' # 'g'\ncr0, cr1, cr2, cr3 = 'orangered', 'firebrick', 'tomato', 'salmon' # 'r'\ncp0, cp1, cp2, cp3 = 'purple', 'indigo', 'orchid', 'plum' # 'm'\ncga, cgb, cgc, cgd = 'slategray', 'dimgrey', 'darkgrey', 'lightgray' # 'grey'/'gray'\n# gold, silver, ...\n# More: https://i.stack.imgur.com/lFZum.png\n\nROUND = 0\n\n\nclass BullingerPlots:\n\n @staticmethod # Histogram\n def create_plot_correspondence(file_id, sx, sy, rx, ry, x_ticks, bar_width, t, offset, from_to):\n fig = plt.figure()\n ax = plt.axes()\n ax.grid(b=True, which='minor', axis='both', color='#888888', linestyle=':', alpha=0.2)\n ax.grid(b=True, which='major', axis='both', color='#000000', linestyle=':', alpha=0.2)\n avg_s, avg_r = sum(sy)/t, sum(ry)/t\n plt.axhline(y=avg_r, color='g', linestyle='--', alpha=0.4) # avg\n plt.axhline(y=avg_s, color='b', linestyle='--', alpha=0.4)\n if x_ticks[-1] == Config.SD:\n if len(sx) > 0: plt.axvline(x=sx[-1]-offset/4, color=\"black\")\n plt.bar(sx, sy, width=bar_width, align='center', alpha=0.8, color='blue', label=\"gesendet (\"+str(round(avg_s, 2))+\"/Jahr)\")\n plt.bar(rx, ry, width=bar_width, align='center', alpha=0.8, color='lime', label=\"empfangen (\"+str(round(avg_r, 2))+\"/Jahr)\")\n plt.title(\"Bullingers Korrespondenzen\\n \\\"Heinrich Bullinger\\\" \"+from_to)\n plt.xlabel(\"Zeit [Jahre]\")\n plt.ylabel('#Briefe')\n plt.xticks(sx, x_ticks)\n plt.legend() # loc=\"upper left\"\n fig.savefig('App/static/images/plots/correspondence_' + file_id + '.png')\n plt.close()\n\n @staticmethod\n def create_plot_correspondence_year(file_id, sx, sy, rx, ry, x_ticks, bar_width):\n fig = plt.figure()\n ax = plt.axes()\n ax.grid(b=True, which='minor', axis='both', color='#888888', linestyle=':', alpha=0.2)\n ax.grid(b=True, which='major', axis='both', color='#000000', linestyle=':', alpha=0.2)\n avg_s, avg_r = sum(sy)/12, sum(ry)/12\n plt.axhline(y=avg_r, color='g', linestyle='--', alpha=0.4) # avg\n plt.axhline(y=avg_s, color='b', linestyle='--', alpha=0.4)\n if len(rx) > 12: plt.axvline(x=13, color=\"black\")\n plt.bar(sx, sy, width=bar_width, align='center', alpha=0.8, color='blue', label=\"gesendet (\"+str(round(avg_s, 2))+\"/Monat)\")\n plt.bar(rx, ry, width=bar_width, align='center', alpha=0.8, color='lime', label=\"empfangen (\"+str(round(avg_r, 2))+\"/Monat)\")\n plt.title(\"Bullingers Korrespondenzen\\n \\\"Heinrich Bullinger\\\" \"+\"(Januar - Dezember)\")\n plt.xlabel(\"Zeit [Monate]\")\n plt.ylabel('#Briefe')\n plt.xticks(sx, x_ticks)\n plt.legend() # loc=\"upper left\"\n fig.savefig('App/static/images/plots/correspondence_' + file_id + '.png')\n plt.close()\n\n @staticmethod\n def create_plot_correspondence_month(file_id, sx, sy, rx, ry, x_ticks, bar_width, month, year):\n fig = plt.figure()\n ax = plt.axes()\n ax.grid(b=True, which='minor', axis='both', color='#888888', linestyle=':', alpha=0.2)\n ax.grid(b=True, which='major', axis='both', color='#000000', linestyle=':', alpha=0.2)\n avg_s, avg_r = sum(sy)/31, sum(ry)/31\n plt.axhline(y=avg_r, color='g', linestyle='--', alpha=0.4) # avg\n plt.axhline(y=avg_s, color='b', linestyle='--', alpha=0.4)\n if len(rx) > 31: plt.axvline(x=33, color=\"black\")\n plt.bar(sx, sy, width=bar_width, align='center', alpha=0.8, color='blue', label=\"gesendet (\"+str(round(avg_s, 2))+\"/Monat)\")\n plt.bar(rx, ry, width=bar_width, align='center', alpha=0.8, color='lime', label=\"empfangen (\"+str(round(avg_r, 2))+\"/Monat)\")\n plt.title(\"Bullingers Korrespondenzen\\n \\\"Heinrich Bullinger\\\" \"+\"(\"+month+\" \"+str(year)+\")\")\n plt.xlabel(\"Zeit [Tage]\")\n plt.ylabel('#Briefe')\n plt.xticks(sx, x_ticks)\n plt.legend() # loc=\"upper left\"\n fig.savefig('App/static/images/plots/correspondence_' + file_id + '.png')\n plt.close()\n\n @staticmethod # Pie\n def create_plot_overview_stats(file_id, sizes):\n labels = [\"offen\", \"abgeschlossen\", \"unklar\", \"ungültig\"]\n colors = [\"navy\", \"forestgreen\", \"orange\", \"red\"]\n fig = plt.figure()\n explode = (0, 0.2, 0, 0)\n patches, texts = plt.pie(sizes, explode=explode, colors=colors, shadow=True, startangle=90)\n plt.legend(patches, labels, loc=\"upper right\")\n plt.axis('equal')\n plt.tight_layout()\n fig.savefig('App/static/images/plots/overview_'+file_id+'.png')\n plt.close()\n return 'images/plots/overview_'+file_id+'.png'\n\n\nclass ScatterPlot:\n\n def __init__(self, x, y, alpha=0.7, color='b'):\n self.x, self.y = x, y\n self.alpha = alpha\n self.color = color\n\n @staticmethod\n def create(x, y, alpha=1, color='b', size=10,\n title='', xlabel='', ylabel='',\n x_min=None, x_max=None, y_min=None, y_max=None,\n x_ticks=None, y_ticks=None,\n output_path=None, show=True,\n reverse_x=False, reverse_y=False,\n function=None):\n if isinstance(alpha, list) and isinstance(size, list):\n for i, a in enumerate(alpha):\n plt.scatter(x[i], y[i], alpha=a, s=len(x[i]) * [size[i]], color=color[i])\n else:\n plt.scatter(x, y, alpha=alpha, s=len(x) * [size], color=color)\n if function: function(plt)\n plt.title(title)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.xticks(x_ticks) if x_ticks else None # e.g. np.arange(0, 1, step=0.2)\n plt.yticks(y_ticks) if y_ticks else None\n axes = plt.gca()\n axes.set_xlim([x_min, x_max]) if x_min and x_max else None\n axes.set_ylim([y_min, y_max]) if y_min and y_max else None\n plt.xlim(plt.xlim()[::-1]) if reverse_x else None\n plt.ylim(plt.ylim()[::-1]) if reverse_y else None\n fig = plt.gcf() # get current figure\n if output_path:\n plt.draw()\n fig.savefig(output_path, dpi=200)\n plt.show() if show else plt.close(fig)\n\n\n# Bullinger specific\ndef stats(df, columns=None):\n \"\"\" averages and standard deviations\n :param columns: . indices\n :param df: \n :return: \"\"\"\n s = ['axis', 'mean', 'dev']\n d = pd.DataFrame(columns=s)\n for column in columns:\n mean = round(sum(df.loc[:, column]) / len(list(df.loc[:, column])), ROUND)\n std_dev = round(statistics.stdev(df.loc[:, column]), ROUND)\n d = pd.concat([d, pd.DataFrame({s[0]: [column], s[1]: [mean], s[2]: std_dev})])\n return d\n\n\ndef draw_grid(plt):\n \"\"\" appends the grid of a typical index card to plot \"\"\"\n x0, x1, x2, x3 = 0, 3057, 6508, 9860\n y0, y1, y2, y3, y4, y5, y6, y7, y8 = 0, 1535, 2041, 2547, 3053, 3559, 4257, 5303, 6978\n alpha, linewidth = 0.3, 0.5\n\n # Vertical Lines\n plt.plot((x0, x0), (y0, y8), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x1, x1), (y0, y8), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x2, x2), (y0, y5), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x3, x3), (y0, y8), 'black', alpha=alpha, linewidth=linewidth)\n\n # Horizontal Lines\n plt.plot((x0, x3), (y0, y0), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x0, x3), (y1, y1), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x0, x3), (y2, y2), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x0, x3), (y3, y3), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x0, x3), (y4, y4), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x0, x3), (y5, y5), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x0, x1), (y6, y6), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x1, x3), (y7, y7), 'black', alpha=alpha, linewidth=linewidth)\n plt.plot((x0, x3), (y8, y8), 'black', alpha=alpha, linewidth=linewidth)\n\n\nclass BarChart:\n\n @staticmethod\n def create_plot_overview(file_id, offen, abgeschlossen, unklar, ungueltig):\n fig = plt.figure()\n bars = ('offen', 'abgeschlossen', 'unklar', 'ungültig')\n y_pos = np.arange(len(bars))\n performance = [offen, abgeschlossen, unklar, ungueltig]\n plt.bar(y_pos, performance, align='center', alpha=0.5)\n plt.xticks(y_pos, bars)\n plt.ylabel('Anzahl Karteikarten')\n fig.savefig('App/static/images/plots/overview_' + file_id + '.png')\n plt.close()\n","sub_path":"Tools/Plots.py","file_name":"Plots.py","file_ext":"py","file_size_in_byte":8928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"558443811","text":"import numpy as np\nfrom scipy.optimize import minimize\n\nfrom random import uniform\nfrom sklearn import svm\nfrom sklearn.metrics import accuracy_score\nimport matplotlib.pyplot as plt\n\ndataset = []\nlabels = []\ncolors = []\ncolors_h = []\nn = 100 # training set size (must be larger than m to avoid fuck up)\nm = 2 # features\nC = 1.0/n # SVM regularization parameter\na = 0 # random attack size\nA = 0\nB = 100\neps = 0.1*(B-A) # upper bound for norm of h\ndelta = 1e-7 # iteration precision level\nmaxit = 100 # iteration number limit\nfor i in range(0, n):\n point = []\n for j in range(0, m):\n point.append(uniform(A, B))\n dataset.append(point)\n # change\n if sum([p**2 for p in point]) >= 5000:\n labels.append(1.0)\n colors.append((1, 0, 0))\n else:\n labels.append(-1.0)\n colors.append((0, 0, 1))\n\n# random attack\nfor i in range(0, a):\n if labels[i] == 1:\n labels[i] = -1\n colors[i] = (0, 0, 1)\n else:\n labels[i] = 1\n colors[i] = (1, 0, 0)\nsvc = svm.SVC(kernel='linear', C=C).fit(dataset, labels)\nx_svc = list(svc.coef_[0])\nx_svc.append(svc.intercept_[0])\npredicted_labels = svc.predict(dataset)\nerr_orig = 1 - accuracy_score(labels, predicted_labels)\n\n\ndef adv_obj(x):\n av = 0.0\n for i in range(0, n):\n av += max(labels[i]*(np.dot(dataset[i], x[:m])+x[m]), -1.0)\n return av/n\n\n\ndef class_obj_inf(x):\n av = 0.0\n for i in range(0, n):\n av += max(1-labels[i]*(np.dot(dataset[i], x[:m])+x[m]+x[m+1+i]), 0)\n return np.dot(x[:m], x[:m])/2.0 + C*av\n\n\ndef class_obj_orig(x):\n av = 0.0\n for i in range(0, n):\n av += max(1-labels[i]*(np.dot(dataset[i], x[:m])+x[m]), 0)\n return np.dot(x[:m], x[:m])/2.0 + C*av\n\n\ndef attack_norm_constr(x, w):\n ret = 0.0\n for i in range(0, n):\n ret += x[m+1+i]**2\n return -(ret/n)+np.dot(w, w)*(eps**2)\n\n\ndef adv_constr(x, p, q):\n ret = []\n ret.append(q - adv_obj(x))\n ret.append(adv_obj(x) - p)\n return ret\n\n\ndef obj_h(x):\n return np.dot(x, x)\n\n\ndef constr_h(x, w, g):\n ret = []\n for i in range(0, n):\n ret.append(x[i]*w[0]+x[n+i]*w[1]-g[i])\n return ret\n\n# iterative scheme\nnit = 0\nw_svc = np.array([0.5 for i in range(0, m)])\nw_svc[0] = 0.0\nb_svc = 0\nw_opt = np.array([1.0 for i in range(0, m)])\nb_opt = 1\nx_opt = np.array([1.0 for i in range(0, m+n+1)])\nu = err_orig\nv = 10.0\noptions = {'maxiter': 100}\nwhile abs(w_svc[0]/w_opt[0] - w_svc[1]/w_opt[1]) > delta and nit < maxit:\n print('iteration '+str(nit))\n con1 = {'type': 'ineq', 'fun': attack_norm_constr, 'args': [w_opt]}\n con2 = {'type': 'ineq', 'fun': adv_constr, 'args': [u, v]}\n cons = [con1, con2]\n sol = minimize(class_obj_inf, x_opt, method='SLSQP', bounds=None, options=options, constraints=cons)\n x_opt = list(sol.x)\n w_opt = sol.x[:m]\n b_opt = sol.x[m]\n g_opt = sol.x[m+1:]\n print(sol.message)\n print(sol.nit)\n print('maxcv is ' + str(attack_norm_constr(x_opt, w_opt))+' and '+str(min(adv_constr(x_opt, u, v))))\n if not sol.success:\n print('u = '+str(u)+' v = '+str(v)+' no sol')\n tmp = u\n u = v\n v = 2*v - tmp\n else:\n print('u = ' + str(u) + ' v = ' + str(v) + ' exist sol')\n v = (u+v)/2\n sol.clear()\n # restoring h\n h0 = np.array([1 for i in range(0, 2 * n)])\n con_h = {'type': 'eq', 'fun': constr_h, 'args': [w_opt, g_opt]}\n cons_h = ([con_h])\n sol_h = minimize(obj_h, h0, bounds=None, constraints=cons_h)\n h = list(sol_h.x)\n sol_h.clear()\n dataset_infected = []\n for i in range(0, n):\n temp = []\n for j in range(0, m):\n temp.append(dataset[i][j] + h[j * n + i])\n dataset_infected.append(temp)\n svc = svm.SVC(kernel='linear', C=C).fit(dataset_infected, labels)\n w_svc = svc.coef_[0]\n b_svc = svc.intercept_[0]\n nit += 1\n\npredicted_labels_inf = np.sign([np.dot(dataset[i], w_opt)+b_opt for i in range(0, n)])\nerr_inf = 1 - accuracy_score(labels, predicted_labels_inf)\nprint(w_opt)\nprint(b_opt)\nprint(w_svc)\nprint(b_svc)\nprint(err_orig)\nprint('err on w from opt '+str(err_inf))\npr_lb = svc.predict(dataset)\nerr_infc = 1 - accuracy_score(labels, pr_lb)\nprint('err of csvm on infected' + str(err_infc))\n####################\nnsim = 100\neps_list = [eps]\nh_list = []\n# generating random attacks\ntemp = np.random.normal(0.0, 1.0, nsim*n*2)\nfor i in range(0, n*nsim):\n t = np.array([])\n nrm = 0.0\n for j in range(0, m):\n t = np.append(t, temp[i + j * nsim * n])\n nrm += temp[i + j * nsim * n]**2\n h_list.append([t[k]/nrm**0.5 for k in range(0, m)])\n# separation on nsim lists\nh_d_list = []\nfor i in range(0, nsim):\n h_d_list.append([h_list[i + j * nsim] for j in range(0, n)])\n# c-svm optimization\nerrs = []\nmaxerrs = []\nmaxerr_hs = []\nfor e in eps_list:\n maxerr = 0.0\n maxerr_h = []\n for h in h_d_list:\n infected_dataset = [[dataset[j][i] + e * h[j][i] for i in range(0, m)] for j in range(0, n)]\n svc = svm.SVC(kernel='linear', C=C).fit(infected_dataset, labels)\n predicted_labels = svc.predict(dataset)\n err = 1 - accuracy_score(labels, predicted_labels)\n errs.append(err)\n if err > maxerr:\n maxerr = err\n maxerr_h = h\n maxerrs.append(maxerr)\n maxerr_hs.append(maxerr_h)\n colors_h.append((0, 1, 0))\nprint('svc is done')\nprint('mc maxerr '+str(maxerrs))\n####################\nplt.subplot(221)\nplt.title('original')\nplt.scatter([float(i[0]) for i in dataset], [float(i[1]) for i in dataset], c=colors, cmap=plt.cm.coolwarm)\nplt.subplot(222)\nplt.title('infected')\nplt.scatter([float(i[0]) for i in dataset_infected], [float(i[1]) for i in dataset_infected], c=colors, cmap=plt.cm.coolwarm)\nplt.show()","sub_path":"new_ideas_0517/adversary_upper_bound_test.py","file_name":"adversary_upper_bound_test.py","file_ext":"py","file_size_in_byte":5729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"56647092","text":"import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\n\r\ndef L2norm(f1, f2):\r\n '''\r\n Problem 1:\r\n 2. Implement a function to measure \"Euclidean distance\" between two features (i.e., L2 norm)\r\n '''\r\n return np.linalg.norm(f1 - f2)\r\n\r\ndef main():\r\n '''\r\n main funtion\r\n '''\r\n img1 = cv2.imread('images/box.png', cv2.IMREAD_GRAYSCALE)\r\n img2 = cv2.imread('images/box_in_scene.png', cv2.IMREAD_GRAYSCALE)\r\n if not os.path.exists('output'):\r\n os.makedirs('output')\r\n\r\n '''\r\n Problem 1: SIFT local feature extraction and matching\r\n '''\r\n '''\r\n 1. Extract SIFT features from the images using OpenCV\r\n Save the results as \"box_sift.jpg\" and \"box_in_scene_sift.jpg\"\r\n '''\r\n sift = cv2.xfeatures2d.SIFT_create()\r\n kp1, des1 = sift.detectAndCompute(img1, None)\r\n img = cv2.drawKeypoints(img1, kp1, None)\r\n cv2.imwrite('output/box_sift.jpg', img)\r\n kp2, des2 = sift.detectAndCompute(img2, None)\r\n img = cv2.drawKeypoints(img2, kp2, None)\r\n cv2.imwrite('output/box_in_scene_sift.jpg', img)\r\n\r\n '''\r\n 3. Use the implemented function to measure the pairwise distance between each feature from\r\n box.png and each feature from box_in_scene.png\r\n '''\r\n m1 = des1.shape[0]\r\n m2 = des2.shape[1]\r\n distance = np.zeros((m1, m2))\r\n for x1 in range(m1):\r\n for x2 in range(m2):\r\n distance[x1, x2] = L2norm(des1[x1], des2[x2])\r\n '''\r\n 4. Based on the distance matrix, for each feature in box.png, find the corresponding feature in\r\n box_in_scene.png. Visualize the matching results with lines. Only display 50 best matches\r\n '''\r\n distp = distance.reshape(m1 * m2)\r\n min50idx = distp.argsort()\r\n smp1 = min50idx / m2 # match point in image 1\r\n smp2 = min50idx % m2 # match point in image 2\r\n # find matches (not duplicated features)\r\n mp1 = []\r\n mp2 = []\r\n count = 0\r\n ip = 0\r\n while count < 50:\r\n if not(smp1[ip] in mp1) and not(smp2[ip] in mp2):\r\n mp1.append(smp1[ip])\r\n mp2.append(smp2[ip])\r\n count += 1\r\n ip += 1\r\n\r\n '''\r\n Visualize the matching results with lines\r\n '''\r\n h1, w1 = img1.shape\r\n h2, w2 = img2.shape\r\n out_image = np.zeros((max(h1, h2), w1 + w2))\r\n out_image[0:h1, 0:w1] = img1\r\n out_image[0:h2, w1:] = img2\r\n plt.figure()\r\n plt.imshow(out_image)\r\n for i in range(len(mp1)):\r\n ip1 = mp1[i]\r\n ip2 = mp2[i]\r\n plt.plot((kp1[ip1].pt[0], kp2[ip2].pt[0] + w1) , (kp1[ip1].pt[1], kp2[ip2].pt[1]), 'k-')\r\n plt.savefig('output/matching.jpg')\r\n\r\n '''\r\n 5. Use BFMatcher of OpenCV to do the same matching\r\n '''\r\n # create BFMatcher object\r\n bf = cv2.BFMatcher()\r\n # Match descriptors.\r\n matches = bf.knnMatch(des1, des2, k=2)\r\n # Apply ratio test\r\n good = []\r\n for m, n in matches:\r\n if m.distance < 0.75 * n.distance:\r\n good.append(m)\r\n # cv2.drawMatchesKnn expects list of lists as matches.\r\n img3 = cv2.drawMatches(img1, kp1, img2, kp2, good, None, flags=2)\r\n plt.figure()\r\n plt.imshow(img3)\r\n plt.savefig('output/matching2.jpg')\r\n\r\n '''\r\n Problem 2: SIFT matching spatial verification\r\n '''\r\n #match_RANSAC(kp1, des1, kp2, des2, 'output/box_match_RANSAC.jpg')\r\n '''\r\n 1. Use the OpenCV's cv2.findHomography function to find the homography between SIFT features\r\n in one image (box.png) to SIFT features in the other image (box_in_scene.png) using RANSAC\r\n '''\r\n src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)\r\n dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)\r\n\r\n M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)\r\n matchesMask = mask.ravel().tolist()\r\n\r\n '''\r\n 2. Visualize the bounding box of the object in box_in_scene.png using the homography matrix.\r\n Also visualize the valid SIFT matches yourself\r\n '''\r\n h, w = img1.shape\r\n pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)\r\n dst = cv2.perspectiveTransform(pts, M)\r\n\r\n img2 = cv2.polylines(img2, [np.int32(dst)], True, 255, 3, cv2.LINE_AA)\r\n\r\n draw_params = dict(matchColor=(0, 255, 0), # draw matches in green color\r\n singlePointColor=None,\r\n matchesMask=matchesMask, # draw only inliers\r\n flags=2)\r\n\r\n img3 = cv2.drawMatches(img1, kp1, img2, kp2, good, None, **draw_params)\r\n\r\n plt.figure()\r\n plt.imshow(img3, 'gray')\r\n plt.savefig('output/box_match_RANSAC.jpg')\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"pa6/pa5.py","file_name":"pa5.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"400356254","text":"\"\"\"\n\n\"\"\"\nimport csv\nimport cStringIO\nimport datetime\nimport inspect\nfrom webob import Response\nfrom pyramid_handlers import action\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom gateway.models import Base\nfrom gateway import models\nfrom gateway.utils import nice_print\n\nsession = models.DBSession()\n\ndef findModel(modelName):\n \"\"\" Inspects model module and returns dict \"\"\"\n klass = getattr(models,modelName)\n if klass:\n query = session.query(klass).all()\n mapper = klass.__mapper__ \n return {\"class\" : klass, \"query\" : query, \"mapper\" : mapper}\n else:\n return None\n\ndef findTable(possible):\n if inspect.isclass(possible[1]):\n if issubclass(possible[1],Base):\n return possible[1]\n\nclass ExportLoadHandler(object):\n def __init__(self,request):\n self.request = request\n self.breadcrumbs = [{\"text\":\"Manage Home\", \"url\":\"/\"}]\n\n @action(renderer=\"sys/index.mako\")\n def index(self):\n return {} \n\n @action()\n def export(self):\n s = cStringIO.StringIO()\n csvWriter = csv.writer(s)\n modelName = str(self.request.params.get(\"model\"))\n results = findModel(modelName)\n if results:\n csvWriter.writerow(nice_print(results[\"query\"][0]).keys()) \n csvWriter.writerows([nice_print(x).values() for x in results[\"query\"]])\n s.reset()\n resp = Response(s.getvalue())\n resp.content_type = 'application/x-csv'\n resp.headers.add('Content-Disposition',\n 'attachment;filename=%s:data.csv' % modelName)\n return resp \n else:\n return Response(\"Unable to find table\") \n\n @action(renderer=\"sys/download.mako\",permission=\"admin\")\n def download(self):\n breadcrumbs = self. breadcrumbs[:]\n breadcrumbs.append({'text': 'Download data'})\n tables = []\n members = inspect.getmembers(models)\n for member in members:\n table = findTable(member)\n if table:\n tables.append(table)\n return {\n 'breadcrumbs': breadcrumbs,\n 'tables' : tables}\n\n\n","sub_path":"gateway/sys.py","file_name":"sys.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"295449631","text":"from pyppl import PyPPL, Proc\n\npHeatmap = Proc(desc = 'Draw heatmap.')\npHeatmap.input = {'seed': [1,2,3,4,5]}\npHeatmap.output = \"outfile:file:heatmap{{i.seed}}.png\"\npHeatmap.exdir = \"./export\"\n# Don't cache jobs for debugging\npHeatmap.cache = False\n# Output debug information for all jobs, but don't echo stdout and stderr\npHeatmap.echo = {'jobs': range(5), 'type': ''}\npHeatmap.args.ncol = 10\npHeatmap.args.nrow = 10\npHeatmap.lang = 'Rscript' # or /path/to/Rscript if it's not in $PATH\npHeatmap.script = \"\"\"\nset.seed({{i.seed}})\nmat = matrix(rnorm({{args.ncol, args.nrow | lambda x, y: x*y}}), ncol={{args.ncol}})\npng(filename = \"{{o.outfile}}\", width=150, height=150)\n\n# have to be on stderr\ncat(\"pyppl.log.debug:Plotting heatmap #{{job.index | lambda x: int(x) + 1}} ...\", file = stderr())\n\nheatmap(mat)\ndev.off()\n\"\"\"\n\nPyPPL({\n\t'_log': {\n\t\t'levels' : 'basic',\n\t\t'lvldiff': []\n\t}\n}).start(pHeatmap).run()","sub_path":"tutorials/debugScript/debugScript.py","file_name":"debugScript.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"195502604","text":"import requests\r\n\r\n# Build base URL\r\nHOST = \"https://api.census.gov/data\"\r\nyear = \"2010\"\r\ndataset = \"dec/sf1\"\r\nbase_url = \"/\".join([HOST, year, dataset])\r\n# https://api.census.gov/data/2010/dec/sf1\r\n\r\n# Specify Census variables and other predicates\r\n\r\n# \"P013001\" (median age)\r\n# \"P037001\" (average family size)\r\n\r\nget_vars = [\"NAME\", \"P013001\", \"P037001\"]\r\npredicates = {}\r\npredicates[\"get\"] = \",\".join(get_vars)\r\npredicates[\"for\"] = \"state:*\"\r\n\r\n# Execute the request, examine text of response object\r\nr = requests.get(base_url, params=predicates)\r\nprint(r.text)","sub_path":"40. census_api_request/census_api_request.py","file_name":"census_api_request.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"204219592","text":"################################################\r\n############### LinkedIn Scraper ###############\r\n################################################ \r\n\r\n\r\n\r\n#########################\r\n######### Notes #########\r\n#########################\r\n\r\n# Note that this was created for a research project. The algorithm signs into your\r\n# LinkedIn account and then performs automated searches, looking first for the user's\r\n# name and \"World Bank\" (ex: \"John Smith World Bank\"). If the user is not found, it\r\n# searches for the user's name and \"IFC\" (ex: \"John Smith IFC\"). If the user is still\r\n# not found, it searches for the user's name only (ex: \"John Smith\"). The algorithm\r\n# then goes to the user's LinkedIn page and scrapes information about the user \r\n# (handling all possible edge cases) and outputs the data as a dataframe with the \r\n# following columns:\r\n # author: User's name\r\n # curr_location: User's current location from LinkedIn page\r\n # connections: Number of user's connections \r\n # jobs: List of JSOBObjects/hash tables/data dictionaries, one for each job listed on LinkedIn page, as follows:\r\n # job_title: User's title at job\r\n # company: Company listed for user's job\r\n # beg_month: If the user worked at this job form Aug 2013 - May 2017, \"Aug\"\r\n # beg_year: If the user worked at this job form Aug 2013 - May 2017, \"2013\"\r\n # end_month: If the user worked at this job form Aug 2013 - May 2017, \"May\"\r\n # end_year: If the user worked at this job form Aug 2013 - May 2017, \"2017\"\r\n # location: Location of this job\r\n # education: List of JSOBObjects/hash tables/data dictionaries, one for each education listed on LinkedIn page, as follows:\r\n # university: University for this education\r\n # degree level: i.e. Ph.D., B.S., M.A.\r\n # field of study: i.e. Finance, Mathematics, Computer Science\r\n # beg_month: If the user studied at this university form Aug 2013 - May 2017, \"Aug\"\r\n # beg_year: If the user studied at this university form Aug 2013 - May 2017, \"2013\"\r\n # end_month: If the user studied at this university form Aug 2013 - May 2017, \"May\"\r\n # end_year: If the user studied at this university form Aug 2013 - May 2017, \"2017\"\r\n\r\n\r\n# If you want to use this algorithm for your own purposes, remove \r\n# '%20World%20Bank' from the URL in lines 176, delete lines 185 to 204, and add \r\n# print('\\n' + authors[i] + ' not found.') or something similar in the except clause 185.\r\n\r\n\r\n###############################################\r\n################### Example ################### \r\n############################################### \r\n \r\n### Before running, you must install:\r\n # 1. selenium\r\n # 2. requests\r\n # 3. bs4\r\n # 4. Webdriver (download chrome webdriver from the internet like any other file to a location on your computer you can easily reference. Selenium will most likely never find the version that was authomatically installed.)\r\n\r\n########################\r\n# Open Chrome Webdriver (wait for it to open before doing anything else)\r\n \r\n # This is where you saved webdriver on your computer\r\nwhere_you_saved_webdriver = r'C:\\Users\\...'\r\nbr = webdriver.Chrome(where_you_saved_webdriver)\r\n\r\n########################\r\n# Read in authors\r\n\r\n # Set working directory\r\nimport os\r\nos.chdir(r'C:\\Users\\...')\r\n\r\ndataset = pd.read_csv('dataset.csv')\r\n\r\nLinkedIn_Users = dataset['LinkedIn Users']\r\n\r\n########################\r\n# Scrape the data\r\n\r\n# Initialize Class\r\nmy_scraper = LinkedIn_Scraper()\r\n\r\n# Sign into LinkedIn\r\nmy_scraper.Login(\"yourEmail@gmail.net\", \"yourPassword\")\r\n\r\n# Scrape the data and capture it as my_data\r\nmy_data = my_scraper.scrape_all(LinkedIn_Users)\r\n\r\n# If you have to stop the code before it finishes looking for all LinkedIn users, \r\n# you can capture the data as follows:\r\nmy_data = my_scraper.authors_df\r\n\r\nmy_data.to_csv('LinkedIn_Scrape.csv')\r\n\r\n###############################################\r\n################## Your Work ################## \r\n############################################### \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n###################################################\r\n################## The Algorithm ################## \r\n###################################################\r\n\r\n\r\n\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.by import By\r\nfrom time import sleep\r\nfrom random import randint\r\nfrom requests import get\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport re\r\n\r\nclass LinkedIn_Scraper:\r\n \r\n def __init__(self):\r\n \r\n \"\"\"Wait for Headless Chrome to open before running anything else.\"\"\"\r\n\r\n from selenium import webdriver\r\n from selenium.webdriver.common.keys import Keys\r\n from selenium.webdriver.common.by import By\r\n from time import sleep\r\n from random import randint\r\n from requests import get\r\n from bs4 import BeautifulSoup\r\n import pandas as pd\r\n import re\r\n \r\n # Login\r\n def Login(self, username_val, password_val):\r\n \r\n br.get(\"https://www.linkedin.com/m/login\") \r\n sleep(randint(5,7))\r\n br.switch_to_frame(br.find_element_by_tag_name(\"iframe\"))\r\n sleep(1)\r\n go_to_sign_in = br.find_element_by_class_name('sign-in-link')\r\n sleep(1)\r\n go_to_sign_in.click()\r\n \r\n sleep(3)\r\n print('Typing in your username and password.')\r\n email = br.find_element_by_id('session_key-login')\r\n password = br.find_element_by_id(\"session_password-login\")\r\n email.send_keys(username_val)\r\n password.send_keys(password_val)\r\n \r\n sleep(1.5)\r\n login_attempt = br.find_element_by_xpath(\"//*[@type='submit']\")\r\n login_attempt.submit()\r\n \r\n sleep(randint(5,8))\r\n if br.current_url == \"https://www.linkedin.com/feed/\": \r\n print('Successfully logged in!')\r\n else:\r\n # Deal with recaptcha, if given:\r\n try:\r\n recaptcha = br.find_element_by_class_name('recaptcha-slkdfjsdf') # I can't remember what the class name is... check this later\r\n recaptcha.click()\r\n sleep(randint(5,8))\r\n if br.current_url == \"https://www.linkedin.com/feed/\": \r\n print('Successfully logged in!')\r\n else:\r\n print('Your browser is stuck at ' + br.current_url + '\\nWe were not able to pass the recaptcha test.')\r\n except:\r\n print('Something is not right. Your browser is stuck at ' + br.current_url + '\\nCheck your username and password.')\r\n \r\n def scrape_list(self, authors, subset_num):\r\n \r\n for i in range(len(authors)):\r\n # i=25\r\n url = ('https://www.linkedin.com/search/results/index/?keywords=' + authors[i].replace(' ', '%20') + '%20World%20Bank&origin=GLOBAL_SEARCH_HEADER')\r\n br.get(url)\r\n sleep(randint(4,6)) \r\n try:\r\n result = br.find_element_by_class_name('search-result__result-link')\r\n result_link = result.get_attribute('href')\r\n br.get(result_link)\r\n found = True\r\n except: \r\n url = ('https://www.linkedin.com/search/results/index/?keywords=' + authors[i].replace(' ', '%20') + '%20IFC&origin=GLOBAL_SEARCH_HEADER')\r\n br.get(url)\r\n sleep(randint(4,6)) \r\n try:\r\n result = br.find_element_by_class_name('search-result__result-link')\r\n result_link = result.get_attribute('href')\r\n br.get(result_link) \r\n found = True\r\n except:\r\n url = ('https://www.linkedin.com/search/results/index/?keywords=' + authors[i].replace(' ', '%20') + '&origin=GLOBAL_SEARCH_HEADER')\r\n br.get(url)\r\n sleep(randint(4,6)) \r\n try:\r\n result = br.find_element_by_class_name('search-result__result-link') \r\n result_link = result.get_attribute('href')\r\n br.get(result_link) \r\n found = True\r\n except:\r\n print('\\n' + authors[i] + ' not found.') \r\n found = False\r\n \r\n if found:\r\n print('\\n\\n\\nAuthor ' + authors[i] + ' found! Pulling additional information...')\r\n sleep(randint(9,11)) \r\n try: \r\n see_more = br.find_element_by_css_selector(\".pv-profile-section__see-more-inline.link[aria-expanded$='false']\")\r\n see_more.click()\r\n print('\\nJobs expanded. (1)')\r\n sleep(3)\r\n except:\r\n print('\\nNo jobs to expand. (1)')\r\n try: \r\n see_more = br.find_element_by_css_selector(\".pv-profile-section__see-more-inline.link[aria-expanded$='false']\")\r\n see_more.click() \r\n print('\\nJobs expanded. (2)')\r\n sleep(3)\r\n except:\r\n print('\\nNo jobs to expand. (2)') \r\n \r\n # Get job name\r\n try: \r\n sleep(randint(6,8)) \r\n whole_jobs_ = br.find_elements_by_class_name('pv-entity__summary-info')\r\n jobs = []\r\n for whole_job_ in whole_jobs_:\r\n job = whole_job_.find_elements_by_xpath('.//h3[@class=\"Sans-17px-black-85%-semibold\"]') \r\n if job != []:\r\n jobs.append(job[0].text) \r\n else:\r\n jobs.append('no job') \r\n if len(jobs) == 0:\r\n jobs_found = False\r\n print('\\nNo jobs found.')\r\n else:\r\n jobs_found = True\r\n print('\\nJobs found.')\r\n except:\r\n print('\\nNo jobs found (possible error).') \r\n \r\n if jobs_found:\r\n # Get job company\r\n try: \r\n whole_jobs_ = br.find_elements_by_class_name('pv-entity__summary-info')\r\n companies = []\r\n for whole_job_ in whole_jobs_:\r\n company = whole_job_.find_elements_by_xpath('.//span[@class=\"pv-entity__secondary-title\"]') \r\n if company != []:\r\n companies.append(company[0].text) \r\n else:\r\n companies.append('no company')\r\n print('Companies found.')\r\n except:\r\n print('\\nNo companies found.') \r\n # Get job date \r\n try: \r\n whole_jobs_ = br.find_elements_by_class_name('pv-entity__summary-info')\r\n dates = []\r\n for whole_job_ in whole_jobs_:\r\n date = whole_job_.find_elements_by_class_name('pv-entity__date-range') \r\n if date != []:\r\n dates.append(date[0].text[15:]) \r\n else: \r\n dates.append('no date') \r\n print('Dates found.')\r\n except:\r\n print('\\nNo dates found.') \r\n # Get job location\r\n try: \r\n whole_jobs_ = br.find_elements_by_class_name('pv-entity__summary-info')\r\n locations = []\r\n for whole_job_ in whole_jobs_:\r\n location = whole_job_.find_elements_by_class_name('pv-entity__location') \r\n if location != []:\r\n locations.append(location[0].text[9:]) \r\n else:\r\n locations.append('no location') \r\n print('Locations found.' )\r\n except:\r\n print('\\nNo locations found.') \r\n \r\n # Get education university\r\n try: \r\n whole_jobs_ = br.find_elements_by_class_name('pv-entity__summary-info')\r\n universities = []\r\n for whole_job_ in whole_jobs_:\r\n university = whole_job_.find_elements_by_class_name('pv-entity__school-name') \r\n if university != []:\r\n universities.append(university[0].text) \r\n else:\r\n universities.append('no university') \r\n if universities == []:\r\n print('No education found.')\r\n edu_found = False\r\n else: \r\n print('Education found.')\r\n edu_found = True\r\n except:\r\n print('\\nNo education found.') \r\n if edu_found:\r\n # Get education degree level\r\n try: \r\n whole_jobs_ = br.find_elements_by_class_name('pv-entity__summary-info')\r\n degree_levels = []\r\n for whole_job_ in whole_jobs_:\r\n degree_level = whole_job_.find_elements_by_class_name('pv-entity__degree-name') \r\n if degree_level != []:\r\n degree_levels.append(degree_level[0].text[12:]) \r\n else:\r\n degree_levels.append('no degree level') \r\n print('Degree levels found.')\r\n except:\r\n print('\\nNo degree levels found.') \r\n # Get education degree field of study\r\n try: \r\n whole_jobs_ = br.find_elements_by_class_name('pv-entity__summary-info')\r\n degree_foss = []\r\n for whole_job_ in whole_jobs_:\r\n degree_fos = whole_job_.find_elements_by_class_name('pv-entity__fos') \r\n if degree_fos != []:\r\n degree_foss.append(degree_fos[0].text[15:]) \r\n else:\r\n degree_foss.append('no degree fos') \r\n print('Degree fields of study found.')\r\n except:\r\n print('\\nNo degree fields of study found.') \r\n # Get education year\r\n try: \r\n whole_jobs_ = br.find_elements_by_class_name('pv-entity__summary-info')\r\n edu_dates = []\r\n for whole_job_ in whole_jobs_:\r\n edu_date = whole_job_.find_elements_by_class_name('pv-entity__dates') \r\n if edu_date != []:\r\n edu_dates.append(edu_date[0].text[38:]) \r\n else:\r\n edu_dates.append('no education date') \r\n print('Education dates found.')\r\n except:\r\n print('\\nNo education dates found.') \r\n \r\n # Get current location\r\n try: \r\n curr_location = br.find_element_by_class_name('pv-top-card-section__location').text\r\n print('Current location found.')\r\n except:\r\n curr_location = 'no location'\r\n print('\\nNo current location found.') \r\n \r\n # Get number of connections\r\n try: \r\n connections_ = br.find_element_by_class_name('pv-top-card-section__connections')\r\n connections = connections_.find_element_by_tag_name('span').text\r\n print('Connections found.') \r\n except:\r\n connections = 'no connections'\r\n print('\\nNo number of connections found.') \r\n \r\n \r\n \r\n #####################\r\n # Jobs\r\n if jobs_found:\r\n jobs_s_ = pd.Series(jobs) \r\n jobs_s = jobs_s_[jobs_s_ != 'no job']\r\n jobs_l = list(jobs_s) \r\n \r\n companies_s = pd.Series(companies) \r\n companies_s = companies_s[jobs_s_ != 'no job']\r\n companies_l = list(companies_s) \r\n \r\n dates_s = pd.Series(dates) \r\n dates_s = dates_s[jobs_s_ != 'no job']\r\n dates_l = list(dates_s) \r\n \r\n locations_s = pd.Series(locations) \r\n locations_s = locations_s[jobs_s_ != 'no job']\r\n locations_l = list(locations_s)\r\n \r\n # Parse Job Dates \r\n beg_month = []\r\n beg_year = []\r\n end_month = []\r\n end_year = []\r\n for k in range(len(dates_l)): \r\n if dates_l[k] == 'no date':\r\n beg_month.append('no date')\r\n beg_year.append('no date')\r\n end_month.append('no date')\r\n end_year.append('no date')\r\n else: \r\n try:\r\n beg_year.append(dates_l[k].split(' – ')[0].split(' ')[1])\r\n beg_month.append(dates_l[k].split(' – ')[0].split(' ')[0]) \r\n except:\r\n beg_month.append('None')\r\n beg_year.append(dates_l[k].split(' – ')[0].split(' ')[0])\r\n if dates_l[k].split(' – ')[1] != \"Present\":\r\n try:\r\n end_year.append(dates_l[k].split(' – ')[1].split(' ')[1])\r\n end_month.append(dates_l[k].split(' – ')[1].split(' ')[0]) \r\n except:\r\n end_month.append('None')\r\n end_year.append(dates_l[k].split(' – ')[1].split(' ')[0])\r\n else:\r\n end_month.append('Present')\r\n end_year.append('Present') \r\n \r\n # Create Job JSON\r\n jobs_desc = []\r\n for k in range(len(jobs_l)):\r\n job_desc = {\r\n \r\n \"job_title\": jobs_l[k],\r\n \"company\": companies_l[k],\r\n \"beg_month\": beg_month[k],\r\n \"beg_year\": beg_year[k],\r\n \"end_month\": end_month[k],\r\n \"end_year\": end_year[k],\r\n \"location\": locations_l[k],\r\n \r\n }\r\n jobs_desc.append(job_desc) \r\n else:\r\n jobs_desc = ['no jobs found'] \r\n\r\n \r\n \r\n \r\n #####################\r\n # Education\r\n if edu_found:\r\n universities_s_ = pd.Series(universities) \r\n universities_s = universities_s_[universities_s_ != 'no university']\r\n universities_l = list(universities_s) \r\n \r\n degree_levels_s = pd.Series(degree_levels) \r\n degree_levels_s = degree_levels_s[universities_s_ != 'no university']\r\n degree_levels_l = list(degree_levels_s) \r\n \r\n degree_foss_s = pd.Series(degree_foss) \r\n degree_foss_s = degree_foss_s[universities_s_ != 'no university']\r\n degree_foss_l = list(degree_foss_s) \r\n \r\n edu_dates_s = pd.Series(edu_dates) \r\n edu_dates_s = edu_dates_s[universities_s_ != 'no university']\r\n edu_dates_l = list(edu_dates_s) \r\n \r\n # Parse Education Dates\r\n beg_month_edu = []\r\n beg_year_edu = []\r\n end_month_edu = []\r\n end_year_edu = []\r\n for k in range(len(edu_dates_l)):\r\n if edu_dates_l[k] == 'no education date':\r\n beg_month_edu.append('no date')\r\n beg_year_edu.append('no date')\r\n end_month_edu.append('no date')\r\n end_year_edu.append('no date')\r\n else: \r\n try:\r\n beg_year_edu.append(edu_dates_l[k].split(' – ')[0].split(' ')[1])\r\n beg_month_edu.append(edu_dates_l[k].split(' – ')[0].split(' ')[0]) \r\n except:\r\n beg_month_edu.append('None')\r\n beg_year_edu.append(edu_dates_l[k].split(' – ')[0].split(' ')[0])\r\n if len(edu_dates_l[k].split(' – ')) > 1:\r\n if edu_dates_l[k].split(' – ')[1] != \"Present\":\r\n try: \r\n end_year_edu.append(edu_dates_l[k].split(' – ')[1].split(' ')[1])\r\n end_month_edu.append(edu_dates_l[k].split(' – ')[1].split(' ')[0])\r\n except:\r\n end_month_edu.append('None')\r\n end_year_edu.append(edu_dates_l[k].split(' – ')[1].split(' ')[0])\r\n else:\r\n end_month_edu.append('Present')\r\n end_year_edu.append('Present') \r\n else:\r\n end_month_edu.append('None')\r\n end_year_edu.append('None')\r\n \r\n # Create Education JSON\r\n edus_desc = []\r\n for k in range(len(universities_l)):\r\n edu_desc = {\r\n \r\n \"univeristy\": universities_l[k],\r\n \"degree level\": degree_levels_l[k],\r\n \"field of study\": degree_foss_l[k],\r\n \"beg_month\": beg_month_edu,\r\n \"beg_year\": beg_year_edu,\r\n \"end_month\": end_month_edu,\r\n \"end_year\": end_year_edu\r\n \r\n } \r\n edus_desc.append(edu_desc) \r\n else:\r\n edus_desc = ['no education found']\r\n\r\n \r\n author_df = pd.DataFrame({\r\n \r\n \"author\": [authors[i]],\r\n \"curr_location\": [curr_location],\r\n \"connections\": [connections],\r\n \"jobs\": [\"null value\"],\r\n \"education\": [\"null value\"]\r\n \r\n })\r\n \r\n author_df[\"jobs\"][0] = jobs_desc \r\n author_df[\"education\"][0] = edus_desc \r\n \r\n else: \r\n \r\n author_df = pd.DataFrame({\r\n \r\n \"author\": [authors[i]],\r\n \"curr_location\": [\"no LinkedIn\"],\r\n \"connections\": [\"no LinkedIn\"],\r\n \"jobs\": [\"no LinkedIn\"],\r\n \"education\": [\"no LinkedIn\"]\r\n \r\n }) \r\n\r\n if i == 0:\r\n authors_df = author_df \r\n else:\r\n authors_df = pd.concat([authors_df, author_df])\r\n \r\n print('\\nAuthor number ' + str(i + 1) + ' (' + authors[i] + ') of subset ' + str(subset_num + 1) + ' done!')\r\n \r\n return authors_df\r\n \r\n def scrape_all(self, authors):\r\n \r\n for i in range(len(authors)):\r\n author = authors[i]\r\n authors_ = author.split(\",\") \r\n \r\n for j in range(len(authors_)):\r\n authors_[j] = authors_[j].strip()\r\n \r\n self.author_df = self.scrape_list(authors_, i)\r\n \r\n if i == 0:\r\n \r\n self.authors_df = self.author_df\r\n \r\n else:\r\n \r\n self.authors_df = pd.concat([self.authors_df, self.author_df])\r\n \r\n print('\\n\\nAuthor subset ' + str(i + 1) + ' done!')\r\n \r\n return authors_df\r\n\r\n","sub_path":"LinkedIn Scraper - B00 (GitHub).py","file_name":"LinkedIn Scraper - B00 (GitHub).py","file_ext":"py","file_size_in_byte":26564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"254166807","text":"#!/usr/bin/python3\n\nimport os\nimport sys\n\nif len(sys.argv) >= 2:\n directory = str(sys.argv[1])\nelse:\n print('Not enough arguments!')\n sys.exit(0) \nnoBytes = 0\n\nfileName = ''\nfor root, dirs, files in os.walk(directory):\n for file in files:\n pathname = os.path.join(root, file)\n if os.path.exists(pathname):\n if noBytes < os.path.getsize(pathname):\n noBytes = os.path.getsize(pathname)\n fileName = pathname\n\nprint(fileName)\nprint('Size: ', noBytes)","sub_path":"CodingAcademy_Programs/PyScripts/findBig.py","file_name":"findBig.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"579520182","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n def __str__(self):\n s = \"\"\n current = self\n s = s + str(current.val)\n while current.next:\n current = current.next\n s = s + \" -> \"\n s = s + str(current.val)\n return s\n\n\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n first = head\n if not first:\n return None\n\n second = first.next\n if not second:\n return first\n\n if first.val == second.val:\n while second and first.val == second.val:\n second = second.next\n first.next = second\n return self.deleteDuplicates(first)\n else:\n next = self.deleteDuplicates(second)\n first.next = next\n return first\n\n\nif __name__ == '__main__':\n current = ListNode(0)\n head = current\n for i in range(1, 21):\n node1 = ListNode(i)\n node2 = ListNode(i)\n node1.next = node2\n current.next = node1\n current = node2\n current.next = ListNode(21)\n current = current.next\n current.next = ListNode(22)\n print(head)\n sol = Solution()\n l1 = sol.deleteDuplicates(head)\n print(l1)","sub_path":"python/leetcode/83.py","file_name":"83.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"488234405","text":"# -*- coding: utf-8 -\n#\n# This file is part of flower released under the MIT license. \n# See the NOTICE for more information.\n\nimport os\nimport signal\nimport sys\nimport time\nimport traceback\n\nimport gevent\n\nfrom flower import util\nfrom flower.workertmp import WorkerTmp\n\n\nclass Worker(object):\n\n _SIGNALS = map(\n lambda x: getattr(signal, \"SIG%s\" % x),\n \"HUP QUIT INT TERM USR1 USR2 WINCH CHLD\".split()\n )\n \n _PIPE = []\n\n def __init__(self, conf, log, age=0, ppid=0):\n\n self.name = conf.sname\n\n self.log = log\n self.age = age\n self.ppid = ppid\n self.timeout = conf.timeout\n self.conf = conf\n\n\n # initialize\n self.booted = False\n self.alive = True\n self.tmp = WorkerTmp(self.conf)\n\n\n def pid(self):\n return os.getpid()\n pid = util.cached_property(pid)\n\n def notify(self):\n \"\"\"\\\n Your worker subclass must arrange to have this method called\n once every ``self.timeout`` seconds. If you fail in accomplishing\n this task, the master process will murder your workers.\n \"\"\"\n self.tmp.notify()\n\n\n def run(self):\n \"\"\"\\\n This is the mainloop of a worker process. You should override\n this method in a subclass to provide the intended behaviour\n for your particular evil schemes.\n \"\"\"\n while True:\n self.notify()\n gevent.sleep(0.1)\n\n def init_process(self):\n \"\"\"\\\n If you override this method in a subclass, the last statement\n in the function should be to call this method with\n super(MyWorkerClass, self).init_process() so that the ``run()``\n loop is initiated.\n \"\"\"\n util.set_owner_process(self.conf.uid, self.conf.gid)\n\n # Reseed the random number generator\n util.seed()\n\n # For waking ourselves up\n self._PIPE = os.pipe()\n map(util.set_non_blocking, self._PIPE)\n map(util.close_on_exec, self._PIPE)\n \n # Prevent fd inherientence\n util.close_on_exec(self.tmp.fileno())\n self.init_signals()\n \n # Enter main run loop\n self.booted = True\n self.run()\n\n def init_signals(self):\n map(lambda s: signal.signal(s, signal.SIG_DFL), self._SIGNALS)\n signal.signal(signal.SIGQUIT, self.handle_quit)\n signal.signal(signal.SIGTERM, self.handle_exit)\n signal.signal(signal.SIGINT, self.handle_exit)\n signal.signal(signal.SIGWINCH, self.handle_winch)\n \n def handle_quit(self, sig, frame):\n self.alive = False\n\n def handle_exit(self, sig, frame):\n self.alive = False\n sys.exit(0)\n \n def handle_winch(self, sig, fname):\n # Ignore SIGWINCH in worker. Fixes a crash on OpenBSD.\n return\n","sub_path":"flower/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"644045804","text":"# bl_info\nbl_info = {\n \"name\": \"Add Smooth Monkey\",\n \"author\": \"feiHua\",\n \"version\": (1,0),\n \"blender\": (2,79),\n \"location\": \"View3D > Add > Mesh > Add Smooth Monkey\",\n \"description\": \"Add a new smooth monkey\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"category\": \"Add Mesh\"\n}\n\nimport bpy\n\n# classes\nclass OBJECT_OT_add_smooth_monkey(bpy.types.Operator):\n \"\"\"Add a smooth monkey to\"\"\"\n bl_label = \"Smooth Monkey\"\n bl_idname = \"mesh.add_smooth_monkey\"\n bl_options = {'REGISTER', 'UNDO'}\n\n # redo last properties\n smoothness = bpy.props.IntProperty(\n name = \"Smoothness\",\n default = 2,\n description = \"Subsurf level\"\n )\n\n size = bpy.props.FloatProperty(\n name = \"Size\",\n default = 1,\n description = \"Size of monkey added\"\n )\n name = bpy.props.StringProperty(\n name = \"Name\",\n default = \"Nonkey\",\n description = \"Name of added monkey\"\n )\n\n def execute(self, context):\n bpy.ops.mesh.primitive_monkey_add(radius=self.size)\n bpy.ops.object.shade_smooth()\n bpy.ops.object.modifier_add(type='SUBSURF')\n bpy.context.object.modifiers[\"Subsurf\"].levels = self.smoothness\n bpy.context.object.modifiers[\"Subsurf\"].render_levels = self.smoothness\n bpy.context.object.name = self.name\n\n return{'FINISHED'}\n\n\nclass smooth_monkey_panel(bpy.types.Panel):\n \"\"\"The smooth monkey add panel\"\"\"\n bl_label = \"Smooth Monkey\"\n bl_idname = \"OBJECT_PT_smooth_monkey\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"TOOLS\"\n bl_category = \"Create\"\n bl_context = \"objectmode\"\n\n def draw(self, context):\n layout = self.layout\n col = layout.column()\n col.label(text = \"Add smooth monkey named:\")\n col.prop(context.scene, \"smooth_monkey_name\", text = \"\", icon = \"MESH_MONKEY\")\n p = col.operator(OBJECT_OT_add_smooth_monkey.bl_idname)\n p.name=context.scene.smooth_monkey_name\n\n\n\ndef add_object_button(self, context):\n self.layout.operator(\n OBJECT_OT_add_smooth_monkey.bl_idname,\n icon = \"MESH_MONKEY\"\n )\n\n\n# registration\ndef register():\n bpy.types.Scene.smooth_monkey_name = bpy.props.StringProperty(\n name = \"Monkey Name\",\n default = \"Suzanne\",\n description = \"Name of the object after adding to the scene\"\n )\n bpy.utils.register_class(OBJECT_OT_add_smooth_monkey)\n bpy.utils.register_class(smooth_monkey_panel)\n bpy.types.INFO_MT_mesh_add.append(add_object_button)\n\ndef unregister():\n bpy.utils.unregister_class(OBJECT_OT_add_smooth_monkey)\n bpy.utils.unregister_class(smooth_monkey_panel)\n bpy.types.INFO_MT_mesh_add.remove(add_object_button)\n del bpy.types.Scene.smooth_monkey_name\n\n\n\nif __name__==\"__main__\":\n register()\n\n\n\n","sub_path":"add_smooth_monkey.py","file_name":"add_smooth_monkey.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"653537788","text":"\"\"\"Faça um Programa que peça dois números e imprima o maior deles.\"\"\"\nn1 = int(input('Digite um número: '))\nn2 = int(input('Digite outro número: '))\n\nif n1 > n2:\n print(f'{n1} é o maior número. ')\nif n1 == n2:\n print(f'Os números são iguais.')\nelse:\n print(f'{n2} é o maior número.')","sub_path":"estruturadedecisao/ex_doisnum.py","file_name":"ex_doisnum.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"308026840","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n@File :T1.py\n@Time :2020/07/06 16:43:19\n@Author :kevenano\n@Description :栈的应用:多类型括号混合匹配\n@Version :1.0\n\"\"\"\n\nfrom CLASS_STACK import Stack\n\n\nclass Solution:\n def isRightString(self, string: str) -> bool:\n S = Stack()\n opener = \"([{\"\n closer = \")]}\"\n for item in string:\n if item in opener:\n S.push(item)\n if item in closer:\n if S.isEmpty():\n return False\n if self._isMatch(S.peek(), item):\n S.pop()\n else:\n return False\n return S.isEmpty()\n\n def _isMatch(self, opener: str, closer: str):\n return \"([{\".find(opener) == \")]}\".find(closer)\n\n\ndef main():\n testString = \"((()))(a{s(fsag[f]a,[sd]346,4{(1)2}(y45)ssss,gdt(ete),[63(53)7,{g(fa),[t],{gag},[yu]}fsef])})\"\n SLT = Solution()\n print(SLT.isRightString(testString))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"DSAP/Stack/T1.py","file_name":"T1.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"302241543","text":"import pathlib\nimport sys\n\nsys.path.insert(1, str(pathlib.Path(__file__).parent.absolute())+\"/../../../../parser\")\n#sys.path.insert(1, '/usr/workspace/wsa/laguna/fpchecker/FPChecker/parser')\nfrom tokenizer import Tokenizer\n\nFILENAME = str(pathlib.Path(__file__).parent.absolute()) + \"/simple.cu\"\n\ndef test_1():\n p = str(pathlib.Path(__file__).parent.absolute())+\"/../../../parser\"\n print(p)\n l = Tokenizer(FILENAME)\n count = 0\n for token in l.tokenize():\n count += 1\n sys.stdout.write('\\n'+str(type(token))+':')\n sys.stdout.write(str(token))\n print('Len:', count)\n\n assert count == 38\n\nif __name__ == '__main__':\n test_1()\n","sub_path":"tests/parser/static/test_tokenize_strings/test_tokenize_strings.py","file_name":"test_tokenize_strings.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"495317960","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 13 10:31:12 2017\n\n@author: shiyunchao\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nfrom sklearn.preprocessing import OneHotEncoder\nfrom time import strftime, localtime\nfrom tools import get_tradeDay\nfrom datetime import datetime\n\nfrom xutils import (Date,\n Calendar,\n Period)\n\n# 设定为上交所的交易日历\ncal = Calendar('China.SSE')\n\n\ndef get_filename(tradeday):\n exposure_list = []\n cov_list = []\n for day in tradeday:\n if day > '20140930':\n cov_list.append('CNE5S%s.COV' % day[2:])\n exposure_list.append('CNE5S_X_%s.RSK' % day[2:])\n else:\n cov_list.append('CNE5S%s.COV' % day[2:6])\n exposure_list.append('CNE5S%s.RSK' % day[2:6])\n return exposure_list, cov_list\n\n\ndef get_exposure(dirpath, output, day):\n factor_col = ['BETA', 'MOMENTUM', 'SIZE', 'EARNYILD', 'RESVOL', 'GROWTH', 'BTOP', 'LEVERAGE', 'LIQUIDTY', 'SIZENL']\n ind_col = ['ENERGY ', 'CHEM ', 'CONMAT ', 'MTLMIN ', 'MATERIAL',\n 'AERODEF ', 'BLDPROD ', 'CNSTENG ', 'ELECEQP ', 'INDCONG ',\n 'MACH ', 'TRDDIST ', 'COMSERV ', 'AIRLINE ', 'MARINE ',\n 'RDRLTRAN', 'AUTO ', 'HOUSEDUR', 'LEISLUX ', 'CONSSERV',\n 'MEDIA ', 'RETAIL ', 'PERSPRD ', 'BEV ', 'FOODPROD',\n 'HEALTH ', 'BANKS ', 'DVFININS', 'REALEST ', 'SOFTWARE',\n 'HDWRSEMI', 'UTILITIE']\n ind_col2 = list(map(lambda x: x.strip(), ind_col))\n\n df = pd.read_csv('%s/CNE5S_LOCALID_%s.RSK' % (dirpath, day[2:]), skiprows=1)\n df = df[df['ESTU'] == 1]\n\n df = df[df['LOCID'] != 'CHNFBC1 ']\n\n df['LOCID'] = df['LOCID'].apply(lambda x: x.split('CN')[1] + '-CN')\n df['SRISK%'] = df['SRISK%'] / 100\n df_factor = df[['LOCID'] + factor_col]\n\n # factor_col = map(lambda x: 'Style.' + x, factor_col)\n df_factor.columns = [\"LOCID\"] + factor_col\n\n y = df['IND'].values\n y.shape = (len(y), 1)\n ysample = OneHotEncoder().fit_transform(y)\n y = ysample.toarray()\n\n # ind_col2 = map(lambda x: 'Industry.' + x, ind_col2)\n df_ind = pd.DataFrame(y, columns=ind_col2)\n df_ind['LOCID'] = df['LOCID'].values\n\n df_exposure = pd.merge(df_factor, df_ind, on='LOCID')\n df_exposure['COUNTRY'] = df['COUNTRY'].values\n\n df_exposure = df_exposure.merge(df[['LOCID', 'SRISK%']], on='LOCID')\n\n df_exposure = df_exposure[['LOCID'] + factor_col + ind_col2 + ['COUNTRY'] + ['SRISK%']]\n\n col = [np.nan] + df_exposure.columns.tolist()[1:-1] + [np.nan]\n df_tmp = pd.DataFrame([col, col], columns=df_exposure.columns)\n df_new = pd.concat([df_tmp, df_exposure])\n\n df_new.to_csv('%s/Exposure_%s.csv' % (output, day), index=None, header=None)\n\n\ndef get_cov(dirpath, output, day):\n df = pd.read_csv('%s/CNE5S%s.COV' % (dirpath, day[2:]), skiprows=2)\n df = df.iloc[:, 1:-1]\n col_cov = list(map(lambda x: x.strip(), df.columns.tolist()))\n # col2 = ['Style.'] * 10 + ['Industry.'] * 32 + ['Country.']\n # col3 = [col2[i] + col_cov[i] for i in range(len(col_cov))]\n df.columns = col_cov\n df = df / 10000.0\n df.index = col_cov\n df = df.reset_index()\n df.columns = [np.nan] + df.columns.tolist()[1:]\n df.to_csv('%s/Covariance_%s.csv' % (output, day), index=None)\n\n\n\ndef run(start, end, flag, dirpath, output1, output2):\n if not os.path.exists(output1):\n os.mkdir(output1)\n if not os.path.exists(output2):\n os.mkdir(output2)\n\n if flag == 0:\n fre = 'day'\n tradeday = get_tradeDay.wind(start, end, fre=fre)\n for day in tradeday:\n print(day)\n get_exposure(dirpath, output1, day)\n get_cov(dirpath, output2, day)\n else:\n today = end\n # today = datetime.strftime(today.toDateTime(), \"%Y%m%d\")\n get_exposure(dirpath, output1, today)\n get_cov(dirpath, output2, today)\n\nif __name__ == '__main__':\n dirpath = 'Z:/MSCI/daily'\n output1 = 'Z:/axioma_data/barra_model/Exposure'\n output2 = 'Z:/axioma_data/barra_model/Covariance'\n\n start = '20171201'\n # end = strftime(\"%Y%m%d\", localtime())\n today = strftime(\"%Y%m%d\", localtime())\n today = Date.strptime(today, '%Y%m%d')\n today = cal.advanceDate(today, Period('-1b'))\n end = today.strftime(\"%Y%m%d\")\n\n flag = 0\n run(start, end, flag, dirpath, output1, output2)","sub_path":"factor_daily/barra_risk/read_barra_daily_backtest.py","file_name":"read_barra_daily_backtest.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"50662068","text":"sentences = \"\"\"Thomas Jefferson began building Monticello at the\\\r\nage of 26.\\n\"\"\"\r\nsentences += \"\"\"Construction was done mostly by local masons and\\\r\ncarpenters.\\n\"\"\"\r\nsentences += \"He moved into the South Pavilion in 1770. the \\n\"\r\nsentences += \"\"\"Turning Monticello into a neoclassical masterpiece\\\r\n was Jefferson's obsession.\"\"\"\r\ncorpus = {}\r\nfor i, sent in enumerate(sentences.split('\\n')):\r\n corpus['sent{}'.format(i)] = dict((tok, 1) for tok in sent.split()) \r\nprint(corpus.keys())\r\nfor k,v in corpus.items():\r\n print(k,v)\r\n","sub_path":"scripts/NLP/bow.py","file_name":"bow.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"266594969","text":"import json\nwith open('list_count.txt') as f:\n dict1 = {}\n dict2 = {}\n for i in f:\n x = i.strip().split(':')\n if(x[0]=='0000'):\n dict1['0'] = x[1]\n else:\n dict1[x[0].lstrip('0')] = x[1]\n\n flag = 0\n for i in range(64):\n flag += 1\n for j in range(flag, 64):\n dict2[str(j*64+i)] = dict1[str(i*64+j)]\n\n\n flag = 0\n for i in range(1,64):\n flag += 1\n for j in range(flag):\n dict2[str(j*64+i)] = dict1[str(i*64+j)]\n\n for i in range(64):\n for j in range(64):\n if (i==j):\n dict2[str(i*64+j)] = dict1[str(i*64+j)]\n\nwith open('data3.json', 'w') as outfile:\n json.dump(dict2, outfile)\n\n##with open('every_location_count.txt', 'w') as f:\n## r = [int(i) for i in dict2.keys()]\n## for i in sorted(r):\n## f.write(str(i)+\":\"+dict2[str(i)]+'\\n')\n","sub_path":"modeling/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"441060262","text":"# external imports\nfrom flask import Flask, session, request, redirect, url_for\nfrom flask import render_template,flash\nfrom flask_paginate import Pagination, get_page_parameter, get_page_args\nfrom flask_table import Table, Col\nimport sqlite3\nimport requests\n# internal imports\nfrom db import server_names, find_realm_id, find_item_id, get_items, get_total_quantity, get_items_by_type, get_mount_list_info, get_total_mounts_info\nfrom blizzardAPI import Blizzard\n\n\n# constant variables\nBLIZZARD_CLIENT_ID = \"6eef8ac48dbc417197ed8a34c731e398\"\nBLIZZARD_CLIENT_SECRET = \"mxzBzxKXxQZsYU3ogGjPhoodi9O6VVmQ\"\nITEM_CLASS_DICT = {\"Weapons\":\"Weapon\", \"Armor\":\"Armor\", \"Containers\":\"Container\", \"Gems\":\"Gem\",\"Item Enhancements\":\"Item Enhancement\",\n\"Consumables\":\"Consumable\",\"Glyphs\":\"Glyph\", \"Trade Goods\":\"Tradeskill\",\"Recipes\":\"Recipe\",\"Battle Pets\":\"Battle Pets\",\"Quest Items\":\"Quest\",\n\"Miscellaneous\":\"Miscellaneous\",\"WoW Token\":\"WoW Token\"}\n\napp = Flask(__name__)\napp.secret_key = 'test'\n\ndef get_offset(mount_list, offset=0, per_page=60):\n return mount_list[offset: offset + per_page]\n\n@app.route('/', methods=['GET'])\ndef home():\n session['server_list'] = server_names()\n return render_template('home.html')\n\n\n@app.route('/login')\ndef login():\n return redirect(f\"https://eu.battle.net/oauth/authorize?\"\n f\"client_id={BLIZZARD_CLIENT_ID}&\"\n f\"scope=wow.profile&\"\n f\"redirect_uri=http://127.0.0.1:5000/authorized&\"\n f\"response_type=code\")\n\n\n@app.route('/authorized')\ndef authorized():\n code = request.args.get(\"code\")\n res = requests.post(\"https://eu.battle.net/oauth/token\", data={\n \"client_id\": BLIZZARD_CLIENT_ID,\n \"client_secret\": BLIZZARD_CLIENT_SECRET,\n \"grant_type\": \"authorization_code\",\n \"redirect_uri\": \"http://127.0.0.1:5000/authorized\",\n \"scope\": \"wow.profile\",\n \"code\": code})\n response = res.json()\n session['access_token'] = response['access_token']\n get_user_info = requests.get(f\"https://eu.battle.net/oauth/userinfo?access_token={session['access_token']}\")\n user_info = get_user_info.json()\n session['battletag'] = user_info['battletag']\n session['account_id'] = user_info['id']\n return redirect(url_for('home'))\n\n\n@app.route('/logout')\ndef logout(): \n session.pop('access_token', None)\n session.pop('battletag', None)\n session.pop('account_id', None)\n return redirect(url_for('home'))\n\n\n@app.route('/auction-house', methods=[\"POST\", \"GET\"])\ndef auction_house():\n # realms list\n realm_list = server_names()\n # connection to realms auction data\n if request.method == 'POST' and \"realm_name\" in request.form:\n session['server'] = request.form.get('realm_name')\n # display auction item data\n if request.method == 'POST' and \"item_name\" in request.form:\n session['item_name'] = request.form['item_name']\n filter_list = request.form.getlist('my_checkbox')\n if not session['item_name'] and not filter_list:\n flash(\"Please insert an item\")\n elif session['item_name'] and filter_list:\n pass\n elif session['item_name'] and not filter_list:\n connection = Blizzard(connected_realm=find_realm_id(session['server']))\n auction_data = connection.get_data(connected_realm=find_realm_id(session['server']))\n item_dict = get_items(session['item_name'], auction_data)\n if not item_dict:\n flash(\"No such item exists\")\n item_total = get_total_quantity(item_dict)\n return render_template('auction.html',realm_list=realm_list,item_class=ITEM_CLASS_DICT, item_dict=item_dict, item_total=item_total)\n else:\n connection = Blizzard(connected_realm=find_realm_id(session['server']))\n auction_data = connection.get_data(connected_realm=find_realm_id(session['server']))\n item_dict = get_items_by_type(filter_list, auction_data)\n if not item_dict:\n flash(\"No such item exists\")\n item_total = get_total_quantity(item_dict)\n return render_template('auction.html', realm_list=realm_list, item_class=ITEM_CLASS_DICT, item_dict=item_dict, item_total=item_total)\n return render_template('auction.html', realm_list=realm_list, item_class=ITEM_CLASS_DICT)\n\n\n@app.route('/statistics', methods=[\"POST\", \"GET\"])\ndef statistics():\n return render_template('statistics.html')\n\n\n@app.route('/profile', methods=[\"POST\", \"GET\"])\ndef profile():\n return render_template('profile.html')\n\n\n@app.route('/profile/characters', methods=[\"POST\", \"GET\"])\ndef profile_characters():\n test_dict = {}\n connection = Blizzard()\n data = connection.get_character_list(profile_token=session['access_token'])\n for server in data: # TODO: DELETE\n test_dict.update({server: len(data[server])})\n return render_template('profile_characters.html', char_list=data, char_server= test_dict)\n\n\n@app.route('/profile/mounts', methods=[\"POST\", \"GET\"])\ndef profile_mounts():\n mount_data = get_mount_list_info(profile_token=session['access_token'])\n total_mounts_info, total_mounts = get_total_mounts_info(profile_token=session['access_token'])\n total_collected_mounts = len(mount_data)\n total_collected_mounts_percent = (total_collected_mounts * 100) // total_mounts\n return render_template('profile_mounts.html',mounts=mount_data, total_mounts=total_mounts,\n total_collected_mounts=total_collected_mounts,\n total_collected_mounts_percent=total_collected_mounts_percent,\n total_mounts_info=total_mounts_info)\n\n@app.route('/profile/pets', methods=[\"POST\", \"GET\"])\ndef profile_pets():\n return render_template('profile_pets.html')\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"627437216","text":"'''\nCreated on Nov 29, 2014\n\n@author: Richard\n'''\nfrom pygame import Rect\nfrom game import mouse_position, is_left_mouse_clicked\n\nclass Element:\n def __init__(self, rect = None, layer=0, visible=True, active=True):\n if rect is not None:\n self.rect = rect\n else:\n self.rect = Rect((0, 0), (0, 0))\n self.old_active = None\n self.old_visible = None\n self.old_rect = None\n self.layer = layer\n self.visible = visible\n self.active = active\n self.dirty_list = []\n return\n \n def draw(self, screen):\n return\n \n def update(self):\n def rects_are_synchronized():\n r = self.rect\n o = self.old_rect\n return (r.x, r.y, r.size) == (o.x, o.y, o.size)\n if self.old_rect is None:\n self.dirty_list.append(self.rect.inflate(5, 5))\n self.old_rect = Rect((self.rect.x, self.rect.y), (self.rect.w, self.rect.h))\n elif not rects_are_synchronized():\n self.refresh()\n self.old_rect = Rect((self.rect.x, self.rect.y), (self.rect.w, self.rect.h))\n self.update_active_and_visible()\n self.remove_duplicate_dirty_rects()\n return\n \n def remove_duplicate_dirty_rects(self):\n unique_list = []\n for dirty_rect in self.dirty_list:\n if not dirty_rect in unique_list:\n unique_list.append(dirty_rect)\n self.dirty_list = unique_list\n return\n \n def update_active_and_visible(self):\n if self.old_visible is None or self.old_visible != self.visible \\\n or self.old_active is None or self.old_active != self.active:\n self.refresh()\n self.old_active = self.active\n self.old_visible = self.visible\n return\n \n def refresh(self):\n if self.old_rect is not None:\n self.dirty_list.append(self.old_rect.inflate(5, 5))\n self.dirty_list.append(self.rect.inflate(5, 5))\n return\n \n def suspend(self):\n self.active = False\n self.visible = False\n return\n \n def restore(self):\n self.active = True\n self.visible = True\n return\n \n def decorated_element(self):\n return self\n \n def is_mouse_over(self):\n return self.visible and self.rect.collidepoint(mouse_position())\n \n def is_mouse_clicking(self):\n return self.visible and is_left_mouse_clicked() and self.is_mouse_over()","sub_path":"core/elements/base_elements/element.py","file_name":"element.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"467257217","text":"#!/usr/bin/env python\n# _*_ coding: utf-8 _*_\n# Author:shichao\n# File: .py\n\nFile_open = open(\"file\",mode=\"r+\",encoding=\"utf-8\")\n\nFile_open.write(\"我要创建文件\")\nFile_open.write(\"python read file is name\")\n\ndata = File_open.read(1) #从文件开始读取,读取到最后一行,如果不给指定或为负则读取读取所有\nprint(data) #打印读取所有的数据\n\nFile_open.close() #打印完成后关闭文件","sub_path":"day2/文件/python-写入文件.py","file_name":"python-写入文件.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"62054713","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom rest_framework import routers\nfrom koboform.views import SurveyDraftViewSet\n\n\nrouter = routers.DefaultRouter(trailing_slash=False)\nrouter.register(r'survey_drafts', SurveyDraftViewSet, 'SurveyDraft')\n\nadmin.autodiscover()\n\nurlpatterns = patterns(\n '',\n url(r'^api/', include(router.urls)),\n url(r'^$', 'dkobo.koboform.views.spa', name='spa'),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^csv$', 'dkobo.koboform.views.csv_to_xform'),\n url(r'^accounts/', include('registration.backends.default.urls')),\n url(r'^account/', include('django.contrib.auth.urls')),\n url(r'^spa/$', 'dkobo.koboform.views.spa'),\n # fallback on koboform app-specific urls:\n url(r'^koboform/', include('dkobo.koboform.urls')),\n # we should re-think a RESTful accessor for the URLs below\n url(r'^question_library_forms$', 'dkobo.koboform.views.list_forms_in_library'),\n url(r'^survey_drafts$', 'dkobo.koboform.views.list_forms_for_user'),\n # url(r'^survey_drafts$', 'dkobo.koboform.views.list_forms_for_user'),\n url(r'^forms/(\\d+)', 'dkobo.koboform.views.export_form_to_xform'),\n)\n","sub_path":"dkobo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"563507117","text":"import os\nimport firebase_admin\nfrom firebase_admin import credentials\n\n\ncred = credentials.Certificate({\n \"type\":\"service_account\",\n \"project_id\": os.environ.get('FIREBASE_PROJECT_ID'),\n \"private_key_id\": os.environ.get('FIREBASE_PROJECT_KEY_ID'),\n \"private_key\": os.environ.get('FIREBASE_PROJECT_KEY').replace('\\\\n', '\\n'),\n \"client_email\": os.environ.get('FIREBASE_CLIENT_EMAIL'),\n \"client_id\": os.environ.get('FIREBASE_CLIENT_ID'),\n \"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\n \"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\n \"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\",\n \"client_x509_cert_url\": os.environ.get('FIREBASE_CLIENT_CERT_URL')\n})\n\ndefault_app = firebase_admin.initialize_app(cred)\n\n\nclass FirebaseAuthentication(authentication.BaseAuthentication):\n def authenticate(self, request):\n auth_header = request.META.get(\"HTTP_AUTHORIZATION\")\n if not auth_header:\n raise NoAuthToken(\"No auth token provided\")\n\n id_token = auth_header.spilt(\" \").pop()\n decoded_token = None\n try:\n decoded_token= auth.verify_id_toke(id_token)\n except Exception:\n raise InvalidAuthToken(\"Invalid auth token\")\n\n if not id_token or not decoded_token:\n return None\n\n try:\n uid = decoded_token.get(\"uid\")\n except Exception:\n raise FirebaseError()\n\n user, created = User.objeccts.get_or_create(usernname=uid)\n user.profile.last_activity = timezone.localtime()\n\n return (user, None)","sub_path":"firebase_auth/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"82859697","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\ndef midpoint_linkedlist(head):\n slow = head\n fast = head\n while fast.next and fast.next.next is not None:\n slow = slow.next\n fast = fast.next.next\n return slow\ndef ll(arr):\n if len(arr)==0:\n return None\n head = Node(arr[0])\n last = head\n for data in arr[1:]:\n last.next = Node(data)\n last = last.next\n return head\narr=list(int(i) for i in input().strip().split(' '))\nl = ll(arr[:-1])\nnode = midpoint_linkedlist(l)\nif node:\n print(node.data)\n","sub_path":"Midpoint of LL.py","file_name":"Midpoint of LL.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"21795928","text":"import matplotlib.pyplot as plt\nfrom numpy import arange, repeat\nfrom math import log\n\na = 0.5\nb = 1.5\nc = 1\nd = 1\ndt = 0.001\n\nx0 = d/c\ny0 = a/b\n\nX0 = arange(0.1,x0,0.1)\nY0 = repeat(round(y0,1),len(X0))\n\nplt.figure(figsize=(15,5))\nplt.subplot(111).set_aspect('equal')\nplt.plot(x0,y0,'xb',label='Fixed point')\nplt.plot(X0,Y0,'vk',label='Initial points')\nplt.grid()\n\nfor x,y in zip(X0,Y0):\n\tX = [x]\n\tY = [y]\n\twhile len(X)<1/dt or (X[0]-X[-1])**2 + (Y[0]-Y[-1])**2 > dt/10:\n\t\tdx = a*x - b*x*y\n\t\tdy = d*x*y - c*y\n\t\tx += dx*dt\n\t\ty += dy*dt\n\t\tX.append(x)\n\t\tY.append(y)\n\tplt.plot(X,Y,'-',label=f\"$C={d*x-c*log(x)+b*y-a*log(y):.2f}$\")\n\nplt.xlabel('Prey\\n(x1000)')\nplt.ylabel('Predators\\n(x1000)')\nplt.legend(loc=\"center right\",bbox_to_anchor=(1.25,0.5))\nplt.title(f\"Lotka-Volterra Model\\n($a={a:.1f}$, $b={b:.1f}$, $c={c:.1f}$, $d={d:.1f}$)\")\n\nplt.show()\n","sub_path":"tutorials/Theory/lotka_volterra.py","file_name":"lotka_volterra.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"179431494","text":"import sys, csv, json\r\n\r\nif not len(sys.argv) == 4:\r\n print(\"\"\"\r\n A command-line utility used to transform a .csv map file to\r\n a JSON file understood by the main application.\r\n \r\n Usage: transform.py infile.csv transformfile.json outfile.json\"\"\")\r\n sys.exit(0)\r\n sys.argv.append(\"dipl_map.CSV\")\r\n sys.argv.append(\"dipl_transform.txt\")\r\n sys.argv.append(\"dipl_output.txt\")\r\n \r\nwith open(sys.argv[2]) as trans_file:\r\n decoder = json.JSONDecoder()\r\n translate = decoder.decode(trans_file.read())\r\n\r\nresult = []\r\nmissing = 0\r\nwith open(sys.argv[1]) as f:\r\n c = csv.reader(f)\r\n for line in c:\r\n l = []\r\n print(line)\r\n for cell in line:\r\n if not cell: continue\r\n cell = cell.strip()\r\n try:\r\n l.append(translate[cell])\r\n except:\r\n l.append(cell)\r\n missing += 1\r\n result.append(l)\r\n\r\nprint(\"The translation dictionary couldn't translate %d items.\" % missing)\r\nencoder = json.encoder.JSONEncoder()\r\nwith open(sys.argv[3], 'w') as outfile:\r\n outfile.write(encoder.encode(result))\r\n print(\"Done\")\r\n\r\n","sub_path":"TerraSim/trunk/TerraSim/Tools/map_transform.py","file_name":"map_transform.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"52331448","text":"# Copyright 2015 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport json\nimport os\n\nfrom testing_utils import testing\n\nfrom common.retry_http_client import RetryHttpClient\nfrom waterfall import buildbot\nfrom waterfall import swarming_util\n\n\nclass SwarmingHttpClient(RetryHttpClient):\n def __init__(self):\n self.responses = dict()\n\n def _ResponseForUrl(\n self, master_name, builder_name, build_number):\n if builder_name == 'download_failed':\n return\n\n url = swarming_util.TEMPLATE_URL.format(\n master=master_name, buildername=builder_name, buildnumber=build_number)\n\n swarming_tasks_file = os.path.join(\n os.path.dirname(__file__), 'data', 'sample_swarming_build_tasks.json')\n with open(swarming_tasks_file, 'r') as f:\n response = f.read()\n\n cursor_swarming_data = {\n 'cursor': None,\n 'items': [],\n 'state': 'all',\n 'limit': 100,\n 'sort': 'created_ts'\n }\n cursor_url = ('%s?cursor=thisisacursor') % url\n\n self.responses[url] = response\n self.responses[cursor_url] = json.dumps(cursor_swarming_data)\n\n def _Get(self, url, *_):\n if url not in self.responses:\n return 404, 'Download Failed!'\n return 200, self.responses[url]\n\n def _Post(self, *_): # pragma: no cover\n pass\n\n\nclass SwarmingUtilTest(testing.AppengineTestCase):\n def setUp(self):\n super(SwarmingUtilTest, self).setUp()\n self.http_client = SwarmingHttpClient()\n\n def testUpdateSwarmingTaskIdForFailedSteps(self):\n master_name = 'm'\n builder_name = 'b'\n build_number = 123\n failed_steps = {\n 'a_tests': {\n 'current_failure': 2,\n 'first_failure': 0\n },\n 'unit_tests': {\n 'current_failure': 2,\n 'first_failure': 0\n },\n 'compile':{\n 'current_failure': 2,\n 'first_failure': 0\n }\n }\n\n self.http_client._ResponseForUrl(master_name, builder_name, build_number)\n\n result = swarming_util.UpdateSwarmingTaskIdForFailedSteps(\n master_name, builder_name, build_number, failed_steps, self.http_client)\n expected_failed_steps = {\n 'a_tests': {\n 'current_failure': 2,\n 'first_failure': 0,\n 'swarming_task_ids': ['2944af95a8b97f10']\n },\n 'unit_tests': {\n 'current_failure': 2,\n 'first_failure': 0,\n 'swarming_task_ids': ['2944afa502297110', '2944afa502297111']\n },\n 'compile':{\n 'current_failure': 2,\n 'first_failure': 0\n }\n }\n self.assertTrue(result)\n self.assertEqual(expected_failed_steps, failed_steps)\n\n def testUpdateSwarmingTaskIdForFailedStepsDownloadFailed(self):\n master_name = 'm'\n builder_name = 'download_failed'\n build_number = 123\n failed_steps = {\n 'a_tests': {\n 'current_failure': 2,\n 'first_failure': 0\n },\n 'unit_tests': {\n 'current_failure': 2,\n 'first_failure': 0\n }\n }\n\n self.http_client._ResponseForUrl(master_name, builder_name, build_number)\n\n result = swarming_util.UpdateSwarmingTaskIdForFailedSteps(\n master_name, builder_name, build_number, failed_steps, self.http_client)\n expected_failed_steps = {\n 'a_tests': {\n 'current_failure': 2,\n 'first_failure': 0\n },\n 'unit_tests': {\n 'current_failure': 2,\n 'first_failure': 0\n }\n }\n self.assertFalse(result)\n self.assertEqual(expected_failed_steps, failed_steps)\n","sub_path":"appengine/findit/waterfall/test/swarming_util_test.py","file_name":"swarming_util_test.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"481989483","text":"#!/usr/bin/env python\n# encoding: utf-8\n'''\ntask.crawl.launch -- Launches the Frequent Crawls\n\n@author: Andrew Jackson\n\n@copyright: 2018 The British Library.\n\n@license: Apache 2.0\n\n@contact: Andrew.Jackson@bl.uk\n@deffield updated: 2018-09-04\n'''\n\nimport datetime\nimport time\nimport json\nimport luigi\nimport logging\nfrom tasks.crawl.w3act import CrawlFeed\nfrom lib.targets import IngestTaskDBTarget\nfrom prometheus_client import CollectorRegistry, Gauge\nfrom crawlstreams import enqueue\n\n\nlogger = logging.getLogger('luigi-interface')\n\nclass UpdateScopeFiles(luigi.Task):\n \"\"\"\n Get the lists of all targets and updates the crawlers scope files.\n \"\"\"\n task_namespace = 'crawl'\n date = luigi.DateHourParameter(default=datetime.datetime.today())\n\n def requires(self):\n # Get the crawl feed of interest:\n return {\n 'all' : CrawlFeed(frequency='all', date=self.date),\n 'nevercrawl': CrawlFeed(frequency='nevercrawl', date=self.date)\n }\n\n def output(self):\n return IngestTaskDBTarget('crawl', self.task_id)\n\n def run(self):\n # Load the targets:\n with self.input()['all'].open() as f:\n all_targets = json.load(f)\n self.write_surt_file(all_targets, self.scope_in_file)\n self.write_watched_surt_file(all_targets, self.scope_watched_file)\n # Load the block list:\n with self.input()['nevercrawl'].open() as f:\n blocked_targets = json.load(f)\n self.write_surt_file(blocked_targets, self.scope_blocked_file)\n # Record that all went well:\n self.output().touch()\n\n def write_surt_file(self, targets, filename):\n with open(filename, 'w') as f:\n for t in targets:\n for seed in t['seeds']:\n # f.write(\"%s\\n\" % url_to_surt(seed)) # needs a '+'?\n f.write(\"%s\\n\" % seed)\n\n def write_watched_surt_file(self, targets, filename):\n with open(filename, 'w') as f:\n for t in targets:\n if t['watched']:\n for seed in t['seeds']:\n # f.write(\"%s\\n\" % url_to_surt(seed))\n f.write(\"%s\\n\" % seed)\n\n\nclass LaunchCrawls(luigi.Task):\n \"\"\"\n Get the lists of all targets from the crawl feed and launch those that need launching.\n \"\"\"\n task_namespace = 'crawl'\n frequency = luigi.Parameter(default='all')\n date = luigi.DateHourParameter(default=datetime.datetime.today())\n kafka_server = luigi.Parameter(default='crawler02.n45.bl.uk:9094')\n queue = luigi.Parameter(default='fc.candidates')\n\n # The message launcher:\n launcher = None\n i_launches = 0\n target_errors = 0\n\n def requires(self):\n # Get the crawl feed of interest:\n return CrawlFeed(frequency=self.frequency, date=self.date)\n\n def output(self):\n return IngestTaskDBTarget('crawl', self.task_id)\n\n def run(self):\n # Load the targets:\n with self.input().open() as f:\n all_targets = json.load(f)\n\n # Grab detailed target data:\n logger.info(\"Filtering detailed information for %i targets...\" % len(all_targets))\n\n # Set up launcher:\n self.launcher = enqueue.KafkaLauncher(kafka_server=self.kafka_server, topic=self.queue)\n\n # Get current time\n now = self.date\n logger.debug(\"Now timestamp: %s\" % str(now))\n\n # Process looking for due:\n self.i_launches = 0\n for t in all_targets:\n logger.debug(\"----------\")\n logger.debug(\"Looking at %s (tid:%d)\" % (t['title'], t['id']))\n\n # Look out for problems:\n if len(t['seeds']) == 0:\n logger.error(\"This target has no seeds! tid: %d\" % t['id'])\n self.target_errors += 1\n continue\n\n # Add a source tag if this is a watched target:\n source = \"tid:%d:%s\" % (t['id'], t['seeds'][0])\n\n # Check the scheduling:\n for schedule in t['schedules']:\n # Skip if target schedule outside of start/end range\n if schedule['startDate']:\n startDate = datetime.datetime.strptime(schedule['startDate'], \"%Y-%m-%d %H:%M:%S\")\n logger.debug(\"Target schedule start date: %s\" % str(startDate))\n if (now < startDate):\n logger.debug(\"Start date %s not yet reached\" % startDate)\n continue\n else:\n logger.debug(\"Skipping target schedule start date: %s\" % schedule['startDate'])\n continue\n endDate = 'N/S'\n if schedule['endDate']:\n endDate = datetime.datetime.strptime(schedule['endDate'], \"%Y-%m-%d %H:%M:%S\")\n if now > endDate:\n logger.debug(\"End date %s passed\" % endDate)\n continue\n logger.debug(\"Target schedule end date: %s\" % str(endDate))\n logger.debug(\"Target frequency: %s\" % schedule['frequency'])\n\n # Check if the frequency and date match up:\n if schedule['frequency'] == \"DAILY\":\n self.launch_by_hour(now, startDate, endDate, t, source, 'DAILY')\n\n elif schedule['frequency'] == \"WEEKLY\":\n if now.isoweekday() == startDate.isoweekday():\n self.launch_by_hour(now, startDate, endDate, t, source, 'WEEKLY')\n else:\n logger.debug(\"WEEKLY: isoweekday %s differs from schedule %s\" % (\n now.isoweekday(), startDate.isoweekday()))\n\n elif schedule['frequency'] == \"MONTHLY\":\n if now.day == startDate.day:\n self.launch_by_hour(now, startDate, endDate, t, source, 'MONTHLY')\n else:\n logger.debug(\"MONTHLY: date %s does not match schedule %s\" % (\n now, startDate))\n logger.debug(\"MONTHLY: day %s differs from schedule %s\" % (now.day, startDate.day))\n\n elif schedule['frequency'] == \"QUARTERLY\":\n if now.day == startDate.day and now.month % 3 == startDate.month % 3:\n self.launch_by_hour(now, startDate, endDate, t, source, 'QUARTERLY')\n else:\n logger.debug(\"QUARTERLY: date %s does not match schedule %s\" % (\n now, startDate))\n logger.debug(\n \"QUARTERLY: month3 %s versus schedule %s\" % (now.month % 3, startDate.month % 3))\n\n elif schedule['frequency'] == \"SIXMONTHLY\":\n if now.day == startDate.day and now.month % 6 == startDate.month % 6:\n self.launch_by_hour(now, startDate, endDate, t, source, 'SIXMONTHLY')\n else:\n logger.debug(\"SIXMONTHLY: date %s does not match schedule %s\" % (\n now, startDate))\n logger.debug(\n \"SIXMONTHLY: month6 %s versus schedule %s\" % (now.month % 6, startDate.month % 6))\n\n elif schedule['frequency'] == \"ANNUAL\":\n if now.day == startDate.day and now.month == startDate.month:\n self.launch_by_hour(now, startDate, endDate, t, source, 'ANNUAL')\n else:\n logger.debug(\"ANNUAL: date %s does not match schedule %s\" % (\n now, startDate))\n logger.debug(\"ANNUAL: month %s versus schedule %s\" % (now.month, startDate.month))\n elif schedule['frequency'] == \"DOMAINCRAWL\":\n logger.debug(\"Skipping crawl frequency \" + schedule['frequency'])\n else:\n logger.error(\"Don't understand crawl frequency \" + schedule['frequency'])\n\n logger.info(\"Closing the launcher to ensure everything is pushed to Kafka...\")\n self.launcher.flush()\n #self.launcher.close()\n\n logger.info(\"Completed. Launches this hour: %s\" % self.i_launches)\n # Record that all went well:\n self.output().touch()\n\n def get_metrics(self, registry):\n # type: (CollectorRegistry) -> None\n\n g = Gauge('ukwa_seeds_launched',\n 'Total number of seeds launched.',\n labelnames=['stream'], registry=registry)\n g.labels(stream=self.frequency).set(self.i_launches)\n\n g = Gauge('ukwa_target_errors',\n 'Total number of targets that appear malformed.',\n labelnames=['stream'], registry=registry)\n g.labels(stream=self.frequency).set(self.target_errors)\n\n def launch_by_hour(self, now, startDate, endDate, t, source, freq):\n # Is it the current hour?\n if now.hour is startDate.hour:\n logger.info(\n \"%s target %s (tid: %s) scheduled to crawl (now: %s, start: %s, end: %s), sending to FC-3-uris-to-crawl\" % (\n freq, t['title'], t['id'], now, startDate, endDate))\n counter = 0\n for seed in t['seeds']:\n # Assume all are true seeds, which will over-crawl where sites have aliases that are being treated as seeds.\n # TODO Add handling of aliases\n isSeed = True\n\n # Set-up sheets\n sheets = []\n\n # Robots.txt\n if t['ignoreRobotsTxt']:\n sheets.append('ignoreRobots')\n # Scope\n if t['scope'] == 'subdomains':\n sheets.append('subdomainsScope')\n elif t['scope'] == 'plus1Scope':\n sheets.append('plus1Scope')\n # Limits\n if t['depth'] == 'CAPPED_LARGE':\n sheets.append('higherLimit')\n elif t['depth'] == 'DEEP':\n sheets.append('noLimit')\n\n # Set up the launch_ts: (Should be startDate but if that happens to be in the future this will all break)\n launch_timestamp = time.strftime(\"%Y%m%d%H%M%S\", time.gmtime(time.mktime(now.timetuple())))\n \n # How many parallel queues:\n parallel_queues = 1\n if 'twitter.com' in seed:\n parallel_queues = 2\n\n # And send launch message, always resetting any crawl quotas:\n self.launcher.launch(seed, source, isSeed, forceFetch=True, sheets=sheets, reset_quotas=True, launch_ts=launch_timestamp, inherit_launch_ts=False,parallel_queues=parallel_queues)\n counter = counter + 1\n self.i_launches = self.i_launches + 1\n\n else:\n logger.debug(\"The hour (%s) is not current.\" % startDate.hour)\n\n\nif __name__ == '__main__':\n luigi.run(['crawl.LaunchCrawls', '--kafka-server', 'crawler02.n45.bl.uk:9094', '--queue', 'fc.to-crawl', '--local-scheduler'])\n","sub_path":"tasks/crawl/launch.py","file_name":"launch.py","file_ext":"py","file_size_in_byte":11134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"105170880","text":"import os\nimport pickle\nimport time\nimport asyncio\nfrom datetime import date\nimport datetime as dt\n\nimport discord\nfrom discord.ext import commands,tasks\nfrom dotenv import load_dotenv\n\nload_dotenv()\nTOKEN = os.getenv('DISCORD_TOKEN')\nCHANNEL_ID = os.getenv('CHANNEL_ID')\nCHANNEL_ID2 = os.getenv('CHANNEL_ID2')\n\nclient = discord.Client()\nchannel = client.get_channel(CHANNEL_ID)\nchannel2 = client.get_channel(CHANNEL_ID2)\n\n#Loading dictionary\nfileName = \"birthdays.txt\"\n\ndef loadFile(fileName):\n inFile = open(fileName,\"rb\")\n try:\n birthdaysDict = pickle.load(inFile)\n if birthdaysDict == None:\n birthdaysDict = {}\n except:\n print(\"Couldn't load pickle file\")\n birthdaysDict = {}\n print(\"Orginal birthday dictionary: \", birthdaysDict)\n inFile.close()\n return birthdaysDict\n\ndef leapYear(year): #Checks if leap year\n if (year % 4) == 0: \n if (year % 100) == 0: \n if (year % 400) == 0: \n return True \n else: \n return False \n else: \n return True \n else: \n return False \n\ndef checkMonth(date): #Checks for the maximum month date\n longMonth = [\"01\",\"03\",\"05\",\"07\",\"08\",\"10\",\"12\"]\n shortMonth = [\"04\",\"06\",\"09\",\"11\"]\n leapMonth = [\"02\"]\n if date[:2] in leapMonth:\n isLeapYear = leapYear(int(date[6:10]))\n if isLeapYear == True:\n return 29\n else:\n return 28\n elif date[:2] in longMonth:\n return 31\n elif date[:2] in shortMonth:\n return 30\n else:\n return False\n\ndef getUserInfo(userInfo):\n newUserInfo = userInfo.split(\",\")\n userName = newUserInfo[0]\n userName = userName.strip()\n newUserInfo[1] = newUserInfo[1].replace(\" \",\"\")\n maxDate = checkMonth(newUserInfo[1]) #Gets max date\n if maxDate == False: #If max date isn't correct\n return False\n if len(newUserInfo[1]) != 10: #If user input isn't correct format\n return False\n elif newUserInfo[1][:2] < \"01\" or newUserInfo[1][:2] > \"12\": #If month isn't a correct month\n return False\n elif newUserInfo[1][3:5] < \"01\" or newUserInfo[1][3:5] > str(maxDate): #If date isn't a correct date\n return False\n elif newUserInfo[1][6:10] < \"0000\": #if year isn't propper\n return False\n else:\n userBirthday = newUserInfo[1]\n userBirthday = userBirthday.strip()\n userBirthdayTest = userBirthday.replace(\"/\",\"\")\n if len(userBirthdayTest) != 8: #Checks if date is correct format\n return False\n try:\n checkUserBirthday = int(userBirthdayTest) \n except:\n return False\n return [userName,userBirthday]\n\ndef saveUserInfo(userInfo,addUser):\n if addUser == True: #To add a user\n if userInfo[0] in birthdaysDict:\n return False\n else:\n birthdaysDict[userInfo[0]] = userInfo[1]\n if addUser == False: #To delete a user\n if userInfo in birthdaysDict:\n birthdaysDict.pop(userInfo,None)\n else:\n print(\"User not in dictionary\")\n\n outFile = open(fileName,\"wb\")\n pickle.dump(birthdaysDict,outFile)\n outFile.close()\n\ndef getDate():\n today = date.today()\n month = today.strftime(\"%m\")\n day = today.strftime(\"%d\")\n year = today.strftime(\"%y\")\n combinedDate = month + \"/\" + day \n print(combinedDate)\n return(combinedDate)\n\ndef checkDict():\n print(\"In checkDict\")\n userNames = []\n birthdaysDict = loadFile(fileName)\n today = getDate()\n for keys in birthdaysDict:\n if birthdaysDict[keys][:5] == today:\n print(\"Birthday is found\")\n userNames.append(keys)\n print(userNames)\n return userNames\n\ndef findUser(dictionary,user):\n for key in dictionary:\n if user == key:\n return dictionary[key]\n return False\n\nbirthdaysDict = loadFile(fileName) #Get's dictionary\n\n@client.event\nasync def on_ready():\n print(f'{client.user} has connected to Discord!')\n happyBirthday.start()\n\n@client.event\nasync def on_message(message):\n id = client.get_guild(CHANNEL_ID)\n\n if message.content.startswith(\"-birthdayhelp\"):\n await message.channel.send(\"To add a birthday in form xx/xx/xxxx\" + \"\\n\" + \"-birthdayadd @user,month/day/year\" + \"\\n\" + \"-bda @user,month/day/year\")\n await message.channel.send(\"To delete a birthday\" + \"\\n\" + \"-birthdaydelete @user\" + \"\\n\" + \"-bdd @user\")\n await message.channel.send(\"To find a birthday\" + \"\\n\" + \"-birthdaylist @user\" + \"\\n\" + \"bdl @user\")\n \n elif message.content.startswith(\"-bdh\"):\n await message.channel.send(\"To add a birthday in from xx/xx/xxxx\" + \"\\n\" + \"-birthdayadd @user,month/day/year\" + \"\\n\" + \"-bda @user,month/day/year\")\n await message.channel.send(\"To delete a birthday\" +\"\\n\" + \"-birthdaydelete @user\" +\"\\n\" + \"-bdd @user\")\n await message.channel.send(\"To find a birthday\" + \"\\n\" + \"-birthdaylist @user\" + \"\\n\" + \"-bdl @user\")\n\n if message.content.startswith(\"-birthdayadd\"):\n if message.content[13:] != \"\": #Makes sure user inoutted something\n userInput = message.content[13:]\n print(userInput)\n userInfo = getUserInfo(userInput)\n print (userInfo)\n if userInfo == False:\n await message.channel.send(\"Incorrect birthday format\")\n else:\n saveUserInfo(userInfo, True)\n print (birthdaysDict)\n await message.channel.send(\"User Birthday Added: \" + userInfo[0] + \", \" + userInfo[1])\n else:\n await message.channel.send(\"Add a birthday by typing in '@user,month/date/year'\")\n\n elif message.content.startswith(\"-bda\"):\n if message.content[5:] != \"\": #Makes sure user inoutted something\n userInput = message.content[5:]\n print(userInput)\n userInfo = getUserInfo(userInput)\n print (userInfo)\n if userInfo == False:\n await message.channel.send(\"Incorrect birthday format\")\n else:\n saveUserInfo(userInfo, True)\n print (birthdaysDict)\n await message.channel.send(\"User Birthday Added: \" + userInfo[0] + \", \" + userInfo[1])\n else:\n await message.channel.send(\"Add a birthday by typing in '@user,month/date/year'\")\n \n if message.content.startswith(\"-birthdaydelete\"):\n if message.content[16:] != \"\":\n userInput = message.content[16:]\n userName = userInput.strip()\n saveUserInfo(userName, False)\n print (birthdaysDict)\n await message.channel.send(userName + \" Birthday Deleted\")\n else:\n await message.channel.send(\"Delete a birthday by typing in '@user'\")\n \n elif message.content.startswith(\"-bdd\"):\n if message.content[5:] != \"\":\n userInput = message.content[5:]\n userName = userInput.strip()\n saveUserInfo(userName, False)\n print (birthdaysDict)\n await message.channel.send(userName + \" Birthday Deleted\")\n else:\n await message.channel.send(\"Delete a birthday by typing in '@user'\")\n \n if message.content.startswith(\"-bdl\"):\n if message.content[5:] != \"\":\n userInput = message.content[5:]\n userName = userInput.strip()\n birthday = findUser(birthdaysDict,userName)\n if birthday != False:\n await message.channel.send(userName + \" Birthday is: \" + birthday)\n else:\n await message.channel.send(\"User doesn't exist\")\n else:\n await message.channel.send(\"Find a birthday by using '-bdl @user'\")\n \n if message.content.startswith(\"-birthdaylist\"):\n if message.content[14:] != \"\":\n userInput = message.content[14:]\n userName = userInput.strip()\n birthday = findUser(birthdaysDict,userName)\n if birthday != False:\n await message.channel.send(userName + \" Birthday is: \" + birthday)\n else:\n await message.channel.send(\"User doesn't exist\")\n else:\n await message.channel.send(\"Find a birthday by using '-birthdaylist @user'\")\n \n@tasks.loop(hours=24)\nasync def happyBirthday():\n await client.wait_until_ready()\n channel2 = client.get_channel(int(CHANNEL_ID2))\n birthdays = checkDict()\n print(\"Here are the birthdays\", birthdays)\n for user in birthdays:\n print(user)\n await channel2.send(\"Happy Birthday\" + user + \"!\")\n\n@happyBirthday.before_loop\nasync def before_happyBirthday():\n for i in range (60*60*24):\n if dt.datetime.now().hour == 12+10:\n print(\"it is time\")\n return\n await asyncio.sleep(1)\n\nclient.run(TOKEN)","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":8863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"639710281","text":"#!/usr/bin/python\n# -*- coding: utf8 -*-\n# -*-coding:cp1251 -*-\n\n# ============================================================\n#\n#\n# ============================================================\n#\n# ============================================================\n# ============================================================\nimport os\nimport time\nimport sys\nimport psutil\n# import serial\n\n# ser = serial.Serial(2) #Change this according to your own COM-port. \n# Remeber that the value you should add is one less than the number of your COM-port.\n\nclass CPU_Info():\n def __init__(self, _max_ctr = 10):\n ''' '''\n self.exit_loop = False\n self.set_internal_ctr(_max_ctr)\n self.internal_ctr = 0\n self.cpuload = 0\n self.vmemload = 0\n self.memload = 0\n\n def set_internal_ctr(self, _max_ctr = 0):\n self.max_ctr = _max_ctr\n\n def get_cpu_load(self):\n _tmp_cpu_load = psutil.cpu_percent(interval=0.2)\n self.cpuload = '%.0f'%(_tmp_cpu_load)\n # self.cpuload = 'cpu load: ' + self.cpuload + '%'\n return self.cpuload\n\n def get_mem_load(self):\n # return the memory usage in percentage\n process = psutil.Process(os.getpid())\n _tmp_mem_load = process.memory_percent()\n # print _tmp_mem_load\n #_tmp_mem_load = psutil.phymem_usage() - deprecated function!\n # mem = '%.0f'%(q.percent/10)\n _mem_load_float = '%.0f'%(_tmp_mem_load*1000)\n # self.memload = 'memory: ' + _tmp_mem_load_float + '%'\n return _mem_load_float\n \n def get_vmem_load(self):\n _tmp_vmem_load = psutil.virtmem_usage()\n # mem = '%.0f'%(q.percent/10)\n _tmp_vmem_load_float = '%.0f'%(_tmp_vmem_load.percent)\n self.memload = 'virt.memory: ' + _tmp_vmem_load_float + '%'\n return self.vmemload\n\n def print_info(self):\n cpu_load = self.get_cpu_load()\n mem_load = self.get_mem_load()\n # status = \"%d - CPU:%s%% MEMORY:%s%%\" % (self.internal_ctr, cpu_load, mem_load)\n status = \"%d - MEMORY:%s%% CPU:%s%% \" % (cpu_load, mem_load, self.internal_ctr)\n status = status + chr(8)*(len(status)+1)\n print (status,)\n\n def print_graph(self):\n str_graph = ''\n cpu_load = self.get_cpu_load()\n mem_load = self.get_mem_load()\n # status = \"%d - CPU:%s%% MEMORY:%s%%\" % (self.internal_ctr, cpu_load, mem_load)\n # status = \"CPU:%s%% MEMORY:%s%%\" % (cpu_load, mem_load)\n status = \"MEMORY:%s%% CPU:%s%%\" % (mem_load, cpu_load)\n print (status,)\n \n if (int(cpu_load)<=0):\n a = 1\n else: \n a = 100/(100/int(cpu_load))# int(int(cpu_load)/50)\n # print '-', a , '-',\n\n for i in range(int(a)):\n str_graph = str_graph + '|'\n #str_graph = str_graph + chr(254)#'|'\n # print '|',\n print (str_graph,)\n #status = status + str_graph + chr(8)*(len(status + str_graph) + 1)\n #print status,\n print ('')\n # status = status + chr(8)*(len(status)+1)\n \n\n def run(self):\n while not self.exit_loop:\n _str_to_print = self.get_cpu_load() + '\\n' + self.get_mem_load() + '\\n'\n # _str_to_print = self.get_cpu_load() + ' ; ' + self.get_mem_load() \n # print \"%s\" % (_str_to_print),\n _str_to_print = _str_to_print + chr(8)*(len(_str_to_print)+1)\n # print _str_to_print\n # self.print_info()\n self.print_graph()\n \n # time.sleep(0.01)\n self.internal_ctr = self.internal_ctr + 1\n \n if (self.internal_ctr > self.max_ctr):\n self.exit_loop = True \n # print '\\n'\n #ser.write(virtmem)\n #ser.close\n #end while\n\ndef info_loop(max_ctr = 100):\n exit_loop = False\n internal_ctr = 0\n\n while not exit_loop:\n q = psutil.cpu_percent(interval=1)\n #q = q/10\n cpuload = '%.0f'%(q)\n cpuload = 'cpu load: ' + cpuload + '%'\n print (cpuload)\n #ser.write(cpuload)\n q = psutil.phymem_usage()\n # mem = '%.0f'%(q.percent/10)\n mem = '%.0f'%(q.percent)\n mem = 'memory: ' + mem + '%'\n print (mem)\n #ser.write(mem)\n q = psutil.virtmem_usage()\n virtmem = '%.0f'%(q.percent/10)\n virtmem = 'virtmem: '+virtmem + '%'\n print (virtmem)\n time.sleep(0.5)\n internal_ctr = internal_ctr + 1\n \n if (internal_ctr > max_ctr):\n self.exit_loop = True \n print ('\\n')\n #ser.write(virtmem)\n #ser.close\n #end while\n#end def\n\n# main entrance point:\nif __name__ == \"__main__\":\n print (u\"Программа началась.\")\n print (\"\")\n\n # info_loop(100)\n a = CPU_Info(1000000)\n a.run()\n\n print (\"\")\n print (\"Main program end.\")\n","sub_path":"cpu_mem_info/run_cpu_info.py","file_name":"run_cpu_info.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"181531461","text":"import random\nfrom functools import partial\nimport sys\nsys.path.append('/Users/rileylittlefield/Desktop/notes/readingnotes/python-ml/data-science-from-scratch/05-exercises')\n\nfrom my_list_vectors import dot_product, magnitue, distance, scalar_multiply\nfrom my_list_matrices import shape, get_row, get_col, make_matrix\n\nfrom fb_friend_data import users, friendships\nimport pdb\n\ndef matrix_product_entry(A, B, i, j):\n return dot_product(get_row(i, A), get_col(j, B))\n\ndef matrix_multiply(A, B):\n n1, k1 = shape(A)\n n2, k2 = shape(B)\n\n if k1 != n2:\n raise ArithmeticError('Incompatible Matrix Shapes!')\n\n return make_matrix(n1, k2, partial(matrix_product_entry, A, B))\n \ndef vector_as_matrix(vector):\n return [\n [ component ]\n for component\n in vector\n ]\n\ndef vector_from_matrix(vector_as_matrix):\n return [\n row[0]\n for row\n in vector_as_matrix\n ]\n\ndef matrix_operate(A, v):\n v_as_matrix = vector_as_matrix(v)\n product = matrix_multiply(A, v_as_matrix)\n return vector_from_matrix(product)\n\ndef find_eigenvector(A, tolerance=0.00001):\n guess = [ random.random() for _ in A ]\n\n while True:\n result = matrix_operate(A, guess)\n length = magnitue(result)\n next_guess = scalar_multiply(1 / length, result)\n\n if distance(guess, next_guess) < tolerance:\n eigenvector, eigenvalue = next_guess, length\n return eigenvector, eigenvalue\n else:\n guess = next_guess\n\ndef entry_fn(node_i, node_j):\n return 1 if (node_i, node_j) in friendships or (node_j, node_i) in friendships else 0\n\nadjacency_matrix_dimension = len(users)\nfriendships_adjacency_matrix = make_matrix(\n adjacency_matrix_dimension,\n adjacency_matrix_dimension,\n entry_fn\n)\n# pdb.set_trace()\neigenvector_centralities, _ = find_eigenvector(friendships_adjacency_matrix)\nprint(eigenvector_centralities)\n ","sub_path":"22-exercises-network-analysis/eigenvector_centrality.py","file_name":"eigenvector_centrality.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"470636332","text":"# ---------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# ---------------------------------------------------------\n\n# pylint: disable=unused-argument,no-self-use,no-else-return\n\nfrom marshmallow import fields, EXCLUDE\nfrom marshmallow.decorators import post_load, pre_dump\nfrom azure.ai.ml._schema.core.schema_meta import PatchedSchemaMeta\nfrom azure.ai.ml._schema.core.fields import StringTransformedEnum\nfrom azure.ai.ml._schema.core.fields import NestedField\nfrom azure.ai.ml.entities._workspace.networking import (\n ManagedNetwork,\n FqdnDestination,\n ServiceTagDestination,\n PrivateEndpointDestination,\n)\nfrom azure.ai.ml.constants._workspace import IsolationMode, OutboundRuleCategory, OutboundRuleType\nfrom azure.ai.ml._utils.utils import camel_to_snake, _snake_to_camel\n\nfrom azure.ai.ml._utils._experimental import experimental\n\n\n@experimental\nclass DestinationSchema(metaclass=PatchedSchemaMeta):\n service_resource_id = fields.Str()\n subresource_target = fields.Str()\n spark_enabled = fields.Bool()\n service_tag = fields.Str()\n protocol = fields.Str()\n port_ranges = fields.Str()\n\n\n@experimental\nclass ManagedNetworkStatusSchema(metaclass=PatchedSchemaMeta):\n spark_ready = fields.Bool()\n status = fields.Str()\n\n\n@experimental\nclass OutboundRuleSchema(metaclass=PatchedSchemaMeta):\n name = fields.Str(required=True)\n type = StringTransformedEnum(\n allowed_values=[OutboundRuleType.FQDN, OutboundRuleType.PRIVATE_ENDPOINT, OutboundRuleType.SERVICE_TAG],\n casing_transform=camel_to_snake,\n metadata={\"description\": \"outbound rule type.\"},\n )\n destination = fields.Raw(required=True)\n category = StringTransformedEnum(\n allowed_values=[\n OutboundRuleCategory.REQUIRED,\n OutboundRuleCategory.RECOMMENDED,\n OutboundRuleCategory.USER_DEFINED,\n ],\n casing_transform=camel_to_snake,\n metadata={\"description\": \"outbound rule category.\"},\n )\n status = fields.Str(dump_only=True)\n\n @pre_dump\n def predump(self, data, **kwargs):\n if data and isinstance(data, FqdnDestination):\n data.destination = self.fqdn_dest2dict(data.destination)\n if data and isinstance(data, PrivateEndpointDestination):\n data.destination = self.pe_dest2dict(data.service_resource_id, data.subresource_target, data.spark_enabled)\n if data and isinstance(data, ServiceTagDestination):\n data.destination = self.service_tag_dest2dict(data.service_tag, data.protocol, data.port_ranges)\n return data\n\n @post_load\n def createdestobject(self, data, **kwargs):\n dest = data.get(\"destination\", False)\n category = data.get(\"category\", OutboundRuleCategory.USER_DEFINED)\n name = data.get(\"name\", None)\n status = data.get(\"status\", None)\n if dest:\n if isinstance(dest, str):\n return FqdnDestination(name=name, destination=dest, category=_snake_to_camel(category), status=status)\n else:\n if dest.get(\"subresource_target\", False):\n return PrivateEndpointDestination(\n name=name,\n service_resource_id=dest[\"service_resource_id\"],\n subresource_target=dest[\"subresource_target\"],\n spark_enabled=dest[\"spark_enabled\"],\n category=_snake_to_camel(category),\n status=status,\n )\n return ServiceTagDestination(\n name=name,\n service_tag=dest[\"service_tag\"],\n protocol=dest[\"protocol\"],\n port_ranges=dest[\"port_ranges\"],\n category=_snake_to_camel(category),\n status=status,\n )\n\n def fqdn_dest2dict(self, fqdndest):\n res = fqdndest\n return res\n\n def pe_dest2dict(self, service_resource_id, subresource_target, spark_enabled):\n pedest = {}\n pedest[\"service_resource_id\"] = service_resource_id\n pedest[\"subresource_target\"] = subresource_target\n pedest[\"spark_enabled\"] = spark_enabled\n return pedest\n\n def service_tag_dest2dict(self, service_tag, protocol, port_ranges):\n service_tag_dest = {}\n service_tag_dest[\"service_tag\"] = service_tag\n service_tag_dest[\"protocol\"] = protocol\n service_tag_dest[\"port_ranges\"] = port_ranges\n return service_tag_dest\n\n\n@experimental\nclass ManagedNetworkSchema(metaclass=PatchedSchemaMeta):\n isolation_mode = StringTransformedEnum(\n allowed_values=[\n IsolationMode.DISABLED,\n IsolationMode.ALLOW_INTERNET_OUTBOUND,\n IsolationMode.ALLOW_ONLY_APPROVED_OUTBOUND,\n ],\n casing_transform=camel_to_snake,\n metadata={\"description\": \"isolation mode for the workspace managed network.\"},\n )\n outbound_rules = fields.List(NestedField(OutboundRuleSchema, allow_none=False, unknown=EXCLUDE), allow_none=True)\n network_id = fields.Str(required=False)\n status = NestedField(ManagedNetworkStatusSchema, dump_only=True)\n\n @post_load\n def make(self, data, **kwargs):\n outbound_rules = data.get(\"outbound_rules\", False)\n if outbound_rules:\n return ManagedNetwork(_snake_to_camel(data[\"isolation_mode\"]), outbound_rules)\n else:\n return ManagedNetwork(_snake_to_camel(data[\"isolation_mode\"]))\n","sub_path":"sdk/ml/azure-ai-ml/azure/ai/ml/_schema/workspace/networking.py","file_name":"networking.py","file_ext":"py","file_size_in_byte":5521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"324297187","text":"import cv2\nimport os\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport time\nimport similarity_util\n\nif __name__ == '__main__':\n # check_path = r'C:\\Users\\Administrator\\Desktop\\zawu\\similarity\\check'\n # check_path = r'F:\\pub_pic\\004'\n # save_hist_path = r'C:\\Users\\Administrator\\Desktop\\zawu\\similarity\\res_hist'\n # save_MD5_path = r'C:\\Users\\Administrator\\Desktop\\zawu\\similarity\\res_md5'\n # standard_path = r'C:\\Users\\Administrator\\Desktop\\zawu\\similarity\\dui'\n\n check_path = r'/opt/10.20.31.124.pub.pic'\n save_hist_path = r'res_hist'\n save_MD5_path = r'res_md5'\n standard_path = r'dui'\n need_file_count = False\n\n point_file_name = r'hist.point'\n img_min_wh = 100\n hist_size = 256\n hist_min_similar = 0.75\n run_hist = True\n run_MD5 = False\n print('run_hist:', run_hist)\n print('run_MD5:', run_MD5)\n if not os.path.exists(save_hist_path):\n os.makedirs(save_hist_path)\n if not os.path.exists(save_MD5_path):\n os.makedirs(save_MD5_path)\n\n if need_file_count:\n file_count = 0\n for fpathe, dirs, check_img_names in os.walk(check_path):\n for check_img_name in check_img_names:\n file_count += 1\n print('file_count:', file_count)\n\n duiHistArr = similarity_util.initDuiHistArr(standard_path, hist_size)\n duiMD5Arr = similarity_util.initDuiMD5Arr(standard_path)\n\n t = time.time()\n i = 0\n point_num = 0\n if os.path.exists(point_file_name):\n with open(point_file_name, 'r') as point_file:\n point_num = int(point_file.readline())\n\n for fpathe, dirs, check_img_names in os.walk(check_path):\n for check_img_name in check_img_names:\n i += 1\n if i < point_num:\n continue\n try:\n font, ext = os.path.splitext(check_img_name)[0], os.path.splitext(check_img_name)[1]\n if ext == '.gif':\n continue\n check_img_path_name = os.path.join(fpathe, check_img_name)\n # print('start:', os.path.join(fpathe, check_img_name))\n vis = cv2.imread(check_img_path_name)\n if vis.shape[0] < img_min_wh or vis.shape[1] < img_min_wh:\n continue\n if run_hist:\n corrcuomean, minbc = similarity_util.check_one_img_hist(vis, duiHistArr, hist_size)\n # print(os.path.join(fpathe, check_img_name), corrcuomean, minbc)\n if corrcuomean > hist_min_similar:\n font, ext = os.path.splitext(check_img_name)[0], os.path.splitext(check_img_name)[1]\n corrcuomean = ('%.2f' % corrcuomean)\n cv2.imwrite(os.path.join(save_hist_path, font+\"_\"+str(corrcuomean)+ext), vis)\n\n # mD5相似\n if run_MD5:\n is_MD5_similar = similarity_util.check_one_img_md5(check_img_path_name, duiMD5Arr)\n if is_MD5_similar:\n cv2.imwrite(os.path.join(save_MD5_path, check_img_name), vis)\n\n if i % 1000 == 0:\n print('耗时:', str(time.time()-t), check_img_path_name, i)\n point_num = i\n with open(point_file_name, 'w+') as point_file:\n point_file.write(str(i))\n except Exception as e:\n print('error:', os.path.join(fpathe, check_img_name))\n\n","sub_path":"img/_04_similarity/similarity_hist.py","file_name":"similarity_hist.py","file_ext":"py","file_size_in_byte":3469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"123247237","text":"# -*- coding: utf-8 -*-\n'''\n Created by hushiwei on 2019-02-15\n Desc : \n Note : \n'''\n\nimport json\nimport numpy as np\nimport pandas as pd\n\nfile = open(r\"/Users/hushiwei/IdeaProjects/ConvertLightGBM/src/main/resources/gbm_has_missing.json\", \"rb\") # 读取模型json文件\n# file = open(r\"/Users/hushiwei/IdeaProjects/ConvertLightGBM/src/main/resources/gbm.json\", \"rb\") # 读取模型json文件\n# file = open(r\"/Users/hushiwei/Downloads/model2/model/gbm.json\", \"rb\") # 读取模型json文件\nmodel = json.load(file)\n\nfeature_names = model['feature_names'] # 获取模型中所用的特征变量\n\n\n# 定义一个函数判断每一个leaf是走left还是right\ndef decison(data,threshold,default_left):\n '''\n :param data: 特征值\n :param threshold: 分割判断值\n :param default_left: 默认分支 default_left= True or False\n :return: 返回结果left_child or right_child\n '''\n if ((np.isnan(data)) and (default_left is True)):\n return 'left_child'\n elif data <= threshold:\n return 'left_child'\n else:\n return 'right_child'\n\n# 定义预测函数\ndef predict_gbm(data):\n score = 0\n for i in range(len(model['tree_info'])): # 遍历每一个节点\n num_leaves = model['tree_info'][i]['num_leaves'] # 获取每颗树的节点数\n tree = model['tree_info'][i]['tree_structure'] # 获取每一颗树结构\n for i in range(num_leaves): # 遍历节点数\n # 到达节点leaf,进行走向判断\n threshold = tree.get('threshold')\n default_left = tree.get('default_left')\n split_feature = feature_names[tree['split_feature']] # 获取叶子节点的分割特征变量\n next_decison = decison(data[split_feature], threshold, default_left)\n # 获取下一个分支leaf\n tree = tree[next_decison]\n if tree.get('left_child', 'not found') == 'not found': # 如果到达节点节点停止遍历,返回对应值\n score = score + tree['leaf_value']\n break\n return (score)\n\n\n# 进行测试\ninput = \"/Users/hushiwei/IdeaProjects/ConvertLightGBM/src/main/resources/test.csv\"\n# input = \"/Users/hushiwei/IdeaProjects/ConvertLightGBM/src/main/resources/test_woe.csv\"\n# input = \"/Users/hushiwei/IdeaProjects/ConvertLightGBM/src/main/resources/test_no_missing.csv\"\ndf = pd.read_csv(input)\ndf = df.iloc[:, 1:]\npredict_df = []\nfor i in range(len(df)):\n predict_data = predict_gbm(df.iloc[i, :]) # 分值\n predict_dt = 1 / (np.exp(-predict_data) + 1) # 将预测分值转为p值\n predict_df.append(predict_dt)\n\nprint(predict_df)\n","sub_path":"MachineLearning/LightGBM/predict_by_python.py","file_name":"predict_by_python.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"301087481","text":"import os\nimport subprocess\nimport sys\n\n# Env variables\nsample_id = os.environ['SAMPLE_ID']\ndownload_bucket = os.environ['DOWNLOAD_BUCKET']\nupload_bucket = os.environ['UPLOAD_BUCKET']\nthreads = os.environ['THREADS'] # 22\nmin_MAF = os.environ['MIN_MAF'] # 0.1\nmin_count = os.environ['MIN_COUNT'] # 100\n\n# Variables\nhome_dir = \"/home/ec2-user\"\nmnt_dir = \"/home/ec2-user/vol_mnt\"\n\n# Function to run shell commands\n\n\ndef run_command(cmd):\n try:\n subprocess.run(f'echo {cmd}', shell=True)\n subprocess.run(cmd, shell=True, stderr=subprocess.PIPE, check=True)\n except subprocess.CalledProcessError as e:\n print(f\"Stderr: {e.stderr}\")\n sys.exit()\n\n\n# File directory\ndownload_path = os.path.join(mnt_dir, sample_id)\noutput_dir = os.path.join(mnt_dir, f\"{sample_id}_cellSNP\")\n\n# Download files\ncmd = f\"aws s3 sync s3://{download_bucket}/{sample_id} {download_path}\"\nsubprocess.run(\"echo '###### Downloading Input Files #######' \", shell=True)\nrun_command(cmd)\nsubprocess.run(\"echo '###### Checking Free Disk Volume #######' \", shell=True)\nsubprocess.run(\"df -h\", shell=True)\n\n# Bam, barcode path\nbamfile_path = \"\"\nbarcode_path = \"\"\nfor dirpath, dirnames, filenames in os.walk(download_path):\n for file in filenames:\n if file == \"possorted_genome_bam.bam\":\n bamfile_path = os.path.join(dirpath, file)\n elif file == \"barcodes.tsv.gz\":\n cmd = f\"gunzip {os.path.join(dirpath,file)}\"\n run_command(cmd)\n barcode_path = os.path.join(dirpath, \"barcodes.tsv\")\n elif file == \"barcodes.tsv\":\n barcode_path = os.path.join(dirpath, file)\n\n# Run command\ncmd = f\"cellsnp-lite -s {bamfile_path} -b {barcode_path} -O {output_dir} -p {threads} --minMAF {min_MAF} --minCOUNT {min_count} --gzip\"\nsubprocess.run(\"echo '###### Running Main Command #######' \", shell=True)\nrun_command(cmd)\n\n# Upload output files\ncmd = f\"aws s3 sync {output_dir} s3://{upload_bucket}/{sample_id}\"\nsubprocess.run(\"echo '###### Uploading Result Files #######' \", shell=True)\nrun_command(cmd)\n\n# Clean up\nsubprocess.run(\"echo '###### Checking Free Disk Volume #######' \", shell=True)\nsubprocess.run(\"df -h\", shell=True)\nsubprocess.run(f\"rm -rf {download_path}\", shell=True)\nsubprocess.run(f\"rm -rf {output_dir}\", shell=True)\n","sub_path":"Docker/cellSNP_lite/cellsnp_lite.py","file_name":"cellsnp_lite.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"495648279","text":"from PyQt5.QtWidgets import (QApplication,QWidget,QPushButton,QLCDNumber,QFormLayout,QLineEdit,QLabel,QGridLayout)\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtCore import Qt,QTimer,QDateTime,QDate,QTime,QSize\nimport sys\n\nclass Example(QWidget):\n def __init__(self):\n super(Example, self).__init__()\n self.initUI()\n\n def initUI(self):\n self.setGeometry(300,300,330,310)\n self.setWindowTitle(\"数字键盘输入\")\n gridLayout = QGridLayout()\n self.display = QLineEdit(\"0\")\n self.display.setFixedSize(QSize(287,40))\n self.display.setReadOnly(True)\n self.display.setAlignment(Qt.AlignRight)\n self.display.setFont(QFont(\"微软雅黑\",14,QFont.Bold))\n gridLayout.addWidget(self.display,0,0,1,4)\n self.showNum = \"\"\n\n keys = ['Clear',\n '7', '8', '9',\n '4', '5', '6', '',\n '1', '2', '3', 'Enter',\n '0', '', '.', '']\n position = [(0, 0),\n (1, 0), (1, 1), (1, 2),\n (2, 0), (2, 1), (2, 2), (2, 2),\n (3, 0), (3, 1), (3, 2), (3, 3),\n (4, 0), (4, 1), (4, 2), (4, 3), ]\n for item in range(len(keys)):\n btn = QPushButton(keys[item])\n btn.setFixedSize(QSize(60, 40))\n btn.setFont(QFont(\"微软雅黑\",12,QFont.Bold))\n # btn.clicked.connect(self.btnFuck)\n btn.clicked.connect(self.btnClicked)\n if keys[item] == \"+\":\n gridLayout.addWidget(btn, 2, 3, 2, 1)\n btn.setFixedSize(QSize(60, 90))\n elif keys[item] == \"Enter\":\n self.enterBtn = btn\n gridLayout.addWidget(self.enterBtn, 4, 3, 2, 1)\n self.enterBtn.setFixedSize(QSize(60, 90))\n elif keys[item] == \"0\":\n gridLayout.addWidget(btn, 5, 0, 1, 2)\n btn.setFixedSize(QSize(142, 40))\n elif keys[item] == \"\":\n continue\n else:\n gridLayout.addWidget(btn, position[item][0]+1, position[item][1], 1, 1)\n self.setLayout(gridLayout)\n\n def btnFuck(self):\n self.display.setText(\"fuck\")\n\n def btnClicked(self):\n sender = self.sender()\n symbols = [\"Clear\",\"/\",\"*\",\"-\",\"+\",\"Enter\"]\n if sender.text() not in symbols:\n self.showNum += sender.text()\n self.display.setText(self.showNum)\n print(self.showNum)\n elif sender.text() == \"Clear\":\n self.display.setText(\"0\")\n self.showNum = \"\"\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n ex.show()\n sys.exit(app.exec_())","sub_path":"Python/GrabImage/ui2/keyboard2.py","file_name":"keyboard2.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"26680886","text":"#!/usr/bin/env python\n#\n# Copyright (c) 2013, 2014, 2015, 2016, 2017. Evident.io (Evident). All Rights Reserved. \n# \n# Evident.io shall retain all ownership of all right, title and interest in and to \n# the Licensed Software, Documentation, Source Code, Object Code, and API's (\"Deliverables\"), \n# including (a) all information and technology capable of general application to Evident.io's\n# customers; and (b) any works created by Evident.io prior to its commencement of any\n# Services for Customer.\n# \n# Upon receipt of all fees, expenses and taxes due in respect of the relevant Services, \n# Evident.io grants the Customer a perpetual, royalty-free, non-transferable, license to \n# use, copy, configure and translate any Deliverable solely for internal business operations\n# of the Customer as they relate to the Evident.io platform and products, and always\n# subject to Evident.io's underlying intellectual property rights.\n# \n# IN NO EVENT SHALL EVIDENT.IO BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, \n# INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF \n# THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF EVIDENT.IO HAS BEEN HAS BEEN\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# \n# EVIDENT.IO SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. \n# THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED \"AS IS\". \n# EVIDENT.IO HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,\n# OR MODIFICATIONS.\n# \n# ---\n#\n# This script reads from a csv file containing a list of ESP users and attempts to create each one.\n# It looks for a file called \"esp_users.csv\" is the same directory the script is executed in.\n#\n# CSV File Format:\n#\n# First_Name,Last_Name,Email,Role,Teams\n# Jimmy,Page,jimmy@rock.io,customer,TeamA,TeamB\n# Randy,Rhodes,randy@rock.io,manager,TeamB\n# Eric,Clapton,eric@rock.io,manager\n#\n# The first 3 fields are required; First_Name, Last_Name and Email. The Role and Teams fields\n# are optional. The default role is \"manager\" if one is not given.\n#\n# Requirements:\n#\n# * Python3 (Tested with version 3.6.1)\n# `python --version`\n#\n# * Valid ESP credentials / API keys\n# https://esp.evident.io/settings/api_keys\n# export ESP_ACCESS_KEY_ID=\n# export ESP_SECRET_ACCESS_KEY=\n#\n# Options:\n#\ncsv_delimiter = ','\nreq_fields = 3\n\n\nfrom wsgiref.handlers import format_date_time\nfrom datetime import datetime\nfrom time import mktime\n\nimport hashlib\nimport codecs\nimport hmac\nimport base64\nimport requests\nimport json\nimport csv\nimport os\nimport re\n\n# API keys from shell env\npub_key = os.environ[\"ESP_ACCESS_KEY_ID\"]\nsecret_key = os.environ[\"ESP_SECRET_ACCESS_KEY\"]\n\n\ndef api_call(method, uri, data, timeout):\n \"\"\" API call \"\"\"\n\n # ESP API endpoint - http://api-docs.evident.io/\n url = 'https://api.evident.io'\n\n # Uses the RFC-1123 spec. Note: Must be in the GMT timezone.\n now = datetime.now()\n stamp = mktime(now.timetuple())\n dated = format_date_time(stamp)\n\n # The Content-MD5 header should include a MD5 base64 hexdigest of the request body.\n hex = hashlib.md5(data.encode('UTF-8')).hexdigest()\n body = codecs.encode(codecs.decode(hex, 'hex'), 'base64').decode().rstrip('\\n')\n\n # Create a canonical string using your HTTP headers containing the HTTP method,\n # content-type, content-MD5, request URI and the timestamp.\n canonical = '%s,%s,%s,%s,%s' % (method, 'application/vnd.api+json', body, uri, dated)\n\n # Convert from string to bytes.\n secret = bytes(secret_key, 'UTF-8')\n canonical = bytes(canonical, 'UTF-8')\n\n # Use the HMAC-SHA1 algorithm to encode the string with your secret key.\n hashed = hmac.new(secret, canonical, hashlib.sha1)\n encoded = base64.b64encode(hashed.digest())\n auth = str(encoded, 'UTF-8')\n\n # Add an Authorization header with the ‘APIAuth’, the public key, and the encoded\n # canonical string.\n\n headers = { 'Date' : '%s' % (dated),\n 'Content-MD5' : '%s' % (body),\n 'Content-Type' : 'application/vnd.api+json',\n 'Accept' : 'application/vnd.api+json',\n 'Authorization' : 'APIAuth %s:%s' % (pub_key, auth) }\n\n # Using requests\n # http://docs.python-requests.org/en/latest/user/advanced/\n\n r = requests.Request(method, url+uri, data=data, headers=headers)\n p = r.prepare()\n s = requests.Session()\n ask = s.send(p, timeout=timeout)\n response = ask.json()\n\n return response\n\n\ndef read_user_data(csv_file_name):\n \"\"\" Read ESP users csv file \"\"\"\n\n users = []\n with open(csv_file_name, 'r') as csvUserData:\n csvReader = csv.reader(csvUserData, delimiter = csv_delimiter)\n for row in csvReader:\n if len(row) < req_fields:\n continue\n if re.match('[A-Za-z]', row[0]) == None or re.match('[A-Za-z]', row[1]) == None:\n continue\n if re.search('[@]', row[2]) == None:\n continue\n\n try:\n role = row[3]\n except IndexError:\n role = ''\n\n try:\n team_names = []\n for team in row[4:]:\n team = re.sub('\\s', '+', team)\n team_names.append(team)\n except IndexError:\n team_names = ''\n\n team_ids = list_esp_teams(team_names)\n\n user = ( row[0], row[1], row[2], role, team_ids )\n users.append(user)\n\n return users\n\n\ndef list_esp_teams(team_names):\n \"\"\" Convert Team names to Ids \"\"\"\n\n method = 'GET'\n ##uri = '/api/v2/teams'\n data = ''\n timeout = (3, 10)\n\n team_ids = []\n for team in team_names:\n uri = '/api/v2/teams.json?filter[name_eq]=%s' % (team)\n response = api_call(method, uri, data, timeout)\n \n try:\n team_id = response['data'][0]['id']\n except KeyError:\n pass\n else:\n team_ids.append(int(team_id))\n\n return team_ids\n\n\ndef create_esp_users(users):\n \"\"\" Create ESP users \"\"\"\n\n method = 'POST'\n uri = '/api/v2/users'\n ##data = ''\n timeout = (3, 10)\n\n for user in users:\n role_id = '3' if (user[3] == 'customer') else '2'\n data = '{\"data\": {\"type\": \"users\", \"attributes\": {\"first_name\": \"%s\", \"last_name\": \"%s\", \"email\": \"%s\", \"role_id\": \"%s\", \"team_ids\": %s }}}' % (user[0], user[1], user[2], role_id, user[4] )\n response = api_call(method, uri, data, timeout)\n\n try:\n print('Created ESP user -> %s' % (response['data']['attributes']['email']))\n except KeyError:\n print('Failed to create ESP user -> %s' % (user[2]))\n\n return\n\n\ndef main(csv_file_name):\n \"\"\" Run checks and do the work \"\"\"\n\n if os.path.exists(csv_file_name) != True:\n print(\"Error: Can't find file, \" + csv_file_name + '.')\n exit(1)\n\n users = read_user_data(csv_file_name)\n result = create_esp_users(users)\n\n\nif __name__ == \"__main__\":\n\n main(csv_file_name = 'esp_users.csv')\n","sub_path":"create_esp_users.py","file_name":"create_esp_users.py","file_ext":"py","file_size_in_byte":7213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"649336836","text":"# 从尾到头打印单链表的值\n\n# 链表节点的定义\nclass LinkNode:\n def __init__(self, value):\n self.value = value\n self.next = None\n\ndef print_link_node(phead):\n pnode = phead\n if pnode.next != None:\n print_link_node(pnode.next) \n print(pnode.value)\n\nnode_head = pre_node = LinkNode(-1)\nfor i in range(5):\n node = LinkNode(i)\n pre_node.next = node\n pre_node = node\n\nprint_link_node(node_head)\n","sub_path":"python-implement/print_linknode.py","file_name":"print_linknode.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"217280579","text":"import flask\nimport logging\n\nimport tesg\nimport atb\nimport weather\n\nLOG_FILENAME = \"nana.log\"\n\napp = flask.Flask(__name__)\n\n@app.route(\"/tesg\")\ndef tesg_redirect():\n\t\"\"\"redirect to most recent /tesg/ thread in 4chan's /vg/ board.\"\"\"\n\tthreads = tesg.find_threads()\n\tif threads:\n\t\tthread = tesg.find_most_recent2(threads)\n\t\treturn flask.redirect(\"https://boards.4chan.org/vg/thread/\" + str(thread[\"no\"]))\n\telse:\n\t\treturn flask.redirect(\"http://catalog.neet.tv/vg\")\n\n@app.route(\"/havstad\")\ndef havstad_bus():\n\thavstad_stops = atb.getUserRealTimeForecastByStop(\"16011169\")\n\ttrondheim_weather = weather.get_weather_for_trondheim()\n\treturn flask.render_template(\"atb.html\", havstad_stops=havstad_stops, trondheim_weather=trondheim_weather)\n\n@app.route(\"/\")\ndef index():\n\t#return flask.render_template(\"index.html\")\n\t#thread = tesg.get_thread(tesg.find_most_recent(tesg.find_threads()))\n\t#return str(thread)\n\treturn havstad_bus()\n\nfile_handler = logging.FileHandler(\"nana.log\")\nfile_handler.setLevel(logging.DEBUG)\nfile_handler.setFormatter(logging.Formatter(\"%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)s]\"))\napp.logger.addHandler(file_handler)\napp.run(debug=False, host=\"0.0.0.0\", port=80)\n","sub_path":"master/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"433645330","text":"import requests\r\n\r\nclient_id = 'a1b2c3d4e5f6g7h8i9j0'\r\n\r\napi_key = 'a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6'\r\n\r\n# EXAMPLES:\r\n# query = 'sovereutilizeignty.com'\r\n# query = '814a37d89a79aa3975308e723bc1a3a67360323b7e3584de00896fe7c59bbb8e'\r\n# query = '75.102.25.76'\r\n# query = 'SearchProtocolHost.exe'\r\nquery = ''\r\n\r\nurl = 'https://api.amp.cisco.com/v1/computers/activity'\r\n\r\nresponse = requests.get(url, auth=(client_id, api_key), params={'q':query})\r\n\r\nresponse_json = response.json()\r\n\r\ntotal = response_json['metadata']['results']['total']\r\n\r\nprint(total)\r\n","sub_path":"01_get_total.py","file_name":"01_get_total.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"316998375","text":"# fix import paths\nimport os\nimport sys\nsys.path.append(\n os.path.abspath(os.path.join(\n os.path.dirname(__file__),\n os.path.pardir,\n os.path.pardir\n ))\n)\n\nimport random\nfrom airflow import DAG\nfrom ariadne.operators import *\nfrom datetime import datetime, timedelta\nfrom pprint import pprint\nimport pandas as pd\nimport web_pdb\n\nerror_threshold = .2\n\ndefault_args = {\n 'owner': 'Airflow',\n 'depends_on_past': False,\n 'start_date': datetime(2019, 12, 1),\n 'email': ['allen.leis@gmail.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 0,\n 'retry_delay': timedelta(minutes=2),\n # 'queue': 'bash_queue',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n}\n\ndag = DAG('test-random-error', default_args=default_args)\n\ndef csv_pop(data, *args, **kwargs):\n if kwargs.get(\"test_mode\", False):\n web_pdb.set_trace()\n\n waste_time(1000000)\n path = \"data/csv/aapl.csv\"\n df = pd.read_csv(path)\n\n if df.size > 0:\n item = df.iloc[0].to_dict()\n df.drop(0, inplace=True)\n df.to_csv(path, index=False)\n\n item.pop(\"Volume\")\n return item\n\nt1 = PythonOperator(\n task_id='start',\n provide_context=True,\n python_callable=csv_pop,\n dag=dag,\n)\n\ndef waste_time(incr=1000000):\n iters = int(random.random() * incr)\n for i in range(iters):\n v = i * i / 2\n\ndef handler(data, field, *args, **kwargs):\n if kwargs.get(\"test_mode\", False):\n web_pdb.set_trace()\n\n waste_time()\n if random.random() < error_threshold:\n raise Exception(\"invalid data encountered\")\n return data[field]\n\ndef handlerDiff(data, *args, **kwargs):\n if kwargs.get(\"test_mode\", False):\n web_pdb.set_trace()\n\n waste_time()\n return data[1] - data[0]\n\nt2 = PythonOperator(\n task_id='handlerOpen',\n provide_context=True,\n python_callable=handler,\n op_kwargs={\"field\": \"Open\"},\n dag=dag,\n)\nt3 = PythonOperator(\n task_id='handlerClose',\n provide_context=True,\n python_callable=handler,\n op_kwargs={\"field\": \"Close\"},\n dag=dag,\n)\n\nt4 = PythonOperator(\n task_id='handlerDiff',\n provide_context=True,\n python_callable=handlerDiff,\n dag=dag,\n)\n\nt1 >> [t2, t3] >> t4\n","sub_path":"airflow/dags/test-random-error.py","file_name":"test-random-error.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"391400905","text":"#!/usr/bin/env python\n\nimport logging, os, sys, json, csv, time\nfrom cgi import parse_header\n\n\ndef getJsonData():\n logging.info(\"start reading request\")\n cl, _ = parse_header(os.environ['CONTENT_LENGTH'])\n data = json.loads(sys.stdin.read(int(cl)))\n logging.info(\"src data:\" + str(data))\n print(data)\n return data\n\ngerechtNaam = getJsonData()\nstringetje = str(gerechtNaam)\n\ndef verwijderen():\n\n gerechten = csv.reader(open(\"gerechten.csv\", \"rb\"))\n temp = csv.writer(open(\"test.csv\", \"wb\"))\n for line in gerechten:\n if stringetje[15:-2] not in line:\n temp.writerow(line)\n print(line)\n\n\ndef kopieren():\n temp = csv.reader(open(\"test.csv\", \"rb\"))\n gerechten = csv.writer(open(\"gerechten.csv\", \"wb\"))\n\n for line in temp:\n gerechten.writerow(line)\n\n temp.close()\n gerechten.close()\n\nverwijderen()\nkopieren()","sub_path":"app/cgi-bin/verwijderen.py","file_name":"verwijderen.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"565086124","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom .forms import UserRegisterForm\nfrom django.contrib.auth.models import User\nimport random\nfrom .models import UserOTP\nfrom .import forms\nfrom django.core.mail import send_mail\nfrom django.conf import settings\n\n\ndef register(request):\n if request.method == 'POST':\n\n #verify otp\n otp_present = request.POST.get('otp')\n\n if otp_present:\n get_user = request.POST.get('usr')\n usr = User.objects.get(username=get_user)\n if not usr.is_active:\n if int(otp_present)== UserOTP.objects.filter(user = usr).last().otp:\n usr.is_active = True\n usr.save()\n messages.success(request, f'Account created for {usr.username}')\n return redirect('login')\n else:\n messages.error(request, f'Account not created for {usr.username}. Please validate OTP')\n return render(request, 'user/register.html', {'otp': True, 'usr': usr})\n\n\n\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n \n\n\n usr = User.objects.get(username=username)\n usr.is_active = False\n usr.email = usr.email\n usr.save() #cannot login until otp is entered\n\n usr_otp = random.randint(10000, 999999)\n\n #creating user otp here\n UserOTP.objects.create(user=usr, otp = usr_otp)\n\n #creating mail msg\n msg = f\"Hi {username}, \\n Your OTP is {usr_otp}.\"\n\n #create an email\n send_mail(\n \"Welcome to ExamFunda. Verify your email.\",\n msg,\n settings.EMAIL_HOST_USER,\n [usr.email],\n fail_silently = False\n )\n\n return render(request, 'users/register.html', {'otp':True, 'usr':usr})\n \n\n\n \n else:\n form = UserRegisterForm()\n return render(request, 'users/register.html', {'form': form})\n\n","sub_path":"QuizApp/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"600844111","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\ndef busca_binaria(list, search):\n inicio = 0\n fim = len(list) - 1\n centro = 0\n\n while inicio <= fim:\n centro = inicio + (fim - inicio) / 2\n if search == list[centro]:\n return centro\n elif search > list[centro]:\n inicio = centro + 1\n else:\n fim = centro - 1\n return -1\n\n\n\nlist = [3, 4, 11, 12, 21, 34, 65, 77, 78, 98]\nprint(busca_binaria(list, 77))","sub_path":"04_metodos_busca/02_busca_binaria/busca_binaria.py","file_name":"busca_binaria.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"613183250","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2015 liukelin\n#\n# @author: iiukelin 314566990@qq.com\n# \"\"\"\n# * 类名:AlipaySubmit\n# * 功能:支付宝各接口请求提交类\n# * 详细:构造支付宝各接口表单HTML文本,获取远程HTTP数据\n# * 说明:\n# * 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。\n# * 该代码仅供学习和研究支付宝接口使用,只是提供一个参考。\n# \"\"\"\nimport alipay_core_function\nimport alipay_md5_function\n\nclass AlipaySubmit:\n alipay_config = \"\"\n #支付宝网关地址(新)\n alipay_gateway_new = 'https://mapi.alipay.com/gateway.do?'\n\n def __init__(self, alipay_config) :\n self.alipay_config = alipay_config\n\n def AlipaySubmit(self, alipay_config) :\n self.__init__(alipay_config)\n\n # \"\"\"\n # * 生成签名结果\n # * @param $para_sort 已排序要签名的数组\n # * return 签名结果字符串\n # \"\"\"\n def buildRequestMysign(self, para_sort) :\n\n #对待签名参数数组排序\n keys = alipay_core_function.argSort(para_sort)\n #把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串\n prestr = alipay_core_function.createLinkstring(para_sort, keys)\n if self.alipay_config['sign_type'].upper() == 'MD5':\n mysign = alipay_md5_function.md5Sign(prestr, self.alipay_config['key'])\n else :\n mysign = \"\"\n return mysign\n\n # \"\"\"\n # * 生成要请求给支付宝的参数数组\n # * @param $para_temp 请求前的参数数组\n # * @return 要请求的参数数组\n # \"\"\"\n def buildRequestPara(self, para_temp) :\n #除去待签名参数数组中的空值和签名参数\n para_sort = alipay_core_function.paraFilter(para_temp)\n\n #生成签名结果\n mysign = self.buildRequestMysign(para_sort)\n \n # print \"para_filter:%s,para_sort:%s,mysign:%s\" %(para_filter,para_sort,mysign)\n\n #签名结果与签名方式加入请求提交参数组中\n para_sort['sign'] = mysign;\n para_sort['sign_type'] = self.alipay_config['sign_type'].upper()\n \n return para_sort\n\n # \n # 建立请求,以表单HTML形式构造(默认)\n # @param $para_temp 请求参数数组\n # @param $method 提交方式。两个值可选:post、get\n # @param $button_name 确认按钮显示文字\n # @return 提交表单HTML文本\n # \n def buildRequestForm(self, para_temp, method, button_name) :\n\n # print \"===%s=%s=%s=%s====\" %(self.alipay_config,para_temp, method, button_name )\n\n #待请求参数数组\n para = self.buildRequestPara(para_temp)\n sHtml = \"\"\"
\"\"\" \\\n %( self.alipay_gateway_new, self.alipay_config['input_charset'].lower() , method)\n for k in para :\n sHtml += \"\" %(str(k), str(para[k]))\n\n #submit按钮控件请不要含有name属性\n sHtml = \"%s
\" %(sHtml , button_name)\n sHtml = \"%s\" %(sHtml)\n \n return sHtml\n\n # \n # * 建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果\n # * @param $para_temp 请求参数数组\n # * @return 支付宝处理结果\n # \n def buildRequestHttp(self, para_temp) :\n sResult = ''\n #待请求参数数组字符串\n request_data = self.buildRequestPara(para_temp)\n #远程获取数据\n sResult = alipay_core_function.getHttpResponsePOST(self.alipay_gateway_new, self.alipay_config['cacert'], request_data, self.alipay_config['input_charset'].lower() )\n return sResult\n #\n # * 建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果,带文件上传功能\n # * @param $para_temp 请求参数数组\n # * @param $file_para_name 文件类型的参数名\n # * @param $file_name 文件完整绝对路径\n # * @return 支付宝返回处理结果\n #\n def buildRequestHttpInFile(self, para_temp, file_para_name, file_name) :\n \n #待请求参数数组\n para = self.buildRequestPara(para_temp);\n para[file_para_name] = \"@%s\" % file_name\n \n #远程获取数据\n sResult = alipay_core_function.getHttpResponsePOST(self.alipay_gateway_new, self.alipay_config['cacert'], para, self.alipay_config['input_charset'].lower());\n\n return sResult\n\n # \n # 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数\n # 注意:该功能PHP5环境及以上支持,因此必须服务器、本地电脑中装有支持DOMDocument、SSL的PHP配置环境。建议本地调试时使用PHP开发软件\n # return 时间戳字符串\n # \n def query_timestamp(self) :\n url = \"%sservice=query_timestamp&partner=%s&_input_charset=%s\" %(self.alipay_gateway_new, self.alipay_config['partner'].lower(), self.alipay_config['input_charset'].lower() )\n encrypt_key = \"\"\n\n # $doc = new DOMDocument();\n # $doc->load($url);\n # $itemEncrypt_key = $doc->getElementsByTagName( \"encrypt_key\" );\n # $encrypt_key = $itemEncrypt_key->item(0)->nodeValue;\n return encrypt_key\n","sub_path":"vip_ticketing_server/alipay/lib/alipay_submit_class.py","file_name":"alipay_submit_class.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"271424618","text":"\r\nimport os, random, sys, math\r\nimport pygame\r\nfrom pygame.locals import *\r\nfrom configuracion import *\r\nfrom extras import *\r\nfrom funciones import *\r\n\r\n\r\n#Funcion principal\r\ndef main():\r\n\r\n #Centrar la ventana y despues inicializar pygame\r\n os.environ[\"SDL_VIDEO_CENTERED\"] = \"1\"\r\n pygame.init()\r\n #Preparar la ventana\r\n pygame.display.set_caption(\"Subtimpsons...\")\r\n screen = pygame.display.set_mode((ANCHO, ALTO))\r\n\r\n pygame.mixer.music.load(\"The Simpsons Theme [8 Bit Tribute to The Simpsons] - 8 Bit Universe.mp3\")#Cargamos musica del juego.\r\n\r\n while True:#Este ciclo mantiene corriendo el juego constantemente y solo podemos salir de el cerrando la ventana.\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit(0)\r\n return()\r\n pantallaInicio(screen)#Pantalla inicio, en ellas estan las reglas.\r\n pantallaJugando(screen)#De esta pantalla se despliega el juego, incluso dentro suyo se encuentra el llamado a la pantalla de records.\r\n\r\n\r\n\r\n\r\n#Programa Principal ejecuta Main\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"298424410","text":"\n###############################################################################\n# Copyright 2012 The University of Texas at Austin #\n# #\n# Licensed under the Apache License, Version 2.0 (the \"License\"); #\n# you may not use this file except in compliance with the License. #\n# You may obtain a copy of the License at #\n# #\n# http://www.apache.org/licenses/LICENSE-2.0 #\n# #\n# Unless required by applicable law or agreed to in writing, software #\n# distributed under the License is distributed on an \"AS IS\" BASIS, #\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #\n# See the License for the specific language governing permissions and #\n# limitations under the License. #\n###############################################################################\n\nimport subprocess\nimport os\nimport sys\nimport time\n\nfrom ipf.data import Data, Representation\nfrom ipf.error import StepError\nfrom ipf.sysinfo import ResourceName\nfrom ipf.step import Step\n\n#######################################################################################################################\n\nclass KitsStep(Step):\n def __init__(self):\n Step.__init__(self)\n\n self.description = \"produces data describing what TeraGrid kits are available on the resource\"\n self.time_out = 10\n self.requires = [ResourceName]\n self.produces = [Kits]\n self._acceptParameter(\"core_kit_directory\",\"the path to the TeraGrid core kit installation\",True)\n\n def run(self):\n resource_name = self._getInput(ResourceName).resource_name\n \n try:\n corekit_dir = self.params[\"core_kit_directory\"]\n except KeyError:\n raise StepError(\"core_kit_directory not specified\")\n\n cmd = os.path.join(corekit_dir,\"bin\",\"kits-reg.pl\")\n status, output = subprocess.getstatusoutput(cmd)\n if status != 0:\n raise StepError(\"'%s' failed: %s\" % (cmd,output))\n\n self._output(Kits(resource_name,output))\n\n#######################################################################################################################\n\nclass Kits(Data):\n def __init__(self, resource_name, kits):\n Data.__init__(self,resource_name)\n self.kits = kits\n\n#######################################################################################################################\n\nclass KitsXml(Representation):\n data_cls = Kits\n\n def __init__(self, data):\n Representation.__init__(self,Representation.MIME_TEXT_XML,data)\n\n def get(self):\n return self.data.kits\n\n#######################################################################################################################\n","sub_path":"ipf/teragrid/kits.py","file_name":"kits.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"485461951","text":"import argparse\n\nfrom python_exercise.tools.aws.cf_manager import CFManager\nfrom python_exercise.tools.palindrome import validate_palindrome, is_palindrome\nfrom python_exercise.tools.scaffold import django\n\nparser = argparse.ArgumentParser(\n description='''\n Thank you for asking for help. \n These tools are used to generate a Django project and convert CloudFormation code from YAML to JSON.\n ''',\n prog='python_exercise',\n)\n\nparser.add_argument(\n '-cp', '--check-palindrome',\n help='Use this flag to check if the name of the project is palindrome (default: %(default)s)',\n dest='check_palindrome',\n default=True,\n action='store_true'\n)\n\nparser.add_argument(\n '-cf', '--convert-cf',\n help='Use this flag to transform a CF yaml file to json. We\\'ll use the name of the project',\n dest='cf_file',\n)\n\nparser.add_argument(\n '-sdp', '--scaffold-django-project',\n help='Use this flag to indicate you want to scaffold a django project in the provided path',\n dest='django_project_path',\n)\n\nparser.add_argument('project_name', help='The project name')\n\noptions = parser.parse_args()\n\nif options.check_palindrome:\n validate_palindrome(options.project_name)\n\nif options.cf_file:\n manager = CFManager(options.cf_file)\n manager.dump_json(target=options.project_name)\n\nif options.django_project_path:\n if is_palindrome(options.project_name):\n django.create_project(options.project_name, path=options.django_project_path)\n else:\n print('You must provide a palindrome project name')\n","sub_path":"part1/src/python_exercise/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"621320607","text":"import os # Operating system library\nfrom glob import glob # Handles file path names\nfrom setuptools import setup # Facilitates the building of packages\n\npackage_name = 'maa_robot_spawner_pkg'\n# Path of the current directory\ncur_directory_path = os.path.abspath(os.path.dirname(__file__))\n\nsetup(\n name=package_name,\n version='0.1.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n \n # Path to the launch file \n (os.path.join('share', package_name,'launch'), glob('launch/*.launch.py')),\n\n # Path to the world file\n (os.path.join('share', package_name,'worlds/'), glob('./worlds/*')),\n\n # Path to the warehouse sdf file\n (os.path.join('share', package_name,'models/maa_cenario2/'), glob('./models/maa_cenario2/*')),\n\n # Path to the mobile robot sdf file\n (os.path.join('share', package_name,'models/maa_robot/'), glob('./models/maa_robot/*')),\n \n # Path to the world file (i.e. warehouse + global environment)\n (os.path.join('share', package_name,'models/'), glob('./worlds/*')),\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='Mauricio A Almeida',\n maintainer_email='d2021101420@unifei.edu.br',\n description='Trabalho de CCO0116 - Mauricio A.ALmeida 2021101420',\n license='TODO: License declaration',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n 'spawn_demo = maa_robot_spawner_pkg.spawn_demo:main'\n ],\n },\n)\n","sub_path":"maa_robot_spawner_pkg/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"592037073","text":"\ndef smart():\n a = int(input(\"숫자1을 입력하세요 : \"))\n b = int(input(\"숫자2를 입력하세요 : \"))\n return a + b # 호출한 곳으로 되돌아갑니다. c = smart()로 가는거지\n\nc = smart()\nprint('결과는 %d입니다.' %c)\n\n\ndef mydef02(i,j):\n print(i+j)\nmydef02(10,20)\n# 계산할 숫자를 두 개 입력합니다.\ndef mydef03(i, j, p): # 3개의 인수를 받는 함수를 선언합니다.\n if p == '+':\n print(i+j)\n elif p == '-':\n print(i-j)\n elif p == '*':\n print(i*j)\n elif p == '/':\n print(i/j)\n n = int(input(\"첫번째 숫자를 입력하세요 : \"))\n m = int(input(\"두번째 숫자를 입력하세요 : \"))\n p = input(\"연산자를 입력하세요(+, -, *, /)\")\nmydef03(n,m,p)","sub_path":"[Study]PythonApplication/PythonApplication1(20210705)/PythonApplication1(20210705)/def02.py","file_name":"def02.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"96417690","text":"import math\nfrom mnist import MNIST\n\nmndata = MNIST(path='./MNIST', mode='rounded_binarized', return_type='numpy', gz=False)\nimages, labels = mndata.load_training()\n#images = images[:10]\n#labels = labels[:10]\n\nimages_testing, labels_testing = mndata.load_testing()\n\nprint('finished loading')\n\nsums = {}\ncount = {}\nfor i in range(10):\n sums[i] = 0\n count[i] = 0\n\nfor image, label in zip(images, labels):\n sum_of_pixels = image.sum()\n sums[label] += sum_of_pixels\n count[label] += 1\n\nmeans = {}\nfor label, sums_of_lable in sums.items():\n try:\n means[label] = sums_of_lable / count[label]\n except:\n pass\n\n\nnum_of_correct_answers = 0\nnum_of_wrong_answers = 0\nfor image, label in zip(images_testing, labels_testing):\n sum_of_pixels = image.sum()\n min_diff = math.inf\n ans = -1\n for means_label, means_mean in means.items():\n diff = abs(sum_of_pixels - means_mean)\n if diff < min_diff:\n min_diff = diff\n ans = means_label\n\n if ans == label:\n num_of_correct_answers += 1\n else:\n num_of_wrong_answers += 1\n\nprint('num_of_correct_answers', num_of_correct_answers)\nprint('num_of_wrong_answers', num_of_wrong_answers)\nprint('success rate:', num_of_correct_answers / (num_of_wrong_answers + num_of_wrong_answers))\n","sub_path":"classify_using_black_percentage.py","file_name":"classify_using_black_percentage.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"149803904","text":"# Import Tkinter\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import messagebox\n\n# Import Bult in Modules\nimport os\nimport sys\nimport zipfile\nimport pickle\nimport xml.etree.cElementTree as ET\nimport math\n\n# Other modules\nimport pyminizip\n\nLARGE_FONT= (\"Verdana\", 12)\nSMALL_FONT='Helvetica 10 bold'\n\npath_of_app = os.path.dirname(sys.argv[0]) # path_of_app = os.path.dirname(__file__)\nos.chdir(path_of_app)\n\nfilemenu = \"\"\noptionmenu = \"\"\ntest_list = [] #[[\"1.1\",\"1.2\"],[\"2.1\",\"2.2\"],[\"3.1\",\"3.2\"]]\nzip_files = []\noptions = []\nframes = []\npage_class_list = []\npassword = \"\"\n\ncolumns_number = 2\n\nclass App(tk.Tk):\n def quit_and_save(self):\n zip_files = globals()[\"zip_files\"]\n options = globals()[\"options\"]\n password = globals()[\"password\"]\n test_list = globals()[\"test_list\"]\n\n zip_files[-1][1] = test_list\n for i in zip_files:\n f = open(i[0], 'wb')\n pickle.dump(i[1], f)\n f.close()\n\n empty_array = []\n i = 0\n while i < len(zip_files):\n empty_array.append(\"\")\n i += 1\n\n if os.path.exists(\"myzip.zip\"):\n os.remove(\"myzip.zip\")\n\n print(options)\n print(zip_files)\n pyminizip.compress_multiple(options, empty_array,\"myzip.zip\", password, 2)\n\n for i in zip_files:\n os.remove(i[0])\n\n self.destroy()\n\n def __init__(self, *args, **kwargs):\n \n tk.Tk.__init__(self, *args, **kwargs) \n\n tk.Tk.iconbitmap(self, default=\"icon.ico\")\n tk.Tk.title(self, \"List Notes\")\n self.resizable(False, False)\n self.geometry(\"456x410\")\n \n \n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand = True)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n\n menubar = tk.Menu(container)\n\n filemenu = tk.Menu(menubar, tearoff=0)\n\n filemenu.add_command(label=\"New file\", command = lambda: self.show_frame(New_file), accelerator = \"Ctrl + N\")\n self.bind('', lambda e: self.show_frame(New_file))\n\n filemenu.add_command(label=\"Open file\", command = lambda: self.show_frame(Open_file), accelerator = \"Ctrl + O\")\n self.bind('', lambda e: self.show_frame(Open_file))\n\n filemenu.add_command(label=\"Export\", command = lambda: self.show_frame(Export))\n filemenu.add_command(label=\"Import\", command = lambda: self.show_frame(Import))\n\n filemenu.add_separator()\n filemenu.add_command(label=\"Quit and save\", command = lambda: self.quit_and_save())\n\n optionmenu = tk.Menu(container, tearoff=0)\n\n optionmenu.add_command(label=\"Viev\", command = lambda: self.show_frame(Viev))\n optionmenu.add_command(label=\"Add\", command = lambda: self.show_frame(Add))\n\n # Title of menu that contains submenus\n menubar.add_cascade(label=\"File\", menu=filemenu)\n menubar.add_cascade(label=\"Option\", menu=optionmenu)\n\n globals()[\"filemenu\"] = filemenu\n globals()[\"optionmenu\"] = optionmenu\n\n ### Configuer Enable Disable menu\n filemenu.entryconfig(0, state=DISABLED)\n filemenu.entryconfig(1, state=DISABLED)\n filemenu.entryconfig(2, state=DISABLED)\n filemenu.entryconfig(3, state=DISABLED)\n # 4 it's a seperator\n filemenu.entryconfig(5, state=DISABLED)\n\n optionmenu.entryconfig(0, state=DISABLED)\n optionmenu.entryconfig(1, state=DISABLED)\n\n tk.Tk.config(self, menu=menubar)\n\n self.frames = {} \n\n page_class_list = (StartPage, New_file, Open_file, Export, Viev, Add, Import)\n globals()[\"page_class_list\"] = page_class_list\n for F in page_class_list:\n\n frame = F(container, self)\n\n self.frames[F] = frame\n\n frame.grid(row=0, column=0, sticky=\"nsew\")\n\n globals()[\"frames\"] = self.frames\n self.show_frame(StartPage) ### Starting Frame\n\n def show_frame(self, cont):\n\n frame = self.frames[cont]\n frame.tkraise()\n \nclass StartPage(tk.Frame):\n def pass_to_zip(self):\n password = self.password_text.get()\n password = password.strip()\n globals()[\"password\"] = password\n password = password.encode()\n\n if os.path.exists(\"myzip.zip\"):\n myzip = zipfile.ZipFile('myzip.zip', 'r')\n myzip.setpassword(password)\n\n list_of_files = myzip.namelist()\n\n # check if pickle is not empty or broken\n zip_files = []\n options = []\n\n number = 0\n good_password = True\n for i in list_of_files:\n try:\n file = myzip.open(i)\n other_array = pickle.load(file)\n filename = os.path.basename(list_of_files[number])\n value = [filename, other_array]\n zip_files.append(value)\n options.append(filename)\n number += 1\n except RuntimeError: \n good_password = False\n\n if good_password:\n filemenu.entryconfig(0, state=NORMAL)\n filemenu.entryconfig(5, state=NORMAL)\n filemenu.entryconfig(3, state=NORMAL)\n\n if len(zip_files) > 0:\n globals()[\"zip_files\"] = zip_files \n globals()[\"options\"] = options\n\n filemenu.entryconfig(1, state=NORMAL)\n frames = globals()[\"frames\"]\n page_class_list = globals()[\"page_class_list\"]\n\n # page_class_list = (StartPage, New_file, Open_file, Export, Viev, Add)\n frames[page_class_list[2]].reset()\n\n # There is no zip file\n else:\n filemenu.entryconfig(0, state=NORMAL)\n filemenu.entryconfig(3, state=NORMAL)\n\n\n def __init__(self, parent, controller):\n\n tk.Frame.__init__(self,parent)\n\n label_title = tk.Label(self, text=\"Start Page\", font=LARGE_FONT)\n label_title.pack(pady=4,padx=4)\n\n frame_header = ttk.Frame(self)\n frame_header.pack(padx=5, pady=5)\n\n # frame 1.1\n label = ttk.Label(frame_header, text = \"Provide a password:\",style=\"White.TLabel\")\n label.pack(fill = X,padx=10,pady=5)\n\n self.password_text = Entry(frame_header, width=49,show=\"*\")\n self.password_text.pack(side=LEFT,padx=10)\n #text.insert(INSERT, \"https://www.youtube.com/watch?v=g_9nsFJS_pk&list=PLXmMXHVSvS-AyIwEYkGNa4WE1AR1_45mv\")\n\n B = ttk.Button(frame_header, text = \"Ok\", command = lambda: self.pass_to_zip())\n B.pack(side=LEFT,padx=5) \n\n\nclass New_file(tk.Frame):\n def create_new_pickle(self):\n columns = self.spinbox.get()\n columns = int(columns)\n\n file_name = self.text.get(\"1.0\",END).rstrip()\n file_name = file_name + \".pickle\"\n\n globals()[\"columns_number\"] = columns\n\n empty_list = []\n i = 0\n while i < columns:\n empty_list.append(\"\")\n i += 1\n\n globals()[\"test_list\"] = [empty_list]\n globals()[\"zip_files\"].append([file_name,empty_list])\n globals()[\"options\"].append(file_name)\n\n # Menu options\n frames = globals()[\"frames\"]\n page_class_list = globals()[\"page_class_list\"]\n\n # page_class_list = (StartPage, New_file, Open_file, Export, Viev, Add)\n frames[page_class_list[3]].reset()\n frames[page_class_list[4]].reset()\n frames[page_class_list[5]].reset()\n\n filemenu = globals()[\"filemenu\"]\n optionmenu = globals()[\"optionmenu\"]\n\n filemenu.entryconfig(2, state=NORMAL)\n filemenu.entryconfig(3, state=NORMAL)\n\n optionmenu.entryconfig(0, state=NORMAL)\n optionmenu.entryconfig(1, state=NORMAL)\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n label_title = tk.Label(self, text=\"New File\", font=LARGE_FONT)\n label_title.pack(pady=10,padx=10)\n\n frame_header = ttk.Frame(self)\n frame_header.pack()\n\n frame_1 = ttk.Frame(frame_header)\n frame_1.pack(fill = BOTH)\n\n label = ttk.Label(frame_1, text = \"Title:\",style=\"White.TLabel\")\n label.pack(side=LEFT,padx=5) \n\n self.text = Text(frame_1, width=49, height=1)\n self.text.pack(side=LEFT,padx=10)\n\n frame_2 = ttk.Frame(frame_header)\n frame_2.pack(fill = BOTH,pady=10)\n\n label = ttk.Label(frame_2, text = \"Number of colums:\",style=\"White.TLabel\")\n label.pack(side=LEFT,padx=5) \n\n self.spinbox = Spinbox(frame_2, from_=1, to=2,width= 10)\n self.spinbox.pack(side=LEFT,padx=10)\n #text.insert(INSERT, \"https://www.youtube.com/watch?v=g_9nsFJS_pk&list=PLXmMXHVSvS-AyIwEYkGNa4WE1AR1_45mv\")\n\n frame_3 = ttk.Frame(frame_header)\n frame_3.pack(fill = BOTH,pady=10)\n\n B = ttk.Button(frame_3, text = \"Ok\", command = lambda: self.create_new_pickle())\n B.pack(side=LEFT,padx=5) \n\nclass Open_file(tk.Frame):\n def open_file_name(self):\n file_name = self.variable.get()\n zip_files = self.zip_files\n\n for i in self.zip_files:\n if i[0] == file_name:\n columns_number = len(i[1][0])\n\n globals()[\"columns_number\"] = columns_number\n globals()[\"test_list\"] = i[1]\n\n frames = globals()[\"frames\"]\n page_class_list = globals()[\"page_class_list\"]\n\n # page_class_list = (StartPage, New_file, Open_file, Export, Import, Viev, Add)\n frames[page_class_list[3]].reset()\n frames[page_class_list[4]].reset()\n frames[page_class_list[5]].reset()\n\n filemenu = globals()[\"filemenu\"]\n optionmenu = globals()[\"optionmenu\"]\n\n filemenu.entryconfig(2, state=NORMAL)\n filemenu.entryconfig(5, state=NORMAL)\n\n optionmenu.entryconfig(0, state=NORMAL)\n optionmenu.entryconfig(1, state=NORMAL)\n break\n\n def reset(self):\n label_title = tk.Label(self, text=\"Open File\", font=LARGE_FONT)\n label_title.pack(pady=10,padx=10)\n\n frame_header = ttk.Frame(self)\n frame_header.pack()\n\n frame_1 = ttk.Frame(frame_header)\n frame_1.pack(fill = BOTH)\n\n label = ttk.Label(frame_1, text = \"Choose file:\")\n label.pack(side=LEFT,padx=5) \n\n self.variable = StringVar(frame_header)\n\n self.zip_files = globals()[\"zip_files\"] \n\n self.options = globals()[\"options\"] \n\n w = OptionMenu(frame_1, self.variable, *self.options)\n w.pack()\n\n frame_2 = ttk.Frame(frame_header)\n frame_2.pack(fill = BOTH)\n\n B = ttk.Button(frame_2, text = \"Ok\", command = lambda: self.open_file_name())\n B.pack(pady=10,padx=5) \n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n\nclass Export(tk.Frame):\n def open_savepath(self):\n os.popen(\"explorer \" + self.label_path[\"text\"])\n\n def select_savefolder(self):\n filename = filedialog.askdirectory()\n filename = os.path.abspath(filename)\n self.label_path[\"text\"] = filename\n\n def export_as_file(self):\n export_format = self.pickle_xml_var.get()\n path = self.label_path[\"text\"]\n array = globals()[\"test_list\"]\n\n if export_format == \"Pickle\":\n save_path = os.path.join(path, \"mylist.pickle\")\n f = open(save_path, 'wb')\n pickle.dump(array, f)\n f.close()\n else:\n save_path = os.path.join(path, \"mylist.xml\")\n root = ET.Element(\"data\")\n items = ET.SubElement(root, \"items\")\n\n for i in array:\n ET.SubElement(items, \"item\", name=i[0]).text = i[1]\n\n tree = ET.ElementTree(root)\n tree.write(save_path)\n\n def reset(self):\n # png\n folder_image = os.path.join(\"images\",\"folder.png\")\n\n # Photo images\n self.folder_photo = PhotoImage(file = folder_image).subsample(8,8)\n\n label_title = tk.Label(self, text=\"Export\", font=LARGE_FONT)\n label_title.pack(pady=10,padx=10)\n\n frame_header = ttk.Frame(self)\n frame_header.pack(fill = BOTH)\n\n frame_1 = ttk.Frame(frame_header)\n frame_1.pack(fill = BOTH,padx=10)\n\n label = ttk.Label(frame_1, text = \"Save in\",style=\"White.TLabel\")\n label.pack(side=LEFT)\n\n save_in = ttk.Button(frame_1, image = self.folder_photo, command = lambda: self.select_savefolder())\n save_in.pack(side=LEFT)\n\n self.save_path = os.path.join(os.environ[\"SYSTEMDRIVE\"],os.environ[\"HOMEPATH\"],\"Documents\")\n\n self.label_path = Label(frame_1, text=self.save_path, fg=\"blue\", cursor=\"hand2\")\n self.label_path.pack(side=LEFT)\n self.label_path.bind(\"\", lambda e: self.open_savepath())\n\n frame_2 = LabelFrame(frame_header, text=\"Format option:\")\n frame_2.pack(fill = BOTH, pady=3,padx=10)\n\n self.pickle_xml_var = StringVar()\n\n frame_2_1 = ttk.Frame(frame_2)\n frame_2_1.pack(fill = BOTH)\n\n R1 = Radiobutton(frame_2_1, text=\"Pickle\", variable=self.pickle_xml_var, value=\"Pickle\")\n R1.pack(side=LEFT)\n R1.select()\n\n frame_2_2 = ttk.Frame(frame_2)\n frame_2_2.pack(fill = BOTH)\n\n R2 = Radiobutton(frame_2_2, text=\"Xml (work only when 2 columns)\", variable=self.pickle_xml_var, value=\"Xml\")\n R2.pack(side=LEFT) \n\n columns_number = globals()[\"columns_number\"]\n if (columns_number % 2) != 0:\n R2.config(state=DISABLED)\n\n frame_3 = ttk.Frame(frame_header)\n frame_3.pack(fill = BOTH)\n\n B = ttk.Button(frame_3, text = \"Ok\", command = lambda: self.export_as_file())\n B.pack(pady=10,padx=10) \n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n\nclass Viev(tk.Frame):\n def forget_frame(self):\n self.frame_header.forget()\n self.reset()\n def find_in_grid(self):\n list_rows = []\n list_columns = []\n number = 0\n\n i = 0\n j = 0\n\n while i < self.number_of_rows:\n while j < self.number_of_columns:\n text = self.list_of_entry[number].get()\n number += 1\n list_columns.append(text)\n j += 1\n list_rows.append(list_columns)\n list_columns = []\n i +=1\n j = 0\n\n globals()[\"test_list\"] = list_rows\n\n def list_to_entry(self,init_number):\n counting = 0\n number = init_number # starting from 0 so it will be 20 if we put 19\n i = 0\n\n while number < len(self.test_list):\n if counting >= 20:\n break\n\n for j in self.test_list[number]:\n self.list_of_entry[i].delete(0, 'end')\n self.list_of_entry[i].config(state='normal')\n self.list_of_entry[i].insert(0,j)\n i += 1\n \n self.list_of_labels[counting].config(text=number + 1)\n number += 1\n counting += 1\n\n if self.playlist_item == self.number_of_page and self.items_left_last_page_1 != 0:\n counting = self.items_left_last_page_1\n init_number = init_number + 21 - self.items_left_last_page_2\n print(\"counting\",counting)\n print(\"init_number\",init_number)\n while counting < 20:\n self.list_of_labels[counting].config(text=init_number)\n counting += 1\n init_number += 1\n\n start = 20 - self.items_left_last_page_2\n start = start * self.number_of_columns\n\n while start < 40:\n try:\n self.list_of_entry[start].delete(0, 'end')\n self.list_of_entry[start].config(state='disabled')\n except:\n pass\n start += 1\n\n def spinbox_change(self):\n w = self.spinbox_page\n self.playlist_item = int(w.get())\n item = self.playlist_item - 1\n self.list_to_entry(item * 20)\n\n def reset(self):\n self.playlist_item = 1\n self.test_list = globals()[\"test_list\"]\n\n self.number_of_columns = len(self.test_list[0])\n self.number_of_rows = len(self.test_list)\n\n self.frame_header = ttk.Frame(self)\n self.frame_header.pack()\n\n frame_1 = ttk.Frame(self.frame_header)\n frame_1.pack(fill = BOTH)\n\n height = 20\n width = self.number_of_columns\n\n number = 0\n list_number = 0\n\n self.list_of_entry = []\n self.list_of_labels = []\n\n for i in range(height): #Rows\n number += 1\n\n self.list_of_labels.append(ttk.Label(frame_1, text = number,style=\"White.TLabel\"))\n self.list_of_labels[-1].grid(row=i, column=0)\n\n for j in range(width): #Columns\n list_number += 1\n self.list_of_entry.append(Entry(frame_1, text=\"\"))\n self.list_of_entry[-1].grid(row=i, column=j+1)\n\n frame_2 = ttk.Frame(self.frame_header)\n frame_2.pack(fill = BOTH)\n\n B = ttk.Button(frame_2, text = \"Update\", command = lambda: self.find_in_grid())\n B.pack(side=LEFT,padx=5) \n\n number_of_items = len(self.test_list)\n\n self.number_of_page = number_of_items / 20\n self.number_of_page = math.ceil(self.number_of_page)\n\n self.items_left_last_page_1 = number_of_items % 20\n self.items_left_last_page_2 = 20 - self.items_left_last_page_1\n\n label_max_number_page = ttk.Label(frame_2, text = \"/{}\".format(self.number_of_page),font='times 15')\n label_max_number_page.pack(side=RIGHT)\n\n self.spinbox_page = Spinbox(frame_2, from_=1, to=self.number_of_page,width= 10, command = lambda: self.spinbox_change())\n self.spinbox_page.pack(side=RIGHT)\n\n self.list_to_entry(0)\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n\nclass Add(tk.Frame):\n\n def add_new_value(self):\n columns = []\n\n for i in self.list_of_entry:\n text = i.get()\n columns.append(text)\n\n i.delete(0, END)\n\n globals()[\"test_list\"].append(columns)\n\n frames = globals()[\"frames\"]\n # page_class_list = (StartPage, New_file, Open_file, Export, Viev, Add)\n page_class_list = globals()[\"page_class_list\"]\n frames[page_class_list[4]].forget_frame()\n\n self.number_of_rows += 1\n self.label_number.config(text=self.number_of_rows) \n\n def reset(self):\n label_title = tk.Label(self, text=\"Add\", font=LARGE_FONT)\n label_title.pack(pady=10,padx=10)\n\n frame_header = ttk.Frame(self)\n frame_header.pack()\n\n frame_1 = ttk.Frame(frame_header)\n frame_1.pack(fill = BOTH)\n\n test_list = globals()[\"test_list\"]\n columns_number = globals()[\"columns_number\"]\n\n self.number_of_rows = len(test_list)\n self.number_of_rows += 1\n\n new_value = \"{}: \".format(self.number_of_rows)\n\n self.list_of_entry = []\n\n i = 0\n\n self.label_number = ttk.Label(frame_1, text = new_value)\n self.label_number.pack(side=LEFT)\n\n while i < columns_number:\n self.list_of_entry.append(Entry(frame_1, text=\"\"))\n self.list_of_entry[-1].pack(side=LEFT)\n i += 1\n\n frame_2 = ttk.Frame(frame_header)\n frame_2.pack(fill = BOTH)\n\n B = ttk.Button(frame_2, text = \"Ok\", command = lambda: self.add_new_value())\n B.pack(pady=10) \n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n\nclass Import(tk.Frame):\n def add_import_files(self):\n file_path = self.label_path[\"text\"]\n if len(file_path) > 0:\n zip_files = globals()[\"zip_files\"]\n options = globals()[\"options\"]\n\n f = open(file_path,'rb')\n other_array = pickle.load(f)\n f.close()\n\n filename = os.path.basename(file_path)\n value = [filename, other_array]\n zip_files.append(value)\n options.append(filename)\n\n globals()[\"zip_files\"] = zip_files \n globals()[\"options\"] = options\n\n frames = globals()[\"frames\"]\n page_class_list = globals()[\"page_class_list\"]\n\n # page_class_list = (StartPage, New_file, Open_file, Export, Import, Viev, Add)\n frames[page_class_list[2]].reset()\n\n filemenu = globals()[\"filemenu\"]\n\n filemenu.entryconfig(1, state=NORMAL)\n\n def select_savefolder(self):\n filename = filedialog.askopenfilename(title = \"Select file\",filetypes = ((\"pickle files\",\"*.pickle\"),(\"all files\",\"*.*\")))\n filename = os.path.abspath(filename)\n self.label_path[\"text\"] = filename\n\n def reset(self):\n label_title = tk.Label(self, text=\"Import\", font=LARGE_FONT)\n label_title.pack(pady=4,padx=4)\n\n # png\n folder_image = os.path.join(\"images\",\"folder.png\")\n\n # Photo images\n self.folder_photo = PhotoImage(file = folder_image).subsample(8,8)\n\n frame_header = ttk.Frame(self)\n frame_header.pack(fill = BOTH,padx=5)\n\n frame_1 = ttk.Frame(frame_header)\n frame_1.pack(fill = BOTH)\n\n # frame 1.2\n label = ttk.Label(frame_1, text = \"Import file\",style=\"White.TLabel\")\n label.pack(side=LEFT)\n\n save_in = ttk.Button(frame_1, image = self.folder_photo, command = lambda: self.select_savefolder())\n save_in.pack(side=LEFT)\n\n self.label_path = Label(frame_1, text=r\"\", fg=\"blue\")\n self.label_path.pack(side=LEFT)\n\n frame_2 = ttk.Frame(frame_header)\n frame_2.pack(fill = BOTH)\n\n B = ttk.Button(frame_2, text = \"Ok\", command = lambda: self.add_import_files())\n B.pack() \n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.reset()\n\napp = App() \n\napp.mainloop()","sub_path":"main_script.py","file_name":"main_script.py","file_ext":"py","file_size_in_byte":22305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"555285598","text":"import sys \nfrom etats import *\nfrom transition import *\nfrom automate import *\n\n\n\n\ndef verifAfdMot(mot, etat):\n\t# while(1):\n\t# \tfor i in mot:\n\tk = 0\n\tj=0\n\twhile j < len(etat.listTransition):\n\t\t# on trouve la lettre = chgt : Etat + lettreMot\n\t\t# lorsque k = len(mot) ou j = len(Transition)-> etat acceptant ?\n\t\tif ( etat.listTransition[j].verifTransition(mot[k])): #mot[k]\n\t\t\tetat = etat.listTransition[j].etatB\n\t\t\tj = 0\n\t\t\tk = k+1\n\t\t\tif (k == len(mot)):\n\t\t\t\tif (etat.acceptant == True):\n\t\t\t\t\treturn 1\n\t\t\t\telse:\n\t\t\t\t\treturn 0\n\t\telse:\n\t\t\tj+=1\n\n\treturn 0\n\ndef verifAfnMot(mot, etat):\n\t# while(1):\n\t# \tfor i in mot:\n\tk = 0\n\tj=0\n\ts = -1\n\ti = len(etat.listTransition)\n\tancienEtat = etat\n\tancienMot = mot\n\tfor i in range(len(etat.listTransition)):\n\t\tmot = ancienMot\n\t\ts+= 1\n\t\twhile j < len(etat.listTransition):\n\t\t\t# on trouve la lettre = chgt : Etat + lettreMot\n\t\t\t# lorsque k = len(mot) ou j = len(Transition)-> etat acceptant ?\n\t\t\tif ( etat.listTransition[j].verifTransition(mot[k])): #mot[k]\n\t\t\t\tetat = etat.listTransition[j].etatB\n\t\t\t\tj = s\n\t\t\t\tk = k+1\n\t\t\t\tif (k == len(mot)):\n\t\t\t\t\tif (etat.acceptant == True):\n\t\t\t\t\t\treturn 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tj+=1\n\n\treturn 0\ndef initialisation(automate):\n\t\n\t# On separe l'entree en deux tableaux\n\tauto1 = automate[:4]\n\t\n\tauto2 = []\n\tfor a in automate[4:]:\n\t\tauto2 = auto2 + a.split()\n\t# init AlphaB\n\tauto = Automate()\n\tfor alphaB in auto1:\n\t\tauto.recupAlphabet(alphaB)\n\n\t#init Etats\n\tfor i in range(int(auto1[1])):\n\t\tauto.recupEtats(Etats(i))\n\t# nbInit = auto[2] et nbFin = auto[3]\n\tauto.setInitAcceptant(auto1[2], auto1[3])\n\n\t# init Transition\n\tfor i in range(0, len(auto2),3):\n\t\tnumEtat = int(auto2[i]) # recup le 1er num qui arrive\n\t\tauto.ajoutTransition(numEtat, int(auto2[i+1]), auto2[i+2])\n\t\t\n\treturn auto, int(auto1[2])\n\t\n\t\n\t\ndef main(automate, mot, sortie, mode):\n\n\tres = []\n\ttmp = 0\n\tauto, init = initialisation(automate)\n\tfor i in mot:\n\t\tif (mode == '0'):\n\t\t\ttmp = verifAfdMot(i, auto.listEtat[init])\n\t\t\n\t\tif (mode == 1):\n\t\t\tprint(\"Fonction non entierement implementee\")\n\t\t\t#tmp = verifAfnMot(i, auto.listEtat[auto[2]])\n\t\tres.append(str(tmp) + '\\n')\n\n\tsortie = open( sortie, \"w\")\n\tfor i in res:\n\t\tsortie.write(i)\n\tsortie.close()\n\treturn tmp\n\nif __name__ == \"__main__\":\n\tif (len(sys.argv) != 5 ):\n\t\tprint(\" Utilisation : \")\n\t\tprint( \"nom du script + 'mode (0 ou 1)' + fichier de l'automate + fichier de mots + fichier de sortie\")\n\t\tsys.exit()\n\telse:\n\t\ttry:\n\t\t\tfichier = open(sys.argv[2], 'r')\t\n\t\t\tfichierMot = open(sys.argv[3], 'r')\n\t\texcept Exception as exc:\n \t\t raise RuntimeError(\"erreur ouverture fichier\\n\") from exc\n\t\t\t\n\n\t\tmode = sys.argv[1]\n\t\tautomate = fichier.read().splitlines()\n\t\t\n\t\tmot = fichierMot.read().splitlines()\n\t\tsortie = sys.argv[4]\n\n\t\tfichier.close()\n\t\tfichierMot.close()\n\n\t\t\n\t\tmain(automate, mot, sortie, mode)","sub_path":"algo_tp/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"652827797","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport socket\nimport platform\nimport serial\nimport subprocess\nimport vlc\nimport binascii\nimport re\nimport threading\nfrom _thread import *\nimport RPi.GPIO as GPIO\nfrom time import sleep\nfrom PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QDialog, QStatusBar\nfrom PySide2.QtCore import Qt, Slot, Signal, QThread\nfrom PagingControl_UI import Ui_MainWindow\nfrom PopupDialog import Ui_DialogQuestion, Ui_DialogInfo, Ui_DialogEM, Ui_DialogKeypad_ip, Ui_DialogKeypad_Port\nfrom Sovico_DRG116 import sovico_DRG116\nfrom Blue_Relay import blueRg\nfrom Hiqnet_Check import hiqnet_checksum\n\n# Bagic veriable\nosPlatform = None\ntcpServerPort = 8888\nserialBaud = 115200\nem_Set_State = None\nclientServerIP = None\nclientServerPort = None\nLocalID = None\nbssLevelPresence = ['0']*48\nudpLogDest = ('192.168.1.105', 9999)\n\n\nclass Main_UI(QMainWindow, Ui_MainWindow):\n tcpServerReturnString = Signal(str)\n tcpServerReset = Signal()\n serialReturnString = Signal(str)\n setSerialBaudChange = Signal(str)\n player_play = Signal(int)\n player_pause = Signal()\n player_stop = Signal()\n bssHiqnetString = Signal(str)\n\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n\n global clientServerIP, clientServerPort, LocalID, logServerIp, udpLogDest\n\n self.tcpServerNetworkStatus = False\n self.ind_Streaming_State = False\n self.tcpServerAddress = [\n '0', '192.168.1.199', '255.255.255.0', '0.0.0.0', '8888', '127.0.0.1', '12302', '1']\n self.ip = ['0']*4\n self.nm = ['0']*4\n self.gw = ['0']*4\n self.clientIp = ['0']*4\n self.btn_State_FileName = [\n 'ButtonState_RG1.txt', 'ButtonState_RG2.txt', 'ButtonState_RG3.txt', 'ButtonState_RG4.txt']\n self.btn_Name_FileName = [\n 'ButtonName_RG1.txt', 'ButtonName_RG2.txt', 'ButtonName_RG3.txt', 'ButtonName_RG4.txt']\n self.btn_Name = [self.lineEdit_Setup_Buttons_Name_1_, self.lineEdit_Setup_Buttons_Name_2_,\n self.lineEdit_Setup_Buttons_Name_3_, self.lineEdit_Setup_Buttons_Name_4_]\n self.btn_Ui = [self.btn_RG1_, self.btn_RG2_,\n self.btn_RG3_, self.btn_RG4_]\n\n self.em_Popup = False\n self.serialMode = 0\n self.ipTouchInpusStatus = 0\n\n self.change_IP_Address(False)\n\n tcpServerPort = int(self.tcpServerAddress[4])\n clientServerIP = self.tcpServerAddress[5]\n clientServerPort = self.tcpServerAddress[6]\n LocalID = self.tcpServerAddress[7]\n\n # thread 변수 선언\n self.TcpSoketServer = TCPServer_Socket()\n self.serial_BssMeterRT = serial_BssMeterRT()\n self.audioStreamReceiver = audioStreamReceiver()\n self.udpSendBssMeter = udpSendBssMeter()\n self.em_Alarm = EM_Alarm()\n\n # thread 변수 연결\n self.TcpSoketServer.TCPServerReceiveString.connect(\n self.server_data_parcing)\n self.TcpSoketServer.TCPServerConnectClient.connect(\n self.serverConnectClient)\n self.TcpSoketServer.TCPServerComm.connect(self.Communicate_State_Start)\n self.tcpServerReturnString.connect(self.TcpSoketServer.stringReturn)\n self.player_play.connect(self.audioStreamReceiver.play)\n self.player_stop.connect(self.audioStreamReceiver.stop)\n self.audioStreamReceiver.player_State.connect(self.player_State_Return)\n self.audioStreamReceiver.play_on.connect(self.streaming_Play_On)\n self.em_Alarm.em_Set.connect(self.em_Alarm_Set)\n self.bssHiqnetString.connect(self.serial_BssMeterRT.bssReboot)\n self.udpSendBssMeter.udpMeterRT.connect(self.bssMeterReturn)\n\n # Popup Setup\n self.qdialog = QDialog()\n self.qdialog.Qui = Ui_DialogQuestion()\n self.qdialog.Qui.setupUi(self.qdialog)\n self.idialog = QDialog()\n self.idialog.Qui = Ui_DialogInfo()\n self.idialog.Qui.setupUi(self.idialog)\n self.emdialog = QDialog()\n self.emdialog.Qui = Ui_DialogEM()\n self.emdialog.Qui.setupUi(self.emdialog)\n self.touch4bayDialog = QDialog()\n self.touch4bayDialog.Qui = Ui_DialogKeypad_ip()\n self.touch4bayDialog.Qui.setupUi(self.touch4bayDialog)\n self.touch1bayDialog = QDialog()\n self.touch1bayDialog.Qui = Ui_DialogKeypad_Port()\n self.touch1bayDialog.Qui.setupUi(self.touch1bayDialog)\n self.touch4bay_text_ip = [self.touch4bayDialog.Qui.text_Ip1, self.touch4bayDialog.Qui.text_Ip2,\n self.touch4bayDialog.Qui.text_Ip3, self.touch4bayDialog.Qui.text_Ip4]\n\n self.setSerialfrom_() # Serial Port Setup\n self.buttonNameLoad_() # Button Name\n\n self.TcpSoketServer.start()\n print('TCP Server Loading Completed')\n self.serial_BssMeterRT.start()\n self.udpSendBssMeter.start()\n self.audioStreamReceiver.start()\n print('Audio Stream Receiver Ready')\n self.em_Alarm.start()\n\n # serial Port\n try:\n if self.serialMode == 0:\n self.serNum2 = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)\n elif self.serialMode == 1:\n self.serNum2 = serial.Serial('/dev/ttyUSB0', 19200, timeout=1)\n except:\n start_new_thread(self.udpLogReturn, (LocalID,\n 'Paging Control -- USB Serial 디바이스 없습니다.'))\n\n start_new_thread(self.udpLogReturn,\n (LocalID, 'Paging Control -- 시스템이 시작되었습니다.'))\n # UI Start\n self.show()\n # Button State Reload\n sleep(1)\n self.buttonStateFileLoad()\n\n # Log Sender\n def udpLogReturn(self, localId, RtString):\n try:\n self.udpLogRt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.udpLogRt.sendto('{},{}'.format(\n localId, RtString).encode('utf8'), udpLogDest)\n self.udpLogRt.close()\n start_new_thread(self.Communicate_State, (True,))\n except:\n self.statusBar().showMessage('네트워크가 활성화 되지 않았습니다.', 5000)\n\n # EM Alarm\n @Slot(bool, int)\n def em_Alarm_Set(self, state, pinNum):\n if state == 1:\n start_new_thread(self.udpLogReturn, (LocalID,\n 'Paging Control -- 비상이 발생하였습니다.PIN {}'.format(pinNum)))\n # dialog\n if self.em_Popup == False:\n try:\n start_new_thread(self.udpReturnThread,\n ('e,{},1,!'.format(LocalID), ))\n except:\n self.statusBar().showMessage('네트워크가 활성화 되지 않았습니다.', 5000)\n\n self.em_Popup = True\n # EM Popup\n self.emdialog.Qui.Title_message.setText(\" EM\")\n self.emdialog.Qui.Main_Message.setText(\"비상이 발생하였습니다.\")\n if self.emdialog.exec_():\n self.em_Popup = False\n start_new_thread(\n self.udpLogReturn, (LocalID, 'Paging Control -- 지점에서 비상 상황을 확인 하였습니다.'))\n elif state == 0:\n start_new_thread(self.udpLogReturn, (LocalID,\n 'Paging Control -- 비상이 해제되었습니다.PIN {}'.format(pinNum)))\n start_new_thread(self.udpReturnThread,\n ('e,{},0,!'.format(LocalID), ))\n elif state == 2:\n start_new_thread(self.udpLogReturn, (LocalID,\n 'Paging Control -- 비상 감지 시스템에 장애가 발생 하였습니다.'))\n elif state == 3:\n start_new_thread(self.udpLogReturn, (LocalID,\n 'Paging Control -- 비상 감지 시스템을 시작 하였습니다.'))\n # Touch Input\n\n @Slot()\n def touchInput_IP(self):\n\n if self.ipTouchInpusStatus == 0:\n self.ipTouchInpusStatus = 1\n self.touch4bayDialog.Qui.Title_message.setText(\" IP 설정\")\n for i, items in enumerate(self.touch4bay_text_ip):\n items.setText(self.lineEdit_IP[i].text())\n if self.touch4bayDialog.exec_():\n for i, items in enumerate(self.touch4bay_text_ip):\n self.lineEdit_IP[i].setText(items.text())\n self.ipTouchInpusStatus = 0\n else:\n for item in self.lineEdit_IP:\n item.deselect()\n self.ipTouchInpusStatus = 0\n\n @Slot()\n def touchInput_NM(self):\n if self.ipTouchInpusStatus == 0:\n self.ipTouchInpusStatus = 1\n self.touch4bayDialog.Qui.Title_message.setText(\" NETMASK 설정\")\n for i, items in enumerate(self.touch4bay_text_ip):\n items.setText(self.lineEdit_NM[i].text())\n if self.touch4bayDialog.exec_():\n for i, items in enumerate(self.touch4bay_text_ip):\n self.lineEdit_NM[i].setText(items.text())\n self.ipTouchInpusStatus = 0\n else:\n for item in self.lineEdit_NM:\n item.deselect()\n self.ipTouchInpusStatus = 0\n\n @Slot()\n def touchInput_GW(self):\n if self.ipTouchInpusStatus == 0:\n self.ipTouchInpusStatus = 1\n self.touch4bayDialog.Qui.Title_message.setText(\" GATEWAY 설정\")\n for i, items in enumerate(self.touch4bay_text_ip):\n items.setText(self.lineEdit_GW[i].text())\n if self.touch4bayDialog.exec_():\n for i, items in enumerate(self.touch4bay_text_ip):\n self.lineEdit_GW[i].setText(items.text())\n self.ipTouchInpusStatus = 0\n else:\n for item in self.lineEdit_GW:\n item.deselect()\n self.ipTouchInpusStatus = 0\n\n @Slot()\n def touchInput_CLIENT(self):\n if self.ipTouchInpusStatus == 0:\n self.ipTouchInpusStatus = 1\n self.touch4bayDialog.Qui.Title_message.setText(\" AMX 서버 주소 설정\")\n for i, items in enumerate(self.touch4bay_text_ip):\n items.setText(self.lineEdit_Client[i].text())\n if self.touch4bayDialog.exec_():\n for i, items in enumerate(self.touch4bay_text_ip):\n self.lineEdit_Client[i].setText(items.text())\n self.ipTouchInpusStatus = 0\n else:\n for item in self.lineEdit_Client:\n item.deselect()\n self.ipTouchInpusStatus = 0\n\n @Slot()\n def touchInput_ServerPort(self):\n if self.ipTouchInpusStatus == 0:\n self.ipTouchInpusStatus = 1\n self.touch1bayDialog.Qui.Title_message.setText(\" 통신 포트 설정\")\n self.touch1bayDialog.Qui.text_Port.setText(\n self.lineEdit_Server_Port.text())\n if self.touch1bayDialog.exec_():\n self.lineEdit_Server_Port.setText(\n self.touch1bayDialog.Qui.text_Port.text())\n self.ipTouchInpusStatus = 0\n else:\n self.lineEdit_Server_Port.deselect()\n self.ipTouchInpusStatus = 0\n\n @Slot()\n def touchInput_ClientPort(self):\n if self.ipTouchInpusStatus == 0:\n self.ipTouchInpusStatus = 1\n self.touch1bayDialog.Qui.Title_message.setText(\" AMX 포트 설정\")\n self.touch1bayDialog.Qui.text_Port.setText(\n self.lineEdit_Client_Port.text())\n if self.touch1bayDialog.exec_():\n self.lineEdit_Client_Port.setText(\n self.touch1bayDialog.Qui.text_Port.text())\n self.ipTouchInpusStatus = 0\n else:\n self.lineEdit_Client_Port.deselect()\n self.ipTouchInpusStatus = 0\n\n @Slot()\n def touchInput_LocalID(self):\n if self.ipTouchInpusStatus == 0:\n self.ipTouchInpusStatus = 1\n self.touch1bayDialog.Qui.Title_message.setText(\" LOCAL ID 설정\")\n self.touch1bayDialog.Qui.text_Port.setText(\n self.lineEdit_Client_ID.text())\n if self.touch1bayDialog.exec_():\n self.lineEdit_Client_ID.setText(\n self.touch1bayDialog.Qui.text_Port.text())\n self.ipTouchInpusStatus = 0\n else:\n self.lineEdit_Client_ID.deselect()\n self.ipTouchInpusStatus = 0\n\n # Bss Reboot\n @Slot()\n def bssReoot_function(self):\n # dialog\n self.qdialog.Qui.Title_message.setText(\" BSS BLU 재부팅\")\n self.qdialog.Qui.Main_Message.setText(\"BSS BLU DSP를 재부팅 하시겠습니까?\")\n # OK\n if self.qdialog.exec_():\n self.hiqnetNodeAddr = [0]*6\n self.rebootHqinetNodeAddr = self.lineEdit_Bss_Reboot_Code.text()\n self.hiqnetNodeAddr[0] = self.rebootHqinetNodeAddr[:2]\n self.hiqnetNodeAddr[1] = self.rebootHqinetNodeAddr[2:4]\n self.hiqnetNodeAddr[2] = self.rebootHqinetNodeAddr[4:6]\n self.hiqnetNodeAddr[3] = self.rebootHqinetNodeAddr[6:8]\n self.hiqnetNodeAddr[4] = self.rebootHqinetNodeAddr[8:10]\n self.hiqnetNodeAddr[5] = self.rebootHqinetNodeAddr[10:12]\n\n try:\n self.bssSetString = hiqnet_checksum(\n '88', self.hiqnetNodeAddr, 1, 1)\n self.bssHiqnetString.emit(self.bssSetString)\n self.statusBar().showMessage('BSS BLU DSP가 재부팅 됩니다. 최대 5분정도 소요됩니다.', 5000)\n self.udpLogReturn(\n LocalID, 'Paging Control -- BSS DSP가 Paging Control에 의해서 재부팅 되었습니다.')\n except:\n self.udpLogReturn(\n LocalID, 'Paging Control -- BSS장비와의 통신에 문제가 발생했습니다.')\n self.statusBar().showMessage('BSS장비와의 통신에 문제가 발생했습니다.', 5000)\n\n @Slot()\n def bssLocalMic_Btn(self):\n self.hiqnet_localid = str(LocalID).zfill(2)\n\n if self.setFunctionButton1.isChecked():\n # type,nodeAddr,nodeId,parameterValue\n self.hiqnetNodeAddr = [\n '20', self.hiqnet_localid, '03', '00', '07', '01']\n self.bssSetString = hiqnet_checksum(\n '88', self.hiqnetNodeAddr, 33, 0)\n else:\n self.hiqnetNodeAddr = [\n '20', self.hiqnet_localid, '03', '00', '07', '01']\n self.bssSetString = hiqnet_checksum(\n '88', self.hiqnetNodeAddr, 33, 1)\n\n try:\n self.bssHiqnetString.emit(self.bssSetString)\n if self.setFunctionButton1.isChecked():\n self.udpLogReturn(\n LocalID, 'Paging Control -- 지점 마이크 사용이 시작 되었습니다.')\n self.statusBar().showMessage('지점 마이크 사용이 시작 되었습니다.', 5000)\n else:\n self.udpLogReturn(\n LocalID, 'Paging Control -- 지점 마이크 사용이 종료 되었습니다.')\n self.statusBar().showMessage('지점 마이크 사용이 종료 되었습니다.', 5000)\n except:\n self.udpLogReturn(\n LocalID, 'Paging Control -- BSS장비와의 통신에 문제가 발생했습니다.')\n self.statusBar().showMessage('BSS장비와의 통신에 문제가 발생했습니다.', 5000)\n\n @Slot()\n def bssFuction_Btn(self):\n self.hiqnet_localid = str(LocalID).zfill(2)\n\n if self.setFunctionButton2.isChecked():\n # type,nodeAddr,nodeId,parameterValue\n self.hiqnetNodeAddr = [\n '20', self.hiqnet_localid, '03', '00', '07', '01']\n self.bssSetString = hiqnet_checksum(\n '88', self.hiqnetNodeAddr, 35, 0)\n else:\n self.hiqnetNodeAddr = [\n '20', self.hiqnet_localid, '03', '00', '07', '01']\n self.bssSetString = hiqnet_checksum(\n '88', self.hiqnetNodeAddr, 35, 1)\n\n try:\n self.bssHiqnetString.emit(self.bssSetString)\n if self.setFunctionButton1.isChecked():\n self.udpLogReturn(\n LocalID, 'Paging Control -- 지점 이벤트 기능이 활성화 되었습니다.')\n self.statusBar().showMessage('지점 이벤트 기능이 활성화 되었습니다.', 5000)\n else:\n self.udpLogReturn(\n LocalID, 'Paging Control -- 지점 이벤트 기능이 종료 되었습니다.')\n self.statusBar().showMessage('지점 이벤트 기능이 종료 되었습니다.', 5000)\n except:\n self.udpLogReturn(\n LocalID, 'Paging Control -- BSS장비와의 통신에 문제가 발생했습니다.')\n self.statusBar().showMessage('BSS장비와의 통신에 문제가 발생했습니다.', 5000)\n\n @Slot()\n def player_State_Return(self, rtData):\n self.statusBar().showMessage(rtData, 5000)\n start_new_thread(self.udpLogReturn, (LocalID, rtData))\n\n @Slot(bool)\n def streaming_Play_On(self, state):\n if state == True:\n self.Main_Menu_Indcators[0].setChecked(True)\n self.ind_Streaming_State = True\n else:\n self.Main_Menu_Indcators[0].setChecked(False)\n self.ind_Streaming_State = False\n\n # Button Name Save\n @Slot()\n def RG_All_Name_Save(self):\n # dialog\n self.qdialog.Qui.Title_message.setText(\" 버튼 이름 저장\")\n self.qdialog.Qui.Main_Message.setText(\"버튼의 이름을 저장 하시겠습니까?\")\n # OK\n if self.qdialog.exec_():\n self.buttonNameSave_()\n else:\n self.buttonNameLoad_()\n\n def buttonNameSave_(self):\n for group in range(4):\n with open(self.btn_Name_FileName[group], 'w') as file:\n for i in range(24):\n file.write(self.btn_Name[group][i].text() + '\\n')\n self.btn_Ui[group][i].setText(\n self.btn_Name[group][i].text())\n self.statusBar().showMessage('버튼 이름을 저장 하였습니다.', 5000)\n start_new_thread(self.udpLogReturn,\n (LocalID, 'Paging Control -- 릴레이 버튼 이름이 변경되었습니다.'))\n\n # Button Name Load\n # Popup Check\n @Slot()\n def RG_All_Name_Load(self):\n # dialog\n self.qdialog.Qui.Title_message.setText(\" 전체 버튼 이름 불러오기\")\n self.qdialog.Qui.Main_Message.setText(\"전체 버튼의 이름을 불러 오시겠습니까?\")\n # OK\n if self.qdialog.exec_():\n self.buttonNameLoad_()\n self.statusBar().showMessage('버튼 이름을 불러왔습니다.', 5000)\n\n # Loding Action\n def buttonNameLoad_(self):\n try:\n for group in range(4):\n with open(self.btn_Name_FileName[group], 'r') as file:\n self.line = file.read().splitlines()\n for i in range(24):\n self.btn_Name[group][i].setText(self.line[i])\n self.btn_Ui[group][i].setText(self.line[i])\n except:\n pass\n\n # 버튼 상태 저장하기\n def buttonStateSave(self):\n # dialog\n self.qdialog.Qui.Title_message.setText(\" 버튼 상태값 저장\")\n self.qdialog.Qui.Main_Message.setText(\"버튼 상태값을 저장 하시겠습니까?\")\n\n if self.qdialog.exec_():\n self.buttonStateFileSave()\n\n def buttonStateFileSave(self):\n for group in range(4):\n with open(self.btn_State_FileName[group], 'w') as file:\n for i in range(24):\n if self.btn_Ui[group][i].isChecked():\n file.write('1\\n')\n else:\n file.write('0\\n')\n start_new_thread(self.udpLogReturn,\n (LocalID, 'Paging Control -- 버튼 상태값이 저장되었습니다.'))\n self.statusBar().showMessage('버튼 상태값이 저장되었습니다.', 5000)\n\n # 버튼 상태 불러오기\n @Slot()\n def buttonStateLoad(self):\n # dialog\n self.qdialog.Qui.Title_message.setText(\" 버튼 상태값 블러오기\")\n self.qdialog.Qui.Main_Message.setText(\"버튼 상태값을 불러 오시겠습니까?\")\n\n if self.qdialog.exec_():\n self.buttonStateFileLoad()\n\n # Button Status Load From Files\n def buttonStateFileLoad(self):\n try:\n for group in range(4):\n with open(self.btn_State_FileName[group], 'r') as file:\n line = file.read().splitlines()\n for i in range(24):\n if line[i] == '1':\n self.btn_Ui[group][i].setChecked(True)\n start_new_thread(\n self.udpReturnThread, ('r,{},{},{},1,!'.format(LocalID, group+1, i+1),))\n else:\n self.btn_Ui[group][i].setChecked(False)\n start_new_thread(\n self.udpReturnThread, ('r,{},{},{},0,!'.format(LocalID, group+1, i+1),))\n if self.serialMode == 0:\n self.BleuRg_Action(0)\n elif self.serialMode == 1:\n self.DRG116_Action(0) # DRG116 상태 갱신\n start_new_thread(self.udpLogReturn, (LocalID,\n 'Paging Control -- 버튼 상태값 불러오기를 실행하였습니다.'))\n self.statusBar().showMessage('버튼 상태값 불러오기를 실행하였습니다.', 5000)\n\n except:\n pass\n\n # Return to Home\n @Slot()\n def setHome(self):\n self.Main_Menu_Buttons[0].setChecked(True)\n self.Main_View.setCurrentIndex(0)\n\n # Serial Mode Change\n def serialModeChange(self):\n self.serialMode = self.comboBox_Serial_Mode.currentIndex()\n if self.serialMode == 0:\n self.serNum2.close()\n sleep(.1)\n self.serNum2 = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)\n elif self.serialMode == 1:\n self.serNum2.close()\n sleep(.1)\n self.serNum2 = serial.Serial('/dev/ttyUSB0', 19200, timeout=1)\n\n # Serial mode save to file\n @Slot()\n def serialModeSaveToFile(self):\n # dialog\n self.qdialog.Qui.Title_message.setText(\" 시리얼 통신 설정 변경\")\n self.qdialog.Qui.Main_Message.setText(\"시리얼 통신 설정을 변경 하시겠습니까?\")\n # OK\n if self.qdialog.exec_():\n with open(\"Serial.txt\", 'w') as file:\n file.write(str(self.serialMode)+'\\n')\n file.write(self.lineEdit_Bss_Reboot_Code.text()+'\\n')\n start_new_thread(self.udpLogReturn, (LocalID,\n 'Paging Control -- Serial Mode 설정이 변경되었습니다.'))\n self.statusBar().showMessage(' Paging Serial Mode 설정이 변경되었습니다.', 5000)\n\n # Serial Mode Load from File\n def setSerialfrom_(self):\n try:\n with open('Serial.txt', 'r') as file:\n line = file.read().splitlines()\n self.serialMode = int(line[0])\n self.comboBox_Serial_Mode.setCurrentIndex(int(line[0]))\n self.lineEdit_Bss_Reboot_Code.setText(line[1])\n except:\n pass\n\n # IP Seve\n def serverIpAddressSave(self):\n # dialog\n self.qdialog.Qui.Title_message.setText(\" IP 주소를 저장\")\n self.qdialog.Qui.Main_Message.setText(\n \"시스템 IP 주소를 저장하시겠습니까?\\n재부팅 이후 적용 됩니다.\")\n\n if self.qdialog.exec_():\n try:\n self.change_IP_Address(True)\n start_new_thread(\n self.udpLogReturn, (LocalID, 'Paging Control -- IP가 변경되었습니다. {}'.format(' '.join(self.tcpServerAddress)),))\n self.statusBar().showMessage(' Paging IP 설정이 저장 되었습니다. 리부팅 이후 적용됩니다.', 5000)\n except:\n self.change_IP_Address(True)\n start_new_thread(self.udpLogReturn, (LocalID,\n 'Paging Control -- IP 설정 저장 중 문제가 발생하였습니다.'))\n self.statusBar().showMessage(' Paging IP 설정 저장 중 문제가 발생하였습니다.', 5000)\n\n # IP Change\n def change_IP_Address(self, ipChange):\n if ipChange == True:\n for i in range(4):\n if self.lineEdit_IP[i].text() == '':\n self.ip[i] = '0'\n else:\n self.ip[i] = self.lineEdit_IP[i].text()\n\n if self.lineEdit_NM[i].text() == '' and i != 3:\n self.nm[i] = '255'\n elif self.lineEdit_NM[i].text() == '' and i == 3:\n self.nm[i] = '0'\n else:\n self.nm[i] = self.lineEdit_NM[i].text()\n\n if self.lineEdit_GW[i].text() == '':\n self.gw[i] = '0'\n else:\n self.gw[i] = self.lineEdit_GW[i].text()\n\n self.clientIp[i] = self.lineEdit_Client[i].text()\n\n self.tcpServerAddress[1] = '.'.join(self.ip)\n if self.tcpServerAddress[1] == '0.0.0.0':\n self.tcpServerAddress[1] = '192.168.1.199'\n self.tcpServerAddress[2] = '.'.join(self.nm)\n self.tcpServerAddress[3] = '.'.join(self.gw)\n if self.lineEdit_Server_Port.text() == '':\n self.tcpServerAddress[4] = '8888'\n else:\n self.tcpServerAddress[4] = self.lineEdit_Server_Port.text()\n self.tcpServerAddress[5] = '.'.join(self.clientIp)\n self.tcpServerAddress[6] = self.lineEdit_Client_Port.text()\n self.tcpServerAddress[7] = self.lineEdit_Client_ID.text()\n\n with open('ipset.txt', 'w') as file:\n for i in range(8):\n file.write(self.tcpServerAddress[i]+'\\n')\n\n try:\n with open('/etc/dhcpcd.conf', 'w') as file:\n file.write('interface eth0\\nstatic ip_address={}/24\\nstatic routers={}'.format(\n self.tcpServerAddress[1], self.tcpServerAddress[3]))\n except:\n pass\n else:\n try:\n with open('ipset.txt', 'r') as file:\n self.line = file.read().splitlines()\n for i in range(8):\n self.tcpServerAddress[i] = self.line[i]\n self.ip = self.tcpServerAddress[1].split('.')\n self.nm = self.tcpServerAddress[2].split('.')\n self.gw = self.tcpServerAddress[3].split('.')\n self.clientIp = self.tcpServerAddress[5].split('.')\n\n for i in range(4):\n self.lineEdit_IP[i].setText(self.ip[i])\n self.lineEdit_NM[i].setText(self.nm[i])\n self.lineEdit_GW[i].setText(self.gw[i])\n self.lineEdit_Client[i].setText(self.clientIp[i])\n\n self.lineEdit_Server_Port.setText(self.tcpServerAddress[4])\n self.lineEdit_Client_Port.setText(self.tcpServerAddress[6])\n self.lineEdit_Client_ID.setText(self.tcpServerAddress[7])\n except:\n pass\n # Network Module\n # TCP Server Indicator Event\n\n @Slot(bool)\n def serverConnectClient(self, state):\n if state == True:\n self.Main_Menu_Indcators[2].setChecked(True)\n self.tcpServerNetworkStatus = True\n start_new_thread(self.udpLogReturn,\n (LocalID, '네트워크 클라이언트가 연결 되었습니다.'))\n self.statusBar().showMessage('네트워크 클라이언트가 연결되었습니다.', 5000)\n\n else:\n self.Main_Menu_Indcators[2].setChecked(False)\n self.tcpServerNetworkStatus = False\n start_new_thread(self.udpLogReturn(\n LocalID, '네트워크 클라이언트가 연결이 해제 되었습니다.'))\n self.statusBar().showMessage('네트워크 클라이언트가 연결이 해제 되었습니다.', 5000)\n # Network Indcator\n\n @Slot()\n def ind_Network_Check(self):\n if self.tcpServerNetworkStatus == True:\n self.Main_Menu_Indcators[2].setChecked(True)\n else:\n self.Main_Menu_Indcators[2].setChecked(False)\n\n def Communicate_State(self, state):\n self.Main_Menu_Indcators[1].setChecked(state)\n sleep(.5)\n self.Main_Menu_Indcators[1].setChecked(False)\n\n @Slot(bool)\n def Communicate_State_Start(self, state):\n start_new_thread(self.Communicate_State, (state,))\n\n # Server Data Parcing\n @Slot(str)\n def server_data_parcing(self, data):\n try:\n if data == 'recall':\n self.buttonStateFileLoad()\n elif data == 'save':\n self.buttonStateFileSave()\n else:\n self.set_RG_Btn = data.split(',')\n if self.set_RG_Btn[0] == 'r' and len(self.set_RG_Btn) == 4:\n self.relay_Btn_Act_('Remote', int(self.set_RG_Btn[1]), int(\n self.set_RG_Btn[2]), int(self.set_RG_Btn[3]))\n if self.set_RG_Btn[0] == 'play':\n self.player_play.emit(int(self.set_RG_Btn[1])-1)\n elif self.set_RG_Btn[0] == 'stop':\n self.player_stop.emit()\n except:\n self.tcpServerReturnString.emit(\n 'Error Message {0}'.format(len(self.rg_btn_Status)))\n start_new_thread(self.udpLogReturn, (LocalID, '네트워크 명령이 잘못되었습니다.'))\n self.statusBar().showMessage('네트워크 명령이 잘못되었습니다.', 5000)\n\n # Button Event\n # interup\n\n def keyPressEvent(self, event):\n if event.key() == Qt.Key_Escape:\n start_new_thread(self.udpLogReturn,\n (LocalID, 'Paging Control -- 어플리케이션이 종료 되었습니다.'))\n sys.exit()\n # System reboot\n\n @Slot()\n def systemReboot(self):\n # dialog\n self.qdialog.Qui.Title_message.setText(\" 시스템 재부팅\")\n self.qdialog.Qui.Main_Message.setText(\"시스템을 재부팅 하시겠습니까?\")\n # ok\n if self.qdialog.exec_():\n start_new_thread(self.udpLogReturn,\n (LocalID, 'Paging Control -- 시스템을 재부팅합니다.'))\n subprocess.run('sudo reboot', shell=True)\n\n @Slot()\n def main_Page_Change(self):\n self.mainPageNum = self.buttonGroup_MainMenu.checkedId()\n self.Main_View.setCurrentIndex(self.mainPageNum)\n\n @Slot(int)\n def setup_Page_Change(self, num):\n self.stackedWidget_Setup.setCurrentIndex(num)\n # Realy Group Button 1\n\n @Slot(int)\n def btn_Clicked_RG_1(self, btnNum):\n self.btn_Clicked(1, btnNum)\n # Realy Group Button 2\n\n @Slot(int)\n def btn_Clicked_RG_2(self, btnNum):\n self.btn_Clicked(2, btnNum)\n # Realy Group Button 3\n\n @Slot(int)\n def btn_Clicked_RG_3(self, btnNum):\n self.btn_Clicked(3, btnNum)\n # Realy Group Button 4\n\n @Slot(int)\n def btn_Clicked_RG_4(self, btnNum):\n self.btn_Clicked(4, btnNum)\n # Relay Group Button Action\n\n def btn_Clicked(self, id, btnNum):\n if btnNum == 24:\n self.relayChannel = 0\n self.relayValue = 1\n elif btnNum == 25:\n self.relayChannel = 0\n self.relayValue = 0\n else:\n self.relayChannel = btnNum + 1\n if self.btn_Ui[id-1][btnNum].isChecked():\n self.relayValue = 1\n else:\n self.relayValue = 0\n self.relay_Btn_Act_('Local', id, self.relayChannel, self.relayValue)\n # 버튼 및 릴레이 동작 함수\n\n def relay_Btn_Act_(self, _from, _relayGroup, _relayChannel, _relayValue):\n # 채널별 동작\n if _relayChannel != 0:\n self.btn_Ui[_relayGroup-1][_relayChannel-1].setChecked(_relayValue)\n # 전체 동작\n else:\n if _relayValue == 1:\n for i in range(24):\n self.btn_Ui[_relayGroup-1][i].setChecked(True)\n elif _relayValue == 0:\n for i in range(24):\n self.btn_Ui[_relayGroup-1][i].setChecked(False)\n\n # 릴레이 그룹에 전달\n if self.serialMode == 0:\n self.BleuRg_Action(_relayGroup)\n\n elif self.serialMode == 1:\n self.DRG116_Action(_relayGroup)\n\n # 서버 전달\n start_new_thread(self.udpLogReturn, (LocalID, 'Paging Control -- {} ID {} CH {} Value {}'.format(\n _from, _relayGroup, _relayChannel, _relayValue)))\n if _from == 'Local':\n start_new_thread(self.udpReturnThread, ('r,{},{},{},{},!'.format(\n LocalID, _relayGroup, _relayChannel, _relayValue), ))\n start_new_thread(self.Communicate_State, (True,))\n # BLUE RELAY 동작\n\n def BleuRg_Action(self, groupId):\n if groupId == 0:\n for group in range(4):\n for i in range(24):\n if i == 0:\n if self.btn_Ui[group][i].isChecked():\n self.relayActionData = '1'\n else:\n self.relayActionData = '0'\n else:\n if self.btn_Ui[group][i].isChecked():\n self.relayActionData = self.relayActionData + ',1'\n else:\n self.relayActionData = self.relayActionData + ',0'\n self.rtSerialData = blueRg(group+1, self.relayActionData)\n try:\n self.serNum2.write(\n binascii.unhexlify(self.rtSerialData.run()))\n sleep(.1)\n except:\n pass\n else:\n for i in range(24):\n if i == 0:\n if self.btn_Ui[groupId-1][i].isChecked():\n self.relayActionData = '1'\n else:\n self.relayActionData = '0'\n else:\n if self.btn_Ui[groupId-1][i].isChecked():\n self.relayActionData = self.relayActionData + ',1'\n else:\n self.relayActionData = self.relayActionData + ',0'\n self.rtSerialData = blueRg(groupId, self.relayActionData)\n try:\n self.serNum2.write(binascii.unhexlify(self.rtSerialData.run()))\n except:\n pass\n # DRG116 동작\n\n def DRG116_Action(self, groupId):\n if groupId == 0:\n for group in range(4):\n for i in range(16):\n if i == 0:\n if self.btn_Ui[group][i].isChecked():\n self.relayActionData = '1'\n else:\n self.relayActionData = '0'\n else:\n if self.btn_Ui[group][i].isChecked():\n self.relayActionData = self.relayActionData + ',1'\n else:\n self.relayActionData = self.relayActionData + ',0'\n self.rtSerialData = sovico_DRG116(\n group+1, self.relayActionData)\n try:\n self.serNum2.write(binascii.unhexlify(\n self.rtSerialData.drg116()))\n sleep(.1)\n except:\n pass\n else:\n for i in range(16):\n if i == 0:\n if self.btn_Ui[groupId-1][i].isChecked():\n self.relayActionData = '1'\n else:\n self.relayActionData = '0'\n else:\n if self.btn_Ui[groupId-1][i].isChecked():\n self.relayActionData = self.relayActionData + ',1'\n else:\n self.relayActionData = self.relayActionData + ',0'\n self.rtSerialData = sovico_DRG116(groupId, self.relayActionData)\n try:\n self.serNum2.write(binascii.unhexlify(\n self.rtSerialData.drg116()))\n except:\n pass\n # Bss Meter udp return\n\n @Slot()\n def bssMeterReturn(self):\n try:\n rtData = ','.join(bssLevelPresence)\n start_new_thread(self.udpReturnThread,\n ('m,{},{},!'.format(LocalID, rtData), ))\n start_new_thread(self.Communicate_State, (True,))\n except:\n start_new_thread(self.udpReturnThread, ('error', ))\n start_new_thread(self.Communicate_State, (True,))\n\n def udpReturnThread(self, rtData):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.sock.sendto(rtData.encode('utf-8'),\n (clientServerIP, int(clientServerPort)))\n self.sock.close()\n\n def audioPlayButton_Clicked(self, channel):\n if channel == 8:\n self.player_stop.emit()\n else:\n self.player_play.emit(channel)\n\n# TCP서버 클래스\n\n\nclass TCPServer_Socket(QThread):\n TCPServerReceiveString = Signal(str)\n TCPServerConnectClient = Signal(bool)\n TCPServerComm = Signal(bool)\n\n def __init__(self, parent=None):\n super(TCPServer_Socket, self).__init__(parent)\n global tcpServerPort\n self.clients = []\n self.print_Lock = threading.Lock()\n\n # Tcp Server Start\n def run(self):\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_socket.bind((\"\", tcpServerPort))\n print('Waiting Clients')\n server_socket.listen(50)\n\n while True:\n client, client_Addr = server_socket.accept()\n print('Client Connect to :', client_Addr[0], client_Addr[1])\n if client:\n self.clients.append(client)\n self.TCPServerConnectClient.emit(True)\n self.stringReturn('{} : Connected'.format(client_Addr))\n start_new_thread(self.tcp_Client_Thread, (client, client_Addr))\n server_socket.close()\n\n def tcp_Client_Thread(self, c, addr):\n while True:\n data = c.recv(1024)\n if not data:\n print(addr, 'Disconnect')\n self.clients.remove(c)\n if self.clients:\n self.stringReturn('{} Disconnect'.format(addr))\n else:\n self.TCPServerConnectClient.emit(False)\n break\n self.print_Lock.acquire()\n self.TCPServerReceiveString.emit(data.decode('utf-8'))\n self.TCPServerComm.emit(True)\n self.print_Lock.release()\n c.close()\n\n # TCP Server Return\n @Slot(str)\n def stringReturn(self, message):\n if self.clients:\n for client in self.clients:\n client.send(message.encode('utf-8'))\n self.TCPServerComm.emit(True)\n\n# BSS Serial Data 갱신\n\n\nclass serial_BssMeterRT(QThread):\n def __init__(self, parent=None):\n super(serial_BssMeterRT, self).__init__(parent)\n global bssLevelPresence\n\n self.ser = serial.Serial('/dev/ttyAMA0', 115200, timeout=1)\n print('serial port 1 start')\n\n def run(self):\n while True:\n if self.ser.isOpen():\n try:\n self.serResponse = self.ser.readline().decode()\n if self.serResponse == '':\n pass\n else:\n print(self.serResponse)\n self.re_P = re.compile(r'(\\d+),(\\d)')\n self.bluMeterPresence = self.re_P.search(\n self.serResponse)\n self.levelAddr = int(self.bluMeterPresence.group(1))\n self.levelValue = self.bluMeterPresence.group(2)\n print(self.bluMeterPresence.group(1),\n self.bluMeterPresence.group(2))\n bssLevelPresence[self.levelAddr-1] = self.levelValue\n except:\n pass\n else:\n sleep(1)\n self.ser.close()\n try:\n self.ser = serial.Serial('/dev/ttyAMA0', 115200, timeout=1)\n except:\n pass\n\n @Slot(str)\n def bssReboot(self, data):\n if self.ser.isOpen():\n self.ser.write(binascii.unhexlify(data))\n\n else:\n self.ser.close()\n wait(.1)\n self.ser.open()\n self.ser.write(binascii.unhexlify(data))\n\n# BSS Meter Data Return\n\n\nclass udpSendBssMeter(QThread):\n udpMeterRT = Signal()\n\n def __init__(self, parent=None):\n super(udpSendBssMeter, self).__init__(parent)\n\n def run(self):\n while True:\n sleep(5)\n self.udpMeterRT.emit()\n\n# Audio Streamer Class\n\n\nclass audioStreamReceiver(QThread):\n player_State = Signal(str)\n play_on = Signal(bool)\n\n def __init__(self, parent=None):\n super(audioStreamReceiver, self).__init__(parent)\n self.audio_file = ['1.wav', '2.wav', '3.wav',\n '4.wav', '5.wav', '6.wav', '7.wav', '8.wav']\n self.instance = vlc.Instance()\n self.player = self.instance.media_player_new()\n self.player.audio_set_volume(100)\n self.Event_Manager = self.player.event_manager()\n self.Event_Manager.event_attach(\n vlc.EventType.MediaPlayerEndReached, self.songFinished)\n\n @Slot(int)\n def play(self, index):\n playmedia = \"/home/page/paging/audio/\" + \\\n self.audio_file[index] # Set audio file folder\n print(playmedia)\n if os.path.isfile(playmedia):\n self.media = self.instance.media_new(playmedia)\n self.player.set_media(self.media)\n self.player.play()\n self.player_State.emit('Local Event Play - {}'.format(playmedia))\n self.play_on.emit(True)\n else:\n self.player_State.emit('Local Event Play End')\n self.play_on.emit(False)\n\n @Slot()\n def stop(self):\n self.player.stop()\n self.player_State.emit('Local Event Stop')\n self.play_on.emit(False)\n\n self.instance = vlc.Instance()\n self.player = self.instance.media_player_new()\n self.player.audio_set_volume(100)\n self.Event_Manager = self.player.event_manager()\n self.Event_Manager.event_attach(\n vlc.EventType.MediaPlayerEndReached, self.songFinished)\n\n def songFinished(self, data):\n self.player_State.emit('Local Event Play End')\n self.play_on.emit(False)\n\n\nclass EM_Alarm(QThread):\n em_Set = Signal(int, int)\n\n def __init__(self, parent=None):\n super(EM_Alarm, self).__init__(parent)\n self.pin17 = False\n self.pin18 = False\n self.pin27 = False\n self.pin22 = False\n\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(17, GPIO.IN)\n GPIO.setup(18, GPIO.IN)\n GPIO.setup(27, GPIO.IN)\n GPIO.setup(22, GPIO.IN)\n\n self.em_Set.emit(3, 0)\n\n def run(self):\n try:\n while True:\n\n if GPIO.input(17) == False and self.pin17 == False:\n self.pin17 = True\n self.em_Set.emit(1, 17)\n elif GPIO.input(17) == True and self.pin17 == True:\n self.pin17 = False\n self.em_Set.emit(0, 17)\n\n if GPIO.input(18) == False and self.pin18 == False:\n self.pin18 = True\n self.em_Set.emit(True, 18)\n elif GPIO.input(18) == True and self.pin18 == True:\n self.pin18 = False\n self.em_Set.emit(False, 18)\n\n if GPIO.input(27) == False and self.pin27 == False:\n self.pin27 = True\n self.em_Set.emit(True, 27)\n elif GPIO.input(27) == True and self.pin27 == True:\n self.pin27 = False\n self.em_Set.emit(False, 27)\n\n if GPIO.input(22) == False and self.pin22 == False:\n self.pin22 = True\n self.em_Set.emit(True, 22)\n elif GPIO.input(22) == True and self.pin22 == True:\n self.pin22 = False\n self.em_Set.emit(False, 22)\n sleep(1)\n except:\n self.em_Set.emit(2, 0)\n\n\nif __name__ == \"__main__\":\n osPlatform = platform.system()\n print('현제 운영 시스템은 {} 입니다.'.format(osPlatform))\n app = QApplication(sys.argv)\n main = Main_UI()\n sys.exit(app.exec_())\n","sub_path":"Paging_DESKTOP-0V335C5_6-03-105813-2021_Conflict.py","file_name":"Paging_DESKTOP-0V335C5_6-03-105813-2021_Conflict.py","file_ext":"py","file_size_in_byte":45554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"530137715","text":"#!/usr/bin/env python\n\"\"\"Render a Mustache template, optionally populated with JSON data\"\"\"\n\n\nimport pystache\nimport json\nimport sys\n\n\nclass partials(object):\n partials_root = 'templates/partials'\n def get(self, name):\n \"\"\"return the template code of a partial located\n in templates/partials/\n \"\"\"\n r = \"\"\n try:\n with open(self.partials_root+'/'+name+'.mustache') as partial:\n r = partial.read().decode('utf-8')\n except IOError:\n sys.stderr.write('Couldn\\'t find partial '+name+'\\n')\n return r\n\n\ntry:\n template = open(sys.argv[1]).read().decode('utf-8')\nexcept Exception:\n sys.stderr.write(\"usage: compile_templates template.mustache [data.json]\\n\")\n sys.exit(1)\n\ntry:\n view = json.load(open(sys.argv[2]))\nexcept:\n view = {}\n\nrenderer = pystache.Renderer(partials=partials())\nsys.stdout.write(renderer.render(template, view).encode('utf-8'))\n","sub_path":"compile_mustache.py","file_name":"compile_mustache.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"170097821","text":"from study_session.models import Label, StudySession\nfrom django.contrib.auth.models import User\nfrom users.models import UserProfile\nfrom oauth2client.contrib.django_orm import Storage\nfrom users.models import CredentialsModel\nfrom apiclient import discovery\nimport httplib2\n\n#make sure all users have the default labels and a profile\nDEFAULT_LABELS = ['None', 'School', 'Work', 'Personal']\n\nclass ModelsCheck(object):\n\n def __init__(self):\n\n self.all_users = User.objects.all()\n\n def user_prof_check(self):\n #check to see if each user has a profile, if not create one\n for user in self.all_users:\n user_prof = UserProfile.objects.get_or_create(user = user)\n print('Getting User ' + user.username + '.....')\n if user_prof[1] == True:\n print('Profile Created')\n else:\n print('Profile Exists')\n\n #get_or_create returns a True if object in user_prof(1) is created, False if already exists\n\n def label_check(self):\n\n for user in self.all_users:\n print(user + 'info')\n\n for label in DEFAULT_LABELS:\n check_label = Label.objects.get_or_create(name = label, owner = user)\n if check_label[1] == True:\n print(user.username + ' ' + label + ' label Created')\n else:\n print(label + ' label exists')\n\n def google_event_check(self):\n\n for user in self.all_users:\n\n try:\n user_prof = UserProfile.objects.get(user = user)\n\n except UserProfile.DoesNotExist:\n continue\n\n sessions = StudySession.objects.filter(owner = user)\n credential_storage = Storage(CredentialsModel, 'id', user, 'credential')\n credentials = credential_storage.get()\n\n http = credentials.authorize(httplib2.Http())\n service = discovery.build('calendar', 'v3', http=http)\n\n for session in sessions:\n\n if session.event_id == 'None':\n new_event = service.events().insert(calendarId = user_prof.calendar_id, body = {'summary': session.label.name,\n 'start': {'timezone': 'America/Los_Angeles', 'dateTime': session.start_time.isoformat()}, 'description': session.description,\n 'end': {'dateTime': session.end_time.isoformat()}}).execute()\n\n #if event has a event on google already print so. If not, create one\n","sub_path":"study_session/management/commands/maintenance.py","file_name":"maintenance.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"379260008","text":"\"\"\" This module is the testing module for available deliveries controller \"\"\"\n\nimport unittest\nfrom unittest.mock import patch, MagicMock\n\nfrom app import APP, PREFIX\nfrom controllers.available_deliveries_controller import AVAILABLE_DELIVERIES_ROUTE\nfrom models import User\n\n\nclass DeliveriesDisponiblesControllerTestCase(unittest.TestCase):\n \"\"\" This class is the test case for available deliveries controller \"\"\"\n\n def setUp(self):\n APP.config['TESTING'] = True\n self.app = APP.test_client()\n\n #\n # Success Tests\n #\n\n @patch(\n 'controllers.available_deliveries_controller.delivery_service',\n autospec=True)\n def test_success_query_nearby_deliveries(self, mock_service):\n \"\"\" Test success query nearby deliveries \"\"\"\n # mocks\n mock_service.return_value = MagicMock()\n mock_service.query_nearby_deliveries.return_value = [User(\n \"1\", \"Santiago\", \"https://urlimagen.com\", [-58.3772300, -34.6131500])]\n\n # call controller\n params = \"?radius=5&latitude=-58.3772300&longitude=-34.6131500\"\n response = self.app.get(f'{PREFIX}/' + AVAILABLE_DELIVERIES_ROUTE + params,\n content_type='application/json')\n\n assert response.status_code == 200\n","sub_path":"test/controllers/test_available_deliveries_controller.py","file_name":"test_available_deliveries_controller.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"612316099","text":"from datetime import date\n\ndef get_recent_order_date(orderA, orderB):\n return orderA.order_date if orderA.more_recent_than(orderB) else orderB.order_date\n\nclass Order:\n def __init__(self,\n member_no,\n member_connection_count,\n product_no,\n order_product_price,\n order_product_quantity,\n order_date):\n tokens = order_date.split('-')\n \n self.member_no = member_no # 고객 번호\n self.member_connection_count = member_connection_count # 고객 접속수\n self.product_no = product_no # 상품 번호\n self.order_product_price = order_product_price # 상품 판매가\n self.order_product_quantity = order_product_quantity # 상품 구입수량\n self.order_date = date(int(tokens[0]), int(tokens[1]), int(tokens[2])) # 주문 일자\n \n def more_recent_than(self, order):\n return self.order_date > order.order_date\n\nclass OrderList:\n def __init__(self, sorted_by_date=False):\n self.orders = []\n self.members_no = set()\n self.products_no = set()\n self.sorted_by_date = sorted_by_date\n \n def add(self, order):\n self.orders.append(order)\n self.members_no.add(order.member_no)\n self.products_no.add(order.product_no)\n \n def count_orders(self):\n return len(self.orders)\n \n def count_products_variety(self):\n return len(self.products_no)\n \n def filter_member(self, member_no):\n order_list = OrderList()\n for order in self.orders:\n if (order.member_no == member_no):\n order_list.add(order)\n return order_list\n \n def filter_product(self, product_no):\n order_list = OrderList()\n for order in self.orders:\n if (order.product_no == product_no):\n order_list.add(order)\n return order_list\n \n def sort_by_date(self):\n if self.sorted_by_date:\n return self.orders\n else:\n orders = sorted(self.orders, key=lambda x: x.order_date)\n return orders\n \n def limit_to_date(self, last_date):\n limited_order_list = OrderList()\n orders = self.orders if self.sorted_by_date else self.sort_by_date()\n for order in orders:\n if order.order_date <= last_date:\n limited_order_list.add(order)\n else:\n return limited_order_list\n \n return limited_order_list","sub_path":"order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"438031966","text":"# 괄호 변환\n\n\ndef isCorrect(p):\n bracket = 0\n\n for i in p:\n if i == \"(\":\n bracket += 1\n else:\n bracket -= 1\n\n if bracket < 0:\n return False\n\n return True\n\n\ncorrect = \"\"\n\n\ndef solution(p):\n if p == \"\" or isCorrect(p):\n return p\n\n while True:\n u = p[0]\n v = \"\"\n for i in range(1, len(p)):\n u += p[i]\n if u.count(\"(\") == u.count(\")\"):\n if i + 1 < len(p):\n v = p[i + 1 :]\n break\n if isCorrect(u):\n global correct\n correct += u\n p = v\n else:\n answer = \"\"\n for i in u[1:-1]:\n if i == \"(\":\n answer += \")\"\n else:\n answer += \"(\"\n return correct + \"(\" + solution(v) + \")\" + answer\n\n\nprint(solution(\"(()())()\"))\nprint(solution(\")(\"))\nprint(solution(\"()))((()\"))","sub_path":"coding-test-for-python/dfs-bfs/q18.py","file_name":"q18.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"637373193","text":"import sys\n\nsys.stdin = open('input.txt', 'r')\n\nT = int(input())\n\nfor test_case in range(1, 1+T):\n N = int(input())//10\n result = 1\n if N % 2:\n for _ in range(N//2):\n result *= 4\n result += 1\n else:\n for _ in range(N//2):\n result *= 4\n result -= 1\n print('#{} {}'.format(test_case, result))\n","sub_path":"Algorithm/swea/4869. 종이붙이기/4869. 종이붙이기.py","file_name":"4869. 종이붙이기.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"365278057","text":"#!/usr/bin/python3\r\nimport sys\r\n\r\ng8r = \"\"\"\\\r\n─────▄▄████▀█▄\r\n───▄██████████████████▄\r\n─▄█████.▼.▼.▼.▼.▼.▼.▼\r\n▄███████▄.▲.▲.▲.▲.▲.▲\r\n█████████████████████▀▀\r\n\"\"\"\r\n\r\ndef replacer(str, i, max, half_blocks=True, end_lines=True):\r\n if half_blocks and max > 1:\r\n if i < max/2:\r\n str = str.replace(\"▄\", \"─\")\r\n str = str.replace(\"▀\", \"█\")\r\n else:\r\n str = str.replace(\"▄\", \"█\")\r\n str = str.replace(\"▀\", \"─\")\r\n \r\n if end_lines:\r\n i = 1\r\n for t in [c for c in str.strip()[::-1]]:\r\n if t != \"─\":\r\n break\r\n i += 1\r\n \r\n str = str[:-i] + \"\\n\"\r\n \r\n return str\r\n\r\ndef to_int(str, default=2):\r\n try:\r\n return int(str)\r\n except ValueError:\r\n return 2\r\n \r\ndef print_usage():\r\n print(\"usage: %s [width [height [output]]]\" % sys.argv[0])\r\n exit()\r\n \r\n# arguments\r\nargc = len(sys.argv)\r\nw, h, filename = 2, 2, \"g8r.txt\"\r\n\r\nif argc == 1:\r\n pass\r\nelif argc == 2:\r\n if sys.argv[1] in ['-h', 'help']: print_usage()\r\n w = to_int(sys.argv[1])\r\n h = to_int(sys.argv[1])\r\nelif argc == 3:\r\n w = to_int(sys.argv[1])\r\n h = to_int(sys.argv[2])\r\nelif argc == 4:\r\n w = to_int(sys.argv[1])\r\n h = to_int(sys.argv[2])\r\n filename = sys.argv[3]\r\nelse:\r\n print_usage()\r\n\r\n# create g8r\r\nline = \"\"\r\nwith open(filename, 'w') as f:\r\n for c in g8r:\r\n if c == \"\\n\":\r\n line += \"\\n\"\r\n for i in range(h):\r\n r = replacer(line, i, h)\r\n f.write(r)\r\n print(r, end=\"\")\r\n \r\n line = \"\"\r\n else:\r\n line += c * w\r\n","sub_path":"g8r.py","file_name":"g8r.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"157084434","text":"# -*- coding: utf-8 -*-\r\nimport os\r\nimport json\r\nimport pickle\r\nimport logging\r\nimport numpy as np\r\nimport pandas as pd\r\nimport time\r\nimport sys\r\nfrom functions_ml import prepare_set, fix_variables\r\nsys.path.append(\"..\")\r\nfrom solver.solve_polynomial_knapsack import solve_polynomial_knapsack\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n\tlog_name = \"logs/polynomial_knapsack.log\"\r\n\tlogging.basicConfig(\r\n\t\tfilename=log_name,\r\n\t\tformat='%(asctime)s %(levelname)s: %(message)s',\r\n\t\tlevel=logging.INFO, datefmt=\"%H:%M:%S\",\r\n\t\tfilemode='w'\r\n\t)\r\n\tfile_model = './model_data/finalized_model_rTrees.sav'\r\n\tCONFIG_PATH = \"./config/\"\r\n\tN_FEATURES = 6\r\n\tFIXED_PERCENTAGE = 0.85\r\n\tlist_of_files = os.listdir(CONFIG_PATH)\r\n\r\n\tfor name_file in list_of_files:\r\n\t\t\r\n\t\tRESULTS_PATH = f\"Results/resultsMLHeu.txt\"\r\n\t\tprint(\"\\tDoing file {} of {})\".format(name_file,len(list_of_files)))\r\n\t\tfp = open(CONFIG_PATH+name_file, 'r')\r\n\t\tdict_data = json.load(fp)\r\n\t\tfp.close()\r\n\t\tN_ITEMS = dict_data['n_items']\r\n\t\tstart=time.time()\r\n\t\tclf = pickle.load(open(file_model, 'rb'))\r\n\t\t#EVALUATE CONTINUOUS SOLUTION\r\n\t\tvar_type = 'continuous'\r\n\t\tof, sol_cont, comp_time = solve_polynomial_knapsack(dict_data, var_type,False,[])\t\t\r\n\t\tX = prepare_set(N_ITEMS, N_FEATURES, dict_data, sol_cont)\r\n\t\t#PREDICT STEP\r\n\t\ty_mlProba = clf.predict_proba(X)\r\n\t\t#HANDLE THE RESULT \t\t\t\t\r\n\t\ty_ml = fix_variables(N_ITEMS, y_mlProba, FIXED_PERCENTAGE)\r\n\t\t#RUN THE DISCRETE MODEL\r\n\t\tvar_type = 'discrete'\r\n\t\tof_ml, sol_ml, comp_time_ml = solve_polynomial_knapsack(dict_data, var_type, True,indexes=y_ml)\r\n\t\tstop=time.time()\r\n\t\twith open(RESULTS_PATH, 'a+') as f:\r\n\t\t\tf.write('{},{},{}\\n'.format(name_file,of_ml,stop-start))","sub_path":"PolynomialKnapsackProblem/MLHeu/MLHeu.py","file_name":"MLHeu.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"441734390","text":"from autumn.infrastructure.remote.buildkite.buildkite import CommandStep, InputStep, Pipeline\n\nfrom .calibrate import (\n commit_field,\n chains_field,\n runtime_field,\n trigger_field,\n)\nfrom .full import burn_in_field, sample_size_field\n\nfields = [\n chains_field,\n commit_field,\n runtime_field,\n burn_in_field,\n sample_size_field,\n trigger_field,\n]\ninput_step = InputStep(\n key=\"calibration-settings\",\n run_condition=None,\n fields=fields,\n)\ntrigger_step = CommandStep(key=\"run-triggers\", command=\"./scripts/buildkite.sh trigger victoria\")\npipeline = Pipeline(key=\"trigger-victoria\", steps=[input_step, trigger_step])\n","sub_path":"autumn/infrastructure/remote/buildkite/pipelines/trigger_victoria.py","file_name":"trigger_victoria.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"403411969","text":"# question 1\nl=[]\nfor i in range(10):\n a=int(input(\"enter a number\"))\n l.append(a)\nprint(l)\n\n#question 2\nwhile(\"true\"):\n print(\"infinite loop \")\n\n# question 3\na=[]\nb=[]\nfor i in range(5):\n z=int(input(\"enter a no\"))\n a.append(z)\nprint(\"list is=\",a)\nfor j in a:\n s=j*j\n b.append(s)\nprint(\"squares of list is=\",b)\n\n# question 4\nq=[]\nw=[]\ne=[]\nr=[]\nm=int(input(\"enter a integer no\"))\nq.append(m)\nn=float(input(\"enter a float number\"))\nq.append(n)\ne=str(input(\"enter a string\"))\nq.append(n)\nprint(\"list is\",q)\nfor i in q:\n if(type(i) is int):\n w.append(i)\n elif(type(i) is float):\n r.append(i)\n else:\n e.append(i)\nprint(\"list of integer is\",w)\nprint(\"list of float is\",e)\nprint(\"list of string is\",r)\n\n# question 5\nv=[]\nc=[]\nfor i in range(1,101):\n if(i%2==0):\n v.append(i)\n else:\n c.append(i)\nprint(\"even list is\",v)\nprint(\"odd list is\",c)\n\n# question 6\nfor i in range(5):\n print(\"\\n\")\n for j in range(i):\n print(\"*\",end=\"\")\n\n# question 7\nA={\"a\":1,\"b\":2,\"c\":3,\"d\":4}\nfor i in A.values():\n for j in A.keys():\n if(i==A[j]):\n print(\"value=\",i,\"corresponding to key=\",j)\n\n# question 8\nM=[]\nn=0\nfor i in range(5):\n a=int(input(\"enter values=\"))\n M.append(a)\nprint(\"List is \",M)\nv=int(input(\"enter a no that you want to find\"))\nfor j in M:\n if(j==v):\n print(v,\"found at\",j,\"position\")\n M.remove(j)\n c=1\nif(c==1):\n print(\"list is\",M)\nelse:\n print(v,\"is not found in list\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Assignment5.py","file_name":"Assignment5.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"71533256","text":"import os\nimport sys\nimport time\nimport socket\nimport importlib\nimport argparse\n\npackages = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), 'site-packages') # noqa\nsys.path.append(packages) # noqa\n\nfrom simplelib.common import threadpool\nfrom simplelib.http import influxdb\n\nfrom common import logger\nfrom common import config\nfrom common import constants\n# from collector import rm\n# from collector import nn\nimport socket\n\nCONF = config.CONF\nLOG = logger.LOG\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-c', '--config', default='./config/agent.conf')\nargs = parser.parse_args()\n\nCONF.load_configuration(args.config)\n\n\ndef get_manager_driver():\n manager_mod, manager_cls = None, None\n if CONF.monitor.manager_driver != constants.AUTO:\n manager_mod, manager_cls = CONF.monitor.manager_driver.split('.')\n if CONF.httpclient.host:\n manager_mod, manager_cls = 'httpdriver', 'ManagerWithRestClient'\n elif CONF.influxdb.host:\n manager_mod, manager_cls = 'influxdbdriver', 'ManagerWithInfluxDB'\n else:\n try:\n importlib.import_module('.{0}'.format(manager_mod), 'manager')\n manager_mod, manager_cls = 'dbdriver', 'ManagerWithDB'\n except ImportError:\n LOG.warn('dbmanager import failed, use logmanager')\n manager_mod, manager_cls = 'base', 'ManagerWithLog'\n module = importlib.import_module('.{0}'.format(manager_mod), 'manager')\n return getattr(module, manager_cls)\n\n\nclass HostMonitor(object):\n\n def __init__(self, interval=1):\n self.interval = interval\n self.monitor = self._get_monitor_driver()\n self.saver = self._get_monitor_driver()\n self.stop = False\n self.collector = self._get_monitor_collector()\n\n def _get_monitor_driver(self):\n try:\n from monitor.host import psutildriver\n return psutildriver.HostMonitorPsutilDriver()\n except ImportError:\n from monitor.host import bashdriver\n return bashdriver.HostMonitorProcFileDriver()\n\n def _get_monitor_collector(self):\n if CONF.monitor.collector == 'influxdbv2':\n from collector import influxdb\n # scheme, host, bucket, org, token, measurement\n return influxdb.InfluxDBV2Collector(\n CONF.hostmonitor_influxdbv2.scheme,\n CONF.hostmonitor_influxdbv2.host,\n CONF.hostmonitor_influxdbv2.bucket,\n CONF.hostmonitor_influxdbv2.org,\n CONF.hostmonitor_influxdbv2.token,\n 'hostmetrics',\n port=CONF.hostmonitor_influxdbv2.port,\n )\n elif CONF.monitor.collector == 'influxdb':\n from collector import influxdb\n # scheme, host, database, measurement, port=8086\n return influxdb.InfluxDBCollector(\n CONF.hostmonitor_influxdb.scheme,\n CONF.hostmonitor_influxdb.host,\n CONF.hostmonitor_influxdb.database,\n 'hostmetrics',\n port=CONF.hostmonitor_influxdb.port,\n )\n\n def start(self):\n # influxdb_client.create_database()\n import os\n from monitor.host import procreader\n \n fs_tab = procreader.FSTab()\n \n while not self.stop:\n time.sleep(self.interval)\n print('=======================')\n for f in fs_tab.get_fs_files():\n statvfs = os.statvfs(f)\n b_used = statvfs.f_blocks - statvfs.f_bavail\n print(f, '\\t', b_used * statvfs.f_bsize, \n '\\t', b_used * 100.0 / statvfs.f_blocks)\n # try:\n # metrics = self.monitor.get_metrics()\n # LOG.debug('host metrics: %s', metrics)\n # self.collector.collect(metrics, host=socket.gethostname())\n # except Exception as e:\n # LOG.exception(e)\n\n\ndef main():\n LOG.info('agent starting')\n monitor_pool = threadpool.ThreadPool(5)\n if CONF.monitor.enable:\n host_monitor = HostMonitor()\n monitor_pool.spawn(host_monitor.start)\n\n # if CONF.namenode_jmx.enable:\n # LOG.info('start NameNodeJMXCollector')\n # monitor = nn.NameNodeJMXCollector()\n # monitor_pool.spawn(monitor.start)\n\n # if CONF.rm_resource_available_monitor.enable:\n # LOG.info('start RMResourceAvailableMonitor')\n # monitor = rm.RMResourceAvailableMonitor()\n # monitor_pool.spawn(monitor.start)\n\n while True:\n time.sleep(10)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Agent/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"223817418","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2020 CERN.\n# Copyright (C) 2020 Northwestern University.\n#\n# Invenio-Records-Resources is free software; you can redistribute it and/or\n# modify it under the terms of the MIT License; see LICENSE file for more\n# details.\n\n\"\"\"Test links.\"\"\"\n\nimport pytest\nfrom marshmallow import Schema, fields\n\n\nclass MockResourceRequestCtx:\n\n url_args = {\"q\": \"\"}\n\n\nclass MockRecordLinksSchema(Schema):\n \"\"\"Schema for a record's links.\"\"\"\n\n self = fields.String(default=\"/api/records/12345-ABCDE\")\n\n\nclass MockSearchLinksSchema(Schema):\n \"\"\"Schema for a search result's links.\"\"\"\n\n self = fields.String(default=\"/api/records?q=\")\n\n\ndef test_search_links(app, service, identity_simple, input_data, es_clear):\n \"\"\"Test record links creation.\"\"\"\n # Create a dummy record\n item = service.create(identity_simple, input_data)\n\n resource_requestctx = MockResourceRequestCtx()\n links_config = {\n \"record\": MockRecordLinksSchema,\n \"search\": MockSearchLinksSchema\n }\n result_list = service.search(\n identity=identity_simple,\n params=resource_requestctx.url_args,\n links_config=links_config,\n ).to_dict()\n\n expected_search_links = {\n \"self\": \"/api/records?q=\"\n }\n\n assert result_list[\"links\"] == expected_search_links\n\n expected_item_links = {\n \"self\": \"/api/records/12345-ABCDE\"\n }\n\n for hit in result_list[\"hits\"][\"hits\"]:\n assert hit[\"links\"] == expected_item_links\n","sub_path":"tests/services/test_links.py","file_name":"test_links.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"442673242","text":"from django.conf.urls import url\n\nfrom dashboard import views\nurlpatterns = [\n url(r'^setup_shop/$', views.setup_shop, name='setup'),\n url(r'^add_seller/$', views.add_seller, name='add_seller'),\n url(r'^add_good/$', views.add_good, name='add_good'),\n url(r'^storage/$', views.storage, name='storage'),\n url(r'^$', views.main_page, name='main_page'),\n]","sub_path":"vn/vitr/dashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"622507480","text":"#!/bin/env python2.7\nimport os\nimport sys\n\ncdir = os.getcwd()\n\nfolder = cdir.split('\\\\')\nn = len(folder)\np = folder[n-1]\n \nf = open(\"f:\\patch.txt\",\"w\")\nf.write(cdir)\nf.close()\n\nif len(sys.argv) > 2:\n seed = sys.argv[2]\nelse: \n seed = \"http://10.135.8.120:1200/integrity_test/wot/\"\n\n\npart = sys.argv[1]\n\nos.system(\"make_torrent -w \" + seed + \" -P -s 2097152 -i f:\\patch.txt -o \" + cdir + os.sep + p + \"_\" + part + \".torrent\")\n\nprint (\"make_torrent -w \" + seed + \" -P -s 2097152 -i f:\\patch.txt -o \" + cdir + os.sep + p + \"_\" + part + \".torrent\")","sub_path":"intg.py","file_name":"intg.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"540390344","text":"from board import Board\nfrom game import Game\nfrom players import Player\nimport logging\nimport json\n\n\ndef main():\n logging.basicConfig(format=\"%(asctime)s.%(msecs)03d %(levelname)s> %(message)s\",\n datefmt=\"%Y/%m/%d %H:%M:%S\",\n level=logging.INFO)\n logging.info(\"Starting a new game\")\n players = [Player(1), Player(2), Player(3)]\n player = {}\n for p in players:\n player[int(p.player_id)] = p\n with open(\"board_map.json\") as json_data:\n board_map = json.load(json_data)\n board = Board(board_map)\n board.generate_new_board()\n game = Game(players, board)\n game.pregame(game.first_player(len(players)))\n while True:\n game.understand_action()\n logging.info(\"Game ended\")\n print(\"Hello\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"catan.py","file_name":"catan.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"626868442","text":"\nfrom dropbox import client, session as dropbox_session\nfrom flask import Blueprint, redirect, url_for, request, flash, session\nimport settings\n\ndropbox_auth = Blueprint('dropbox', __name__)\n\n@dropbox_auth.route('/login')\ndef login():\n sess = dropbox_session.DropboxSession(settings.DROPBOX_APP_KEY, settings.DROPBOX_APP_SECRET, 'app_folder')\n request_token = sess.obtain_request_token()\n session['dropbox_temp_token'] = {\n 'request_token': request_token.key,\n 'request_token_secret': request_token.secret,\n }\n return redirect(sess.build_authorize_url(request_token, oauth_callback=url_for('dropbox.authorised', _external=True,\n next=request.args.get('next') or request.referrer or None)))\n\n@dropbox_auth.route('/authorized')\ndef authorised():\n next_url = request.args.get('next') or url_for('index')\n oauth_token = request.args.get('oauth_token') or None\n temp_token_data = session.get('dropbox_temp_token')\n if not temp_token_data:\n flash('No temp Dropbox token found, please retry', category=\"error\")\n return redirect(next_url)\n if temp_token_data['request_token'] != oauth_token:\n flash('Invalid Dropbox token received, please retry', category=\"error\")\n return redirect(next_url)\n\n del(session['dropbox_temp_token'])\n\n sess = dropbox_session.DropboxSession(settings.DROPBOX_APP_KEY, settings.DROPBOX_APP_SECRET, 'app_folder')\n sess.set_request_token(**temp_token_data)\n access_token = sess.obtain_access_token()\n\n db_cli = client.DropboxClient(sess)\n acc_info = db_cli.account_info()\n session['dropbox_token'] = {\n 'name': acc_info['display_name'],\n 'access_token': {\n 'access_token': access_token.key,\n 'access_token_secret': access_token.secret,\n }\n }\n return redirect(next_url)\n\n@dropbox_auth.route('/logout')\ndef logout():\n del(session['dropbox_token'])\n flash(\"You've logged out Dropbox!\", category=\"info\")\n return redirect(url_for('index'))\n","sub_path":"dropbox_auth.py","file_name":"dropbox_auth.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"47592723","text":"import cv2\r\n\r\nimage_path = 'files/girl.jpg' # image for detect\r\ncascade_path = 'files/cfgFaceDetect_frontalface_default.xml' # model face\r\n\r\nclf = cv2.CascadeClassifier(cascade_path) # create the classifier\r\n\r\nimg = cv2.imread(image_path) # read the image\r\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert to grayscale\r\n\r\n\r\nfaces = clf.detectMultiScale(gray, 1.3, 10)\r\n\r\nfor(x, y, w, h) in faces: # read the faces\r\n img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 255, 0), 2) # draw rectangle\r\n\r\ncv2.imshow('image', img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()","sub_path":"tools/face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"361467514","text":"\nfrom mcts_node import MCTSNode\nfrom random import choice\nfrom math import sqrt, log\n\nnum_nodes = 10\nexplore_faction = 2.\n\ndef traverse_nodes(node, board, state, identity):\n \"\"\" Traverses the tree until the end criterion are met.\n\n Args:\n node: A tree node from which the search is traversing.\n board: The game setup.\n state: The state of the game.\n identity: The bot's identity, either 'red' or 'blue'.\n\n Returns: A node from which the next stage of the search can proceed.\n\n \"\"\"\n \n #return if leaf\n if(len(node.untried_actions)>0):\n leaf_node = node \n return (leaf_node, state)\n else:\n #calculate UCT for all children\n children = []\n #find whose turn\n myMove=(identity == board.current_player(state))\n for child in node.child_nodes:\n value=UCT(node, node.child_nodes[child],myMove)\n children.append((value,child))\n \n #sort by UCT\n children.sort(key=byVal,reverse=True)\n \n for child in children:\n #call recurusively until a leaf is found\n possible_leaf = node.child_nodes[child[1]]\n possible_leaf_pair = traverse_nodes(possible_leaf, board, board.next_state(state, possible_leaf.parent_action), identity)\n if(possible_leaf != None):\n return possible_leaf_pair\n #if no leaf is found return none \n return None\n \n#sort by first in tuple \ndef byVal(e):\n return e[0]\n\ndef expand_leaf(node, board, state,identity):\n \"\"\" Adds a new leaf to the tree by creating a new child node for the given node.\n\n Args:\n node: The node for which a child will be added.\n board: The game setup.\n state: The state of the game.\n\n Returns: The added child node.\n\n \"\"\"\n \n #get random action and remove from untried\n action=choice(node.untried_actions)\n (node.untried_actions).remove(action)\n #make new node with that action and return it\n new_node = MCTSNode(parent=node, parent_action=action, action_list=board.legal_actions(board.next_state(state, action)))\n node.child_nodes[action]=new_node\n return (new_node, board.next_state(state, action))\n\n\ndef rollout(board, state,identity):\n \"\"\" Given the state of the game, the rollout plays out the remainder randomly.\n\n Args:\n board: The game setup.\n state: The state of the game.\n\n \"\"\"\n #if game is over return points\n if(board.is_ended(state)):\n return board.points_values(state)\n else: \n #if some move wins, choose it\n for act in board.legal_actions(state):\n points = board.points_values(board.next_state(state, act))\n if(points!=None and points[identity] == 1):\n return rollout(board, board.next_state(state, act),identity)\n \n #if not make a random choice and call recursively\n action=choice(board.legal_actions(state))\n return rollout(board, board.next_state(state, action),identity) \n\n\ndef backpropagate(node, won):\n \"\"\" Navigates the tree from a leaf node to the root, updating the win and visit count of each node along the path.\n\n Args:\n node: A leaf node.\n won: An indicator of whether the bot won or lost the game.\n\n \"\"\"\n #add to visits, and wins if won\n node.wins=node.wins+won\n node.visits = node.visits+1\n #return if root, call recursively if not\n if(node.parent == None):\n return node\n else:\n backpropagate(node.parent, won)\n \n\n\ndef think(board, state):\n \"\"\" Performs MCTS by sampling games and calling the appropriate functions to construct the game tree.\n\n Args:\n board: The game setup.\n state: The state of the game.\n\n Returns: The action to be taken.\n\n \"\"\"\n identity_of_bot = board.current_player(state)\n root_node = MCTSNode(parent=None, parent_action=None, action_list=board.legal_actions(state))\n \n #False if there are unexplored actions\n fullyExplored= False\n \n for step in range(num_nodes):\n # Copy the game for sampling a playthrough\n sampled_game = state\n\n # Start at root\n node = root_node\n\n # Do MCTS - This is all you!\n \n #traverse, returns node and state\n pair = traverse_nodes(node, board, sampled_game, identity_of_bot)\n #if pair is none, then all nodes are explored, and we can stop searching\n if(pair == None):\n fullyExplored=True\n break\n \n #use found node and state to make a new node and state\n new_pair = expand_leaf(pair[0], board, pair[1], identity_of_bot)\n \n #simulate game to end, return points\n points = rollout(board, board.next_state(new_pair[1], new_pair[0].parent_action),identity_of_bot)\n \n #if we won, then set won to 1, if not 0\n '''if(points[identity_of_bot]==1):\n won=1\n else:\n won=0'''\n won = points[identity_of_bot]\n #give this information to all nodes on path \n backpropagate(new_pair[0],won)\n \n \n\n # Return an action, typically the most frequently used action (from the root) or the action with the best\n # estimated win rate.\n best =[]\n #search all children of root\n for child in root_node.child_nodes:\n loose = False\n model_state=state\n child_node=root_node.child_nodes[child]\n model_state = board.next_state(model_state,child_node.parent_action)\n #check for failing child\n for grand in child_node.child_nodes:\n grandChild = child_node.child_nodes[grand]\n model_state = board.next_state(model_state,grandChild.parent_action)\n points = board.points_values(model_state)\n if(points!=None and points[identity_of_bot]==-1):\n loose=True\n break\n #if fully explored then pick best win rate\n if(fullyExplored):\n best.append((child_node.wins/child_node.visits,child_node,loose))\n else:\n #if not then pick most visited\n best.append((child_node.visits,child_node,loose))\n #sort by win/visit rate\n best.sort(key=byVal,reverse=True)\n #return best without failing child\n for n in best:\n if(n[2]==False):\n return n[1].parent_action\n \n #if not possible return best\n return best[0][1].parent_action\n \n \n#return UCT value\ndef UCT(node, child, myMove):\n winRate = child.wins/child.visits\n #if not my turn use opponants win rate\n if(myMove==False):\n winRate=1-winRate\n exploration = log(node.visits)/child.visits\n return winRate+explore_faction*sqrt(exploration)","sub_path":"P3/mcts_modified.py","file_name":"mcts_modified.py","file_ext":"py","file_size_in_byte":6759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"499862653","text":"__author__ = 'joefalkson'\n\nimport cv2\nimport numpy as np\nimport math\n\ndef expand(image):\n try:\n image=cv2.imread(image,0)\n except TypeError:\n image=image\n\n rows = image.shape[0]\n cols = image.shape[1]\n\n expandedImg=np.zeros((math.ceil(rows),math.ceil(cols*2)))\n\n #3/4 1/8 1/8\n\n #double number of columns\n #even is 1/2 1/2\n for row in range(rows):\n expandedCol=0\n #loop through each column of original image\n #double number of columns\n for col in range(2,cols-1):\n #print \"Row: %r, Col: %r \" %(row,col)\n #expand those columns\n #even pixels\n expandedImg[row,expandedCol] = 3*image[row,col]/4 + image[row,col-1]/8 + \\\n image[row,col+1]/8\n expandedImg[row,expandedCol+1]=image[row,col-1]/2+image[row,col+1]/2\n expandedCol+=2\n\n\n #now we swap rows and columns, and repeat the same code\n expandedImg2=np.zeros((math.ceil(expandedImg.shape[0]*2),math.ceil(expandedImg.shape[1])))\n #double number of rows\n for col in range(2*cols):\n expandedRow=0\n for row in range(2,rows-1):\n #print \"Row: %r, Col: %r \" %(row,col)\n expandedImg2[expandedRow,col] = 3*expandedImg[row,col]/4 + expandedImg[row-1,col]/8 + \\\n expandedImg[row+1,col]/8\n expandedImg2[expandedRow+1,col]=expandedImg[row-1,col]/2+expandedImg[row+1,col]/2\n expandedRow+=2\n\n\n return expandedImg2","sub_path":"ps5_python/expand.py","file_name":"expand.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"440386178","text":"import json\nfrom functools import reduce\n\nfrom django.conf import settings\nfrom django.db import IntegrityError\nfrom django.db.models import Exists\nfrom django.db.models import F\nfrom django.db.models import OuterRef\nfrom django.db.models import Q\nfrom django.db.models import Subquery\nfrom django.http import Http404\nfrom django.utils.timezone import now\nfrom django_filters.rest_framework import CharFilter\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom django_filters.rest_framework import UUIDFilter\nfrom le_utils.constants import content_kinds\nfrom le_utils.constants import exercises\nfrom le_utils.constants import roles\nfrom rest_framework.decorators import detail_route\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.serializers import ChoiceField\nfrom rest_framework.serializers import DictField\nfrom rest_framework.serializers import IntegerField\nfrom rest_framework.serializers import ValidationError\nfrom rest_framework.viewsets import ViewSet\n\nfrom contentcuration.models import AssessmentItem\nfrom contentcuration.models import Channel\nfrom contentcuration.models import ContentNode\nfrom contentcuration.models import ContentTag\nfrom contentcuration.models import File\nfrom contentcuration.models import generate_storage_url\nfrom contentcuration.models import PrerequisiteContentRelationship\nfrom contentcuration.tasks import create_async_task\nfrom contentcuration.viewsets.base import BulkListSerializer\nfrom contentcuration.viewsets.base import BulkModelSerializer\nfrom contentcuration.viewsets.base import BulkUpdateMixin\nfrom contentcuration.viewsets.base import RequiredFilterSet\nfrom contentcuration.viewsets.base import ValuesViewset\nfrom contentcuration.viewsets.common import DotPathValueMixin\nfrom contentcuration.viewsets.common import JSONFieldDictSerializer\nfrom contentcuration.viewsets.common import NotNullMapArrayAgg\nfrom contentcuration.viewsets.common import SQCount\nfrom contentcuration.viewsets.common import UserFilteredPrimaryKeyRelatedField\nfrom contentcuration.viewsets.common import UUIDInFilter\nfrom contentcuration.viewsets.sync.constants import CONTENTNODE\nfrom contentcuration.viewsets.sync.constants import CREATED\nfrom contentcuration.viewsets.sync.constants import DELETED\nfrom contentcuration.viewsets.sync.constants import TASK_ID\nfrom contentcuration.viewsets.sync.utils import generate_delete_event\nfrom contentcuration.viewsets.sync.utils import generate_update_event\n\n\nchannel_query = Channel.objects.filter(main_tree__tree_id=OuterRef(\"tree_id\"))\n\n\n_valid_positions = {\"first-child\", \"last-child\", \"left\", \"right\"}\n\n\nclass ContentNodeFilter(RequiredFilterSet):\n id__in = UUIDInFilter(name=\"id\")\n root_id = UUIDFilter(method=\"filter_root_id\")\n ancestors_of = UUIDFilter(method=\"filter_ancestors_of\")\n parent__in = UUIDInFilter(name=\"parent\")\n _node_id_channel_id___in = CharFilter(method=\"filter__node_id_channel_id\")\n\n class Meta:\n model = ContentNode\n fields = (\n \"parent\",\n \"parent__in\",\n \"id__in\",\n \"kind\",\n \"root_id\",\n \"ancestors_of\",\n \"_node_id_channel_id___in\",\n )\n\n def filter_root_id(self, queryset, name, value):\n return queryset.filter(\n parent=Channel.objects.filter(pk=value).values_list(\n \"main_tree__id\", flat=True\n )\n )\n\n def filter_ancestors_of(self, queryset, name, value):\n # For simplicity include the target node in the query\n target_node_query = ContentNode.objects.filter(pk=value)\n return queryset.filter(\n tree_id=target_node_query.values_list(\"tree_id\", flat=True)[:1],\n lft__lte=target_node_query.values_list(\"lft\", flat=True)[:1],\n rght__gte=target_node_query.values_list(\"rght\", flat=True)[:1],\n )\n\n def filter__node_id_channel_id(self, queryset, name, value):\n query = Q()\n values = value.split(\",\")\n num_pairs = len(values) // 2\n for i in range(0, num_pairs):\n query |= Q(node_id=values[i * 2], channel_id=values[i * 2 + 1])\n return queryset.filter(query)\n\n\ndef bulk_create_tag_relations(tags_relations_to_create):\n if tags_relations_to_create:\n # In Django 2.2 add ignore_conflicts to make this fool proof\n try:\n ContentNode.tags.through.objects.bulk_create(tags_relations_to_create)\n except IntegrityError:\n # One of the relations already exists, so just save them one by one.\n # Django's default upsert behaviour should mean we get no errors this way\n for to_create in tags_relations_to_create:\n to_create.save()\n\n\ndef set_tags(tags_by_id):\n all_tag_names = set()\n tags_relations_to_create = []\n tags_relations_to_delete = []\n for target_node_id, tag_names in tags_by_id.items():\n for tag_name, value in tag_names.items():\n if value:\n all_tag_names.add(tag_name)\n\n # channel is no longer used on the tag object, so don't bother using it\n available_tags = set(\n ContentTag.objects.filter(\n tag_name__in=all_tag_names, channel__isnull=True\n ).values_list(\"tag_name\", flat=True)\n )\n\n tags_to_create = all_tag_names.difference(available_tags)\n\n new_tags = [ContentTag(tag_name=tag_name) for tag_name in tags_to_create]\n ContentTag.objects.bulk_create(new_tags)\n\n tag_id_by_tag_name = {\n t[\"tag_name\"]: t[\"id\"]\n for t in ContentTag.objects.filter(\n tag_name__in=all_tag_names, channel__isnull=True\n ).values(\"tag_name\", \"id\")\n }\n\n for target_node_id, tag_names in tags_by_id.items():\n for tag_name, value in tag_names.items():\n if value:\n tag_id = tag_id_by_tag_name[tag_name]\n tags_relations_to_create.append(\n ContentNode.tags.through(\n contentnode_id=target_node_id, contenttag_id=tag_id\n )\n )\n else:\n tags_relations_to_delete.append(\n Q(contentnode_id=target_node_id, contenttag__tag_name=tag_name)\n )\n bulk_create_tag_relations(tags_relations_to_create)\n if tags_relations_to_delete:\n ContentNode.tags.through.objects.filter(\n reduce(lambda x, y: x | y, tags_relations_to_delete)\n ).delete()\n\n\nclass ContentNodeListSerializer(BulkListSerializer):\n def gather_tags(self, validated_data):\n tags_by_id = {}\n\n for obj in validated_data:\n try:\n tags = obj.pop(\"tags\")\n except KeyError:\n pass\n else:\n if tags:\n tags_by_id[obj[\"id\"]] = tags\n return tags_by_id\n\n def update(self, queryset, all_validated_data):\n tags = self.gather_tags(all_validated_data)\n modified = now()\n for data in all_validated_data:\n data[\"modified\"] = modified\n all_objects = super(ContentNodeListSerializer, self).update(\n queryset, all_validated_data\n )\n if tags:\n set_tags(tags)\n return all_objects\n\n\nclass ExtraFieldsSerializer(JSONFieldDictSerializer):\n type = ChoiceField(\n choices=exercises.MASTERY_MODELS, allow_null=True, required=False\n )\n m = IntegerField(allow_null=True, required=False)\n n = IntegerField(allow_null=True, required=False)\n\n\nclass TagField(DotPathValueMixin, DictField):\n pass\n\n\nclass ContentNodeSerializer(BulkModelSerializer):\n \"\"\"\n This is a write only serializer - we leverage it to do create and update\n operations, but read operations are handled by the Viewset.\n \"\"\"\n\n parent = UserFilteredPrimaryKeyRelatedField(\n queryset=ContentNode.objects.all(), required=False\n )\n extra_fields = ExtraFieldsSerializer(required=False)\n\n tags = TagField(required=False)\n\n class Meta:\n model = ContentNode\n fields = (\n \"id\",\n \"title\",\n \"description\",\n \"kind\",\n \"language\",\n \"license\",\n \"license_description\",\n \"copyright_holder\",\n \"author\",\n \"role_visibility\",\n \"aggregator\",\n \"provider\",\n \"extra_fields\",\n \"thumbnail_encoding\",\n \"parent\",\n \"complete\",\n \"changed\",\n \"tags\",\n )\n list_serializer_class = ContentNodeListSerializer\n nested_writes = True\n\n def create(self, validated_data):\n # Creating a new node, by default put it in the orphanage on initial creation.\n if \"parent\" not in validated_data:\n validated_data[\"parent_id\"] = settings.ORPHANAGE_ROOT_ID\n\n tags = None\n if \"tags\" in validated_data:\n tags = validated_data.pop(\"tags\")\n\n instance = super(ContentNodeSerializer, self).create(validated_data)\n\n if tags:\n set_tags({instance.id: tags})\n\n return instance\n\n def update(self, instance, validated_data):\n if \"parent\" in validated_data:\n raise ValidationError(\n {\"parent\": \"This field should only be changed by a move operation\"}\n )\n\n extra_fields = validated_data.pop(\"extra_fields\", None)\n if extra_fields is not None:\n validated_data[\"extra_fields\"] = self.fields[\"extra_fields\"].update(\n instance.extra_fields, extra_fields\n )\n if \"tags\" in validated_data:\n tags = validated_data.pop(\"tags\")\n set_tags({instance.id: tags})\n return super(ContentNodeSerializer, self).update(instance, validated_data)\n\n\ndef retrieve_thumbail_src(item):\n \"\"\" Get either the encoding or the url to use as the src attribute \"\"\"\n try:\n if item.get(\"thumbnail_encoding\"):\n encoding = json.loads(item.get(\"thumbnail_encoding\"))\n if encoding:\n return encoding.get(\"base64\")\n except ValueError:\n pass\n if (\n item[\"thumbnail_checksum\"] is not None\n and item[\"thumbnail_extension\"] is not None\n ):\n return generate_storage_url(\n \"{}.{}\".format(item[\"thumbnail_checksum\"], item[\"thumbnail_extension\"])\n )\n return None\n\n\ndef get_title(item):\n # If it's the root, use the channel name (should be original channel name)\n return item[\"title\"] if item[\"parent_id\"] else item[\"original_channel_name\"]\n\n\nclass PrerequisitesUpdateHandler(ViewSet):\n \"\"\"\n Dummy viewset for handling create and delete changes for prerequisites\n \"\"\"\n\n def _get_values_from_change(self, change):\n return {\n \"target_node_id\": change[\"key\"][0],\n \"prerequisite_id\": change[\"key\"][1],\n }\n\n def _execute_changes(self, change_type, data):\n if data:\n if change_type == CREATED:\n PrerequisiteContentRelationship.objects.bulk_create(\n [PrerequisiteContentRelationship(**d) for d in data]\n )\n elif change_type == DELETED:\n PrerequisiteContentRelationship.objects.filter(\n reduce(lambda x, y: x | y, map(lambda x: Q(**x), data))\n ).delete()\n\n def _check_permissions(self, changes):\n # Filter the passed in contentondes, on both side of the relationship\n allowed_contentnodes = set(\n ContentNode.filter_edit_queryset(\n ContentNode.objects.all(), self.request.user\n )\n .filter(\n id__in=list(map(lambda x: x[\"key\"][0], changes))\n + list(map(lambda x: x[\"key\"][1], changes))\n )\n .values_list(\"id\", flat=True)\n )\n\n valid_changes = []\n errors = []\n\n for change in changes:\n if (\n change[\"key\"][0] in allowed_contentnodes\n and change[\"key\"][1] in allowed_contentnodes\n ):\n valid_changes.append(change)\n else:\n change.update({\"errors\": ValidationError(\"Not found\").detail})\n errors.append(change)\n return valid_changes, errors\n\n def _check_valid(self, changes):\n # Don't allow prerequisites to be created across different trees\n # or on themselves\n valid_changes = []\n errors = []\n\n tree_id_lookup = {\n c[\"id\"]: c[\"tree_id\"]\n for c in ContentNode.objects.filter(\n id__in=list(map(lambda x: x[\"key\"][0], changes))\n + list(map(lambda x: x[\"key\"][1], changes))\n ).values(\"id\", \"tree_id\")\n }\n\n # Do a lookup on existing prerequisite relationships in the opposite direction to the ones we are trying to set\n # Create a lookup string of prerequisite_id:target_node_id which we will compare against target_node_id:prerequisite_id\n existing_relationships_lookup = {\n \"{}:{}\".format(p[\"prerequisite_id\"], p[\"target_node_id\"])\n for p in PrerequisiteContentRelationship.objects.filter(\n # First part of the key is the target_node_id and prerequisite_id the second, so we reverse them here\n reduce(\n lambda x, y: x | y,\n map(\n lambda x: Q(\n target_node_id=x[\"key\"][1], prerequisite_id=x[\"key\"][0]\n ),\n changes,\n ),\n )\n ).values(\"target_node_id\", \"prerequisite_id\")\n }\n\n for change in changes:\n if change[\"key\"][0] == change[\"key\"][1]:\n change.update(\n {\n \"errors\": ValidationError(\n \"Prerequisite relationship cannot be self referential\"\n ).detail\n }\n )\n errors.append(change)\n elif tree_id_lookup[change[\"key\"][0]] != tree_id_lookup[change[\"key\"][1]]:\n change.update(\n {\n \"errors\": ValidationError(\n \"Prerequisite relationship cannot cross trees\"\n ).detail\n }\n )\n errors.append(change)\n elif (\n \"{}:{}\".format(change[\"key\"][0], change[\"key\"][1])\n in existing_relationships_lookup\n ):\n change.update(\n {\n \"errors\": ValidationError(\n \"Prerequisite relationship cannot be reciprocal\"\n ).detail\n }\n )\n errors.append(change)\n else:\n valid_changes.append(change)\n return valid_changes, errors\n\n def _handle_relationship_changes(self, changes):\n change_types = set(map(lambda x: x[\"type\"], changes))\n if len(change_types) > 1:\n raise TypeError(\"Mixed change types passed to change handler\")\n\n change_type = tuple(change_types)[0]\n\n permissioned_changes, permission_errors = self._check_permissions(changes)\n\n if change_type == CREATED and permissioned_changes:\n # Only do validation on create operations and if there are any changes left to validate\n valid_changes, validation_errors = self._check_valid(permissioned_changes)\n errors = permission_errors + validation_errors\n else:\n # For delete operations, just check permissions, but let invalid\n # relationships be deleted\n valid_changes = permissioned_changes\n errors = permission_errors\n\n data = list(map(self._get_values_from_change, valid_changes))\n\n # In Django 2.2 add ignore_conflicts to make this fool proof\n try:\n self._execute_changes(change_type, data)\n except IntegrityError as e:\n for change in valid_changes:\n change.update({\"errors\": str(e)})\n errors.append(change)\n\n return errors or None, None\n\n def create_from_changes(self, changes):\n return self._handle_relationship_changes(changes)\n\n def delete_from_changes(self, changes):\n return self._handle_relationship_changes(changes)\n\n\n# Apply mixin first to override ValuesViewset\nclass ContentNodeViewSet(BulkUpdateMixin, ValuesViewset):\n queryset = ContentNode.objects.all()\n serializer_class = ContentNodeSerializer\n permission_classes = [IsAuthenticated]\n filter_backends = (DjangoFilterBackend,)\n filter_class = ContentNodeFilter\n values = (\n \"id\",\n \"content_id\",\n \"title\",\n \"description\",\n \"author\",\n \"assessment_item_count\",\n \"provider\",\n \"aggregator\",\n \"content_tags\",\n \"role_visibility\",\n \"kind__kind\",\n \"language_id\",\n \"license_id\",\n \"license_description\",\n \"copyright_holder\",\n \"extra_fields\",\n \"node_id\",\n \"root_id\",\n \"channel_id\",\n \"original_source_node_id\",\n \"original_channel_id\",\n \"original_channel_name\",\n \"original_node_id\",\n \"original_parent_id\",\n \"total_count\",\n \"resource_count\",\n \"error_count\",\n \"has_updated_descendants\",\n \"has_new_descendants\",\n \"coach_count\",\n \"thumbnail_checksum\",\n \"thumbnail_extension\",\n \"thumbnail_encoding\",\n \"published\",\n \"modified\",\n \"has_children\",\n \"parent_id\",\n \"complete\",\n \"changed\",\n \"lft\",\n )\n\n field_map = {\n \"language\": \"language_id\",\n \"license\": \"license_id\",\n \"tags\": \"content_tags\",\n \"kind\": \"kind__kind\",\n \"thumbnail_src\": retrieve_thumbail_src,\n \"title\": get_title,\n \"parent\": \"parent_id\",\n }\n\n def _annotate_channel_id(self, queryset):\n return queryset.annotate(\n channel_id=Subquery(channel_query.values_list(\"id\", flat=True)[:1])\n )\n\n def get_queryset(self):\n queryset = super(ContentNodeViewSet, self).get_queryset()\n return self._annotate_channel_id(queryset)\n\n def get_edit_queryset(self):\n queryset = super(ContentNodeViewSet, self).get_edit_queryset()\n return self._annotate_channel_id(queryset)\n\n @detail_route(methods=[\"get\"])\n def requisites(self, request, pk=None):\n if not pk:\n raise Http404\n\n # Here we are fetching the entire prerequisite relationship tree\n # for the channel. It is possible that this could get very large,\n # and cause performance issues, and it may not need to be loaded\n # on every fetch.\n # However, in order to detect potential cyclic prerequisite chains,\n # we load the entire channel's prerequisite tree at once.\n # Do a filter just on the tree_id of the target node, as relationships\n # should not be cross channel, and are not meaningful if they are.\n prereq_table_entries = PrerequisiteContentRelationship.objects.filter(\n target_node__tree_id=ContentNode.objects.filter(pk=pk).values_list(\n \"tree_id\", flat=True\n )[:1]\n ).values(\"target_node_id\", \"prerequisite_id\")\n\n return Response(\n list(\n map(\n lambda x: {\n \"target_node\": x[\"target_node_id\"],\n \"prerequisite\": x[\"prerequisite_id\"],\n },\n prereq_table_entries,\n )\n ),\n )\n\n def annotate_queryset(self, queryset):\n queryset = queryset.annotate(total_count=(F(\"rght\") - F(\"lft\") - 1) / 2)\n\n descendant_resources = (\n ContentNode.objects.filter(\n tree_id=OuterRef(\"tree_id\"),\n lft__gt=OuterRef(\"lft\"),\n rght__lt=OuterRef(\"rght\"),\n )\n .exclude(kind_id=content_kinds.TOPIC)\n .values(\"id\", \"role_visibility\", \"changed\")\n .order_by()\n )\n\n all_descendants = (\n ContentNode.objects.filter(\n tree_id=OuterRef(\"tree_id\"),\n lft__gt=OuterRef(\"lft\"),\n rght__lt=OuterRef(\"rght\"),\n )\n .values(\"id\", \"complete\", \"published\")\n .order_by()\n )\n\n # Get count of descendant nodes with errors\n descendant_errors = all_descendants.filter(complete=False)\n changed_descendants = descendant_resources.filter(changed=True)\n\n thumbnails = File.objects.filter(\n contentnode=OuterRef(\"id\"), preset__thumbnail=True\n )\n original_channel = Channel.objects.filter(\n Q(pk=OuterRef(\"original_channel_id\"))\n | Q(main_tree__tree_id=OuterRef(\"tree_id\"))\n )\n original_node = ContentNode.objects.filter(\n node_id=OuterRef(\"original_source_node_id\")\n ).filter(node_id=F(\"original_source_node_id\"))\n\n root_id = ContentNode.objects.filter(\n tree_id=OuterRef(\"tree_id\"), parent__isnull=True\n ).values_list(\"id\", flat=True)[:1]\n\n assessment_items = (\n AssessmentItem.objects.filter(contentnode_id=OuterRef(\"id\"), deleted=False)\n .values_list(\"assessment_id\", flat=True)\n .distinct()\n )\n\n queryset = queryset.annotate(\n resource_count=SQCount(descendant_resources, field=\"id\"),\n coach_count=SQCount(\n descendant_resources.filter(role_visibility=roles.COACH), field=\"id\",\n ),\n assessment_item_count=SQCount(assessment_items, field=\"assessment_id\"),\n error_count=SQCount(descendant_errors, field=\"id\"),\n has_updated_descendants=Exists(\n changed_descendants.filter(published=True).values(\"id\")\n ),\n has_new_descendants=Exists(\n changed_descendants.filter(published=False).values(\"id\")\n ),\n thumbnail_checksum=Subquery(thumbnails.values(\"checksum\")[:1]),\n thumbnail_extension=Subquery(\n thumbnails.values(\"file_format__extension\")[:1]\n ),\n original_channel_name=Subquery(original_channel.values(\"name\")[:1]),\n original_parent_id=Subquery(original_node.values(\"parent_id\")[:1]),\n original_node_id=Subquery(original_node.values(\"pk\")[:1]),\n has_children=Exists(\n ContentNode.objects.filter(parent=OuterRef(\"id\")).values(\"pk\")\n ),\n root_id=Subquery(root_id),\n )\n queryset = queryset.annotate(content_tags=NotNullMapArrayAgg(\"tags__tag_name\"))\n\n return queryset\n\n def validate_targeting_args(self, target, position):\n position = position or \"last-child\"\n if target is None:\n raise ValidationError(\"A target must be specified\")\n try:\n target = self.get_edit_queryset().get(pk=target)\n except ContentNode.DoesNotExist:\n raise ValidationError(\"Target: {} does not exist\".format(target))\n except ValueError:\n raise ValidationError(\"Invalid target specified: {}\".format(target))\n if position not in _valid_positions:\n raise ValidationError(\n \"Invalid position specified, must be one of {}\".format(\n \", \".join(_valid_positions)\n )\n )\n return target, position\n\n def move_from_changes(self, changes):\n errors = []\n changes_to_return = []\n for move in changes:\n # Move change will have key, must also have target property\n # optionally can include the desired position.\n move_error, move_change = self.move(\n move[\"key\"], target=move.get(\"target\"), position=move.get(\"position\")\n )\n if move_error:\n move.update({\"errors\": [move_error]})\n errors.append(move)\n if move_change:\n changes_to_return.append(move_change)\n return errors, changes_to_return\n\n def move(self, pk, target=None, position=None):\n try:\n contentnode = self.get_edit_queryset().get(pk=pk)\n except ContentNode.DoesNotExist:\n error = ValidationError(\"Specified node does not exist\")\n return str(error), None\n\n try:\n target, position = self.validate_targeting_args(target, position)\n try:\n contentnode.move_to(target, position)\n except ValueError:\n raise ValidationError(\n \"Invalid position argument specified: {}\".format(position)\n )\n\n return (\n None,\n None,\n )\n except ValidationError as e:\n return str(e), None\n\n def copy_from_changes(self, changes):\n errors = []\n changes_to_return = []\n for copy in changes:\n # Copy change will have key, must also have other attributes, defined in `copy`\n # Just pass as keyword arguments here to let copy do the validation\n copy_errors, copy_changes = self.copy(copy[\"key\"], **copy)\n if copy_errors:\n copy.update({\"errors\": copy_errors})\n errors.append(copy)\n if copy_changes:\n changes_to_return.extend(copy_changes)\n return errors, changes_to_return\n\n def copy(\n self,\n pk,\n from_key=None,\n target=None,\n position=None,\n mods=None,\n excluded_descendants=None,\n **kwargs\n ):\n try:\n target, position = self.validate_targeting_args(target, position)\n except ValidationError as e:\n return str(e), None\n\n try:\n source = self.get_queryset().get(pk=from_key)\n except ContentNode.DoesNotExist:\n error = ValidationError(\"Copy source node does not exist\")\n return str(error), [generate_delete_event(pk, CONTENTNODE)]\n\n # Affected channel for the copy is the target's channel\n channel_id = target.channel_id\n\n if ContentNode.objects.filter(pk=pk).exists():\n error = ValidationError(\"Copy pk already exists\")\n return str(error), None\n\n task_args = {\n \"user_id\": self.request.user.id,\n \"channel_id\": channel_id,\n \"source_id\": source.id,\n \"target_id\": target.id,\n \"pk\": pk,\n \"mods\": mods,\n \"excluded_descendants\": excluded_descendants,\n \"position\": position,\n }\n\n task, task_info = create_async_task(\n \"duplicate-nodes\", self.request.user, **task_args\n )\n\n return (\n None,\n [generate_update_event(pk, CONTENTNODE, {TASK_ID: task_info.task_id})],\n )\n","sub_path":"contentcuration/contentcuration/viewsets/contentnode.py","file_name":"contentnode.py","file_ext":"py","file_size_in_byte":27161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"124488924","text":"# -*- coding: utf-8 -*-\n#################################################\n# Source file for the ASM project #\n# #\n#################################################.\n\nfrom wrap import *\nimport math \n\nmetafor = Metafor()\ndomain = metafor.getDomain()\n\ndef getMetafor(p={}): \n return metafor\n \n###########################################\n# BEGIN OF DEFINITION OF THE PARAMETERS #\n###########################################\n\n#Remark: The units must be consistent!\n#Here, lengths in [mm] ; E in [MPa] and Mass in [Tons]\n\n#GEOMETRY:\np= {} \np['GeometryHypothesis'] = \"PLANESTRESS\" #PLANESTRESS or \"PLANESTRAIN\" ; you need to implement PLANESTRAIN yourself! \np['EdgeSize'] = 120 #Length of the cube\n#MESH: \np['Nx'] = 2 #Nb of elements in the x direction\np['Ny'] = 2 #Nb of elements in the y direction\np['Nz'] = 2 #Nb of elements in the z direction\n#TIME:\np['dT'] = 0.1 #Maximum time step \n\n###########################################\n# END OF DEFINITION OF THE PARAMETERS #\n###########################################\n\n#2.0 GEOMETRY\n#===========\ngeometry = domain.getGeometry() \ngeometry.setDim3D() \n\n#2.1 Points\n#----------\npointset = geometry.getPointSet() \n\npointset.define(1,0.,0.,0.) \npointset.define(2,p['EdgeSize'],0.,0.)\npointset.define(3,p['EdgeSize'],p['EdgeSize'],0.)\npointset.define(4,0.,p['EdgeSize'],0.)\npointset.define(5,0.,0.,p['EdgeSize'])\npointset.define(6,p['EdgeSize'],0.,p['EdgeSize'])\npointset.define(7,p['EdgeSize'],p['EdgeSize'],p['EdgeSize'])\npointset.define(8,0.,p['EdgeSize'],p['EdgeSize'])\n\n#2.2 Curves\n#-----------\ncurveset = geometry.getCurveSet() \n\ncurveset.add( Line( 1, pointset( 1), pointset(2) )) \ncurveset.add( Line( 2, pointset( 2), pointset(3) )) \ncurveset.add( Line( 3, pointset( 3), pointset(4) )) \ncurveset.add( Line( 4, pointset( 4), pointset(1) )) \ncurveset.add( Line( 5, pointset( 1), pointset(5) )) \ncurveset.add( Line( 6, pointset( 2), pointset(6) )) \ncurveset.add( Line( 7, pointset( 3), pointset(7) )) \ncurveset.add( Line( 8, pointset( 4), pointset(8) )) \ncurveset.add( Line( 9, pointset( 5), pointset(6) )) \ncurveset.add( Line( 10, pointset( 6), pointset(7) )) \ncurveset.add( Line( 11, pointset( 7), pointset(8) )) \ncurveset.add( Line( 12, pointset( 8), pointset(5) )) \n\n#2.3 Wires\n#------------\nwireset = geometry.getWireSet() \n\nwireset.add( Wire(1, [curveset(1), curveset(2), curveset(3), curveset(4)]) ) \nwireset.add( Wire(2, [curveset(9), curveset(10), curveset(11), curveset(12)]) ) \nwireset.add( Wire(3, [curveset(1), curveset(6), curveset(9), curveset(5)]) ) \nwireset.add( Wire(4, [curveset(2), curveset(7), curveset(10), curveset(6)]) ) \nwireset.add( Wire(5, [curveset(3), curveset(7), curveset(11), curveset(8)]) ) \nwireset.add( Wire(6, [curveset(4), curveset(8), curveset(12), curveset(5)]) ) \n\n#2.4 Sides\n#-------------------\nsideset = geometry.getSideSet() \n\nsideset.add( Side(1,[wireset(1)]) ) \nsideset.add( Side(2,[wireset(2)]) ) \nsideset.add( Side(3,[wireset(3)]) ) \nsideset.add( Side(4,[wireset(4)]) ) \nsideset.add( Side(5,[wireset(5)]) ) \nsideset.add( Side(6,[wireset(6)]) ) \n\n#2.5 Skins\n#-------------------\nskinset = geometry.getSkinSet()\n\nskinset.add( Skin(1,[sideset(1),sideset(2),sideset(3),sideset(4),sideset(5),sideset(6)])) \n\n#2.6 Volume\n#-------------------\nvolumeset = geometry.getVolumeSet()\n\nvolumeset.add(Volume(1,[skinset(1)])) \n\n#3. MESH\n#===========\n\n#3.1 Meshing the lines:\n#-------------------\nfor i in [1, 3, 9, 11]:\n SimpleMesher1D(curveset(i)).execute(p['Nx']) \nfor i in [2, 4, 10, 12]:\n SimpleMesher1D(curveset(i)).execute(p['Ny']) \nfor i in [5, 6, 7, 8]:\n SimpleMesher1D(curveset(i)).execute(p['Nz']) \n\n#3.2 Meshing the Sides:\n#-------------------\nfor i in range(1,7):\n TransfiniteMesher2D(sideset(i)).execute(True, 0)\n\n#3.3 Meshing the Volume:\n#-------------------\nTransfiniteMesher3D(volumeset(1)).execute(True)\n \n#4.0 MATERIALS\n#===========\n\n############################################################\n# BEGIN OF DEFINITION OF THE MATERIALS AND MATERIAL LAWS #\n############################################################\n# no restrictions on the value taken by the three following variable, except\n# that IsoHardening and KinHardening cannot be both zero\n# example: 2, 1, 0 -> mixed non-linear isotropic, linear kinematic hardening\n# example: 1, 0, 1 -> linear isotropic viscoplastic hardening\n# /!\\ pure kinematic hardening doesn't work. A yield stress law for a constant\n# :!\\ sigma_y have still to be implemented to resolve this issue\nIsoHardening = 1 # indicates the isotropic hardening law used\n # if 1: linear\n # if 2: non-linear (saturated/Voce)\n # if 0: no isotropic hardening (simga_y = sigma_y^0)\nKinHardening = 0 # indicates the kinematic hardening law used\n # if 1: linear\n # if 2: non-linear\n # if 0: no kinematic hardening (backstress = 0)\nVisco = 1 # indicates the viscoplastic law used #still to be implemented\n # if 1: Perzyna law\n # if 0: no viscosity effects\nKin_base = 2 # don't modify this!\n\nprescrDisp = 0 # Use prescribed displacement instead of load. Will cancel all loads.\n\n#MATERIAL: \nDensity = 7.85E-9 # Density\nYoung = 20.5E4 # Young's Modulus\nNu = 0.3 # Poisson ratio \nSigmaY_0=200.0 # Elastic limit of virgin material \nh = 30000.0 # Hardening parameter \ntheta_star = 0.2 # Mixed hardening parameter\nSigmaY_inf = 300 # Elastic limit at saturation\neta_k = math.sqrt(2/3) * h/SigmaY_0 # Non-linear kinematic parameter\nviscoRelaxationTime = .8 # [s] = eta / h_i\neta = h*viscoRelaxationTime # Viscoplastic parameter [MPa.s]\n\nif(IsoHardening != 0 and KinHardening != 0): # if mixed hardening\n h_i = theta_star * h\n h_k = (1 - theta_star) * h\nelif(IsoHardening == 0): # if pure kinematic hardening\n h_i = 0\n h_k = h\nelse: # if KinHardening == 0\n h_i = h\n h_k = 0\n\nmaterset = domain.getMaterialSet() \nif(KinHardening == 0):\n material1 = materset.define (1, EvpIsoHHypoMaterial) #Create material number 1 as Elasto-viscoplastic with Isotropic linear hardening \nelse:\n material1 = materset.define (1, EvpMixtHHypoMaterial)\nmaterial1.put(MASS_DENSITY, Density) #Set Material parameters (see required parameters in the documentation)\nmaterial1.put(ELASTIC_MODULUS, Young) \nmaterial1.put(POISSON_RATIO, Nu) \nif(Visco == 0):\n material1.put(YIELD_NUM, IsoHardening) #Number of the hardening law used\nif(KinHardening != 0):\n material1.put(KH_NB, 1)\n material1.put(KH_NUM1, KinHardening + Kin_base) # Number of the kinematic hardening law\nif(Visco != 0):\n material1.put(YIELD_NUM, 5) # poof, a magic number appeared :p\n\nlawset = domain.getMaterialLawSet() \n# Reference pages in the doc:\n# http://metafor.ltas.ulg.ac.be/dokuwiki/doc/user/elements/volumes/isohard\n# http://metafor.ltas.ulg.ac.be/dokuwiki/doc/user/elements/volumes/kinehard\n# http://metafor.ltas.ulg.ac.be/dokuwiki/doc/user/elements/volumes/yield_stress\n\n# No isotropic hardening for pure kinematic hardening\nlawset0 = lawset.define(0, LinearIsotropicHardening) #Create law number 1 as Linear Isotropic hardening law \nlawset0.put(IH_SIGEL, SigmaY_0) #Set law parameters (see required parameters in the documentation)\nlawset0.put(IH_H, 0)\n\n# Linear isotropic hardening\nlawset1 = lawset.define(1, LinearIsotropicHardening) #Create law number 1 as Linear Isotropic hardening law \nlawset1.put(IH_SIGEL, SigmaY_0) #Set law parameters (see required parameters in the documentation)\nlawset1.put(IH_H, h_i)\n\n# Non-linear isotropic hardening (saturated law/Voce's law)\nlawset2 = lawset.define(2, SaturatedIsotropicHardening)\nlawset2.put(IH_SIGEL, SigmaY_0)\nlawset2.put(IH_Q, SigmaY_inf - SigmaY_0)\nlawset2.put(IH_KSI, h_i/(SigmaY_inf - SigmaY_0))\n\n# Linear kinematic hardening\nlawset3 = lawset.define(3, DruckerPragerKinematicHardening)\nlawset3.put(KH_H, h_k)\n\n# Non-linear kinematic hardening\nlawset4 = lawset.define(4, ArmstrongFrederickKinematicHardening)\nlawset4.put(KH_H, h_k)\nlawset4.put(KH_B, eta_k)\n\n# Viscoplastic law ¡TODO!\nlawset5 = lawset.define(5, PerzynaYieldStress)\nlawset5.put(IH_NUM, IsoHardening)\nlawset5.put(PERZYNA_K, eta)\nlawset5.put(PERZYNA_M, 1)\nlawset5.put(PERZYNA_N, 0)\n\n\n############################################################\n# END OF DEFINITION OF THE MATERIALS AND MATERIAL LAWS #\n############################################################ \n \n#5.0 ELEMENTS\n#===========================================\n\n#5.1 Definition of element properties\n#-----------------------------------------------------------\nprp1 = ElementProperties (Volume3DElement) \nprp1.put (MATERIAL, 1) # Number of the material used \nprp1.put (CAUCHYMECHVOLINTMETH,VES_CMVIM_STD) \n\n\n#5.2 Generating elements on the mesh\n#------------------------------------------------------------\napp = FieldApplicator(1) \napp.push(volumeset(1)) \napp.addProperty(prp1) \ndomain.getInteractionSet().add(app) \n\n\n#6. BOUNDARY CONDITIONS\n#============ \n\nloadingset = domain.getLoadingSet() \n\nif p['GeometryHypothesis']==\"PLANESTRESS\":\n loadingset.define(sideset(1),Field1D(TZ,RE),0.) \n loadingset.define(sideset(3),Field1D(TY,RE),0.) \n loadingset.define(sideset(6),Field1D(TX,RE),0.) \n \nelif p['GeometryHypothesis']==\"PLANESTRAIN\":\n loadingset.define(sideset(1),Field1D(TZ,RE),0.) \n loadingset.define(sideset(2),Field1D(TZ,RE),0.) \n loadingset.define(sideset(3),Field1D(TY,RE),0.) \n loadingset.define(sideset(6),Field1D(TX,RE),0.)\n ###################################################################\n # IMPLEMENT BOUNDARY CONDITION TO OBTAIN PLANE STRAIN STATE HERE #\n ###################################################################\n # => what I've done *should* be ok\n \n\n \n#7. LOADS\n#=============\n# 7.1 Definition of the loading function\n#-------------------------------------------------\n\n#LOAD: \nTrac = 305. #Traction\nNcycle = 5 #Number of cycles of loading/unloading\nTcycle = 4. #Duration of one cycle\n\nuMax = 0.5 #Max prescribed displacement \n\nfct = PieceWiseLinearFunction()\nwhichFunction = \"visco2\"\n# whichFunction = \"reverse\"\n# whichFunction = \"visco1\"\n# whichFunction = \"visco2\"\nif whichFunction == \"normal\":\n for i in range (0,Ncycle):\n fct.setData(i*Tcycle+0.,0.) #POINT n°1\n fct.setData(i*Tcycle+Tcycle/4.0,1.0)#POINT n°2\n fct.setData(i*Tcycle+Tcycle*2.0/4.0,0.0)#POINT n°3\n fct.setData(i*Tcycle+Tcycle*3.0/4.0,-1.0)#POINT n°4\n fct.setData(i*Tcycle+Tcycle*4.0/4.0,0.0)#POINT n°5 \nelif whichFunction == \"reverse\": # t = -t(t)\n for i in range (0,Ncycle):\n fct.setData(i*Tcycle+0.,0.) #POINT n°1\n fct.setData(i*Tcycle+Tcycle/4.0,-1.0)#POINT n°2\n fct.setData(i*Tcycle+Tcycle*2.0/4.0,0.0)#POINT n°3\n fct.setData(i*Tcycle+Tcycle*3.0/4.0,1.0)#POINT n°4\n fct.setData(i*Tcycle+Tcycle*4.0/4.0,0.0)#POINT n°5 \nelif whichFunction == \"visco1\": # kept at a non-zero value after one cycle\n staticLoadFraction = 1 # = staticLoad / Trac\n fct.setData(0.,0.) #POINT n°1\n fct.setData(Tcycle/4.0,1.0)#POINT n°2\n fct.setData(Tcycle*2.0/4.0,0.0)#POINT n°3\n fct.setData(Tcycle*3.0/4.0,-1.0)#POINT n°4\n fct.setData(Tcycle*4.0/4.0,0.0)#POINT n°5 \n fct.setData(Tcycle*5.0/4.0,staticLoadFraction)#POINT n°6 \n fct.setData(Tcycle*10.0,staticLoadFraction)#POINT n°7 \nelif whichFunction == \"visco2\":\n # smoothen sawtooth: /¯\\_ _\n # \\_/\n RelaxFractionTime = 1/4\n for i in range (0,Ncycle):\n fct.setData(i*Tcycle*(1+4*RelaxFractionTime)+0.,0.) #POINT n°1\n fct.setData(i*Tcycle*(1+4*RelaxFractionTime)+Tcycle/4.,1.) #POINT n°2\n fct.setData(i*Tcycle*(1+4*RelaxFractionTime)+Tcycle*(1./4.+RelaxFractionTime),1.) #POINT n°3\n fct.setData(i*Tcycle*(1+4*RelaxFractionTime)+Tcycle*(2./4.+RelaxFractionTime),0.) #POINT n°4\n fct.setData(i*Tcycle*(1+4*RelaxFractionTime)+Tcycle*(2./4.+2*RelaxFractionTime),0.) #POINT n°5\n fct.setData(i*Tcycle*(1+4*RelaxFractionTime)+Tcycle*(3./4.+2*RelaxFractionTime),-1.) #POINT n°6\n fct.setData(i*Tcycle*(1+4*RelaxFractionTime)+Tcycle*(3./4.+3*RelaxFractionTime),-1.) #POINT n°7\n fct.setData(i*Tcycle*(1+4*RelaxFractionTime)+Tcycle*(1+3*RelaxFractionTime),0.) #POINT n°8\n fct.setData(i*Tcycle*(1+4*RelaxFractionTime)+Tcycle*(1+4*RelaxFractionTime),0.) #POINT n°9 \n\n#########################################\n# IMPLEMENT A DIFFERENT LOADING FCT HERE#\n#########################################\nif prescrDisp == 1:\n Trac = 0.\n loadingset.define(sideset(4), Field1D(TX,RE), uMax, fct, INCREMENTAL_LOAD)\n \nprp2 = ElementProperties (Traction3DElement) \nprp2.put(PRESSURE, Trac) \nprp2.depend (PRESSURE, fct, Field1D(TM,RE)) # To apply your new function, you can put it instead of \"fct\" here\n\n \n#7.3 Generating the pressure element on the mesh\n#---------------------------------------------------------------------\ntrac = LoadingInteraction(2) \ntrac.push(sideset(4)) \ntrac.addProperty(prp2) \ndomain.getInteractionSet().add(trac) \n\n#8. Integration Scheme\n#========================\n\n#8.1 Gestion des pas de temps\n#-----------------------------\ntsm = metafor.getTimeStepManager() \ntsm.setInitialTime(0.0, p['dT']) \ntsm.setNextTime(Ncycle*Tcycle, int(Ncycle*Tcycle), p['dT']) \n \n#9. Archiving\n#============\nnode_id = 7\n\nvaluesmanager = metafor.getValuesManager() #Access Values Manager\n\nvaluesmanager.add(1, MiscValueExtractor(metafor,EXT_T),'time') \n\nvaluesmanager.add(15, IFNodalValueExtractor(pointset(node_id), IF_SIG_XY),'Sigma_XY' )\nvaluesmanager.add(16, IFNodalValueExtractor(pointset(node_id), IF_SIG_XZ),'Sigma_XZ' )\nvaluesmanager.add(17, IFNodalValueExtractor(pointset(node_id), IF_SIG_YZ),'Sigma_YZ' ) #Archive the time(EXT_T) in a \"time.ascii\" file\n\n#Stress\nvaluesmanager.add(2, IFNodalValueExtractor(pointset(node_id), IF_SIG_XX),'Sigma_XX' )\nvaluesmanager.add(3, IFNodalValueExtractor(pointset(node_id), IF_SIG_YY),'Sigma_YY' )\nvaluesmanager.add(4, IFNodalValueExtractor(pointset(node_id), IF_SIG_ZZ),'Sigma_ZZ' )\nvaluesmanager.add(5, IFNodalValueExtractor(pointset(node_id), IF_EVMS),'SigmaVM' )\nvaluesmanager.add(6, IFNodalValueExtractor(pointset(node_id), IF_YIELD_STRESS),'Sigma_Yield' )\n\n#Strain\nvaluesmanager.add(7, IFNodalValueExtractor(pointset(node_id), IF_EPL),'EPL' )\nvaluesmanager.add(8, IFNodalValueExtractor(pointset(node_id), IF_NAT_STRAIN_XX),'E_XX' )\nvaluesmanager.add(9, IFNodalValueExtractor(pointset(node_id), IF_NAT_STRAIN_YY),'E_YY' )\nvaluesmanager.add(10, IFNodalValueExtractor(pointset(node_id), IF_NAT_STRAIN_ZZ),'E_ZZ' )\nvaluesmanager.add(21, IFNodalValueExtractor(pointset(node_id), IF_NAT_STRAIN_XY),'E_XY' )\nvaluesmanager.add(22, IFNodalValueExtractor(pointset(node_id), IF_NAT_STRAIN_XZ),'E_XZ' )\nvaluesmanager.add(23, IFNodalValueExtractor(pointset(node_id), IF_NAT_STRAIN_YZ),'E_YZ' )\nvaluesmanager.add(24, IFNodalValueExtractor(pointset(node_id), IF_DEPL),'DEPL' )\n#Backstress\nvaluesmanager.add(11, IFNodalValueExtractor(pointset(node_id), IF_ALP_XX),'A_XX' )\nvaluesmanager.add(12, IFNodalValueExtractor(pointset(node_id), IF_ALP_YY),'A_YY' )\nvaluesmanager.add(13, IFNodalValueExtractor(pointset(node_id), IF_ALP_ZZ),'A_ZZ' )\nvaluesmanager.add(18, IFNodalValueExtractor(pointset(node_id), IF_ALP_XY),'A_XY' )\nvaluesmanager.add(19, IFNodalValueExtractor(pointset(node_id), IF_ALP_XZ),'A_XZ' )\nvaluesmanager.add(20, IFNodalValueExtractor(pointset(node_id), IF_ALP_YZ),'A_YZ' )\n\n#Hydrorpessure\nvaluesmanager.add(14, IFNodalValueExtractor(pointset(node_id), IF_P),'IF_P' )\n\n#10. Visualisation of curves in real time (not necessary but useful)\n#=====================================================\n\n#Stress\ndataCurveSX = VectorDataCurve(1, valuesmanager.getDataVector(1), valuesmanager.getDataVector(2),'Sigma_XX')\ndataCurveSY = VectorDataCurve(2, valuesmanager.getDataVector(1), valuesmanager.getDataVector(3),'Sigma_YY')\ndataCurveSZ = VectorDataCurve(3, valuesmanager.getDataVector(1), valuesmanager.getDataVector(4),'Sigma_ZZ')\ndataCurveSVM = VectorDataCurve(4, valuesmanager.getDataVector(1), valuesmanager.getDataVector(5),'Sigma_VM')\ndataCurveSYield = VectorDataCurve(5, valuesmanager.getDataVector(1), valuesmanager.getDataVector(6),'Sigma_Yield')\n\ndataCurveSXY = VectorDataCurve(13, valuesmanager.getDataVector(1), valuesmanager.getDataVector(15),'Sigma_XY')\ndataCurveSXZ = VectorDataCurve(14, valuesmanager.getDataVector(1), valuesmanager.getDataVector(16),'Sigma_XZ')\ndataCurveSYZ = VectorDataCurve(15, valuesmanager.getDataVector(1), valuesmanager.getDataVector(17),'Sigma_YZ')\n\ndataCurveSet2 = DataCurveSet()\ndataCurveSet2.add(dataCurveSX)\ndataCurveSet2.add(dataCurveSY)\ndataCurveSet2.add(dataCurveSZ)\ndataCurveSet2.add(dataCurveSVM)\ndataCurveSet2.add(dataCurveSYield)\n\n\n# dataCurveSet2.add(dataCurveSXY)\n# dataCurveSet2.add(dataCurveSXZ)\n# dataCurveSet2.add(dataCurveSYZ)\n\n\nwinc2 = VizWin()\nwinc2.add(dataCurveSet2)\nmetafor.addObserver(winc2)\n\n#Strain\ndataCurveDEPL = VectorDataCurve(6, valuesmanager.getDataVector(1), valuesmanager.getDataVector(7),'E_PL')\ndataCurveDX = VectorDataCurve(7, valuesmanager.getDataVector(1), valuesmanager.getDataVector(8),'E_XX')\ndataCurveDY = VectorDataCurve(8, valuesmanager.getDataVector(1), valuesmanager.getDataVector(9),'E_YY')\ndataCurveDZ = VectorDataCurve(9, valuesmanager.getDataVector(1), valuesmanager.getDataVector(10),'E_ZZ')\ndataCurveDXY = VectorDataCurve(19, valuesmanager.getDataVector(1), valuesmanager.getDataVector(21),'E_XY')\ndataCurveDXZ = VectorDataCurve(20, valuesmanager.getDataVector(1), valuesmanager.getDataVector(22),'E_XZ')\ndataCurveDYZ = VectorDataCurve(21, valuesmanager.getDataVector(1), valuesmanager.getDataVector(23),'E_YZ')\ndataCurveDDEPL = VectorDataCurve(22, valuesmanager.getDataVector(1), valuesmanager.getDataVector(24),'DE_PL')\n\ndataCurveSet3 = DataCurveSet()\ndataCurveSet3.add(dataCurveDX)\ndataCurveSet3.add(dataCurveDY)\ndataCurveSet3.add(dataCurveDZ)\ndataCurveSet3.add(dataCurveDEPL)\ndataCurveSet3.add(dataCurveDDEPL)\nwinc3 = VizWin()\nwinc3.add(dataCurveSet3)\nmetafor.addObserver(winc3)\n\n#Backstress\ndataCurveAX = VectorDataCurve(10, valuesmanager.getDataVector(1), valuesmanager.getDataVector(11),'A_XX')\ndataCurveAY = VectorDataCurve(11, valuesmanager.getDataVector(1), valuesmanager.getDataVector(12),'A_YY')\ndataCurveAZ = VectorDataCurve(12, valuesmanager.getDataVector(1), valuesmanager.getDataVector(13),'A_ZZ')\ndataCurveAXY = VectorDataCurve(16, valuesmanager.getDataVector(1), valuesmanager.getDataVector(18),'A_XY')\ndataCurveAXZ = VectorDataCurve(17, valuesmanager.getDataVector(1), valuesmanager.getDataVector(19),'A_XZ')\ndataCurveAYZ = VectorDataCurve(18, valuesmanager.getDataVector(1), valuesmanager.getDataVector(20),'A_YZ')\n\n\ndataCurveSet4 = DataCurveSet()\ndataCurveSet4.add(dataCurveAX)\ndataCurveSet4.add(dataCurveAY)\ndataCurveSet4.add(dataCurveAZ)\n# dataCurveSet4.add(dataCurveAXY)\n# dataCurveSet4.add(dataCurveAXZ)\n# dataCurveSet4.add(dataCurveAYZ)\nwinc4 = VizWin()\nwinc4.add(dataCurveSet4)\nmetafor.addObserver(winc4)\n\n# Hydropressure\ndataCurveP = VectorDataCurve(13, valuesmanager.getDataVector(1), valuesmanager.getDataVector(14),'IF_P')\ndataCurveSet5 = DataCurveSet()\ndataCurveSet5.add(dataCurveP)\nwinc5 = VizWin()\nwinc5.add(dataCurveSet5)\nmetafor.addObserver(winc5)\n\n","sub_path":"CubeSurfaceTraction.py","file_name":"CubeSurfaceTraction.py","file_ext":"py","file_size_in_byte":20988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"608217615","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.optimizers import Adam\nfrom keras.utils import np_utils\nfrom numpy import around\n\n# numers: 0,1,2,3,4,5,6,7,8,9\nno_classes = 10\n\nmnist = tf.keras.datasets.mnist\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nplt.imshow(x_test[1], cmap='gray')\nplt.title(y_test[1])\n\nno_inputs = x_train.shape[1] * x_train.shape[2]\n\nx_train = x_train.reshape(len(x_train), no_inputs)\nx_test = x_test.reshape(len(x_test), no_inputs)\n\n# normalize data to be between 0 and 1\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\ny_train = np_utils.to_categorical(y_train, no_classes)\ny_test = np_utils.to_categorical(y_test, no_classes)\n\nmodel = Sequential()\nmodel.add(Dense(no_inputs, input_dim=no_inputs, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(10, activation='softmax'))\nmodel.compile(Adam(lr=0.05), 'categorical_crossentropy', metrics=['accuracy'])\n\nhistory = model.fit(x_train, y_train, epochs=4, validation_split=0.2)\n\nrs = model.predict(np.array([x_test[1]]))\n\n# because result is float32 so we are rounding each array cell to 0 or 1\naround(rs, 2)\n\nprint(y_test[1])\n\ny_pred = model.predict(x_test)\n\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix(y_test.argmax(axis=1), y_pred.argmax(axis=1))\n\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"490822808","text":"from scrapy import Spider, Request\nfrom advisor_reviews.items import AdvisorReviewsItem\nfrom advisor_reviews.activities import DATA\n\n\nclass Advisor(Spider):\n name = \"advisor\"\n start_urls = [(item[\"review_url\"], item[\"title\"]) for item in DATA]\n\n def start_requests(self):\n for url in self.start_urls:\n yield Request(url[0] % ('Attraction_Review', 'Reviews'), self.request_review_user, meta={\"url\": url})\n\n def request_review_user(self, response):\n reviews_ids = response.xpath('//div[@class=\"reviewSelector\"]/@data-reviewid').extract()\n if reviews_ids.__len__() != 0:\n url = response.meta['url']\n yield Request(url[0] % ('ShowUserReviews', 'r' + reviews_ids[0]), self.parse, meta={\"url\": url})\n\n def parse(self, response):\n review_contents = response.xpath('//div[@class=\"reviewSelector\"]')\n for review_content in review_contents:\n review_item = AdvisorReviewsItem()\n review_item[\"title\"] = response.meta[\"url\"][1]\n user_scrname = review_content.xpath('.//span[@class=\"expand_inline scrname\"]/text()').extract_first()\n review_item[\"user_scrname\"] = user_scrname if user_scrname is not None else \"\"\n user_location = review_content.xpath('.//span[@class=\"expand_inline userLocation\"]/text()').extract_first()\n review_item[\"user_location\"] = user_location if user_location is not None else \"\"\n user_contribution = review_content.xpath('.//div[@class=\"memberBadgingNoText\"]//*[@class=\"badgetext\"][1]/text()').extract_first()\n review_item[\"user_contribution\"] = user_contribution if user_contribution is not None else \"\"\n user_helpful_vote = review_content.xpath('.//div[@class=\"memberBadgingNoText\"]//*[@class=\"badgetext\"][2]/text()').extract_first()\n review_item[\"user_helpful_vote\"] = user_helpful_vote if user_helpful_vote is not None else \"\"\n rating_date = review_content.xpath('.//*[@class=\"ratingDate relativeDate\"]/@title').extract_first()\n review_item[\"rating_date\"] = rating_date if rating_date is not None else \"\"\n rating_via = review_content.xpath('.//*[@class=\"viaMobile\"]/text()').extract_first()\n review_item[\"rating_via\"] = rating_via if rating_via is not None else \"\"\n quote = review_content.xpath('.//*[@class=\"noQuotes\"]/text()').extract_first()\n review_item[\"quote\"] = quote if quote is not None else \"\"\n partial_entry = review_content.xpath('.//*[@class=\"partial_entry\"]/text()').extract_first()\n review_item[\"partial_entry\"] = partial_entry if partial_entry is not None else \"\"\n yield review_item\n\n next_url = response.xpath('//*[@class=\"nav next taLnk \"]/@href').extract_first()\n if next_url is not None:\n yield Request(\"http://www.tripadvisor.co.uk\" + next_url, self.parse, meta={\"url\": response.meta[\"url\"]})\n","sub_path":"advisor_reviews/advisor_reviews/spiders/advisor.py","file_name":"advisor.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"57491772","text":"class Heap:\n def __init__(self):\n self.storage = []\n\n def get_parent_index(self, index):\n return (index - 1) // 2\n\n def insert(self, value):\n self.storage.append(value)\n current_index = len(self.storage) - 1\n self._bubble_up(current_index)\n\n def delete(self):\n deleted_value = self.storage.pop(0)\n self._sift_down(0)\n return deleted_value\n\n def get_max(self):\n if self.get_size() is 0:\n return None\n return self.storage[0]\n\n def get_size(self):\n return len(self.storage)\n\n def _bubble_up(self, index):\n parent_index = self.get_parent_index(index)\n parent_value = self.storage[parent_index]\n current_value = self.storage[index]\n if index is not 0 and parent_value < current_value:\n self.storage[index], self.storage[parent_index] = \\\n self.storage[parent_index], self.storage[index]\n if parent_index is not 0:\n self._bubble_up(parent_index)\n\n def _sift_down(self, index):\n size = self.get_size()\n first_child_index = (2 * index) + 1\n second_child_index = (2 * index) + 2\n # if parent has any child (first_child_index would exist)\n if first_child_index < size:\n parent_value = self.storage[index]\n first_child_value = self.storage[first_child_index]\n # if parent has 2 children\n if second_child_index < size:\n second_child_value = self.storage[second_child_index]\n if first_child_value >= second_child_value:\n if parent_value < first_child_value:\n self.storage[index], self.storage[first_child_index] = \\\n first_child_value, parent_value\n elif parent_value < second_child_value:\n self.storage[index], self.storage[second_child_index] = \\\n second_child_value, parent_value\n self._sift_down(index + 1)\n # else parent has only 1 child\n else:\n if parent_value < first_child_value:\n self.storage[index], self.storage[first_child_index] = \\\n first_child_value, parent_value\n self._sift_down(index + 1)\n","sub_path":"heap/heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"227556509","text":"\"\"\"URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.conf.urls import url, include\r\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.conf.urls import url\r\nfrom django.contrib import admin\r\nfrom . import views\r\nfrom .api import views as api_views\r\n\r\napp_name = 'content'\r\nurlpatterns = [\r\n\r\n url(\r\n regex=r'^api/c/$',\r\n view=api_views.ContentListAPIView.as_view(),\r\n ),\r\n url(\r\n regex=r'^api/c/(?P[-\\w]+)/$',\r\n view=api_views.ContentRetrieveAPIView.as_view(),\r\n ),\r\n\r\n url(\r\n regex=r'^api/e/$',\r\n view=api_views.EventListAPIView.as_view(),\r\n ),\r\n\r\n url(\r\n regex=r'^api/v/$',\r\n view=api_views.VentureListAPIView.as_view(),\r\n ),\r\n\r\n url(\r\n regex=r'^api/v/(?P[\\w\\-]+)/services/$',\r\n view=api_views.ServiceListCreateAPIView.as_view(),\r\n ),\r\n\r\n url(\r\n regex=r'^api/v/(?P[\\w\\-]+)/services/(?P[\\w\\-]+)/$',\r\n view=api_views.ServiceRetrieveUpdateDestroyAPIView.as_view(),\r\n ),\r\n\r\n # url(\r\n # regex=r'^api/s/$',\r\n # view=api_views.ServiceListCreateAPIView.as_view(),\r\n # ),\r\n\r\n url(\r\n regex=r'^api/message/$',\r\n view=api_views.MessageListCreateAPIView.as_view(),\r\n ),\r\n\r\n url(\r\n regex=r'^api/(?P[\\w\\-]+)/(?P[\\w\\-]+)/like/$',\r\n view=api_views.like,\r\n ),\r\n\r\n url(r'^c/new/$', views.share_content),\r\n url(r'^c/new-with-slug/(?P[\\w\\-]+)/$', views.new_with_slug),\r\n url(r'^c/new/(?P[\\w\\-]+)/$', views.new_content),\r\n url(r'^c/([\\w\\-]+)/edit/$', views.edit_content),\r\n url(r'^c/([\\w\\-]+)/delete/$', views.delete_content),\r\n url(r'^c/([\\w\\-]+)/$', views.detail_content),\r\n url(r'^c/([\\w\\-]+)/like/(\\d+)/$', views.like_comment),\r\n\r\n url(r'^v/new/$', views.new_venture),\r\n url(r'^v/new-resource/$', views.new_resource),\r\n url(r'^v/([\\w\\-]+)/edit/$', views.edit_venture),\r\n url(r'^v/([\\w\\-]+)/delete/$', views.delete_venture),\r\n url(r'^v/([\\w\\-]+)/$', views.detail_venture),\r\n url(r'^v/([\\w\\-]+)/services/$', views.services),\r\n url(r'^v/$', views.ventures),\r\n\r\n url(r'^e/share/$', views.share_event),\r\n url(r'^e/new/$', views.new_event),\r\n url(r'^e/([\\w\\-]+)/edit/$', views.edit_event),\r\n url(r'^e/([\\w\\-]+)/delete/$', views.delete_event),\r\n url(r'^e/([\\w\\-]+)/$', views.detail_event),\r\n url(r'^e/$', views.events),\r\n\r\n url(r'^h/$', views.history),\r\n url(r'^r/$', views.resources),\r\n url(r'^r/(\\d+)/$', views.resource_list),\r\n]\r\n","sub_path":"wecan/content/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"513257236","text":"# A dictionary of movie critics and their ratings of a small\r\n# set of movies\r\ncritics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,\r\n 'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5, \r\n 'The Night Listener': 3.0},\r\n'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5, \r\n 'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0, \r\n 'You, Me and Dupree': 3.5}, \r\n'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,\r\n 'Superman Returns': 3.5, 'The Night Listener': 4.0},\r\n'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,\r\n 'The Night Listener': 4.5, 'Superman Returns': 4.0,\r\n 'You, Me and Dupree': 2.5},\r\n'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,\r\n 'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,\r\n 'You, Me and Dupree': 2.0},\r\n'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,\r\n 'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},\r\n'Toby': {'Snakes on a Plane':4.5,'You, Me and Dupree':1.0,'Superman Returns':4.0}}\r\n\r\nfrom math import sqrt\r\n\r\n# person1\u001B$B$H\u001B(Bperson2\u001B$B$N5wN%$r4p$K$7$?N`;w@-%9%3%\"$rJV$9\u001B(B\r\ndef sim_distance(prefs,person1,person2):\r\n # \u001B$BFs?M$H$bI>2A$7$F$$$k%\"%$%F%`$N%j%9%H$rF@$k\u001B(B\r\n si={}\r\n for item in prefs[person1]:\r\n if item in prefs[person2]:\r\n si[item]=1\r\n\r\n # \u001B$BN>2A$7$F$$$k$b$N$,0l$D$b$J$1$l$P\u001B(B0\u001B$B$rJV$9\u001B(B\r\n if len(si) == 0: return 0\r\n\r\n # \u001B$B$9$Y$F$N:9$NJ?J}$rB-$79g$o$;$k\u001B(B\r\n sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)\r\n for item in si])\r\n return 1/(1+sqrt(sum_of_squares))\r\n\r\n# p1\u001B$B$H\u001B(Bp2\u001B$B$N%T%\"%=%sAj4X78?t$rJV$9\u001B(B\r\ndef sim_pearson(prefs,p1,p2):\r\n # \u001B$BN>2A$7$F$$$k%\"%$%F%`$N%j%9%H$r2A$7$F$$$k%\"%$%F%`$,$J$1$l$P\u001B(B0\u001B$B$rJV$9\u001B(B\r\n if n==0: return 0\r\n\r\n # \u001B$B$9$Y$F$NSO9%$r9g7W$9$k\u001B(B\r\n sum1 = sum([prefs[p1][it] for it in si])\r\n sum2 = sum([prefs[p2][it] for it in si])\r\n\r\n # \u001B$BJ?J}$r9g7W$9$k\u001B(B\r\n sum1Sq = sum([pow(prefs[p1][it],2) for it in si])\r\n sum2Sq = sum([pow(prefs[p2][it],2) for it in si])\r\n\r\n # \u001B$B@Q$r9g7W$9$k\u001B(B\r\n pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si])\r\n\r\n # \u001B$B%T%\"%=%s$K$h$k%9%3%\"$r7W;;$9$k\u001B(B\r\n num=pSum-(sum1*sum2/n)\r\n den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n))\r\n if den==0: return 0\r\n\r\n r=num/den\r\n\r\n return r\r\n\r\n# \u001B$B%G%#%/%7%g%J%j\u001B(Bpref\u001B$B$+$i\u001B(Bperson\u001B$B$K$b$C$H$b%^%C%A$9$k$b$N$?$A$rJV$9\u001B(B\r\n# \u001B$B7k2L$N?t$HN`;w@-4X?t$O%*%W%7%g%s$N%Q%i%a!<%?\u001B(B\r\ndef topMatches(prefs,person,n=5,similarity=sim_pearson):\r\n scores=[(similarity(prefs,person,other),other)\r\n for other in prefs if other!=person]\r\n # \u001B$B9b%9%3%\"$,%j%9%H$N:G=i$KMh$k$h$&$KJB$SBX$($k\u001B(B\r\n scores.sort()\r\n scores.reverse()\r\n return scores[0:n]\r\n\r\n\r\n# person\u001B$B0J30$NA4%f!<%6!<$NI>E@$N=E$_IU$-J?6Q$r;H$$!\"\u001B(Bperson\u001B$B$X$N?dA&$r;;=P$9$k\u001B(B\r\ndef getRecommendations(prefs,person,similarity=sim_pearson):\r\n totals={}\r\n simSums={}\r\n for other in prefs:\r\n # \u001B$B<+J,<+?H$HHf3S$7$J$$\u001B(B\r\n if other==person: continue\r\n sim=similarity(prefs,person,other)\r\n\r\n # 0 \u001B$B0J2<$N%9%3%\"$OL5;k$9$k\u001B(B\r\n if sim<=0: continue\r\n\r\n for item in prefs[other]:\r\n # \u001B$B$^$@8+$F$$$J$$1G2h$NF@E@$N$_$r;;=P\u001B(B\r\n if item not in prefs[person] or prefs[person][item]==0:\r\n # \u001B$BN`;wEY\u001B(B * \u001B$B%9%3%\"\u001B(B\r\n totals.setdefault(item,0)\r\n totals[item]+=prefs[other][item]*sim\r\n # \u001B$BN`;wEY$r9g7W\u001B(B\r\n simSums.setdefault(item,0)\r\n simSums[item]+=sim\r\n\r\n # \u001B$B@55,2=$7$?%j%9%H$r:n$k\u001B(B\r\n rankings=[(total/simSums[item],item) for item, total in totals.items()]\r\n\r\n # \u001B$B%=!<%H:Q$_$N%j%9%H$rJV$9\u001B(B\r\n rankings.sort()\r\n rankings.reverse()\r\n return rankings\r\n\r\ndef transformPrefs(prefs):\r\n result={}\r\n for person in prefs:\r\n for item in prefs[person]:\r\n result.setdefault(item,{})\r\n # item\u001B$B$H\u001B(Bperson\u001B$B$rF~$lBX$($k\u001B(B\r\n result[item][person]=prefs[person][item]\r\n return result\r\n\r\n\r\n","sub_path":"chapter2/recommendations.py","file_name":"recommendations.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"515005808","text":"#!/usr/bin/python3\n\nimport socket\n\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nhost = socket.gethostname()\n\nport = 9999\n\nserver_socket.bind((host, port))\n\nserver_socket.listen(5)\n\nwhile True:\n client_socket, addr = server_socket.accept()\n\n print(\"Got a connection from %s\" % str(addr))\n\n msg = 'Thank' + \"\\r\\n\"\n client_socket.send(msg.encode('ascii'))\n client_socket.close()","sub_path":"PythonScripts/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"435646423","text":"import numpy as np\nimport matplotlib.pyplot as plt #for displaying data\nimport pandas as pd #to manage dataframe\nimport struct\nimport pylab\nimport scipy.fftpack\n\n\nf = open(\"block.log\", \"rb\")\ni = 0\nadc_1 = []\nadc_2 = []\ntime = []\n\n\n#np.dtype([('f1', np.int16), ('f2', np.int16)])\ntest = np.fromfile(\"block.log\", dtype=([('f1', '2h', f.read(2))\n #adc_1 = struct.unpack('>2h', f.read(4))\n #adc_2 = struct.unpack('>2h', f.read(4))\n \n #adc_1[i], adc_2[i] = f.read(2)#struct.unpack(\">2h2h\", f)\n #adc_1.insert(i, int.from_bytes((f.read(2), 'big')))\n #adc_1,adc_2 = np.fromfile(\"stream.log\", dtype=[('\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom webtest import TestApp\nfrom designate.openstack.common import log as logging\nfrom designate.api import v2 as api_v2\nfrom designate.api import middleware\nfrom designate.tests.test_api import ApiTestCase\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass ApiV2TestCase(ApiTestCase):\n def setUp(self):\n super(ApiV2TestCase, self).setUp()\n\n # Ensure the v2 API is enabled\n self.config(enable_api_v2=True, group='service:api')\n\n # Create the application\n self.app = api_v2.factory({})\n\n # Inject the FaultWrapper middleware\n self.app = middleware.FaultWrapperMiddleware(self.app)\n\n # Inject the TestContext middleware\n self.app = middleware.TestContextMiddleware(\n self.app, self.admin_context.tenant_id,\n self.admin_context.tenant_id)\n\n # Obtain a test client\n self.client = TestApp(self.app)\n\n # Create and start an instance of the central service\n self.central_service = self.start_service('central')\n\n def tearDown(self):\n self.app = None\n self.client = None\n\n super(ApiV2TestCase, self).tearDown()\n\n def _assert_paging(self, data, url, key=None, limit=5, sort_dir='asc',\n sort_key='created_at', marker=None, status=200):\n def _page(marker=None):\n params = {'limit': limit,\n 'sort_dir': sort_dir,\n 'sort_key': sort_key}\n\n if marker is not None:\n params['marker'] = marker\n\n r = self.client.get(url, params, status=status)\n if status != 200:\n return r\n else:\n return r.json[key] if key in r.json else r.json\n\n page_items = _page(marker=marker)\n if status != 200:\n return page_items\n\n x = 0\n length = len(data)\n for i in xrange(0, length):\n assert data[i]['id'] == page_items[x]['id']\n\n x += 1\n # Don't bother getting a new page if we're at the last item\n if x == len(page_items) and i != length - 1:\n x = 0\n page_items = _page(page_items[-1:][0]['id'])\n\n _page(marker=page_items[-1:][0]['id'])\n","sub_path":"designate/tests/test_api/test_v2/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"395490166","text":"\"\"\" Ejercicio 5.\nCrear Una Lista Con El Contenido De Esta Tabla:\nACCIÓN AVENTURA DEPORTES\nGTA ASSINS FIFA 21\nCOD CRASH PRO 21\nPUGB Prince Of Persia MOTO GP 21 \n\nMostrar Esta Información Ordenada \"\"\"\n\ntabla = [\n {\n \"categoria\": \"ACCIÓN\",\n \"juegos\": ['GTA', 'CALL OF DUTY', 'PUGB']\n },\n {\n \"categoria\": \"AVENTURA\",\n \"juegos\": ['ASSASINS', 'CRASH BANDICOOT', 'PRINCE OF PERSIA']\n },\n {\n \"categoria\": \"DEPORTES\",\n \"juegos\": ['FIFA 21', 'PRO 21', 'MOTO GP 21']\n }\n]\n\nfor categoriaPrincipal in tabla:\n print(f'---------------- {categoriaPrincipal[\"categoria\"]} ------------------')\n for juego in categoriaPrincipal[\"juegos\"]:\n print(juego)","sub_path":"17-Ejercicios/04-MasterPython/05-Ejercicio.py","file_name":"05-Ejercicio.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"232424657","text":"# Import numpy package\nimport numpy as np\n\n# baseball is available as a regular list of lists\nb = np.array([[74, 72, 72, 73, 69, 69, 71, 76, 71], [215, 210, 210, 188, 176, 209, 200, 231, 180]])\n\n# Create np_baseball (2 cols)\nnp_baseball = b.transpose()\n\n# Create numpy array: conversion\nconversion = [0.0254, 0.453592]\n\n# Print out product of np_baseball and conversion\nprint(np_baseball * conversion)","sub_path":"Chapter4-1-Numpy/2DArithmetic.py","file_name":"2DArithmetic.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"468657764","text":"# Import python modules\nimport os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\ncurr_path = os.getcwd()\nos.chdir('../../../')\nsys.path.append(os.getcwd())\nos.chdir(curr_path)\n\n# Import local modules\nfrom static_classes.astro_helpers import AstroHelpers\n\n#%%\n'''\nMethod to plot the density weighted mean velocity map.\n'''\ndef plot_mean_velocity(self,which,xL=False,CB=False):\n \n # Set aperture size\n if which != '2deg' and which != '2deg_NN':\n radius = self.r30\n else:\n radius = None\n \n # Get unmasked minimu/maximum\n vmin = np.nanmin([np.nanmin(self.mom1Maps['2deg']),np.nanmin(self.mom1Maps['2deg_NN'])])\n vmax = np.nanmax([np.nanmax(self.mom1Maps['2deg']),np.nanmax(self.mom1Maps['2deg_NN'])])\n \n \n # Get the median density value for colorbar\n half = (vmax-vmin)/2.0 + vmin\n \n # Set axis linewidths\n mpl.rcParams['axes.linewidth'] = 3\n\n # Plot mom1 'which' mask with origin at the bottom\n if radius != None:\n ax = plt.imshow(AstroHelpers.circle(self.mom1Maps[which],radius), origin='lower', vmin=vmin, vmax=vmax)\n else:\n ax = plt.imshow(self.mom1Maps[which],origin='lower',vmin=vmin,vmax=vmax)\n \n # Set box to have fixed dimensions\n plt.gca().set_aspect('equal', adjustable='box')\n \n # No y label or y ticks necessary\n plt.ylabel('')\n plt.yticks(self.yticks,['' for i in range(len(self.yticks))])\n \n # Create circular aperture object\n #circle = plt.Circle(self.center,radius=radius,color='k',fill=False,linewidth=3)\n \n # Add aperture object to plot\n #plt.gcf().gca().add_artist(circle)\n \n # If necessary set x axis label\n if xL == True:\n \n plt.xticks(self.xticks,self.xlabels,fontsize=self.fontsize)\n \n # Set labels for latitudinal axis\n if self.los.lower() == 'z':\n plt.xlabel('X [$^{\\circ}$]',fontsize=self.fontsize)\n \n elif self.los.lower() == 'y':\n plt.xlabel('Z [$^{\\circ}$]',fontsize=self.fontsize)\n \n elif self.los.lower() == 'x':\n plt.xlabel('Y [$^{\\circ}$]',fontsize=self.fontsize)\n else:\n \n plt.xticks(self.xticks,['' for i in range(len(self.xticks))])\n\n #If necessary add colorbar\n if CB == True:\n \n # Create colorbar subplot reference at top of 2nd row\n cax = plt.subplot(self.gs[1,1])\n \n # Create colorbar object\n y = plt.colorbar(ax, ticks = np.array([float(str(vmin + 2)[0:4]),\n float(str(half)[0:4]),\n float(str(vmax)[0:4])]), \n cax=cax, orientation=\"horizontal\")\n # Set colorbar tick positions to top\n y.ax.xaxis.set_ticks_position('top')\n \n # Set colorbar label position to top\n y.ax.xaxis.set_label_position('top')\n \n # Set desired colorbar tick size\n y.ax.tick_params(labelsize=self.fontsize)\n \n # Set colorbar label\n y.set_label('V [km $s^{-1}$]',fontsize=self.fontsize)\n","sub_path":"APJ_Paper/classes/plot/subclasses/simline_plot/class_methods/plot_mean_velocity.py","file_name":"plot_mean_velocity.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"262525870","text":"# Name: Lars Hedlund\n# ID Number: 00308102\n# Tutorial number: 02\n\n\"\"\"\nHEADER: Satisfaction calculator by Lars Hedlund.\nVersion: 0.3 (Cleaned up the if,elif,else statements)\nFeatures: (1) Ask for input (2) Calculate grade point (3) calculate fun point\n(4) Calculate satisfaction\nLanguage: Python 3.3\n\"\"\"\nimport random\n\ndef hours_studying(hours):\n \"\"\" Takes a variable and returns the grade point. The grade point is based on\n a probability and the value of the variable. \"\"\"\n prob = random.randint(1,100)\n if 20 >= hours >= 18: # Grade for 18-20 hours\n if 100 >= prob >= 61:\n return 4\n elif prob >= 36:\n return 3\n elif prob >= 11:\n return 2\n elif prob >= 6:\n return 1\n elif prob >= 0:\n return 0\n else:\n print(\"Unexpected grade return. Please try again.\")\n elif hours >= 10: # Grade for 10-17 hours\n if 100 >= prob >= 81:\n return 4\n elif prob >= 61:\n return 3\n elif prob >= 41:\n return 2\n elif prob >= 21:\n return 1\n elif prob >= 0:\n return 0\n else:\n print(\"Unexpected grade return. Please try again.\")\n elif hours >= 1: # Grade for 1-9 hours\n if 100 >= prob >= 96:\n return 4\n elif prob >= 91:\n return 3\n elif prob >= 66:\n return 2\n elif prob >= 41:\n return 1\n elif prob >= 0:\n return 0\n else:\n print(\"Unexpected grade return. Please try again.\")\n elif hours == 0: # Grade for 0 hours\n if 100 >= prob >= 51:\n return 1\n elif prob >= 0:\n return 0\n else:\n print(\"Unexpected grade return. Please try again.\")\n else:\n print(\"Unexpected error with hours provided. Please try again.\")\n\ndef fun_had(hours):\n \"\"\" Calculate the amount of fun \"\"\"\n return round(hours / 6)\n\ndef main():\n \"\"\"\n The start of the program. First, ask the user for input.\n \"\"\"\n print (\"Please input how much time you've spent studying and having fun.\")\n print (\"Total hours should be equal to 20 hours.\\n\")\n hours_spent = 0 # flag for while loop\n while (hours_spent != 20):\n studying = int(input(\"How much time did you spend studying? \"))\n fun = int(input(\"How much time did you spend having fun? \"))\n hours_spent = studying + fun\n if (hours_spent != 20):\n print (\"Hours were equal to %d, not 20. Please try again.\" % hours_spent)\n else:\n print(\"Thank you for your input.\\n\")\n # calculates satisfaction using the calculator functions and the user's input\n grade_point = hours_studying(studying)\n fun_point = fun_had(fun)\n satisfaction = grade_point + fun_point\n # final output\n print (\"Let's take a look at how satisfied you are...\")\n print (\"You studied for %d hours and received a grade of %d out of 4.\" % (studying, grade_point))\n print (\"You had fun for %d hours and received a fun score of %d out of 3.\\n\" % (fun, fun_point))\n print (\"All said and done, your satisfaction is %d out of 5.\" % satisfaction)\n\nmain()\n","sub_path":"course-assignments/full2/full2_v03.py","file_name":"full2_v03.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"288741220","text":"class DelayedImage(SignalSender, SignalListener):\n\tdef __init__(self, url):\n\t\tself.image = simplegui.load_image(url)\n\t\tif self.is_ready():\n\t\t\tprint(url)\n\t\tself.ready_signal = Signal(\"ready\")\n\t\tself.tic_signal = Signal(\"tic\")\n\t\tSignalSender.__init__(self,self.ready_signal)\n\t\tSignalListener.__init__(self,self.tic_signal)\n\t\tprint('DelayedImage __init__ done')\n\t\t\n\tdef is_ready(self):\n\t\treturn self.image.get_width() > 0\n\t\n\tdef recieve_signal(self,signal):\n\t\tprint('DelayedImage recieve_signal')\n\t\tif signal.name == \"tic\":\n\t\t\tif self.is_ready():\n\t\t\t\tSignalSender.send(self, self.ready_signal)\n","sub_path":"delayedimage.py","file_name":"delayedimage.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"124611428","text":"from tkinter import Toplevel, StringVar\nfrom tkinter.ttk import Frame, Label, Button\nfrom CustomWidgets.WidgetTable import WidgetTable\nfrom Windows import ProjectSettingsWindow\n\nimport pickle\n\n\nclass SettingsWindow(Toplevel):\n def __init__(self, master, settings, proj_settings):\n self.master = master\n Toplevel.__init__(self, self.master)\n self.withdraw()\n if master.winfo_viewable():\n self.transient(master)\n\n self.title('Project Settings')\n\n self.protocol(\"WM_DELETE_WINDOW\", self.exit)\n\n self.deiconify()\n self.focus_set()\n\n self.settings = settings\n self.proj_settings = proj_settings\n\n self._create_widgets()\n\n # wait for window to appear on screen before calling grab_set\n self.wait_visibility()\n self.grab_set()\n self.wait_window(self)\n\n def _create_widgets(self):\n frame = Frame(self)\n frame.grid(sticky='nsew')\n\n Label(frame, text=\"Project defaults\").grid(column=0, row=0)\n self.defaults_list_frame = Frame(frame, borderwidth=2,\n relief='ridge')\n self.projects_table = WidgetTable(\n self.defaults_list_frame,\n headings=[\"Project ID\", \"Project Title\", \"Default Triggers\",\n \" \"],\n pattern=[StringVar, StringVar, StringVar,\n {'text': \"Edit\", 'func': self._edit_project_row,\n 'func_has_row_ctx': True}],\n widgets_pattern=[Label, Label, Label, Button],\n data_array=[self.settings_view(s) for s in self.proj_settings],\n adder_script=self._add_project_row,\n remove_script=self._remove_row)\n self.projects_table.grid(column=0, row=0, sticky='nsew')\n self.defaults_list_frame.grid(column=0, row=1, sticky='nsew')\n Button(frame, text=\"Exit\", command=self.exit).grid(row=2, column=0,\n sticky='sw')\n\n self.defaults_list_frame.grid_rowconfigure(0, weight=1)\n self.defaults_list_frame.grid_columnconfigure(0, weight=1)\n\n frame.grid_columnconfigure(0, weight=1)\n frame.grid_rowconfigure(0, weight=0)\n frame.grid_rowconfigure(1, weight=1)\n frame.grid_rowconfigure(2, weight=0)\n\n self.grid_columnconfigure(0, weight=1)\n self.grid_rowconfigure(0, weight=1)\n\n @staticmethod\n def settings_view(settings):\n # returns a condensed view version fo the project settings to be passed\n # to the WidgetTable as the intial values\n dt = settings.get('DefaultTriggers', None)\n if dt is not None:\n if dt == [[]]:\n return [settings.get('ProjectID', 'None'),\n settings.get('ProjectTitle', 'None'),\n '', None]\n else:\n return [settings.get('ProjectID', 'None'),\n settings.get('ProjectTitle', 'None'),\n ','.join([str(i[0]) for i in dt]), None]\n else:\n return ['', '']\n\n def _add_project_row(self):\n proj_settings = dict()\n ProjectSettingsWindow(self, proj_settings)\n if proj_settings != dict():\n if (proj_settings.get('ProjectID', '') not in\n [d.get('ProjectID', '') for d in self.proj_settings]):\n self.proj_settings.append(proj_settings)\n return self.settings_view(proj_settings)\n else:\n raise ValueError\n\n def _edit_project_row(self, idx):\n curr_row = idx\n proj_settings = self.proj_settings[curr_row]\n ProjectSettingsWindow(self, proj_settings)\n self.projects_table.set_row(curr_row,\n self.settings_view(proj_settings))\n self.proj_settings[curr_row] = proj_settings\n\n def _remove_row(self, idx):\n del self.proj_settings[idx]\n\n def exit(self):\n self._write_settings()\n self.withdraw()\n self.update_idletasks()\n self.master.focus_set()\n #self.master.file_treeview.selection_toggle(\n # self.master.file_treeview.selection())\n self.destroy()\n\n def _write_settings(self):\n with open('proj_settings.pkl', 'wb') as settings:\n print('writing settings')\n pickle.dump(self.proj_settings, settings)\n","sub_path":"Windows/SettingsWindow.py","file_name":"SettingsWindow.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"72280290","text":"#!/usr/bin/python3\n'''\nKakao \n2. 압축\n\nLZW(Lempel–Ziv–Welch) algorithm\n'''\ndef lzw(msg):\n # Set dictionary\n dictionary = [ chr(ord('A')+diff) for diff in range(26) ]\n ret = []\n\n begin = 0\n while begin < len(msg):\n for end in range(len(msg), begin, -1):\n word = msg[begin:end]\n\n if not word in dictionary:\n continue\n\n # Has word in dictionary\n idx = dictionary.index(word)\n ret.append(idx)\n\n # Append new word in dictionary\n new_word = msg[begin:end+1]\n dictionary.append(new_word)\n\n # Set begin into end\n begin = end\n break\n\n return ret\n\n\nif __name__ == '__main__':\n msg = 'TOBEORNOTTOBEORTOBEORNOT'\n ret = lzw(msg)\n ret = [ele+1 for ele in ret]\n print(ret)\n","sub_path":"kakao/pre.3.2.py","file_name":"pre.3.2.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"184883075","text":"import pigpio\n\nclass Motor:\n PWM_FREQUENCY = 200\n\n def __init__(self, pi, pwmPin, forwardPin, reversePin, trim):\n self.pi = pi\n self.pwmPin = pwmPin\n self.forwardPin = forwardPin\n self.reversePin = reversePin\n self.pwmControl = None\n self.trim = trim\n self.__initMotor()\n\n def __initMotor(self):\n self.pi.set_mode(self.forwardPin, pigpio.OUTPUT)\n self.pi.set_mode(self.reversePin, pigpio.OUTPUT)\n self.pi.set_PWM_frequency(self.pwmPin, self.PWM_FREQUENCY)\n self.stop()\n\n def stop(self):\n self.pi.write(self.forwardPin, 0)\n self.pi.write(self.reversePin, 0)\n\n def setMotion(self, dutyCycle):\n self.stop()\n\n if dutyCycle != 0:\n if dutyCycle >= 0:\n self.pi.write(self.forwardPin, 1)\n else:\n self.pi.write(self.reversePin, 1)\n\n targetDC = abs(dutyCycle * self.trim)\n\n # below 20 DC, the motor will stall, which isn't good for anybody\n if targetDC > 20:\n self.pi.set_PWM_dutycycle(self.pwmPin, int(targetDC / 100 * 255))\n else:\n self.pi.set_PWM_dutycycle(self.pwmPin, 0)","sub_path":"motor.py","file_name":"motor.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"567918731","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ..initializer import create_initializer\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, in_channels, out_channels, drop_rate):\n super().__init__()\n\n self.drop_rate = drop_rate\n\n self.bn = nn.BatchNorm2d(in_channels)\n self.conv = nn.Conv2d(in_channels,\n out_channels,\n kernel_size=3,\n stride=1,\n padding=1,\n bias=False)\n\n def forward(self, x):\n y = self.conv(F.relu(self.bn(x), inplace=True))\n if self.drop_rate > 0:\n y = F.dropout(y,\n p=self.drop_rate,\n training=self.training,\n inplace=False)\n return torch.cat([x, y], dim=1)\n\n\nclass BottleneckBlock(nn.Module):\n def __init__(self, in_channels, out_channels, drop_rate):\n super().__init__()\n\n self.drop_rate = drop_rate\n\n bottleneck_channels = out_channels * 4\n\n self.bn1 = nn.BatchNorm2d(in_channels)\n self.conv1 = nn.Conv2d(in_channels,\n bottleneck_channels,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False)\n\n self.bn2 = nn.BatchNorm2d(bottleneck_channels)\n self.conv2 = nn.Conv2d(bottleneck_channels,\n out_channels,\n kernel_size=3,\n stride=1,\n padding=1,\n bias=False)\n\n def forward(self, x):\n y = self.conv1(F.relu(self.bn1(x), inplace=True))\n if self.drop_rate > 0:\n y = F.dropout(y,\n p=self.drop_rate,\n training=self.training,\n inplace=False)\n y = self.conv2(F.relu(self.bn2(y), inplace=True))\n if self.drop_rate > 0:\n y = F.dropout(y,\n p=self.drop_rate,\n training=self.training,\n inplace=False)\n return torch.cat([x, y], dim=1)\n\n\nclass TransitionBlock(nn.Module):\n def __init__(self, in_channels, out_channels, drop_rate):\n super().__init__()\n\n self.drop_rate = drop_rate\n\n self.bn = nn.BatchNorm2d(in_channels)\n self.conv = nn.Conv2d(in_channels,\n out_channels,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False)\n\n def forward(self, x):\n x = self.conv(F.relu(self.bn(x), inplace=True))\n if self.drop_rate > 0:\n x = F.dropout(x,\n p=self.drop_rate,\n training=self.training,\n inplace=False)\n x = F.avg_pool2d(x, kernel_size=2, stride=2)\n return x\n\n\nclass Network(nn.Module):\n def __init__(self, config):\n super().__init__()\n\n model_config = config.model.densenet\n block_type = model_config.block_type\n n_blocks = model_config.n_blocks\n self.growth_rate = model_config.growth_rate\n self.drop_rate = model_config.drop_rate\n self.compression_rate = model_config.compression_rate\n\n assert block_type in ['basic', 'bottleneck']\n if block_type == 'basic':\n block = BasicBlock\n else:\n block = BottleneckBlock\n\n in_channels = [2 * self.growth_rate]\n for index in range(4):\n denseblock_out_channels = int(in_channels[-1] +\n n_blocks[index] * self.growth_rate)\n if index < 3:\n transitionblock_out_channels = int(denseblock_out_channels *\n self.compression_rate)\n else:\n transitionblock_out_channels = denseblock_out_channels\n in_channels.append(transitionblock_out_channels)\n\n self.conv = nn.Conv2d(config.dataset.n_channels,\n in_channels[0],\n kernel_size=7,\n stride=2,\n padding=3,\n bias=False)\n self.bn = nn.BatchNorm2d(in_channels[0])\n self.stage1 = self._make_stage(in_channels[0], n_blocks[0], block,\n True)\n self.stage2 = self._make_stage(in_channels[1], n_blocks[1], block,\n True)\n self.stage3 = self._make_stage(in_channels[2], n_blocks[2], block,\n True)\n self.stage4 = self._make_stage(in_channels[3], n_blocks[3], block,\n False)\n self.bn_last = nn.BatchNorm2d(in_channels[4])\n\n # compute conv feature size\n with torch.no_grad():\n dummy_data = torch.zeros(\n (1, config.dataset.n_channels, config.dataset.image_size,\n config.dataset.image_size),\n dtype=torch.float32)\n self.feature_size = self._forward_conv(dummy_data).view(\n -1).shape[0]\n\n self.fc = nn.Linear(self.feature_size, config.dataset.n_classes)\n\n # initialize weights\n initializer = create_initializer(config.model.init_mode)\n self.apply(initializer)\n\n def _make_stage(self, in_channels, n_blocks, block, add_transition_block):\n stage = nn.Sequential()\n for index in range(n_blocks):\n stage.add_module(\n f'block{index + 1}',\n block(in_channels + index * self.growth_rate, self.growth_rate,\n self.drop_rate))\n if add_transition_block:\n in_channels = int(in_channels + n_blocks * self.growth_rate)\n out_channels = int(in_channels * self.compression_rate)\n stage.add_module(\n 'transition',\n TransitionBlock(in_channels, out_channels, self.drop_rate))\n return stage\n\n def _forward_conv(self, x):\n x = F.relu(self.bn(self.conv(x)), inplace=True)\n x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1)\n x = self.stage1(x)\n x = self.stage2(x)\n x = self.stage3(x)\n x = self.stage4(x)\n x = self.bn_last(x)\n x = F.adaptive_avg_pool2d(x, output_size=1)\n return x\n\n def forward(self, x):\n x = self._forward_conv(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x\n","sub_path":"pytorch_image_classification/models/imagenet/densenet.py","file_name":"densenet.py","file_ext":"py","file_size_in_byte":6791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"415702597","text":"from django.conf.urls.defaults import *\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.views.generic import list_detail\n\nfrom gcd.core.models import MasterPublisher\n\nadmin.autodiscover()\n\npublisher_list_info = {\n 'queryset': MasterPublisher.objects,\n 'paginate_by': 100,\n 'template_object_name': 'publisher',\n}\n\nurlpatterns = patterns('',\n # Example:\n\n # Uncomment the admin/doc line below and add 'django.contrib.admindocs' \n # to INSTALLED_APPS to enable admin documentation:\n # (r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n (r'^admin/', include(admin.site.urls)),\n (r'site_media/(?P.*)$', 'django.views.static.serve',\n { 'document_root' : settings.MEDIA_ROOT }),\n (r'^publishers/', list_detail.object_list, publisher_list_info),\n (r'^.*/', 'gcd.core.views.oops'),\n)\n\n# if settings.DEBUG:\n# urlpatterns += patterns('',\n# (r'site_media/(?P.*)$', 'django.views.static.serve',\n# { 'document_root' : settings.MEDIA_ROOT }))\n\n","sub_path":"gcd/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"77152341","text":"# Copyright 2013 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport cgi\nimport re\n\nfrom recipe_engine import recipe_api\n\n\nclass ChromiteApi(recipe_api.RecipeApi):\n chromite_url = 'https://chromium.googlesource.com/chromiumos/chromite.git'\n manifest_url = 'https://chromium.googlesource.com/chromiumos/manifest.git'\n repo_url = 'https://chromium.googlesource.com/external/repo.git'\n chromite_subpath = 'chromite'\n\n # The number of Gitiles attempts to make before giving up.\n _GITILES_ATTEMPTS = 10\n\n _MANIFEST_CMD_RE = re.compile(r'Automatic:\\s+Start\\s+([^\\s]+)\\s+([^\\s]+)')\n _BUILD_ID_RE = re.compile(r'CrOS-Build-Id: (.+)')\n\n def get_config_defaults(self):\n defaults = {\n 'CBB_CONFIG': self.m.properties.get('cbb_config'),\n 'CBB_BRANCH': self.m.properties.get('cbb_branch'),\n 'CBB_DEBUG': self.m.properties.get('cbb_debug') is not None,\n 'CBB_CLOBBER': 'clobber' in self.m.properties,\n }\n if 'buildnumber' in self.m.properties:\n defaults['CBB_BUILD_NUMBER'] = int(self.m.properties['buildnumber'])\n return defaults\n\n def check_repository(self, repo_type_key, value):\n \"\"\"Scans through registered repositories for a specified value.\n\n Args:\n repo_type_key (str): The key in the 'repositories' config to scan through.\n value (str): The value to scan for.\n Returns (bool): True if the value was found.\n \"\"\"\n def remove_tail(v, tail):\n if v.endswith(tail):\n v = v[:-len(tail)]\n return v\n\n for v in self.c.repositories.get(repo_type_key, ()):\n if remove_tail(v, '.git') == remove_tail(value, '.git'):\n return True\n return False\n\n def load_try_job(self, repository, revision):\n \"\"\"Loads try job arguments from the try job repository.\n\n Loading a tryjob descriptor works as follows:\n - Identify the tryjob commit.\n - Identify the tryjob descriptor file checked into that commit.\n - Load the tryjob descriptor file and parse as JSON.\n\n Args:\n repository (str): The URL of the try job change repository.\n revision (str): The try job change revision.\n Returns (iterable): The extra arguments specified by the tryjob.\n \"\"\"\n # Load the job description from Gitiles.\n commit_log = self.m.gitiles.commit_log(\n repository, revision, step_name='Fetch tryjob commit',\n attempts=self._GITILES_ATTEMPTS)\n\n # Get the list of different files.\n desc_path = None\n for diff in commit_log.get('tree_diff', ()):\n if diff.get('type') == 'add':\n desc_path = diff.get('new_path')\n if desc_path:\n break\n else:\n raise self.m.step.StepFailure('Could not find tryjob description.')\n\n # Load the tryjob description file.\n desc_json = self.m.gitiles.download_file(\n repository, desc_path, branch=revision,\n step_name=str('Fetch tryjob descriptor (%s)' % (desc_path,)),\n attempts=self._GITILES_ATTEMPTS)\n result = self.m.step.active_result\n\n # Parse the commit description from the file (JSON).\n desc = self.m.json.loads(desc_json)\n result.presentation.step_text += '
'.join(\n '%s: %s' % (k, cgi.escape(str(v)))\n for k, v in desc.iteritems())\n return desc.get('extra_args', ())\n\n def load_manifest_config(self, repository, revision):\n \"\"\"Loads manifest-specified parameters from the manifest commit.\n\n This method parses the commit log for the following information:\n - The branch to build (From the \"Automatic\": tag).\n - The build ID (from the CrOS-Build-Id: tag).\n\n Args:\n repository (str): The URL of the repository hosting the change.\n revision (str): The revision hash to load the build ID from.\n \"\"\"\n commit_log = self.m.gitiles.commit_log(\n repository, revision, step_name='Fetch manifest config',\n attempts=self._GITILES_ATTEMPTS)\n result = self.m.step.active_result\n\n # Handle missing/invalid response.\n if not (commit_log and commit_log.get('message')):\n self.m.python.failing_step('Fetch manifest config failure',\n 'Failed to fetch manifest config.')\n\n build_id = None\n loaded = []\n for line in reversed(commit_log['message'].splitlines()):\n # Automatic command?\n match = self._MANIFEST_CMD_RE.match(line)\n if match:\n self.c.chromite_branch = match.group(2)\n loaded.append('Chromite branch: %s' % (self.c.chromite_branch,))\n continue\n\n # Build ID?\n match = self._BUILD_ID_RE.match(line)\n if match:\n self.c.cbb.build_id = match.group(1)\n loaded.append('Build ID: %s' % (self.c.cbb.build_id,))\n continue\n if loaded:\n loaded.insert(0, '')\n result.presentation.step_text += '
'.join(loaded)\n\n @property\n def default_chromite_path(self):\n \"\"\"Returns: (Path) The default Chromite checkout path.\"\"\"\n return self.m.path['slave_build'].join(self.chromite_subpath)\n\n def gclient_config(self):\n \"\"\"Generate a 'gclient' configuration to check out Chromite.\n\n Return: (config) A 'gclient' recipe module configuration.\n \"\"\"\n cfg = self.m.gclient.make_config()\n soln = cfg.solutions.add()\n soln.name = 'chromite'\n soln.url = self.chromite_url\n # Set the revision using 'bot_update' remote branch:revision notation.\n # Omitting the revision uses HEAD.\n soln.revision = '%s:' % (self.c.chromite_branch,)\n return cfg\n\n def checkout(self, manifest_url=None, repo_url=None):\n manifest_url = manifest_url or self.manifest_url\n repo_url = repo_url or self.repo_url\n\n self.m.repo.init(manifest_url, '--repo-url', repo_url)\n self.m.repo.sync()\n\n @property\n def using_old_chromite_layout(self):\n \"\"\"Returns (bool): True if we're using old Chromite checkout layout.\n \"\"\"\n return self.c.chromite_branch in self.c.old_chromite_branches\n\n def cbuildbot(self, name, config, args=None, chromite_path=None, **kwargs):\n \"\"\"Runs the cbuildbot command defined by the arguments.\n\n Args:\n name: (str) The name of the command step.\n config: (str) The name of the 'cbuildbot' configuration to invoke.\n args: (list) If not None, addition arguments to pass to 'cbuildbot'.\n chromite_path: (str) The path to the Chromite checkout; if None, the\n 'default_chromite_path' will be used.\n\n Returns: (Step) The step that was run.\n \"\"\"\n chromite_path = chromite_path or self.default_chromite_path\n args = (args or [])[:]\n args.append(config)\n\n bindir = 'bin'\n if self.using_old_chromite_layout:\n bindir = 'buildbot'\n cmd = [self.m.path.join(chromite_path, bindir, 'cbuildbot')] + args\n return self.m.step(name, cmd, allow_subannotations=True, **kwargs)\n\n def cros_sdk(self, name, cmd, args=None, environ=None, chromite_path=None,\n **kwargs):\n \"\"\"Return a step to run a command inside the cros_sdk.\"\"\"\n chromite_path = chromite_path or self.default_chromite_path\n\n chroot_cmd = self.m.path.join(chromite_path, 'bin', 'cros_sdk')\n\n arg_list = (args or [])[:]\n for t in sorted((environ or {}).items()):\n arg_list.append('%s=%s' % t)\n arg_list.append('--')\n arg_list.extend(cmd)\n\n self.m.python(name, chroot_cmd, arg_list, **kwargs)\n\n def setup_board(self, board, args=None, **kwargs):\n \"\"\"Run the setup_board script inside the chroot.\"\"\"\n self.cros_sdk('setup board',\n ['./setup_board', '--board', board],\n args, **kwargs)\n\n def build_packages(self, board, args=None, **kwargs):\n \"\"\"Run the build_packages script inside the chroot.\"\"\"\n self.cros_sdk('build packages',\n ['./build_packages', '--board', board],\n args, **kwargs)\n\n def configure(self, properties, config_map):\n \"\"\"Loads configuration from build properties into this recipe config.\n\n Args:\n properties (Properties): The build properties object.\n config_map (dict): The configuration map to use.\n \"\"\"\n master = properties['mastername']\n variant = properties.get('cbb_variant')\n\n # Set the master's base configuration.\n config_map = config_map.get(master, {})\n master_config = config_map.get('master_config')\n assert master_config, (\n \"No 'master_config' configuration for '%s'\" % (master,))\n self.set_config(master_config)\n\n # Apply any variant configurations.\n if variant:\n for config_name in config_map.get('variants', {}).get(variant, ()):\n self.apply_config(config_name)\n\n\n # If a config repo was specified, use it.\n if 'config_repo' in properties:\n self.c.cbb.config_repo = self.m.properties['config_repo']\n\n def run_cbuildbot(self, tryjob=False):\n \"\"\"Runs a 'cbuildbot' checkout-and-build workflow.\n\n This workflow uses the registered configuration dictionary to make master-\n and builder-specific changes to the standard workflow.\n\n The specific workflow paths that are taken are also influenced by several\n build properties.\n\n TODO(dnj): When CrOS migrates away from BuildBot, replace property\n inferences with command-line parameters.\n\n This workflow:\n - Checks out the specified 'cbuildbot' repository.\n - Pulls information based on the configured change's repository/revision\n to pass to 'cbuildbot'.\n - Executes the 'cbuildbot' command.\n\n Args:\n tryjob (bool): If True, load a tryjob description from the source\n repository and augment the cbuildbot command-line with it.\n Returns: (Step) the 'cbuildbot' execution step.\n \"\"\"\n # Assert correct configuration.\n assert self.c.cbb.config, 'An empty configuration was specified.'\n assert self.c.cbb.builddir, 'A build directory name must be specified.'\n\n # Load properties from the commit being processed. This requires both a\n # repository and revision to proceed.\n repository = self.m.properties.get('repository')\n revision = self.m.properties.get('revision')\n tryjob_args = []\n if repository and revision:\n if tryjob:\n assert self.check_repository('tryjob', repository), (\n \"Refusing to query unknown tryjob repository: %s\" % (repository,))\n # If we are a tryjob, add parameters specified in the description.\n tryjob_args = self.load_try_job(repository, revision)\n\n # Pull more information from the commit if it came from certain known\n # repositories.\n if (self.c.use_chrome_version and\n self.check_repository('chromium', repository)):\n # If our change comes from a Chromium repository, add the\n # '--chrome_version' flag.\n self.c.cbb.chrome_version = self.m.properties['revision']\n if (self.c.read_cros_manifest and\n self.check_repository('cros_manifest', repository)):\n # This change comes from a manifest repository. Load configuration\n # parameters from the manifest command.\n self.load_manifest_config(repository, revision)\n\n buildroot = self.m.path['root'].join('cbuild', self.c.cbb.builddir)\n cbb_args = [\n '--buildroot', buildroot,\n ]\n if not tryjob:\n cbb_args.append('--buildbot')\n if self.c.chromite_branch and not self.c.cbb.disable_bootstrap:\n cbb_args.extend(['--branch', self.c.chromite_branch])\n if self.c.cbb.build_number is not None:\n cbb_args.extend(['--buildnumber', self.c.cbb.build_number])\n if self.c.cbb.chrome_rev:\n cbb_args.extend(['--chrome_rev', self.c.cbb.chrome_rev])\n if self.c.cbb.debug:\n cbb_args.extend(['--debug'])\n if self.c.cbb.clobber:\n cbb_args.extend(['--clobber'])\n if self.c.cbb.chrome_version:\n cbb_args.extend(['--chrome_version', self.c.cbb.chrome_version])\n if self.c.cbb.config_repo:\n cbb_args.extend(['--config_repo', self.c.cbb.config_repo])\n\n # Set the build ID, if specified.\n if self.c.cbb.build_id:\n cbb_args.extend(['--master-build-id', self.c.cbb.build_id])\n\n # Add tryjob args, if there are any.\n cbb_args.extend(tryjob_args)\n\n # Checkout Chromite.\n self.m.bot_update.ensure_checkout(\n gclient_config=self.gclient_config(),\n update_presentation=False,\n force=True)\n if self.c.chromite_branch and self.c.cbb.disable_bootstrap:\n # Chromite auto-detects which branch to build for based on its current\n # checkout. \"bot_update\" checks out remote branches, but Chromite requires\n # a local branch.\n #\n # Normally we'd bootstrap, but if we're disabling bootstrapping, we have\n # to checkout the local branch to let Chromite know which branch to build.\n self.m.git('checkout', self.c.chromite_branch,\n name=str('checkout chromite branch [%s]' % (self.c.chromite_branch)))\n\n # Run cbuildbot.\n return self.cbuildbot(str('cbuildbot [%s]' % (self.c.cbb.config,)),\n self.c.cbb.config,\n args=cbb_args,\n chromite_path=self.m.path['checkout'],\n cwd=self.m.path['slave_root'])\n","sub_path":"scripts/slave/recipe_modules/chromite/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":13056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"545007675","text":"import pygame\n\nfrom modules.colors import colors\nfrom modules.ant import AntManager\n\nclass Nest():\n def __init__(self, window, board):\n self.window = window\n self.surface = self.window.surface\n\n self.nestX = int((self.window.width-300)//2)\n self.nestY = int(self.window.height//2 - 300)\n\n self.size = 30\n self.sizeHalf = self.size//4\n self.offset = 4\n self.nestRect = pygame.Rect((self.nestX, self.nestY), (self.size, self.size))\n\n self.antManager = AntManager(self.window, board, self.nestRect)\n\n self.foodDots = 0\n self.score = 0\n self.antsLiving = 0\n self.trailDots = 0\n self.antSpawnCount = 100\n\n def draw(self):\n pygame.draw.rect(self.surface, colors['brown'], self.nestRect)\n \n textFood = self.window.font.render(f'{self.score}', False, (0, 0, 0))\n self.surface.blit(textFood,(self.nestX+self.sizeHalf+self.offset, self.nestY+self.sizeHalf+self.offset))\n\n self.antManager.draw()\n\n def setPosition(self, x, y):\n self.nestX, self.nestY = x, y\n self.nestRect = pygame.Rect((self.nestX, self.nestY), (self.size, self.size))\n\n def createAnts(self):\n for i in range(self.antSpawnCount):\n self.antManager.createAnt(self.nestX, self.nestY)\n\n def killAnts(self):\n try:\n for i in range(self.antSpawnCount):\n self.antManager.antList.pop(0)\n except:\n pass\n \n def getStats(self):\n self.antsLiving = len(self.antManager.antList)\n self.trailDots = len(self.antManager.trailFoundFood)\n self.foodDots = len(self.antManager.foodList)\n return (self.antsLiving, self.trailDots, self.foodDots)\n\n def restart(self):\n self.antManager = AntManager(self.window, board)\n\n def clearAll(self):\n self.antManager.clearAll()\n\n def moveAnts(self):\n self.antManager.moveAnts()\n\n\n","sub_path":"modules/nest.py","file_name":"nest.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"413476041","text":"class vitals_alert():\r\n\r\n def __init__(self):\r\n self.heartRate = 0\r\n self.footPressure = 0\r\n self.bloodPressure = [0, 0]\r\n # lower, upper thresholds\r\n self.heartRateThreshold = [0, 0]\r\n self.footPressureThreshold = [0, 0]\r\n self.bloodPressureThresholdSys = [0, 0]\r\n self.bloodPressureThresholdDia = [0, 0]\r\n\r\n # Sets vitals value whenever avaiable\r\n def set_vitals(self, dict={'heartRate': 60, 'footPressure': 75, 'bloodPressure': [120, 80]}):\r\n self.heartRate = dict['heartRate']\r\n self.footPressure = dict['footPressure']\r\n self.bloodPressure = dict['bloodPressure']\r\n\r\n def get_vitals(self):\r\n d = {'heartRate': self.heartRate, 'footPressure': self.footPressure, 'bloodPressure': self.bloodPressure}\r\n\r\n return d\r\n\r\n # Set thresholds for vital alert module\r\n def set_thresholds(self, heartRateThreshold=[40, 200], footPressureThreshold=[0, 200],\r\n bloodPressureThresholdSys=[50, 200], bloodPressureThresholdDia=[50, 150]):\r\n self.heartRateThreshold = heartRateThreshold\r\n self.footPressureThreshold = footPressureThreshold\r\n self.bloodPressureThresholdSys = bloodPressureThresholdSys\r\n self.bloodPressureThresholdDia = bloodPressureThresholdDia\r\n\r\n def get_thresholds(self):\r\n d = {'heartRateThreshold': self.heartRateThreshold, 'footPressureThreshold': self.footPressureThreshold,\r\n 'bloodPressureThresholdSys': self.bloodPressureThresholdSys,\r\n 'bloodPressureThresholdDia': self.bloodPressureThresholdDia}\r\n\r\n return d\r\n\r\n # check if vitals exceeded threshold. This should be run in a thread by the processor\r\n def check_vitals(self):\r\n vitals = self.get_vitals()\r\n thresholds = self.get_thresholds()\r\n alerts = [['n', 0], ['n', 0], ['n', [0, 0]]]\r\n\r\n if vitals['heartRate'] > thresholds['heartRateThreshold'][1]:\r\n alerts[0] = ['h', vitals['heartRate']]\r\n elif vitals['heartRate'] < thresholds['heartRateThreshold'][0]:\r\n alerts[0] = ['l', vitals['heartRate']]\r\n else:\r\n alerts[0] = ['n', vitals['heartRate']]\r\n\r\n if vitals['footPressure'] > thresholds['footPressureThreshold'][1]:\r\n alerts[1] = ['h', vitals['footPressure']]\r\n elif vitals['footPressure'] < thresholds['footPressureThreshold'][0]:\r\n alerts[1] = ['l', vitals['footPressure']]\r\n else:\r\n alerts[1] = ['n', vitals['footPressure']]\r\n\r\n if (vitals['bloodPressure'][0] > thresholds['bloodPressureThresholdSys'][1] or\r\n vitals['bloodPressure'][1] > thresholds['bloodPressureThresholdDia'][1]):\r\n alerts[2] = ['h', vitals['bloodPressure']]\r\n elif (vitals['bloodPressure'][0] < thresholds['bloodPressureThresholdSys'][0] or\r\n vitals['bloodPressure'][1] < thresholds['bloodPressureThresholdDia'][0]):\r\n alerts[2] = ['l', vitals['bloodPressure']]\r\n else:\r\n alerts[2] = ['n', vitals['bloodPressure']]\r\n \r\n return alerts","sub_path":"icu_main/vitals_alert.py","file_name":"vitals_alert.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"298848986","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom datetime import date\n\nfrom flask import session, render_template, url_for, request, redirect, flash\n\nfrom werkzeug.exceptions import default_exceptions, BadRequest, HTTPException, NotFound\n\nfrom peewee import DoesNotExist, IntegrityError\n\nfrom model import City, School, Team, Age\n\nfrom User import login_required\n\n# Команды\n@login_required\ndef listTeam(cityid, schoolid):\n # Список городов и их дочерних школ, название текущего города и школы\n listCity = City.select().order_by(City.cityName)\n listSchool = School.select().join(City).where(City.city_ID == cityid).order_by(School.schoolName)\n try:\n cityname = City.get(city_ID = cityid).cityName\n schoolname = School.get(school_ID = schoolid).schoolName\n except DoesNotExist:\n cityname = None\n schoolname = None\n\n # Список команд в выбранной школе\n listTeam = Team.select().join(School).where(School.school_ID == schoolid).join(City).where(City.city_ID == cityid).switch(Team).join(Age).order_by(Team.teamName)\n for lt in listTeam:\n lt.age_ID.ageName = int(date.today().year) - int(lt.age_ID.ageName)\n\n # Список возрастов по состоянию на текущий год\n listAge = Age.select().order_by(Age.ageName)\n for age in listAge:\n age.ageName = int(date.today().year) - int(age.ageName)\n\n # Переменные для автозаполнения модальной формы добавления/обновления данных в JS-скрипте шаблона\n ## Список полей\n modifyFields = ['teamName', 'filterAge', 'ageName']\n ## Список групп радиокнопок\n modifyRadios = ['filterAge']\n ## Заголовки модального окна\n createHeader = ['\"Создать новую юношескую команду\"']\n updateHeader = ['\"Изменить \"', 'teamName', '\" (возраст \"', 'ageName', '\")\"']\n ## Действия формы\n createAction = ['\"/city/\"', cityid, '\"/school/\"', schoolid, '\"/team/create\"']\n updateAction = ['\"/city/\"', cityid, '\"/school/\"', schoolid, '\"/team/\"', 'PK_ID', '\"/update\"']\n deleteAction = ['\"/city/\"', cityid, '\"/school/\"', schoolid, '\"/team/\"', 'PK_ID', '\"/delete\"']\n\n # Вывод шаблона\n return render_template(\n 'Team.jinja.html', \n listCity = listCity, \n cityid = cityid, \n cityname = cityname, \n listSchool = listSchool, \n schoolid = schoolid, \n schoolname = schoolname,\n listTeam = listTeam,\n listAge = listAge, \n modifyFields = modifyFields,\n modifyRadios = modifyRadios,\n createHeader = createHeader,\n updateHeader = updateHeader,\n createAction = createAction,\n updateAction = updateAction,\n deleteAction = deleteAction)\n\n### Добавление команд\n@login_required\ndef createTeam(cityid, schoolid):\n # Получение полей формы из шаблона\n teamname = request.form['teamName']\n ageid = request.form['filterAge']\n\n # Сохранение новой записи в БД\n if session['demo']:\n pass\n else:\n Team.create(\n school_ID = schoolid, \n age_ID = ageid, \n teamName = teamname)\n\n # Редирект на вид list\n return redirect(\n url_for('listTeam', \n cityid = cityid, \n schoolid = schoolid))\n\n### Изменение команд\n@login_required\ndef updateTeam(cityid, schoolid, teamid):\n # Получение полей формы из шаблона\n teamname = request.form['teamName']\n ageid = request.form['filterAge']\n\n # Обновление текущей записи в БД\n if session['demo']:\n pass\n else:\n team = Team()\n team.team_ID = teamid\n team.school_ID = schoolid\n team.age_ID = ageid\n team.teamName = teamname\n team.save()\n\n # Редирект на вид list\n return redirect(\n url_for('listTeam', \n cityid = cityid, \n schoolid = schoolid,\n teamid = teamid))\n\n### Удаление команд\n@login_required\ndef deleteTeam(cityid, schoolid, teamid):\n # Удаление текущей записи в БД\n if session['demo']:\n pass\n else:\n # Ограничение по внешнему ключу FK_SAST_Team \n # не позволяет удалить команду при наличии связанных с ней игровых этапов.\n try:\n Team.get(school_ID = schoolid, team_ID = teamid).delete_instance()\n except IntegrityError:\n flash('Вы не можете удалить эту команду, пока она добавлена хотя бы в один игровой этап', 'danger')\n\n # Редирект на вид list\n return redirect(\n url_for('listTeam', \n cityid = cityid, \n schoolid = schoolid,\n teamid = teamid))\n","sub_path":"controller/Team.py","file_name":"Team.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"308653555","text":"USER = 'philipp'\n\nif USER == 'philipp':\n DO_NOT_COPY = []\n # dataset\n NAT_IM_BASE = 'data/natural_images'\n\n EXP_FOLDER = './experiments'\n\n PRINT_FREQUENCY = 100\n\n # default training values\n LR = 0.001\n WD = 0.00001\n BS = 16\n MOM = 0.9\n CS = 224\n MT = 'resnet18'\n OPT = 'Adam'\n\nDO_NOT_COPY += [EXP_FOLDER]\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"426139969","text":"#1. Create a class called Rectangle which takes the sides a,b as input.\n#e.g rect = Rectangle(5,4); rect.area() # it should return 20\n\nclass Rectangle:\n\tdef __init__(self,length,breadth):\n\t\tself.length=length\n\t\tself.breadth=breadth\n\tdef area(self):\n\t\treturn self.length*self.breadth\n\nrect=Rectangle(5,4)\nprint(rect.area())\nprint(Rectangle(5,4).area())\n\n\n#2. Create a class called Point which takes x, y coordinates as input. point1 = Point(1,2)\n#Add a method called quadrant which returns the quadrant the point is in.\n# point1.quadrant() # should return 1\n#point2 = Point(-1,-2); point2.quadrant() # should return 3\n\n#Add another method called distance which takes another point and returns the Euclidean distance between the two points\n# point1.distance(point2) # should return 4.47. \n\n#Add another method called is_far which takes another point and returns True if the Euclidean distance is greater than 20.\n#point1.is_far(point2) # should return False\n\n#Add another method called slope that returns the slope of the line joining the two points\n#point1.slope(point2) # should return -1, since the line joining from (1,2) and (-1, -2) has the slope 2. \n\n\nclass Point:\n\tdef __init__(self,xcoor,ycoor):\n\t\tself.xcoor=xcoor\n\t\tself.ycoor=ycoor\n\n\tdef quadrant(self):\n\t\tif self.xcoor>0 and self.ycoor>0:\n\t\t\treturn \"quadrant=1\"\n\t\telif self.xcoor<0 and self.ycoor>0:\n\t\t\treturn \"quadrant=2\"\n\t\telif self.xcoor<0 and self.ycoor<0:\n\t\t\treturn \"quadrant=3\"\n\t\telif self.xcoor>0 and self.ycoor<0:\n\t\t\treturn \"quadrant=4\"\n\t\telif self.xcoor>0 and self.ycoor==0:\n\t\t\treturn \"positive x-axis\"\n\t\telif self.xcoor<0 and self.ycoor==0:\n\t\t\treturn \"negative x-axis\"\n\t\telif self.xcoor==0 and self.ycoor>0:\n\t\t\treturn \"positive y-axis\"\n\t\telif self.xcoor==0 and self.ycoor<0:\n\t\t\treturn \"negative y-axis\"\n\t\telif self.xcoor==0 and self.ycoor==0:\n\t\t\treturn \"origin\"\n\n\tdef distance(self,other):\n\t\treturn (((other.xcoor-self.xcoor)**2)+((other.ycoor-self.ycoor)**2))**(1/2)\n\n\tdef is_far(self,other):\n\t\tdist=self.distance(other)\n\t\treturn dist>20\n\n\tdef slope(self,other):\n\t\treturn (other.ycoor-self.ycoor)/(other.xcoor-self.xcoor)\n\n\tdef is_same(self,other):\n\t\treturn other.xcoor==self.xcoor and other.ycoor==self.xcoor\n\n\npoint1=Point(1,2)\npoint2=Point(-1,2)\npoint3=Point(-1,-2)\npoint4=Point(1,-2)\npoint5=Point(1,0)\npoint6=Point(-1,0)\npoint7=Point(0,2)\npoint8=Point(0,-2)\npoint9=Point(0,0)\npoint10=Point(1,2)\nprint(point1.quadrant())\nprint(point2.quadrant())\nprint(point3.quadrant())\nprint(point4.quadrant())\nprint(point5.quadrant())\nprint(point6.quadrant())\nprint(point7.quadrant())\nprint(point8.quadrant())\nprint(point9.quadrant())\n\nprint(point1.distance(point3))\nprint(point1.is_far(point3))\nprint(point1.slope(point3))\nprint(point1.is_same(point10))\n\n\n#3. Create a class called BankAccount which is initialized with an opening balance. acc = BankAccount(1000)\n#Add a method called balance which returns the account's balance; acc.balance() # should return 1000\n\n#Add a method called deposit which adds money to the account; acc.deposit(100)\n# acc.balance() # should return 1100\n\n#Add a method called withdraw which removes money from the account; acc.withdraw(50)\n#acc.balance() # should return 1050\n\nclass Bankaccount1:\n\n\tdef __init__(self,openbal):\n\t\tself.bal=openbal #self.openbal=bal(wrong; bal not assigned in input)\n\n\tdef deposit(self,deposit):\n\t\tself.bal=self.bal+deposit\n\n\tdef withdraw(self,withdraw):\n\t\tself.bal=self.bal-withdraw\n\n\tdef balance(self):\n\t\treturn self.bal\n\n\nacc1=Bankaccount1(1000)\nacc1.deposit(100)\nacc1.withdraw(50)\nacc1.deposit(400)\nprint(acc1.balance())\n\nclass Bankaccount2:\n\n\tdef __init__(self,openbal):\n\t\tself.bal=openbal #self.openbal=bal(wrong; bal not assigned in input)\n\t\tself.dep=0\n\t\tself.wd=0\n\tdef deposit(self,deposit):\n\t\tself.dep=self.dep+deposit\n\n\tdef withdraw(self,withdraw):\n\t\tself.wd=self.wd+withdraw\n\n\tdef balance(self):\n\t\treturn self.bal+self.dep-self.wd\n\n\nacc2=Bankaccount2(1000)\nacc2.deposit(100)\nacc2.withdraw(50)\nacc2.deposit(400)\nprint(acc2.balance())\n\n\n#4. Create a class called Person which is created with a name; e.g p = Person(\"vishnu\")\n#Add a function called eat which takes an item that the person has eaten\n#p.eat(\"dosa\"); p.eat(\"chutney\")\n\n#Add another function called all which returns all the items eaten by the person\n#p.all() # returns a set {\"dosa\", \"chutney\"}\n\nclass Person:\n\tdef __init__(self,name):\n\t\tself.n=name\n\t\tself.f=[]\n\tdef eat(self,food):\n\t\tself.f.append(food)\n\tdef all(self):\n\t\treturn set(self.f)\n\n\np=Person(\"vishnu\")\np.eat(\"dosa\")\np.eat(\"chutney\")\np.eat(\"chutney\")\np.eat(\"podi\")\nprint(p.all())\n","sub_path":"Assignments/Oops/oops_assign.py","file_name":"oops_assign.py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"104956243","text":"import os\nfrom functools import lru_cache\n\n\"\"\"\n Types of path\n\n FS paths: `fpath`, `fn`, `filename`, `*dir`\n - Canonical or relative to working directory\n - Valid if used with open(), for example\n - Never end in /\n - Only begin with / if canonical\n\n Resource paths: `rpath`\n - Never begin with /\n - Always relative to base directory\n - Valid if passed to os.path.join(basedir, ... )\n - Ends with / <=> refers to folder\n\n\"\"\"\n\n@lru_cache(maxsize=1000)\ndef get_fs_path(basedir : str, rpath : str):\n assert not rpath.startswith(\"/\"), \"rpath cannot start with /\"\n return os.path.join(basedir, rpath)\n\n@lru_cache(maxsize=1000)\ndef get_resource_path(basedir : str, fpath : str):\n assert not fpath.endswith(\"/\"), \"fpath cannot end with /\"\n relpath = os.path.relpath(fpath, basedir)\n if relpath == os.path.curdir: return \"\"\n if os.path.pardir in relpath.split(os.path.pathsep):\n print(fpath)\n print(relpath)\n raise FileNotFoundError(\"fpath is not under basedir\")\n else: return relpath","sub_path":"yant/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"519538720","text":"import os\nfrom grille import *\nfrom random import *\nfrom fonctions import *\n\nos.system('cls')\n#Nombre de joueurs ( 1 ou 2 )\nnb_joueur = 0\n# Nombre de parties jouees\nparties_jouees = 0\n\n# Définir le nombre de joueur\nwhile nb_joueur < 1 or nb_joueur > 2:\n\ttry:\n\t\tnb_joueur = int(input('Combien de joueurs ? 1 ou 2 : '))\n\texcept:\n\t\tnb_joueur = 0\n\nif nb_joueur == 1:\n\tprint(\"Vous allez jouer contre l'ordinateur \\n\")\n\n\n# Scores \nscores = resetScores(nb_joueur)\n\n# Dernier gagnant ( pour déterminer qui commence la partie )\ndernier_gagnant = 0 # 0 au début, 1 pour joueur_1, 2 pour joueur_2 ou ordinateur\nrejouer = True\nwhile rejouer == True:\n\t# Début de partie\n\t# On crée une nouvelle grille\n\tgrille = grid()\n\tprint(grille)\n\n\tif dernier_gagnant == 0:\n\t\tdernier_gagnant = randrange(1, 3)\n\t\t# On détermine aléatoirement celui qui commence\n\n\twhile grille.end == False:\n\t\tif dernier_gagnant == 1:\n\t\t\tgrille = playerPlay(1, grille) # Joueur 1\n\t\t\tif nb_joueur == 1: # Ensuite on fait jouer soit l'ordi soit joueur 2\n\t\t\t\tgrille = ordinateurPlay(grille) # Puis ordinateur\n\t\t\telse:\n\t\t\t\tgrille = playerPlay(2, grille) # Puis joueur 2\n\t\telse: # Si ce n'est pas au joueur 1 de jouer on fait jouer soit l'ordi soit le joueur 2\n\t\t\tif nb_joueur == 1:\n\t\t\t\tgrille = ordinateurPlay(grille) # Ordinateur\n\t\t\t\tgrille = playerPlay(1, grille) # Puis joueur 1\n\t\t\telse:\n\t\t\t\tgrille = playerPlay(2, grille) # Joueur 2\n\t\t\t\tgrille = playerPlay(1, grille) # Puis joueur 1\n\n\tscores = addScores(scores, grille.winner)\n\tif grille.winner == 0:\n\t\tprint('Fin de la partie ! Match nul ')\n\telse:\n\t\tprint('Fin de la partie ! Victoire du joueur ' + str(grille.winner))\n\tdernier_gagnant = grille.winner\n\t# Fin de la partie, on demande si on rejoue\n\trejouer = input('Voulez-vous rejouer ? (o/n) : ')\n\tif rejouer == 'o' or rejouer == 'O':\n\t\trejouer = True\n\t\tdel(grille)\n\t\tos.system('cls')\n\telse:\n\t\trejouer = False\n\t\tprintScores(scores, nb_joueur)\nos.system('pause')","sub_path":"Console game/Tic Tac Toe/jeu.py","file_name":"jeu.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"631368513","text":"import numpy as np\nimport pytest\nimport tensorflow as tf\nfrom lab.tensorflow import B\nfrom matrix import Diagonal, Zero\n\nfrom stheno.input import Input, Unique, WeightedUnique, MultiInput\nfrom stheno.kernel import (\n EQ,\n RQ,\n Matern12,\n Matern32,\n Matern52,\n Delta,\n FixedDelta,\n Kernel,\n Linear,\n OneKernel,\n ZeroKernel,\n PosteriorKernel,\n ShiftedKernel,\n TensorProductKernel,\n CorrectiveKernel,\n DecayingKernel,\n LogKernel,\n perturb,\n num_elements,\n)\nfrom stheno.measure import FDD\nfrom .util import approx\n\n\ndef standard_kernel_tests(k, shapes=None, dtype=np.float64):\n if shapes is None:\n shapes = [\n ((10, 2), (5, 2)),\n ((10, 1), (5, 1)),\n ((10,), (5, 1)),\n ((10, 1), (5,)),\n ((10,), (5,)),\n ((10,), ()),\n ((), (5,)),\n ((), ()),\n ]\n\n # Check various shapes of arguments.\n for shape1, shape2 in shapes:\n x1 = B.randn(dtype, *shape1)\n x2 = B.randn(dtype, *shape2)\n\n # Check that the kernel computes consistently.\n approx(k(x1, x2), B.transpose(reversed(k)(x2, x1)))\n\n # Check `elwise`.\n x2 = B.randn(dtype, *shape1)\n approx(k.elwise(x1, x2), B.diag(k(x1, x2))[:, None])\n # Check againtst fallback brute force computation.\n approx(k.elwise(x1, x2), Kernel.elwise(k, x1, x2))\n # The element-wise computation is more accurate, which is why we allow a\n # discrepancy a bit larger than the square root of the machine epsilon.\n approx(k.elwise(x1)[:, 0], B.diag(k(x1)), atol=1e-6, rtol=1e-6)\n approx(k.elwise(x1), Kernel.elwise(k, x1))\n\n\ndef test_corner_cases():\n with pytest.raises(RuntimeError):\n Kernel()(1.0)\n\n\n@pytest.mark.parametrize(\n \"x1\", [B.randn(10), Input(B.randn(10)), FDD(None, B.randn(10))]\n)\n@pytest.mark.parametrize(\n \"x2\", [B.randn(10), Input(B.randn(10)), FDD(None, B.randn(10))]\n)\ndef test_construction(x1, x2):\n k = EQ()\n\n k(x1)\n k(x1, x2)\n\n k.elwise(x1)\n k.elwise(x1, x2)\n\n # Test `MultiInput` construction.\n approx(\n k(MultiInput(x1, x2)),\n B.concat2d([k(x1, x1), k(x1, x2)], [k(x2, x1), k(x2, x2)]),\n )\n approx(k(x1, MultiInput(x1, x2)), B.concat(k(x1, x1), k(x1, x2), axis=1))\n approx(k(MultiInput(x1, x2), x2), B.concat(k(x1, x2), k(x2, x2), axis=0))\n\n approx(\n k.elwise(MultiInput(x1, x2)),\n B.concat(k.elwise(x1, x1), k.elwise(x2, x2), axis=0),\n )\n with pytest.raises(ValueError):\n k.elwise(MultiInput(x1), MultiInput(x1, x2))\n with pytest.raises(ValueError):\n k.elwise(x1, MultiInput(x1, x2))\n with pytest.raises(ValueError):\n k.elwise(MultiInput(x1, x2), x2)\n\n\ndef test_basic_arithmetic():\n k1 = EQ()\n k2 = RQ(1e-1)\n k3 = Matern12()\n k4 = Matern32()\n k5 = Matern52()\n k6 = Delta()\n k7 = Linear()\n xs1 = B.randn(10, 2), B.randn(20, 2)\n xs2 = B.randn(), B.randn()\n\n approx(k6(xs1[0]), k6(xs1[0], xs1[0]))\n approx((k1 * k2)(*xs1), k1(*xs1) * k2(*xs1))\n approx((k1 * k2)(*xs2), k1(*xs2) * k2(*xs2))\n approx((k3 + k4)(*xs1), k3(*xs1) + k4(*xs1))\n approx((k3 + k4)(*xs2), k3(*xs2) + k4(*xs2))\n approx((5.0 * k5)(*xs1), 5.0 * k5(*xs1))\n approx((5.0 * k5)(*xs2), 5.0 * k5(*xs2))\n approx((5.0 + k7)(*xs1), 5.0 + k7(*xs1))\n approx((5.0 + k7)(*xs2), 5.0 + k7(*xs2))\n approx(k1.stretch(2.0)(*xs1), k1(xs1[0] / 2.0, xs1[1] / 2.0))\n approx(k1.stretch(2.0)(*xs2), k1(xs2[0] / 2.0, xs2[1] / 2.0))\n approx(k1.periodic(1.0)(*xs1), k1.periodic(1.0)(xs1[0], xs1[1] + 5.0))\n approx(k1.periodic(1.0)(*xs2), k1.periodic(1.0)(xs2[0], xs2[1] + 5.0))\n\n\ndef test_reversal():\n x1 = B.randn(10, 2)\n x2 = B.randn(5, 2)\n x3 = B.randn()\n\n # Test with a stationary and non-stationary kernel.\n for k in [EQ(), Linear()]:\n approx(k(x1), reversed(k)(x1))\n approx(k(x3), reversed(k)(x3))\n approx(k(x1, x2), reversed(k)(x1, x2))\n approx(k(x1, x2), reversed(k)(x2, x1).T)\n\n # Test double reversal does the right thing.\n approx(k(x1), reversed(reversed(k))(x1))\n approx(k(x3), reversed(reversed(k))(x3))\n approx(k(x1, x2), reversed(reversed(k))(x1, x2))\n approx(k(x1, x2), reversed(reversed(k))(x2, x1).T)\n\n # Verify that the kernel has the right properties.\n k = reversed(EQ())\n assert k.stationary\n\n k = reversed(Linear())\n assert not k.stationary\n assert str(k) == \"Reversed(Linear())\"\n\n # Check equality.\n assert reversed(Linear()) == reversed(Linear())\n assert reversed(Linear()) != Linear()\n assert reversed(Linear()) != reversed(EQ())\n assert reversed(Linear()) != reversed(DecayingKernel(1, 1))\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_delta():\n k = Delta()\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n assert str(k) == \"Delta()\"\n\n # Check equality.\n assert Delta() == Delta()\n assert Delta() != Delta(epsilon=k.epsilon * 10)\n assert Delta() != EQ()\n\n\n@pytest.mark.parametrize(\n \"x1, w1, x2, w2\",\n [\n (np.array(0), np.ones(1), np.array(1), np.ones(1)),\n (B.randn(10), np.ones(10), B.randn(5), np.ones(5)),\n (B.randn(10, 1), np.ones(10), B.randn(5, 1), np.ones(5)),\n (B.randn(10, 2), np.ones(10), B.randn(5, 2), np.ones(5)),\n ],\n)\ndef test_delta_evaluations(x1, w1, x2, w2):\n k = Delta()\n n1 = num_elements(x1)\n n2 = num_elements(x2)\n\n # Check uniqueness checks.\n approx(k(x1), B.eye(n1))\n approx(k(x1, x2), B.zeros(n1, n2))\n\n # Standard tests:\n standard_kernel_tests(k)\n\n # Test `Unique` inputs.\n assert isinstance(k(Unique(x1), Unique(x1.copy())), Zero)\n assert isinstance(k(Unique(x1), Unique(x1)), Diagonal)\n assert isinstance(k(Unique(x1), x1), Zero)\n assert isinstance(k(x1, Unique(x1)), Zero)\n\n approx(k.elwise(Unique(x1), Unique(x1.copy())), B.zeros(n1, 1))\n approx(k.elwise(Unique(x1), Unique(x1)), B.ones(n1, 1))\n approx(k.elwise(Unique(x1), x1), B.zeros(n1, 1))\n\n # Test `WeightedUnique` inputs.\n assert isinstance(k(WeightedUnique(x1, w1), WeightedUnique(x1.copy(), w1)), Zero)\n assert isinstance(k(WeightedUnique(x1, w1), WeightedUnique(x1, w1)), Diagonal)\n assert isinstance(k(WeightedUnique(x1, w1), x1), Zero)\n assert isinstance(k(x1, WeightedUnique(x1, w1)), Zero)\n\n approx(\n k.elwise(WeightedUnique(x1, w1), WeightedUnique(x1.copy(), w1)), B.zeros(n1, 1)\n )\n approx(k.elwise(WeightedUnique(x1, w1), WeightedUnique(x1, w1)), B.ones(n1, 1))\n approx(k.elwise(WeightedUnique(x1, w1), x1), B.zeros(n1, 1))\n approx(k.elwise(x1, WeightedUnique(x1, w1)), B.zeros(n1, 1))\n approx(k.elwise(x1, WeightedUnique(x1, w1)), B.zeros(n1, 1))\n\n\ndef test_fixed_delta():\n noises = B.rand(3)\n k = FixedDelta(noises)\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n assert str(k) == \"FixedDelta()\"\n\n # Check equality.\n assert FixedDelta(noises) == FixedDelta(noises)\n assert FixedDelta(noises) != FixedDelta(2 * noises)\n assert FixedDelta(noises) != EQ()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n # Check correctness.\n x1 = B.randn(5)\n x2 = B.randn(5)\n approx(k(x1), B.zeros(5, 5))\n approx(k.elwise(x1), B.zeros(5, 1))\n approx(k(x1, x2), B.zeros(5, 5))\n approx(k.elwise(x1, x2), B.zeros(5, 1))\n\n x1 = B.randn(3)\n x2 = B.randn(3)\n approx(k(x1), B.diag(noises))\n approx(k.elwise(x1), B.uprank(noises))\n approx(k(x1, x2), B.zeros(3, 3))\n approx(k.elwise(x1, x2), B.zeros(3, 1))\n\n\ndef test_eq():\n k = EQ()\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n assert str(k) == \"EQ()\"\n\n # Test equality.\n assert EQ() == EQ()\n assert EQ() != Linear()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_rq():\n k = RQ(1e-1)\n\n # Verify that the kernel has the right properties.\n assert k.alpha == 1e-1\n assert k.stationary\n assert str(k) == \"RQ(0.1)\"\n\n # Test equality.\n assert RQ(1e-1) == RQ(1e-1)\n assert RQ(1e-1) != RQ(2e-1)\n assert RQ(1e-1) != Linear()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_exp():\n k = Matern12()\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n assert str(k) == \"Exp()\"\n\n # Test equality.\n assert Matern12() == Matern12()\n assert Matern12() != Linear()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_mat32():\n k = Matern32()\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n assert str(k) == \"Matern32()\"\n\n # Test equality.\n assert Matern32() == Matern32()\n assert Matern32() != Linear()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_mat52():\n k = Matern52()\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n assert str(k) == \"Matern52()\"\n\n # Test equality.\n assert Matern52() == Matern52()\n assert Matern52() != Linear()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_one():\n k = OneKernel()\n\n x1 = B.randn(10, 2)\n x2 = B.randn(5, 2)\n\n # Test that the kernel computes correctly.\n approx(k(x1, x2), np.ones((10, 5)))\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n assert str(k) == \"1\"\n\n # Test equality.\n assert OneKernel() == OneKernel()\n assert OneKernel() != Linear()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_zero():\n k = ZeroKernel()\n x1 = B.randn(10, 2)\n x2 = B.randn(5, 2)\n\n # Test that the kernel computes correctly.\n approx(k(x1, x2), np.zeros((10, 5)))\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n assert str(k) == \"0\"\n\n # Test equality.\n assert ZeroKernel() == ZeroKernel()\n assert ZeroKernel() != Linear()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_linear():\n k = Linear()\n\n # Verify that the kernel has the right properties.\n assert not k.stationary\n assert str(k) == \"Linear()\"\n\n # Test equality.\n assert Linear() == Linear()\n assert Linear() != EQ()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_decaying_kernel():\n k = DecayingKernel(3.0, 4.0)\n\n # Verify that the kernel has the right properties.\n assert not k.stationary\n assert str(k) == \"DecayingKernel(3.0, 4.0)\"\n\n # Test equality.\n assert DecayingKernel(3.0, 4.0) == DecayingKernel(3.0, 4.0)\n assert DecayingKernel(3.0, 4.0) != DecayingKernel(3.0, 5.0)\n assert DecayingKernel(3.0, 4.0) != DecayingKernel(4.0, 4.0)\n assert DecayingKernel(3.0, 4.0) != EQ()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_log_kernel():\n k = LogKernel()\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n assert str(k) == \"LogKernel()\"\n\n # Test equality.\n assert LogKernel() == LogKernel()\n assert LogKernel() != EQ()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_posterior_kernel():\n k = PosteriorKernel(EQ(), EQ(), EQ(), B.randn(5, 2), EQ()(B.randn(5, 1)))\n\n # Verify that the kernel has the right properties.\n assert not k.stationary\n assert str(k) == \"PosteriorKernel()\"\n\n # Standard tests:\n standard_kernel_tests(k, shapes=[((10, 2), (5, 2))])\n\n\ndef test_corrective_kernel():\n a, b = B.randn(3, 3), B.randn(3, 3)\n a, b = a.dot(a.T), b.dot(b.T)\n z = B.randn(3, 2)\n k = CorrectiveKernel(EQ(), EQ(), z, a, b)\n\n # Verify that the kernel has the right properties.\n assert not k.stationary\n assert str(k) == \"CorrectiveKernel()\"\n\n # Standard tests:\n standard_kernel_tests(k, shapes=[((10, 2), (5, 2))])\n\n\ndef test_sum():\n k1 = EQ().stretch(2)\n k2 = 3 * RQ(1e-2).stretch(5)\n k = k1 + k2\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n\n # Test equality.\n assert EQ() + Linear() == EQ() + Linear()\n assert EQ() + Linear() == Linear() + EQ()\n assert EQ() + Linear() != EQ() + RQ(1e-1)\n assert EQ() + Linear() != RQ(1e-1) + Linear()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_product():\n k = (2 * EQ().stretch(10)) * (3 * RQ(1e-2).stretch(20))\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n\n # Test equality.\n assert EQ() * Linear() == EQ() * Linear()\n assert EQ() * Linear() == Linear() * EQ()\n assert EQ() * Linear() != EQ() * RQ(1e-1)\n assert EQ() * Linear() != RQ(1e-1) * Linear()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_stretched():\n k = EQ().stretch(2)\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n\n # Test equality.\n assert EQ().stretch(2) == EQ().stretch(2)\n assert EQ().stretch(2) != EQ().stretch(3)\n assert EQ().stretch(2) != Matern12().stretch(2)\n\n # Standard tests:\n standard_kernel_tests(k)\n\n k = EQ().stretch(1, 2)\n\n # Verify that the kernel has the right properties.\n assert not k.stationary\n\n # Check passing in a list.\n k = EQ().stretch(np.array([1, 2]))\n k(B.randn(10, 2))\n\n\ndef test_periodic():\n k = EQ().stretch(2).periodic(3)\n\n # Verify that the kernel has the right properties.\n assert str(k) == \"(EQ() > 2) per 3\"\n assert k.stationary\n\n # Test equality.\n assert EQ().periodic(2) == EQ().periodic(2)\n assert EQ().periodic(2) != EQ().periodic(3)\n assert Matern12().periodic(2) != EQ().periodic(2)\n\n # Standard tests:\n standard_kernel_tests(k)\n\n k = 5 * k.stretch(5)\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n\n # Check passing in a list.\n k = EQ().periodic(np.array([1, 2]))\n k(B.randn(10, 2))\n\n # Check periodication of a zero.\n k = ZeroKernel()\n assert k.periodic(3) is k\n\n\ndef test_scaled():\n k = 2 * EQ()\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n\n # Test equality.\n assert 2 * EQ() == 2 * EQ()\n assert 2 * EQ() != 3 * EQ()\n assert 2 * EQ() != 2 * Matern12()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n\ndef test_shifted():\n k = ShiftedKernel(2 * EQ(), 5)\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n\n # Test equality.\n assert Linear().shift(2) == Linear().shift(2)\n assert Linear().shift(2) != Linear().shift(3)\n assert Linear().shift(2) != DecayingKernel(1, 1).shift(2)\n\n # Standard tests:\n standard_kernel_tests(k)\n\n k = (2 * EQ()).shift(5, 6)\n\n # Verify that the kernel has the right properties.\n assert not k.stationary\n\n # Check computation.\n x1 = B.randn(10, 2)\n x2 = B.randn(5, 2)\n k = Linear()\n approx(k.shift(5)(x1, x2), k(x1 - 5, x2 - 5))\n\n # Check passing in a list.\n k = Linear().shift(np.array([1, 2]))\n k(B.randn(10, 2))\n\n\ndef test_selection():\n k = (2 * EQ().stretch(5)).select(0)\n\n # Verify that the kernel has the right properties.\n assert k.stationary\n\n # Test equality.\n assert EQ().select(0) == EQ().select(0)\n assert EQ().select(0) != EQ().select(1)\n assert EQ().select(0) != Matern12().select(0)\n\n # Standard tests:\n standard_kernel_tests(k)\n\n # Verify that the kernel has the right properties.\n k = (2 * EQ().stretch(5)).select([2, 3])\n assert k.stationary\n\n k = (2 * EQ().stretch(np.array([1, 2, 3]))).select([0, 2])\n assert k.stationary\n\n k = (2 * EQ().periodic(np.array([1, 2, 3]))).select([1, 2])\n assert k.stationary\n\n k = (2 * EQ().stretch(np.array([1, 2, 3]))).select([0, 2], [1, 2])\n assert not k.stationary\n\n k = (2 * EQ().periodic(np.array([1, 2, 3]))).select([0, 2], [1, 2])\n assert not k.stationary\n\n # Test computation of the kernel.\n k1 = EQ().select([1, 2])\n k2 = EQ()\n x = B.randn(10, 3)\n approx(k1(x), k2(x[:, [1, 2]]))\n\n\ndef test_input_transform():\n k = Linear().transform(lambda x: x - 5)\n\n # Verify that the kernel has the right properties.\n assert not k.stationary\n\n def f1(x):\n return x\n\n def f2(x):\n return x ** 2\n\n # Test equality.\n assert EQ().transform(f1) == EQ().transform(f1)\n assert EQ().transform(f1) != EQ().transform(f2)\n assert EQ().transform(f1) != Matern12().transform(f1)\n\n # Standard tests:\n standard_kernel_tests(k)\n\n # Test computation of the kernel.\n k = Linear()\n x1, x2 = B.randn(10, 2), B.randn(10, 2)\n\n k2 = k.transform(lambda x: x ** 2)\n k3 = k.transform(lambda x: x ** 2, lambda x: x - 5)\n\n approx(k(x1 ** 2, x2 ** 2), k2(x1, x2))\n approx(k(x1 ** 2, x2 - 5), k3(x1, x2))\n\n\ndef test_tensor_product():\n k = TensorProductKernel(lambda x: B.sum(x ** 2, axis=1))\n\n # Verify that the kernel has the right properties.\n assert not k.stationary\n\n # Test equality.\n assert k == k\n assert k != TensorProductKernel(lambda x: x)\n assert k != EQ()\n\n # Standard tests:\n standard_kernel_tests(k)\n\n # Test computation of the kernel.\n k = TensorProductKernel(lambda x: x)\n x1 = np.linspace(0, 1, 100)[:, None]\n x2 = np.linspace(0, 1, 50)[:, None]\n approx(k(x1), x1 * x1.T)\n approx(k(x1, x2), x1 * x2.T)\n\n k = TensorProductKernel(lambda x: x ** 2)\n approx(k(x1), x1 ** 2 * (x1 ** 2).T)\n approx(k(x1, x2), (x1 ** 2) * (x2 ** 2).T)\n\n\ndef test_derivative():\n k = EQ().diff(0)\n\n # Check that the kernel has the right properties.\n assert not k.stationary\n\n # Test equality.\n assert EQ().diff(0) == EQ().diff(0)\n assert EQ().diff(0) != EQ().diff(1)\n assert Matern12().diff(0) != EQ().diff(0)\n\n # Standard tests:\n for k in [EQ().diff(0), EQ().diff(None, 0), EQ().diff(0, None)]:\n standard_kernel_tests(k, dtype=tf.float64)\n\n # Check that a derivative must be specified.\n with pytest.raises(RuntimeError):\n EQ().diff(None, None)(np.array([1.0]))\n with pytest.raises(RuntimeError):\n EQ().diff(None, None).elwise(np.array([1.0]))\n\n\ndef test_derivative_eq():\n # Test derivative of kernel `EQ()`.\n k = EQ()\n x1 = B.randn(tf.float64, 10, 1)\n x2 = B.randn(tf.float64, 5, 1)\n\n # Test derivative with respect to first input.\n approx(k.diff(0, None)(x1, x2), -k(x1, x2) * (x1 - B.transpose(x2)))\n approx(k.diff(0, None)(x1), -k(x1) * (x1 - B.transpose(x1)))\n\n # Test derivative with respect to second input.\n approx(k.diff(None, 0)(x1, x2), -k(x1, x2) * (B.transpose(x2) - x1))\n approx(k.diff(None, 0)(x1), -k(x1) * (B.transpose(x1) - x1))\n\n # Test derivative with respect to both inputs.\n ref = k(x1, x2) * (1 - (x1 - B.transpose(x2)) ** 2)\n approx(k.diff(0, 0)(x1, x2), ref)\n approx(k.diff(0)(x1, x2), ref)\n ref = k(x1) * (1 - (x1 - B.transpose(x1)) ** 2)\n approx(k.diff(0, 0)(x1), ref)\n approx(k.diff(0)(x1), ref)\n\n\ndef test_derivative_linear():\n # Test derivative of kernel `Linear()`.\n k = Linear()\n x1 = B.randn(tf.float64, 10, 1)\n x2 = B.randn(tf.float64, 5, 1)\n\n # Test derivative with respect to first input.\n approx(k.diff(0, None)(x1, x2), B.ones(tf.float64, 10, 5) * B.transpose(x2))\n approx(k.diff(0, None)(x1), B.ones(tf.float64, 10, 10) * B.transpose(x1))\n\n # Test derivative with respect to second input.\n approx(k.diff(None, 0)(x1, x2), B.ones(tf.float64, 10, 5) * x1)\n approx(k.diff(None, 0)(x1), B.ones(tf.float64, 10, 10) * x1)\n\n # Test derivative with respect to both inputs.\n ref = B.ones(tf.float64, 10, 5)\n approx(k.diff(0, 0)(x1, x2), ref)\n approx(k.diff(0)(x1, x2), ref)\n ref = B.ones(tf.float64, 10, 10)\n approx(k.diff(0, 0)(x1), ref)\n approx(k.diff(0)(x1), ref)\n\n\n@pytest.mark.parametrize(\n \"x,result\",\n [\n (np.float64([1]), np.float64([1e-20 + 1 + 1e-14])),\n (np.float32([1]), np.float32([1e-20 + 1 + 1e-7])),\n ],\n)\ndef test_perturb(x, result):\n assert perturb(x) == result # Test NumPy.\n assert perturb(tf.constant(x)).numpy() == result # Test TF.\n\n\ndef test_perturb_type_check():\n with pytest.raises(ValueError):\n perturb(0)\n\n\n@pytest.mark.parametrize(\"dtype\", [tf.float32, tf.float64])\ndef test_nested_derivatives(dtype):\n x = B.randn(dtype, 10, 2)\n\n res = EQ().diff(0, 0).diff(0, 0)(x)\n assert ~B.isnan(res[0, 0])\n\n res = EQ().diff(1, 1).diff(1, 1)(x)\n assert ~B.isnan(res[0, 0])\n","sub_path":"tests/test_kernel.py","file_name":"test_kernel.py","file_ext":"py","file_size_in_byte":20297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"550476200","text":"#!/usr/bin/env python3\n\nfrom typing import List\n\n\nclass Solution:\n\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n\n def dfs(lo, n: int, init: bool) -> List[List[int]]:\n if n == 0:\n return [[]]\n\n res = []\n if not init:\n res += dfs(lo, n - 1, False)\n\n for i in range(lo, len(nums) - n + 1):\n if i == lo or nums[i] != nums[i - 1]:\n res += [[nums[i]] + x for x in dfs(i + 1, n - 1, True)]\n\n return res\n\n nums = sorted(nums)\n\n return dfs(0, len(nums), False)\n","sub_path":"90-subsets-ii/subsets_ii.py","file_name":"subsets_ii.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"122957994","text":"import re\ndef and_or_sub(string):\n\tstring = re.sub(r\" \\&& \", ' and ', string)\n\tstring = re.sub(r\" \\|| \", ' or ', string)\n\treturn string\n\t\nif __name__ == '__main__':\n\tn = int(input())\n\toutput_strings = []\n\tfor _ in range(n):\n\t\tstring = input()\n\t\tresult = and_or_sub(string)\n\t\toutput_strings.append(result)\n\tprint(output_strings, sep = '\\n')\n","sub_path":"regex_sub.py","file_name":"regex_sub.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"132843558","text":"from collections import deque\nfrom copy import deepcopy\n\n#initial = [[8, 1, 2], [0, 4, 3], [7, 6, 5]] #NOT SOLVABLE\n#initial = [[1, 8, 2], [0, 4, 3], [7, 6, 5]]\n#initial = [[1, 2, 3], [6, 4, 5], [7, 0, 8]]\n#initial = [[0, 1, 3], [4, 2, 5], [7, 8, 6]]\n#initial = [[1, 2, 3], [5, 6, 0], [7, 8, 4]]\n#initial = [[1, 5, 3], [6, 7, 2], [0, 4, 8]] \n#initial = [[1, 2, 3], [6, 4, 5], [0, 7, 8]]\ninitial = [[8, 1, 3], [4, 0, 2], [7, 6, 5]]\n\n#initial = []\nfinal = []\nrow = [1, 0, -1, 0]\ncol = [0, -1, 0, 1]\nn = int(input())\nsteps = -1\n\nclass node:\n\tdef __init__(self, cost, matrix, parent, x, y, xnew, ynew):\n\t\tself.matrix = matrix\n\t\tself.parent = parent\n\t\tself.x = xnew\n\t\tself.y = ynew\n\t\tself.cost = cost\n\ndef change(matrix, x, y, xnew, ynew):\n\ttemp = matrix[x][y]\n\tmatrix[x][y] = matrix[xnew][ynew]\n\tmatrix[xnew][ynew] = temp\n\ndef printPath(root):\n\tif root is None:\n\t\treturn\n\tprintPath(root.parent)\n\tglobal steps\n\tsteps = steps + 1\n\tdisplay_board(root.matrix)\n\ndef display_board(matrix):\n\tfor i in range(n):\n\t\tprint(matrix[i])\n\tprint('\\n')\n\ndef cost(S, D):\n\treturn (cost1(S, D) + cost2(S, D))\n\ndef cost1(S, D):\n\tcount = 0\n\tfor i in range(n):\n\t\tfor j in range(n):\n\t\t\tif ((S[i][j] != 0) and (S[i][j] != D[i][j])):\n\t\t\t\tcount = count+1\n\treturn count\n\ndef cost2(S, D):\n\tsumm = 0\n\tfor i in range(n*n):\n\t\tfor x1 in range(n):\n\t\t\tfor y1 in range(n):\n\t\t\t\tif (S[x1][y1] == i):\n\t\t\t\t\tbreak\n\t\t\tbreak\n\n\t\tfor x2 in range(n):\n\t\t\tfor y2 in range(n):\n\t\t\t\tif (D[x2][y2] == i):\n\t\t\t\t\tbreak\n\t\t\tbreak\n\t\tsumm = summ + abs(x1-x2) + abs(y1-y2)\n\n\treturn summ\n\ndef isSafe(x, y):\n\treturn (x >= 0 and x < n and y >= 0 and y < n)\n\ndef isSolvable(matrix):\n\tarr = []\n\tfor i in range(n):\n\t\tfor j in range(n):\n\t\t\tarr.append(matrix[i][j])\n\t\n\tinv_count = 0\n\tfor i in range(8):\n\t\tfor j in range(i+1, 9):\n\t\t\tif arr[i] and arr[j] and arr[i] > arr[j]:\n\t\t\t\tinv_count = inv_count + 1\n\treturn (inv_count % 2 == 0)\n\ndef check(current, final):\n\tif current == final:\n\t\treturn True\n\telse :\n\t\treturn False\n\ndef solve(initial, final, a, b):\n\tpriority_queue = deque()\n\troot = node(0, initial, None, a, b, a, b)\n\tif (check(root.matrix, final)):\n\t\tprintPath(root)\n\t\treturn\n\n\tpriority_queue.append(root)\n\tvisited = []\n\tvisited.append(root.matrix)\n\twhile (priority_queue):\n\t\tpriority = sorted(priority_queue, key=lambda node: node.cost)\n\t\tpriority_queue.clear()\n\t\tfor p in priority:\n\t\t\tpriority_queue.append(p)\n\n\t\tmin = priority_queue.popleft()\n\t\tif (check(min.matrix, final)):\n\t\t\tprintPath(min)\n\t\t\tprint(\"Steps taken = \" + str(steps))\n\t\t\treturn\n\n\t\tfor i in range(4):\n\t\t\tif (isSafe(min.x + row[i], min.y + col[i])):\n\n\t\t\t\tnewmatrix = deepcopy(min.matrix)\n\t\t\t\tchange(newmatrix, min.x, min.y, min.x + row[i], min.y + col[i])\n\t\t\t\tcostt = cost(newmatrix, final)\n\t\t\t\tchild = node(costt, newmatrix, min, min.x, min.y, min.x + row[i], min.y + col[i])\n\n\t\t\t\tif child.matrix not in visited:\n\t\t\t\t\tpriority_queue.append(child)\n\t\t\t\t\tvisited.append(child.matrix)\n\ndef initialise():\n\t'''print(\"Enter Initial State:\")\n\tfor _ in range(n):\n\t\ta = input().strip().split(' ')\n\t\tinitial.append([int(x) for x in a])'''\n\n\tprint(\"Enter Final State:\")\n\tfor _ in range(n):\n\t\ta = input().strip().split(' ')\n\t\tfinal.append([int(x) for x in a])\n\n\tif (n == 3 and not isSolvable(initial)):\n\t\tprint(\"Not Solvable!\")\n\t\treturn\n\n\tfor i in range(n):\n\t\tfor j in range(n):\n\t\t\tif (initial[i][j] == 0):\n\t\t\t\tv1 = i\n\t\t\t\tv2 = j\n\t\t\n\tsolve(initial, final, v1, v2)\n\ninitialise()","sub_path":"IAIN532C/LAB2/npuzzle_greedy.py","file_name":"npuzzle_greedy.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"266281183","text":"import subprocess\nimport os\nimport picamera\nimport time\n\naddress = \"1C:AF:05:90:F1:6C@12\"\ncamera = picamera.PiCamera()\nPHOTOCOUNT = 5\nphoto_index = 0\ntime_delay = 1\n\n#BT auto pairing\n\n#photo shoot\nwhile photo_index < PHOTOCOUNT :\n\tcamera.capture(\"image%d.jpg\"%photo_index, resize = (320,240))\n\tphoto_index = photo_index + 1\n\ttime.sleep(time_delay)\n\tprint(\"%d th image captured\"%photo_index)\n\nprint(\"capture done\")\n\n\nfor i in range(1,PHOTOCOUNT):\n\tfilename = \"image{}.jpg\".format(i)\n\tpath_to_file = os.path.join(\"/home/pi/Jaylen\",filename)\n\tcmd = [\"ussp-push\", address, path_to_file, filename]\n\tsubprocess.call(\" \".join(cmd), shell=True)\n\nprint(\"image sent\")\n\n\n\n\n","sub_path":"picamera/send_img_BTopex.py","file_name":"send_img_BTopex.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"148148674","text":"import torch\n#import torch.autograd as autograd\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport pyro\nimport pyro.distributions as dist\n\n\n# in this case, we use the beta distribution....\nclass Policy(nn.Module):\n def __init__(self, num_inputs, num_outputs):\n super(Policy, self).__init__()\n self.affine1 = nn.Linear(num_inputs, 64)\n self.affine2 = nn.Linear(64, 64)\n\n self.action_alpha = nn.Linear(64, num_outputs)\n self.action_alpha.weight.data.mul_(0.1)\n self.action_alpha.bias.data.mul_(0)\n\n self.action_beta = nn.Linear(64, num_outputs)\n self.action_beta.weight.data.mul_(0.1)\n self.action_beta.bias.data.mul_(0)\n\n def forward(self, x):\n x = F.tanh(self.affine1(x))\n x = F.tanh(self.affine2(x))\n\n action_alpha = F.softplus(self.action_alpha(x)) + 1\n action_beta = F.softplus(self.action_beta(x)) + 1\n\n action = dist.beta(action_alpha, action_beta)\n # remove it from the graph...\n action = action.detach()\n # calculate the log probability....\n log_p = dist.beta.log_pdf(action, action_alpha, action_beta)\n \n return action, log_p\n\n\nclass Value(nn.Module):\n def __init__(self, num_inputs):\n super(Value, self).__init__()\n self.affine1 = nn.Linear(num_inputs, 64)\n self.affine2 = nn.Linear(64, 64)\n\n self.value_head = nn.Linear(64, 1)\n self.value_head.weight.data.mul_(0.1)\n self.value_head.bias.data.mul_(0)\n\n def forward(self, x):\n x = F.tanh(self.affine1(x))\n x = F.tanh(self.affine2(x))\n\n state_value = self.value_head(x)\n\n return state_value\n\n\n# ------------------------------------------------------------------------------------- #\n# For Discrete Control Problem.... (Add the lstm....)\nclass Actor_Critic(nn.Module):\n def __init__(self, num_outputs, deterministic=False):\n super(Actor_Critic, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, 8, stride=4, padding=1)\n self.conv2 = nn.Conv2d(32, 64, 4, stride=2, padding=1)\n self.conv3 = nn.Conv2d(64, 64, 3, stride=1, padding=1)\n\n self.lstm = nn.LSTMCell(64 * 9 * 9, 256)\n\n self.linear_action = nn.Linear(256, num_outputs)\n self.linear_action.weight.data.mul_(0.1)\n self.linear_action.bias.data.mul_(0)\n \n self.linear_value = nn.Linear(256, 1)\n self.linear_value.weight.data.mul_(0.1)\n self.linear_value.bias.data.mul_(0)\n\n self.lstm.bias_ih.data.fill_(0)\n self.lstm.bias_hh.data.fill_(0)\n\n self.deterministic = deterministic\n\n\n def forward(self, inputs):\n inputs, (hx, cx) = inputs \n x = F.relu(self.conv1(inputs))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n\n x = x.view(-1, 64*9*9)\n\n hx, cx = self.lstm(x, (hx, cx))\n x = hx\n\n # get the state_value\n value = self.linear_value(x)\n\n # get the action value...\n action_prob = F.softmax(self.linear_action(x))\n\n # sample the action...\n cat_dist = dist.Categorical(action_prob, one_hot=False)\n\n if self.deterministic:\n _, action = torch.max(action_prob, 1)\n action = action.detach()\n action = action.unsqueeze(0)\n else:\n action = cat_dist()\n log_p = cat_dist.log_pdf(action)\n \n # calculate the entropy...\n entropy = -(action_prob * action_prob.log()).sum(1)\n return value, action, log_p, entropy, (hx, cx)\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":"a3c/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"253169405","text":"import pygame\nimport math as maths\nimport time\n\nfrom Level.block_moving import MovingBlock\nfrom Level.platform import Platform\n\n\nclass Player(pygame.sprite.Sprite):\n \"\"\"\n Represents the main character of the game which the player controls.\n \"\"\"\n\n def __init__(self, game):\n \"\"\" Constructor \"\"\"\n\n # Calling the parent's constructor\n super().__init__()\n\n self.game = game\n\n # Speed vectors of player\n self.change_x = 0\n self.change_y = 0\n\n # List of sprites the player can collide with\n self.level = None\n\n # Direction of the player\n self.direction = \"R\"\n\n # Lists that hold the running frames\n self.running_frames_l = []\n self.running_frames_r = []\n\n # Dimensions of player (fat)\n width = int(game.unit_width)\n height = int(game.unit_height * 2)\n\n path = \"D:/Users/lucas.Lucas/Google Drive/Python/Level-0/.images/\"\n\n self.stand = pygame.transform.scale(pygame.image.load(path + \"stand.png\").convert_alpha(), [width, height])\n\n # Right-facing images\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run0.png\").convert_alpha(), [width, height])\n self.running_frames_r.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run1.png\").convert_alpha(), [width, height])\n self.running_frames_r.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run2.png\").convert_alpha(), [width, height])\n self.running_frames_r.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run3.png\").convert_alpha(), [width, height])\n self.running_frames_r.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run4.png\").convert_alpha(), [width, height])\n self.running_frames_r.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run5.png\").convert_alpha(), [width, height])\n self.running_frames_r.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run6.png\").convert_alpha(), [width, height])\n self.running_frames_r.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run7.png\").convert_alpha(), [width, height])\n self.running_frames_r.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run8.png\").convert_alpha(), [width, height])\n self.running_frames_r.append(image)\n\n # Left-facing images\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run0.png\").convert_alpha(), [width, height])\n image = pygame.transform.flip(image, True, False)\n self.running_frames_l.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run1.png\").convert_alpha(), [width, height])\n image = pygame.transform.flip(image, True, False)\n self.running_frames_l.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run2.png\").convert_alpha(), [width, height])\n image = pygame.transform.flip(image, True, False)\n self.running_frames_l.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run3.png\").convert_alpha(), [width, height])\n image = pygame.transform.flip(image, True, False)\n self.running_frames_l.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run4.png\").convert_alpha(), [width, height])\n image = pygame.transform.flip(image, True, False)\n self.running_frames_l.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run5.png\").convert_alpha(), [width, height])\n image = pygame.transform.flip(image, True, False)\n self.running_frames_l.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run6.png\").convert_alpha(), [width, height])\n image = pygame.transform.flip(image, True, False)\n self.running_frames_l.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run7.png\").convert_alpha(), [width, height])\n image = pygame.transform.flip(image, True, False)\n self.running_frames_l.append(image)\n image = pygame.transform.scale(pygame.image.load(path + \"player_run/run8.png\").convert_alpha(), [width, height])\n image = pygame.transform.flip(image, True, False)\n self.running_frames_l.append(image)\n\n # Starting image\n self.image = self.stand\n\n # Image rectangle for collision\n self.rect = self.image.get_rect()\n\n # Hit points\n self.hp = 100\n\n # Dash control: dashing?, dash time, x, y\n self.dash_list = [False, time.time(), 0, 0]\n\n self.mouse = []\n\n # Energy\n self.energy = 100\n\n # Handling automatic shooting\n self.cooldown = 0.1\n self.shot_time = 0\n self.shooting = False\n\n self.jump_count = 2\n\n # Reverse gravity\n self.reverse_gravity = False\n\n def update(self):\n \"\"\" Moving the player. \"\"\"\n\n # Gravity\n\n if not self.dash_list[0]:\n self.calc_gravity()\n\n # Move left/right\n self.rect.x += self.change_x\n\n # Player position\n pos = self.rect.x + self.level.level_shift\n\n # Animating\n if self.direction == \"R\" and self.change_x != 0:\n frame = (pos // 20) % len(self.running_frames_r)\n if self.reverse_gravity:\n self.image = pygame.transform.flip(self.running_frames_r[frame], False, True)\n else:\n self.image = self.running_frames_r[frame]\n elif self.change_x != 0:\n frame = (pos // 20) % len(self.running_frames_l)\n if self.reverse_gravity:\n self.image = pygame.transform.flip(self.running_frames_l[frame], False, True)\n else:\n self.image = self.running_frames_l[frame]\n else:\n if self.direction == \"R\":\n if self.reverse_gravity:\n self.image = pygame.transform.flip(self.stand, False, True)\n else:\n self.image = self.stand\n else:\n if self.reverse_gravity:\n self.image = pygame.transform.flip(pygame.transform.flip(self.stand, True, False), False, True)\n else:\n self.image = pygame.transform.flip(self.stand, True, False)\n\n # See if we hit anything\n block_hit_list = pygame.sprite.spritecollide(self, self.level.block_list, False)\n for block in block_hit_list:\n # If we are moving right, set our right side to the left side of the item we hit\n if self.change_x > 0:\n self.rect.right = block.rect.left\n elif self.change_x < 0:\n # Otherwise if we are moving left, do the opposite.\n self.rect.left = block.rect.right\n\n # Move up/down\n self.rect.y += self.change_y\n\n # Check and see if we hit anything\n block_hit_list = pygame.sprite.spritecollide(self, self.level.block_list, False)\n for block in block_hit_list:\n\n # Reset our position based on the top/bottom of the object\n if self.change_y > 0:\n self.rect.bottom = block.rect.top\n elif self.change_y < 0 and not isinstance(block, Platform):\n self.rect.top = block.rect.bottom\n\n # Stop our vertical movement\n self.change_y = 0\n\n if isinstance(block, MovingBlock):\n self.rect.x += block.change_x\n\n # Energy regeneration\n self.energy += .2\n if self.energy > 100:\n self.energy = 100\n if self.energy < 0:\n self.energy = 0\n\n # Check if there is a platform below us\n # Move down 2 pixels because it doesn't work well if we only move down 1\n if not self.reverse_gravity:\n self.rect.y += 2\n platform_hit_list = pygame.sprite.spritecollide(self, self.level.block_list, False)\n self.rect.y -= 2\n else:\n self.rect.y -= 2\n platform_hit_list = pygame.sprite.spritecollide(self, self.level.block_list, False)\n self.rect.y += 2\n\n # Reset jump count\n if len(platform_hit_list) > 0 or self.rect.bottom >= self.game.screen_height\\\n or (self.rect.top <= 0 and self.reverse_gravity):\n self.jump_count = 2\n\n def calc_gravity(self):\n \"\"\" Calculate effect of gravity. \"\"\"\n\n if self.change_y == 0:\n if self.reverse_gravity:\n self.change_y = -1\n else:\n self.change_y = 1\n else:\n if self.reverse_gravity:\n self.change_y += -.35\n else:\n self.change_y += .35\n\n # See if we are on the ground.\n if self.rect.y >= self.game.screen_height - self.rect.height and self.change_y >= 0:\n self.change_y = 0\n self.rect.y = self.game.screen_height - self.rect.height\n # See if we are on the ceiling\n if self.rect.y <= 0 and self.change_y <= 0:\n self.change_y = 0\n self.rect.y = 0\n\n # Player-controlled movement:\n\n def jump(self):\n \"\"\" Called when user hits 'jump' button. \"\"\"\n\n if self.jump_count > 0:\n if not self.reverse_gravity:\n self.change_y = -10\n else:\n self.change_y = 10\n self.jump_count -= 1\n\n def go_left(self):\n \"\"\" Called when the user hits the left arrow. \"\"\"\n\n self.change_x = -7\n self.direction = \"L\"\n\n def go_right(self):\n \"\"\" Called when the user hits the right arrow. \"\"\"\n\n self.change_x = 7\n self.direction = \"R\"\n\n def stop(self):\n \"\"\" Called when the user lets off the keyboard. \"\"\"\n\n self.change_x = 0\n \n def dash(self):\n \"\"\" Moves the player towards the mouse. \"\"\"\n\n self.dash_list[1] = time.time()\n diff_x = self.mouse[0] - self.rect.x\n diff_y = self.mouse[1] - self.rect.y\n # Preventing division by zero\n if diff_x == 0:\n diff_x = 1\n # Calculating the angle\n velocity = 15\n angle = maths.atan(diff_y / diff_x)\n if diff_x < 0:\n angle = maths.pi - angle\n angle *= -1\n # Calculating movement\n self.dash_list = [True, time.time(), velocity * maths.cos(angle), velocity * maths.sin(angle)]\n self.energy -= 25\n self.change_x = self.dash_list[2]\n self.change_y = self.dash_list[3]\n","sub_path":"Animate/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":10861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"547196645","text":"import pandas as pd\nimport numpy as np\n\nnumbers = [9, 23, 33, 91, 13, 7]\nplayers = [\"Ron Harper\", \"Michael Jordan\", \"Scottie Pippen\", \"Dennis Rodman\", \"Luc Longley\", \"Toni Kukoc\"]\ncolleges = [\"Miami University\", \"University of North Carolina\", \"University of Central Arkansas\", \"Southeastern Oklahoma State University\", \"University of New Mexico\", None] # None 替換為 np.nan 亦可\ndf = pd.DataFrame()\ndf[\"number\"] = numbers\ndf[\"player\"] = players\ndf[\"college\"] = colleges\nprint(df[\"college\"].isna()) # 判斷大學是否有遺漏值\ndf[df[\"college\"].isna()] # 篩選出大學為遺漏值的列數","sub_path":"dsia_demo_codes/ch0807.py","file_name":"ch0807.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"369816333","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 27 06:47:19 2020\n\nScript to illustrate calculation of partial derivatives using finite differences\n\n@author: zettergm\n\"\"\"\n\n# Imports\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# Grid and function to be differentiated\nlx=20\nly=20\nx=np.linspace(-5,5,lx)\ny=np.linspace(-5,5,ly)\n[X,Y]=np.meshgrid(x,y)\nf=np.exp(-X**2/2/2)*np.exp(-Y**2/2/1)\n# Possibly compute gradient and laplacian analytically to test...\n\n# Coordinate differences\ndx=x[1]-x[0]\ndy=y[1]-y[0]\n\n\n# Compute the gradient of f, centered diffs. with fwd/bwd at edges\ngradx=np.zeros((ly,lx)) #note first index is treated as \"y\"\ngrady=np.zeros((ly,lx))\ngradx[:,0]=(f[:,1]-f[:,0])/dx\nfor ix in range(1,lx-1):\n gradx[:,ix]=(f[:,ix+1]-f[:,ix-1])/2/dx\ngradx[:,lx-1]=(f[:,lx-1]-f[:,lx-2])/dx\n\ngrady[0,:]=(f[1,:]-f[0,:])/dy\nfor iy in range(1,lx-1):\n grady[iy,:]=(f[iy+1,:]-f[iy-1,:])/2/dy\ngrady[lx-1,:]=(f[ly-1,:]-f[ly-2])/dy\n\n\n# Compute Laplacian f by taking div(grad(f)), centered diffs + edges as above\ndivx=np.zeros((ly,lx))\ndivx[:,0]=(gradx[:,1]-gradx[:,0])/dx\nfor ix in range(0,lx-1):\n divx[:,ix]=(gradx[:,ix+1]-gradx[:,ix-1])/2/dx\ndivx[:,lx-1]=(gradx[:,lx-1]-gradx[:,lx-2])/dx\n\ndivy=np.zeros((ly,lx))\ndivy[0,:]=(grady[1,:]-grady[0,:])/dy\nfor iy in range(0,ly-1):\n divy[iy,:]=(grady[iy+1,:]-grady[iy-1,:])/2/dy\ndivy[ly-1,:]=(grady[ly-1,:]-grady[iy-2,:])/dy\nlaplacianf=divx+divy\n\n\n# Take curl of the gradient (to check that is ~0); only concerned with z-comp\n# dvy/dx - dvx/dy is z-comp of curl\ncurlx=np.zeros((ly,lx))\ncurlx[:,0]=(grady[:,1]-grady[:,0])/dx\nfor ix in range(0,lx-1):\n curlx[:,ix]=(grady[:,ix+1]-grady[:,ix-1])/2/dx\ncurlx[:,lx-1]=(grady[:,lx-1]-grady[:,lx-2])/dx\n\ncurly=np.zeros((ly,lx))\ncurly[0,:]=(gradx[1,:]-gradx[0,:])/dy\nfor iy in range(0,ly-1):\n curly[iy,:]=(gradx[iy+1,:]-gradx[iy-1,:])/2/dy\ncurly[ly-1,:]=(gradx[ly-1,:]-gradx[ly-2,:])/dy\ncurl=curlx-curly\n\n\n# Plot the function and derivatives\nplt.figure(1)\nplt.pcolor(X,Y,f)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"f(x,y) and grad(f)\")\nplt.colorbar()\nplt.quiver(X,Y,gradx,grady,color=\"white\",scale=10)\nplt.show()\n\nplt.figure(2)\nplt.pcolor(X,Y,laplacianf)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"laplacian(f)\")\nplt.colorbar()\nplt.show()\n\nplt.figure(3)\nplt.pcolor(X[1:-2,1:-2],Y[1:-2,1:-2],curl[1:-2,1:-2])\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"curl(grad(f))\")\nplt.colorbar()\nplt.show()\n","sub_path":"differentiation/partial_derivative_examples.py","file_name":"partial_derivative_examples.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"328702640","text":"### ---------------------------------------------------------------------------\n### Create by Skeleton!!! (adapted for L2JLisvus by roko91)\n### ---------------------------------------------------------------------------\n\nimport sys\nfrom net.sf.l2j.gameserver.model.quest import State\nfrom net.sf.l2j.gameserver.model.quest import QuestState\nfrom net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest\n\nqn = \"28_ChestCaughtWithABaitOfIcyAir\"\n\n# NPC List\nOFulle=8572\nKiki=8442\n# ~~~\n# Item List\nBigYellowTreasureChest=6503\nKikisLetter=7626\nElvenRing=881\n# ~~~\n\nclass Quest (JQuest) :\n\n def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)\n\n def onEvent (self,event,st) :\n htmltext=event\n if event==\"8572-04.htm\" :\n st.set(\"cond\",\"1\")\n st.playSound(\"ItemSound.quest_accept\")\n elif event==\"8572-07.htm\" :\n if st.getQuestItemsCount(BigYellowTreasureChest) :\n st.set(\"cond\",\"2\")\n st.takeItems(BigYellowTreasureChest,1)\n st.giveItems(KikisLetter,1)\n else :\n htmltext=\"8572-08.htm\"\n elif event==\"8442-02.htm\" :\n if st.getQuestItemsCount(KikisLetter)==1 :\n htmltext=\"8442-02.htm\"\n st.takeItems(KikisLetter,-1)\n st.giveItems(ElvenRing,1)\n st.unset(\"cond\")\n st.setState(COMPLETED)\n st.playSound(\"ItemSound.quest_finish\")\n else :\n htmltext=\"8442-03.htm\"\n return htmltext\n\n def onTalk (self,npc,st):\n htmltext = \"no-quest.htm\"\n npcId = npc.getNpcId()\n id=st.getState()\n if id==CREATED :\n st.setState(STARTED)\n st.set(\"cond\",\"0\")\n cond=st.getInt(\"cond\")\n id = st.getState()\n if npcId==OFulle :\n if cond==0 and id==STARTED:\n if st.getPlayer().getLevel() >= 36 :\n OFullesSpecialBait= st.getPlayer().getQuestState(\"51_OFullesSpecialBait\")\n if OFullesSpecialBait :\n if OFullesSpecialBait.getState().getName() == 'Completed':\n htmltext=\"8572-01.htm\"\n else :\n htmltext=\"8572-02.htm\"\n st.exitQuest(1)\n else :\n htmltext=\"8572-03.htm\"\n st.exitQuest(1)\n else :\n htmltext=\"8572-02.htm\"\n elif cond==1 :\n htmltext=\"8572-05.htm\"\n if st.getQuestItemsCount(BigYellowTreasureChest)==0 :\n htmltext=\"8572-06.htm\"\n elif cond==2 :\n htmltext=\"8572-09.htm\"\n elif cond==0 and id==COMPLETED :\n htmltext=\"This quest has already been completed.\"\n elif npcId==Kiki :\n if cond==2 :\n htmltext=\"8442-01.htm\"\n return htmltext\n\nQUEST = Quest(28,qn,\"Chest Caught With A Bait Of Icy Air\")\nCREATED = State('Start', QUEST)\nSTARTED = State('Started', QUEST)\nCOMPLETED = State('Completed', QUEST)\n\nQUEST.setInitialState(CREATED)\nQUEST.addStartNpc(OFulle)\nQUEST.addTalkId(OFulle)\nQUEST.addTalkId(Kiki)","sub_path":"DataPack/data/scripts/quests/28_ChestCaughtWithABaitOfIcyAir/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"394701620","text":"# -*- coding: utf-8 -*-\n\"\"\"\nFlight Track Visualization Testing\n\nCreated on Fri Aug 21 18:58:10 2015\n@author: Justin\n\"\"\"\n\nimport importlib.machinery\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D, art3d\nfrom matplotlib.patches import Rectangle\n\n#%% Get Track Data\n\n#filename = 'C:/Users/jed/Documents/GitHub/Flight_Track_Visualization/Example_Tracks/LT6_Single_Flight_Track.txt'\nfilename = 'C:/Users/jed/Documents/GitHub/Flight_Track_Visualization/Example_Tracks/20140801.lt6'\n\nloader = importlib.machinery.SourceFileLoader('isd','import_and_structure_data.py')\nisd = loader.load_module('isd')\n\ntracks = isd.get_tracks(filename)\n\n#%% Generate Animation\n\ndef plot_track(track_obj, dim):\n fig = plt.figure()\n \n \n if dim == '2d':\n ax = plt.plot(track_obj.x, track_obj.y)\n elif dim == '3d':\n #ax = fig.gca(projection = '3d') \n #ax = fig.add_subplot(111, projection='3d')\n ax = Axes3D(fig)\n #Draw Runway\n rwy = Rectangle((-1250.529, 1166.953), 3021.95, 61, angle=-3, color='grey') #angle=350.12 angle=-9.88\n ax.add_patch(rwy)\n art3d.pathpatch_2d_to_3d(rwy, z=0,zdir=\"z\")\n \n ax.plot(track_obj.x, track_obj.y, zs = track_obj.z)\n elif dim == '3da':\n ax = fig.gca(projection = '3d')\n u = 1; v = 1; w = 1;\n ax.quiver(track_obj.x, track_obj.y, track_obj.z, u, v, w, length = 100) #self.s)\n ax.set_aspect('equal')\n ax.set_xlim(-2000,20000)\n ax.set_ylim(-3000,5000)\n ax.set_zlim(0,1500)\n plt.show()\n \n#%% Test run area\n \nplot_track(tracks[1],'3d')","sub_path":"Flight_Tracks/Archive/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"498005856","text":"import random\nfrom collections import defaultdict\nimport operator\n\n\ndef evaluate_baseline(pairscore, question, type, combination_models):\n eta = 0.1\n T = 10\n final_weight = defaultdict(lambda: defaultdict())\n for prod_key in pairscore:\n for each_question in pairscore[prod_key]:\n if combination_models:\n question_weight = defaultdict(lambda: list())\n w = [random.random() for _ in range(2)]\n sum_weights = 0\n for i in range(0, 2):\n sum_weights += w[i]\n for i in range(0, 2):\n w[i] = w[i] / sum_weights\n else:\n question_weight = defaultdict(lambda: 0)\n w = random.random()\n for each_review in pairscore[prod_key][each_question]:\n t = 0\n while t < T:\n t += 1\n if combination_models:\n sum = pairscore[prod_key][each_question][each_review]['ROGUE'] + \\\n pairscore[prod_key][each_question][each_review]['BM25+']\n total_sum = w[0] * pairscore[prod_key][each_question][each_review]['ROGUE'] + \\\n w[1] * pairscore[prod_key][each_question][each_review]['BM25+']\n else:\n total_sum = w * pairscore[prod_key][each_question][each_review][type]\n if total_sum > 0.5:\n if question[prod_key][0]['A'] == False:\n if combination_models:\n w[0] -= eta\n w[1] -= eta\n else:\n w -= eta\n else:\n if question[prod_key][0]['A'] == True:\n if combination_models:\n w[0] += eta\n w[1] += eta\n else:\n w += eta\n question_weight[each_question] = w\n final_weight[prod_key] = question_weight\n return final_weight\n\n\ndef calculate_baseline_metrics(baseline_model_rogue, test_pairscore, test_question, type, combination_models):\n total_no = 0\n correct = 0\n incorrect = 0\n c, i = 0, 0\n relevant_reviews = defaultdict(lambda: defaultdict())\n for prod_key in test_pairscore:\n question_review_score = defaultdict(lambda: defaultdict())\n for each_question in test_pairscore[prod_key]:\n # total_no += 5\n review_score = defaultdict()\n for each_review in test_pairscore[prod_key][each_question]:\n score = defaultdict()\n if combination_models:\n weight_list = baseline_model_rogue[prod_key][each_question]\n sum = weight_list[0] * test_pairscore[prod_key][each_question][each_review]['ROGUE'] + \\\n weight_list[1] * test_pairscore[prod_key][each_question][each_review]['BM25+']\n else:\n weight_list = baseline_model_rogue[prod_key][each_question]\n sum = weight_list * test_pairscore[prod_key][each_question][each_review][type]\n\n abs_sum = abs(sum)\n score['score'] = sum\n score['abs_score'] = abs_sum\n\n review_score[each_review] = score\n\n sorted_list = list(reversed(sorted(review_score.iteritems(), key=operator.itemgetter(1))))\n if len(sorted_list) > 5:\n top_list = sorted_list[:5]\n else:\n top_list = sorted_list[:]\n total_no += len(top_list)\n question_review_score[each_question] = review_score\n for score_key, each_score in enumerate(top_list):\n score = each_score[1]['score']\n if score > 0.5:\n if test_question[prod_key][0]['A'] == True:\n correct += 1\n else:\n incorrect += 1\n else:\n if test_question[prod_key][0]['A'] == False:\n correct += 1\n else:\n incorrect += 1\n relevant_reviews[prod_key] = question_review_score\n accuracy = float(correct) / float(total_no)\n print (\"accuracy: %s\" % accuracy)\n return relevant_reviews, accuracy\n","sub_path":"finalProject-question-answering-from-review-data/Methods/Baseline_Models.py","file_name":"Baseline_Models.py","file_ext":"py","file_size_in_byte":4494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"267580358","text":"\"\"\"\n@author: Arokia Anburaj\n@email: arokiaanburaj@gmail.com\n@date: 12-Jul-2015\n\"\"\"\nfrom pages.file_up_loading_page import FileUpLoadingPage\nfrom pages.welcome_page import WelcomePage\nfrom utility.drivermanager import DriverManager\n\n\nclass FileUpLoadingTest(DriverManager):\n def test_file_uploading_functionality(self):\n welcome_page = WelcomePage(self.driver)\n welcome_page.verify_welcome_page().click_on_link(\"File Upload Test\")\n\n file_upload = FileUpLoadingPage(self.driver)\n file_upload.verify_file_uploader_page()\n file_upload.verify_uploaded_file()\n","sub_path":"testcases/file_up_loading_test.py","file_name":"file_up_loading_test.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"52533059","text":"import json\nimport logging\nimport os\nfrom unittest.mock import patch\n\nfrom tests.base_test import BaseTest\n\nfrom SpiffWorkflow.bpmn.specs.EndEvent import EndEvent\nfrom SpiffWorkflow.camunda.specs.UserTask import FormField\n\nfrom crc import session, db, app\nfrom crc.api.common import ApiError\nfrom crc.models.file import FileModel, FileDataModel\nfrom crc.models.protocol_builder import ProtocolBuilderStudySchema\nfrom crc.services.protocol_builder import ProtocolBuilderService\nfrom crc.models.study import StudyModel\nfrom crc.models.workflow import WorkflowSpecModel, WorkflowStatus\nfrom crc.services.file_service import FileService\nfrom crc.services.study_service import StudyService\nfrom crc.services.workflow_processor import WorkflowProcessor\nfrom crc.services.workflow_service import WorkflowService\n\n\nclass TestWorkflowProcessor(BaseTest):\n\n def _populate_form_with_random_data(self, task):\n api_task = WorkflowService.spiff_task_to_api_task(task, add_docs_and_forms=True)\n WorkflowService.populate_form_with_random_data(task, api_task, required_only=False)\n\n def get_processor(self, study_model, spec_model):\n workflow_model = StudyService._create_workflow_model(study_model, spec_model)\n return WorkflowProcessor(workflow_model)\n\n def test_create_and_complete_workflow(self):\n self.load_example_data()\n workflow_spec_model = self.load_test_spec(\"random_fact\")\n study = session.query(StudyModel).first()\n processor = self.get_processor(study, workflow_spec_model)\n self.assertEqual(study.id, processor.bpmn_workflow.data[WorkflowProcessor.STUDY_ID_KEY])\n self.assertIsNotNone(processor)\n self.assertEqual(WorkflowStatus.user_input_required, processor.get_status())\n next_user_tasks = processor.next_user_tasks()\n self.assertEqual(1, len(next_user_tasks))\n task = next_user_tasks[0]\n self.assertEqual(\"Task_User_Select_Type\", task.get_name())\n model = {\"type\": \"buzzword\"}\n if task.data is None:\n task.data = {}\n task.data.update(model)\n processor.complete_task(task)\n self.assertEqual(WorkflowStatus.waiting, processor.get_status())\n processor.do_engine_steps()\n self.assertEqual(WorkflowStatus.complete, processor.get_status())\n data = processor.get_data()\n self.assertIsNotNone(data)\n self.assertIn(\"FactService\", data)\n\n def test_workflow_with_dmn(self):\n self.load_example_data()\n study = session.query(StudyModel).first()\n workflow_spec_model = self.load_test_spec(\"decision_table\")\n files = session.query(FileModel).filter_by(workflow_spec_id='decision_table').all()\n self.assertEqual(2, len(files))\n processor = self.get_processor(study, workflow_spec_model)\n self.assertEqual(WorkflowStatus.user_input_required, processor.get_status())\n next_user_tasks = processor.next_user_tasks()\n self.assertEqual(1, len(next_user_tasks))\n task = next_user_tasks[0]\n self.assertEqual(\"get_num_presents\", task.get_name())\n model = {\"num_presents\": 1}\n if task.data is None:\n task.data = {}\n task.data.update(model)\n processor.complete_task(task)\n processor.do_engine_steps()\n data = processor.get_data()\n self.assertIsNotNone(data)\n self.assertIn(\"message\", data)\n self.assertEqual(\"Oh, Ginger.\", data.get('message'))\n self.assertEqual(\"End\", processor.bpmn_workflow.last_task.task_spec.name)\n self.assertEqual(\"Oh, Ginger.\", processor.bpmn_workflow.last_task.data.get('message'))\n\n\n def test_workflow_with_parallel_forms(self):\n self.load_example_data()\n workflow_spec_model = self.load_test_spec(\"parallel_tasks\")\n study = session.query(StudyModel).first()\n processor = self.get_processor(study, workflow_spec_model)\n self.assertEqual(WorkflowStatus.user_input_required, processor.get_status())\n\n # Complete the first steps of the 4 parallel tasks\n next_user_tasks = processor.next_user_tasks()\n self.assertEqual(4, len(next_user_tasks))\n self._populate_form_with_random_data(next_user_tasks[0])\n self._populate_form_with_random_data(next_user_tasks[1])\n self._populate_form_with_random_data(next_user_tasks[2])\n self._populate_form_with_random_data(next_user_tasks[3])\n processor.complete_task(next_user_tasks[0])\n processor.complete_task(next_user_tasks[1])\n processor.complete_task(next_user_tasks[2])\n processor.complete_task(next_user_tasks[3])\n\n # There are another 4 tasks to complete (each parallel task has a follow-up task)\n next_user_tasks = processor.next_user_tasks()\n self.assertEqual(4, len(next_user_tasks))\n self._populate_form_with_random_data(next_user_tasks[0])\n self._populate_form_with_random_data(next_user_tasks[1])\n self._populate_form_with_random_data(next_user_tasks[2])\n self._populate_form_with_random_data(next_user_tasks[3])\n processor.complete_task(next_user_tasks[0])\n processor.complete_task(next_user_tasks[1])\n processor.complete_task(next_user_tasks[2])\n processor.complete_task(next_user_tasks[3])\n processor.do_engine_steps()\n\n # Should be one last step after the above are complete\n final_user_tasks = processor.next_user_tasks()\n self.assertEqual(1, len(final_user_tasks))\n self._populate_form_with_random_data(final_user_tasks[0])\n processor.complete_task(final_user_tasks[0])\n\n processor.do_engine_steps()\n self.assertTrue(processor.bpmn_workflow.is_completed())\n\n def test_workflow_processor_knows_the_text_task_even_when_parallel(self):\n self.load_example_data()\n study = session.query(StudyModel).first()\n workflow_spec_model = self.load_test_spec(\"parallel_tasks\")\n processor = self.get_processor(study, workflow_spec_model)\n self.assertEqual(WorkflowStatus.user_input_required, processor.get_status())\n next_user_tasks = processor.next_user_tasks()\n self.assertEqual(4, len(next_user_tasks))\n self.assertEqual(next_user_tasks[0], processor.next_task(), \"First task in list of 4\")\n\n # Complete the third open task, so do things out of order\n # this should cause the system to recommend the first ready task that is a\n # child of the last completed task.\n task = next_user_tasks[2]\n self._populate_form_with_random_data(task)\n processor.complete_task(task)\n next_user_tasks = processor.next_user_tasks()\n self.assertEqual(processor.bpmn_workflow.last_task, task)\n self.assertEqual(4, len(next_user_tasks))\n self.assertEqual(task.children[0], processor.next_task())\n\n def test_workflow_processor_returns_next_task_as_end_task_if_complete(self):\n self.load_example_data()\n workflow_spec_model = self.load_test_spec(\"random_fact\")\n study = session.query(StudyModel).first()\n processor = self.get_processor(study, workflow_spec_model)\n processor.do_engine_steps()\n task = processor.next_task()\n task.data = {\"type\": \"buzzword\"}\n processor.complete_task(task)\n self.assertEqual(WorkflowStatus.waiting, processor.get_status())\n processor.do_engine_steps()\n self.assertEqual(WorkflowStatus.complete, processor.get_status())\n task = processor.next_task()\n self.assertIsNotNone(task)\n self.assertIn(\"FactService\", task.data)\n self.assertIsInstance(task.task_spec, EndEvent)\n\n def test_workflow_validation_error_is_properly_raised(self):\n self.load_example_data()\n workflow_spec_model = self.load_test_spec(\"invalid_spec\")\n study = session.query(StudyModel).first()\n with self.assertRaises(ApiError) as context:\n self.get_processor(study, workflow_spec_model)\n self.assertEqual(\"workflow_validation_error\", context.exception.code)\n self.assertTrue(\"bpmn:startEvent\" in context.exception.message)\n\n def test_workflow_spec_key_error(self):\n \"\"\"Frequently seeing errors in the logs about a 'Key' error, where a workflow\n references something that doesn't exist in the midst of processing. Want to\n make sure we produce errors to the front end that allows us to debug this.\"\"\"\n # Start the two_forms workflow, and enter some data in the first form.\n self.load_example_data()\n study = session.query(StudyModel).first()\n workflow_spec_model = self.load_test_spec(\"two_forms\")\n processor = self.get_processor(study, workflow_spec_model)\n self.assertEqual(processor.workflow_model.workflow_spec_id, workflow_spec_model.id)\n task = processor.next_task()\n task.data = {\"color\": \"blue\"}\n processor.complete_task(task)\n\n # Modify the specification, with a major change.\n file_path = os.path.join(app.root_path, '..', 'tests', 'data', 'two_forms', 'mods', 'two_forms_struc_mod.bpmn')\n self.replace_file(\"two_forms.bpmn\", file_path)\n\n # Attempting a soft update on a structural change should raise a sensible error.\n with self.assertRaises(ApiError) as context:\n processor3 = WorkflowProcessor(processor.workflow_model, soft_reset=True)\n self.assertEqual(\"unexpected_workflow_structure\", context.exception.code)\n\n def test_workflow_with_bad_expression_raises_sensible_error(self):\n self.load_example_data()\n\n workflow_spec_model = self.load_test_spec(\"invalid_expression\")\n study = session.query(StudyModel).first()\n processor = self.get_processor(study, workflow_spec_model)\n processor.do_engine_steps()\n next_user_tasks = processor.next_user_tasks()\n self.assertEqual(1, len(next_user_tasks))\n self._populate_form_with_random_data(next_user_tasks[0])\n processor.complete_task(next_user_tasks[0])\n with self.assertRaises(ApiError) as context:\n processor.do_engine_steps()\n self.assertEqual(\"task_error\", context.exception.code)\n\n def test_workflow_with_docx_template(self):\n self.load_example_data()\n study = session.query(StudyModel).first()\n workflow_spec_model = self.load_test_spec(\"docx\")\n files = session.query(FileModel).filter_by(workflow_spec_id='docx').all()\n self.assertEqual(2, len(files))\n workflow_spec_model = session.query(WorkflowSpecModel).filter_by(id=\"docx\").first()\n processor = self.get_processor(study, workflow_spec_model)\n self.assertEqual(WorkflowStatus.user_input_required, processor.get_status())\n next_user_tasks = processor.next_user_tasks()\n self.assertEqual(1, len(next_user_tasks))\n task = next_user_tasks[0]\n self.assertEqual(\"task_gather_information\", task.get_name())\n self._populate_form_with_random_data(task)\n processor.complete_task(task)\n\n files = session.query(FileModel).filter_by(workflow_id=processor.get_workflow_id()).all()\n self.assertEqual(0, len(files))\n processor.do_engine_steps()\n files = session.query(FileModel).filter_by(workflow_id=processor.get_workflow_id()).all()\n self.assertEqual(1, len(files), \"The task should create a new file.\")\n file_data = session.query(FileDataModel).filter(FileDataModel.file_model_id == files[0].id).first()\n self.assertIsNotNone(file_data.data)\n self.assertTrue(len(file_data.data) > 0)\n # Not going any farther here, assuming this is tested in libraries correctly.\n\n def test_load_study_information(self):\n \"\"\" Test a workflow that includes requests to pull in Study Details.\"\"\"\n\n self.load_example_data()\n study = session.query(StudyModel).first()\n workflow_spec_model = self.load_test_spec(\"study_details\")\n processor = self.get_processor(study, workflow_spec_model)\n processor.do_engine_steps()\n task = processor.bpmn_workflow.last_task\n self.assertIsNotNone(task.data)\n self.assertIn(\"StudyInfo\", task.data)\n self.assertIn(\"info\", task.data[\"StudyInfo\"])\n self.assertIn(\"title\", task.data[\"StudyInfo\"][\"info\"])\n self.assertIn(\"last_updated\", task.data[\"StudyInfo\"][\"info\"])\n self.assertIn(\"sponsor\", task.data[\"StudyInfo\"][\"info\"])\n\n def test_spec_versioning(self):\n self.load_example_data()\n study = session.query(StudyModel).first()\n workflow_spec_model = self.load_test_spec(\"decision_table\")\n processor = self.get_processor(study, workflow_spec_model)\n self.assertTrue(processor.get_version_string().startswith('v1.1'))\n file_service = FileService()\n\n file_service.add_workflow_spec_file(workflow_spec_model, \"new_file.txt\", \"txt\", b'blahblah')\n processor = self.get_processor(study, workflow_spec_model)\n self.assertTrue(processor.get_version_string().startswith('v1.1.1'))\n\n file_path = os.path.join(app.root_path, '..', 'tests', 'data', 'docx', 'docx.bpmn')\n file = open(file_path, \"rb\")\n data = file.read()\n\n file_model = db.session.query(FileModel).filter(FileModel.name == \"decision_table.bpmn\").first()\n file_service.update_file(file_model, data, \"txt\")\n processor = self.get_processor(study, workflow_spec_model)\n self.assertTrue(processor.get_version_string().startswith('v2.1.1'))\n\n\n def test_hard_reset(self):\n self.load_example_data()\n\n # Start the two_forms workflow, and enter some data in the first form.\n study = session.query(StudyModel).first()\n workflow_spec_model = self.load_test_spec(\"two_forms\")\n processor = self.get_processor(study, workflow_spec_model)\n self.assertEqual(processor.workflow_model.workflow_spec_id, workflow_spec_model.id)\n task = processor.next_task()\n task.data = {\"color\": \"blue\"}\n processor.complete_task(task)\n next_task = processor.next_task()\n self.assertEqual(\"Step 2\", next_task.task_spec.description)\n\n # Modify the specification, with a major change that alters the flow and can't be serialized effectively.\n file_path = os.path.join(app.root_path, '..', 'tests', 'data', 'two_forms', 'mods', 'two_forms_struc_mod.bpmn')\n self.replace_file(\"two_forms.bpmn\", file_path)\n\n # Assure that creating a new processor doesn't cause any issues, and maintains the spec version.\n processor.workflow_model.bpmn_workflow_json = processor.serialize()\n processor2 = WorkflowProcessor(processor.workflow_model)\n self.assertFalse(processor2.is_latest_spec) # Still at version 1.\n\n # Do a hard reset, which should bring us back to the beginning, but retain the data.\n processor3 = WorkflowProcessor(processor.workflow_model, hard_reset=True)\n self.assertEqual(\"Step 1\", processor3.next_task().task_spec.description)\n self.assertTrue(processor3.is_latest_spec) # Now at version 2.\n task = processor3.next_task()\n task.data = {\"color\": \"blue\"}\n processor3.complete_task(task)\n self.assertEqual(\"New Step\", processor3.next_task().task_spec.description)\n self.assertEqual(\"blue\", processor3.next_task().data[\"color\"])\n\n\n @patch('crc.services.protocol_builder.ProtocolBuilderService.get_studies')\n @patch('crc.services.protocol_builder.ProtocolBuilderService.get_investigators')\n @patch('crc.services.protocol_builder.ProtocolBuilderService.get_required_docs')\n @patch('crc.services.protocol_builder.ProtocolBuilderService.get_study_details')\n def test_master_bpmn_for_crc(self, mock_details, mock_required_docs, mock_investigators, mock_studies):\n\n # Mock Protocol Builder response\n studies_response = self.protocol_builder_response('user_studies.json')\n mock_studies.return_value = ProtocolBuilderStudySchema(many=True).loads(studies_response)\n\n investigators_response = self.protocol_builder_response('investigators.json')\n mock_investigators.return_value = json.loads(investigators_response)\n\n required_docs_response = self.protocol_builder_response('required_docs.json')\n mock_required_docs.return_value = json.loads(required_docs_response)\n\n details_response = self.protocol_builder_response('study_details.json')\n mock_details.return_value = json.loads(details_response)\n\n self.load_example_data(use_crc_data=True)\n app.config['PB_ENABLED'] = True\n\n study = session.query(StudyModel).first()\n workflow_spec_model = db.session.query(WorkflowSpecModel).\\\n filter(WorkflowSpecModel.name == \"top_level_workflow\").first()\n self.assertIsNotNone(workflow_spec_model)\n\n processor = self.get_processor(study, workflow_spec_model)\n processor.do_engine_steps()\n self.assertTrue(\"Top level process is fully automatic.\", processor.bpmn_workflow.is_completed())\n data = processor.bpmn_workflow.last_task.data\n\n logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)\n\n # It should mark Enter Core Data as required, because it is always required.\n self.assertTrue(\"enter_core_info\" in data)\n self.assertEqual(\"required\", data[\"enter_core_info\"])\n\n # It should mark Personnel as required, because StudyInfo.investigators is not empty.\n self.assertTrue(\"personnel\" in data)\n self.assertEqual(\"required\", data[\"personnel\"])\n\n # It should mark the sponsor funding source as disabled since the funding required (12) is not included in the required docs.\n self.assertTrue(\"sponsor_funding_source\" in data)\n self.assertEqual(\"disabled\", data[\"sponsor_funding_source\"])\n\n def test_enum_with_no_choices_raises_api_error(self):\n self.load_example_data()\n workflow_spec_model = self.load_test_spec(\"random_fact\")\n study = session.query(StudyModel).first()\n processor = self.get_processor(study, workflow_spec_model)\n processor.do_engine_steps()\n tasks = processor.next_user_tasks()\n task = tasks[0]\n\n\n field = FormField()\n field.id = \"test_enum_field\"\n field.type = \"enum\"\n field.options = []\n task.task_spec.form.fields.append(field)\n\n with self.assertRaises(ApiError):\n self._populate_form_with_random_data(task)\n\n\n def test_get_role_by_name(self):\n self.load_example_data()\n workflow_spec_model = self.load_test_spec(\"roles\")\n study = session.query(StudyModel).first()\n processor = self.get_processor(study, workflow_spec_model)\n processor.do_engine_steps()\n tasks = processor.next_user_tasks()\n task = tasks[0]\n self._populate_form_with_random_data(task)\n processor.complete_task(task)\n supervisor_task = processor.next_user_tasks()[0]\n self.assertEquals(\"supervisor\", supervisor_task.task_spec.lane)\n\n","sub_path":"tests/workflow/test_workflow_processor.py","file_name":"test_workflow_processor.py","file_ext":"py","file_size_in_byte":19068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"327724412","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, fields, api\nimport datetime\nfrom odoo.exceptions import ValidationError\nfrom dateutil.relativedelta import relativedelta\nimport logging\n_logger = logging.getLogger(__name__)\n\nSEX_TYPES = [\n\t('Masculino',\"Masculino\"),\n\t('Femenino',\"Femenino\"),\n]\n\ndef calculate_age(_birth_date):\n\tage = 0\n\tcurrent_date = datetime.date.today()\n\tbirth_date = _birth_date\n\tborn = relativedelta(current_date,birth_date).years\n\tif born > 0:\n\t\tage = born\n\treturn age\n\n\nclass NeonetyCountry(models.Model):\n\t_name = 'res.country'\n\t_inherit = 'res.country'\n\n\tprovince_ids = fields.One2many('neonety.province', 'country_id', string='Provincias', ondelete='cascade')\n\t# = fields.One2many('neonety.region', 'country_id', string='Regiones', ondelete='cascade')\n\n\nclass NeonetyProvince(models.Model):\n\t_name = 'neonety.province'\n\n\tcode = fields.Char(string='Código', size=3, required=True, translate=True)\n\tname = fields.Char(string='Nombre', size=255, required=True, translate=True)\n\tcountry_id = fields.Many2one('res.country', string='País', required=False, translate=True, compute='_get_country_id', store=True, ondelete='cascade')\n\tdistrict_ids = fields.One2many('neonety.district', 'province_id', string='Distritos')\n\n\t@api.depends('name')\n\tdef _get_country_id(self):\n\t\tcountry = self.pool.get('res.country')\n\t\tcountry_id = self.env['res.country'].search([['name', '=', 'Panama']]).id\n\t\tself.country_id = country_id\n\n\nclass NeonetyDistrict(models.Model):\n\t_name = 'neonety.district'\n\n\tcode = fields.Char(string='Código', size=3, required=True, translate=True)\n\tname = fields.Char(string='Nombre', size=255, required=True, translate=True)\n\tcountry_id = fields.Many2one('res.country', string='País', required=False, translate=True, compute='_get_country_id', store=True)\n\tprovince_id = fields.Many2one('neonety.province', string='Provincia', required=False, translate=True)\n\tsector_ids = fields.One2many('neonety.sector', 'district_id', string='Corregimientos')\n\n\t@api.depends('name')\n\tdef _get_country_id(self):\n\t\tcountry = self.pool.get('res.country')\n\t\tcountry_id = self.env['res.country'].search([['name', '=', 'Panama']]).id\n\t\tself.country_id = country_id\n\n\nclass NeonetySector(models.Model):\n\t_name = 'neonety.sector'\n\n\tcode = fields.Char(string='Código', size=3, required=True, translate=True)\n\tname = fields.Char(string='Nombre', size=255, required=True, translate=True)\n\tcountry_id = fields.Many2one('res.country', string='País', required=False, translate=True, compute='_get_country_id', store=True)\n\tprovince_id = fields.Many2one('neonety.province', string='Provincia', required=False, translate=True)\n\tdistrict_id = fields.Many2one('neonety.district', string='Distrito', required=False, translate=True)\n\n\t@api.depends('name')\n\tdef _get_country_id(self):\n\t\tcountry = self.pool.get('res.country')\n\t\tcountry_id = self.env['res.country'].search([['name', '=', 'Panama']]).id\n\t\tself.country_id = country_id\n\n\nclass NeonetyPartnerConcept(models.Model):\n\t_name = 'neonety.partner.concept'\n\n\tname = fields.Char(string='Concepto', required=True, translate=True)\n\tstatus = fields.Boolean(string='Estatus', required=True, translate=True)\n\n\nclass NeonetyRegion(models.Model):\n\t_name = 'neonety.region'\n\n\tcode = fields.Char(string='Código', size=3, required=True)\n\tname = fields.Char(string='Nombre', size=255, required=True)\n\tcountry_id = fields.Many2one('res.country', string='País', required=False, compute='_get_country_id', store=True, ondelete='cascade')\n\tprovince_id = fields.Many2one('neonety.province', string='Provincia')\n\n\nclass NeonetyPartner(models.Model):\n\t_name = 'res.partner'\n\t_inherit = 'res.partner'\n\n\t@api.depends('name')\n\tdef _get_country_id(self):\n\t\tcountry = self.pool.get('res.country')\n\t\tcountry_id = self.env['res.country'].search([['name', '=', 'Panama']]).id\n\t\tself.country_id = country_id\n\n\truc = fields.Char(string='RUC', size=20)\n\tdv = fields.Char(string='DV', size=2)\n\toperation_notice_number = fields.Char(string=' No. Aviso de Operación', size=50)\n\tpartner_nationality = fields.Selection([\n\t\t('local', 'Local'),\n\t\t('extranjero', 'Extranjero')],\n\t\tstring='Nacionalidad del cliente ó proveedor')\n\tpartner_type = fields.Selection([\n\t\t('natural', 'Persona natural (N)'),\n\t\t('juridica', 'Persona jurídica (J)'),\n\t\t('extranjero', 'Extranjero (E)')],\n\t\tstring='Tipo de cliente ó proveedor')\n\tneonety_partner_concept_id = fields.Many2one('neonety.partner.concept', string='Concepto', default=None)\n\tneonety_country_id = fields.Many2one('res.country', string='País', default=lambda self: self._get_country_id())\n\tcountry_id = fields.Many2one('res.country', string='País', default=lambda self: self._get_country_id())\n\tprovince_id = fields.Many2one('neonety.province', string='Provincia')\n\tdistrict_id = fields.Many2one('neonety.district', string='Distrito')\n\tsector_id = fields.Many2one('neonety.sector', string='Corregimiento')\n\tstreet = fields.Char(string='Dirección')\n\tsex = fields.Selection(SEX_TYPES, string='Sexo')\n\tbirth_date = fields.Date(string='Fecha de Nacimiento')\n\tage = fields.Char(string='Edad', compute='_calculate_age', default='0')\n\n\t@api.depends('birth_date')\n\tdef _calculate_age(self):\n\t\tfor record in self:\n\t\t\trecord.age = '0'\n\t\t\tif record.birth_date:\n\t\t\t\tborn = calculate_age(_birth_date=record.birth_date)\n\t\t\t\tif born > 0:\n\t\t\t\t\trecord.age = '{0} año(s) de edad'.format(born)\n\n\t@api.onchange('birth_date')\n\tdef _onchange_birth_date(self):\n\t\tself.age = '0'\n\t\tif self.birth_date:\n\t\t\tborn = calculate_age(_birth_date=self.birth_date)\n\t\t\tif born > 0:\n\t\t\t\tself.age = '{0} año(s) de edad'.format(born)\n\n\tdef _get_country_id(self):\n\t\tself._cr.execute(\"SELECT id FROM res_country WHERE code LIKE 'PA' LIMIT 1\")\n\t\tcountry_id = self._cr.fetchone()\n\t\treturn country_id\n\n\t@api.onchange('neonety_country_id')\n\tdef onchange_neonety_country_id(self):\n\t\tres = {}\n\t\tif self.neonety_country_id:\n\t\t\tself._cr.execute('SELECT id, name FROM neonety_province WHERE country_id = %s', (self.neonety_country_id.id, ))\n\t\t\tprovinces = self._cr.fetchall()\n\t\t\tids = []\n\n\t\t\tfor province in provinces:\n\t\t\t\tids.append(province[0])\n\t\t\tres['domain'] = {'province_id': [('id', 'in', ids)]}\n\t\treturn res\n\n\t@api.onchange('province_id')\n\tdef onchange_province_id(self):\n\t\tres = {}\n\n\t\tif self.province_id:\n\t\t\tself._cr.execute('SELECT neonety_district.id, neonety_district.name FROM neonety_district WHERE neonety_district.province_id = %s AND neonety_district.country_id = ( SELECT neonety_province.country_id FROM neonety_province WHERE neonety_province.id = %s) ', (self.province_id.id, self.province_id.id))\n\t\t\tdistricts = self._cr.fetchall()\n\t\t\tids = []\n\n\t\t\tfor district in districts:\n\t\t\t\tids.append(district[0])\n\t\t\tres['domain'] = {'district_id': [('id', 'in', ids)]}\n\t\treturn res\n\n\t@api.onchange('district_id')\n\tdef onchange_district_id(self):\n\t\tres = {}\n\n\t\tif self.district_id:\n\t\t\tself._cr.execute('SELECT neonety_sector.id, neonety_sector.name FROM neonety_sector WHERE neonety_sector.district_id = %s AND neonety_sector.country_id = ( SELECT neonety_district.country_id FROM neonety_district WHERE neonety_district.id = %s) ', (self.district_id.id, self.district_id.id))\n\t\t\tsectors = self._cr.fetchall()\n\t\t\tids = []\n\n\t\t\tfor sector in sectors:\n\t\t\t\tids.append(sector[0])\n\t\t\tres['domain'] = {'sector_id': [('id', 'in', ids)]}\n\t\treturn res\n\n\tdef _check_fields_required(self, vals):\n\t\terrors = []\n\t\tif 'email' in vals:\n\t\t\tif vals['email']:\n\t\t\t\timport re\n\t\t\t\tmatch = re.match('^[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{2,4})$', vals['email'])\n\t\t\t\tif match == None:\n\t\t\t\t\terrors.append('El Email tiene un formato inválido, formado esperado: \"example@domain.com\"')\n\t\tif len(errors) > 0:\n\t\t\traise ValidationError(\"\\n\".join(errors))\n\n\tdef _check_ruc_exists(self, vals, pk=0):\n\t\tif 'ruc' in vals:\n\t\t\tif vals['ruc']:\n\t\t\t\truc = vals.get('ruc', False)\n\t\t\t\tif ruc:\n\t\t\t\t\truc = ruc.replace(' ', '') if '-' in ruc else ruc\n\t\t\t\t\truc = ruc.replace(\" \", '') if \" \" in ruc else ruc\n\t\t\t\t\tif pk > 0:\n\t\t\t\t\t\tcounter = self.env['res.partner'].search_count([('ruc', '=', ruc), ('id', '!=', pk)])\n\t\t\t\t\telse:\n\t\t\t\t\t\tcounter = self.env['res.partner'].search_count([('ruc', '=', ruc)])\n\t\t\t\t\tif counter > 0:\n\t\t\t\t\t\traise ValidationError('El RUC ya se encuentra registrado en otra cuenta.')\n\n\t@api.model\n\tdef create(self, vals):\n\t\tself._check_ruc_exists(vals=vals)\n\t\tif 'ruc' in vals:\n\t\t\truc = vals.get('ruc', False)\n\t\t\tif ruc:\n\t\t\t\truc = ruc.replace(' ', '') if '-' in ruc else ruc\n\t\t\t\truc = ruc.replace(\" \", '') if \" \" in ruc else ruc\n\t\t\t\tvals['ruc'] = ruc\n\t\tpartner = super(NeonetyPartner, self).create(vals)\n\t\tself._check_fields_required(vals=vals)\n\t\treturn partner\n \n\tdef write(self, vals):\n\t\tif 'ruc' in vals:\n\t\t\truc = vals.get('ruc', False)\n\t\t\tif ruc:\n\t\t\t\truc = ruc.replace(' ', '') if '-' in ruc else ruc\n\t\t\t\truc = ruc.replace(\" \", '') if \" \" in ruc else ruc\n\t\t\t\tvals['ruc'] = ruc\n\t\tpartner = super(NeonetyPartner, self).write(vals)\n\t\tself._check_fields_required(vals=vals)\n\t\tself._check_ruc_exists(vals=vals, pk=self.id)\n\t\treturn partner","sub_path":"neonety/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"69912062","text":"import time\nimport datetime\nimport json\nimport re\nimport urllib\n\nimport numpy as np\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nimport urls\nimport settings\nimport accounts\n\nchrome_options = Options()\nchrome_options.add_argument(\"--disable-notifications\")\n_driver = webdriver.Chrome(chrome_options=chrome_options)\n_driver.get('https://facebook.com/')\n\n# Login\naccountInput = _driver.find_element_by_id('email')\npasswordInput = _driver.find_element_by_id('pass')\n\nif accountInput:\n accountInput.send_keys(accounts.ACCOUNT)\n passwordInput.send_keys(accounts.PASSWORD)\n _driver.find_element_by_id('loginbutton').click()\ntime.sleep(settings.LOGIN_DELAY)\n\n# Get current year and month\nnow = datetime.datetime.now()\n # Calculating time \nyear = now.year\nmonth = now.month\n\ndata = {}\nindex = 0\nfor urlIndex in range(0, len(urls.scrapeUrls)):\n currentUrl = urls.scrapeUrls[urlIndex][\"url\"]\n groupUrls = []\n\n # Create variations of currentUrl according to settings.QUERY_MONTH_NUM and search param (time, precisely)\n for i in range(0, settings.QUERY_MONTH_NUM):\n variation = currentUrl + urls.scrapeUrlsParam\n variation = variation.replace('__START_YEAR__', str(year))\n variation = variation.replace('__START_MONTH__', str(year) + '-' + str(month))\n variation = variation.replace('__END_YEAR__', str(year))\n variation = variation.replace('__END_MONTH__', str(year) + '-' + str(month))\n\n groupUrls.append(variation)\n\n month -= 1\n if (month == 0):\n month = 12\n year -= 1\n\n # Loop through the newly created groupUrls\n for groupIndex in range(0, settings.QUERY_MONTH_NUM):\n # To search pages\n _driver.execute_script('window.location=\"%s\"' % (groupUrls[groupIndex]))\n time.sleep(settings.PAGE_LOAD_DELAY)\n\n # Wait\n wait = WebDriverWait(_driver, 30)\n\n # Scroll n times to the bottom of the page\n for i in range(0, settings.SCROLL_TIMES):\n _driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(settings.SCROLL_LOAD_DELAY)\n\n # Select all search results - First time\n # First select the two static containers\n posts = _driver.execute_script('return document.getElementById(\"BrowseResultsContainer\").children')\n posts = np.concatenate([posts, _driver.execute_script('''return document.querySelectorAll('[data-testid=\"paginated_results_pagelet\"] [data-testid=\"results\"]')[0].children''')])\n\n # Loop through the additional posts that appear after scrolling and concat to the posts array\n extraPostContainers = _driver.execute_script('''return document.querySelectorAll('div[id*=\"fbBrowseScrollingPagerContainer\"]')''')\n for i in range(0, len(extraPostContainers)):\n posts = np.concatenate([posts, extraPostContainers[i].find_elements_by_xpath('.//div[@data-testid=\"results\"]/div')])\n\n # Click on each item (in case it's in \"short\" form)\n for i in range(0, len(posts)):\n _driver.execute_script('arguments[0].click();', posts[i])\n time.sleep(settings.SHORT_FORM_CLICK_DELAY)\n\n # -------------------------------------------------\n\n # Select all search results - Second time\n posts = None\n posts = _driver.execute_script('return document.getElementById(\"BrowseResultsContainer\").children')\n posts = np.concatenate([posts, _driver.execute_script('''return document.querySelectorAll('[data-testid=\"paginated_results_pagelet\"] [data-testid=\"results\"]')[0].children''')])\n\n extraPostContainers = _driver.execute_script('''return document.querySelectorAll('div[id*=\"fbBrowseScrollingPagerContainer\"]')''')\n for i in range(0, len(extraPostContainers)):\n posts = np.concatenate([posts, extraPostContainers[i].find_elements_by_xpath('.//div[@data-testid=\"results\"]/div')])\n\n # Loop through the posts array and fetch data\n for i in range(0, len(posts)):\n time.sleep(settings.FETCH_DELAY)\n\n # Click on the item (in case it's in \"short\" form)\n _driver.execute_script('arguments[0].click();', posts[i])\n\n # Find \"theater\" link (Links that belong to Facebook and will be displayed by Ajax)\n try:\n theaterLink = posts[i].find_element_by_xpath('.//a[@rel=\"theater\"]')\n\n # If theaterLink exists (meaning the post belongs to Facebook)\n _driver.execute_script('arguments[0].click();', theaterLink)\n time.sleep(settings.THEATER_DELAY)\n\n # Fetch the container\n theater = _driver.execute_script('return document.querySelectorAll(\"div._n3\")[0]')\n \n # Fetch data (link, image, caption, reations, comments, shares)\n link = _driver.execute_script('return window.location.href')\n\n try:\n poster = theater.find_element_by_xpath('.//div[contains(@id, \"fbPhotoSnowliftAuthorName\")]/a')\n posterName = poster.get_attribute('innerText')\n posterLink = poster.get_attribute('href')\n except:\n posterName = ''\n posterLink = ''\n\n try:\n postedTime = theater.find_element_by_xpath('.//abbr[contains(@class, timestamp)]').get_attribute('title')\n except:\n try:\n postedTime = theater.find_element_by_xpath('.//abbr[@data-utime]').get_attribute('title')\n except:\n postedTime = ''\n\n try:\n imageSrc = theater.find_element_by_css_selector('img').get_attribute('src')\n except:\n imageSrc = ''\n\n try:\n caption = theater.find_element_by_css_selector('.fbPhotosPhotoCaption .hasCaption').get_attribute('innerText')\n except:\n try:\n caption = theater.find_element_by_css_selector('.userContent p').get_attribute('innerText')\n except:\n caption = ''\n\n try:\n like = theater.find_element_by_css_selector('span[data-tooltip-uri *= \"reaction/tooltip\"]').get_attribute('innerText')\n except:\n like = ''\n \n try:\n comment = theater.find_element_by_css_selector('a[href *= \"comment_tracking\"]').get_attribute('innerText')\n except:\n comment = ''\n \n try:\n share = theater.find_element_by_css_selector('a[href *= \"/shares\"]').get_attribute('innerText')\n except:\n share = ''\n\n postData = {}\n postData['posterName'] = posterName\n postData['posterLink'] = posterLink\n postData['postedTime'] = postedTime\n postData['link'] = link\n postData['imageSrc'] = imageSrc\n postData['caption'] = caption\n postData['like'] = like\n postData['comment'] = comment\n postData['share'] = share\n\n data[str(index)] = postData\n index += 1\n\n theaterCloseButton = _driver.execute_script('return document.querySelectorAll(\"div._n3 > a\")[0]')\n theaterCloseButton.click()\n\n continue\n\n except:\n pass\n\n # If theaterLink doesn't exists\n # Try video\n try:\n video = posts[i].find_element_by_xpath('.//video')\n\n videoLink = posts[i].find_element_by_xpath('.//a[@data-video-channel-id]')\n _driver.execute_script('arguments[0].click();', videoLink)\n time.sleep(settings.VIDEO_CLICK_DELAY)\n\n videoLink = videoLink.get_attribute('href')\n\n content = _driver.execute_script('''return document.querySelectorAll('[data-insertion-position=\"0\"]')[0].parentElement''')\n\n try:\n posterLink = content.find_element_by_xpath('.//a[@data-hovercard-prefer-more-content-show]').get_attribute('href')\n posterName = content.find_element_by_xpath('.//a[@data-hovercard-prefer-more-content-show]//img').get_attribute('aria-label')\n except:\n posterLink = ''\n posterName = ''\n\n try:\n postedTime = content.find_element_by_xpath('.//abbr[contains(@class, timestamp)]').get_attribute('title')\n except:\n try:\n postedTime = content.find_element_by_xpath('.//abbr[@data-utime]').get_attribute('title')\n except:\n postedTime = ''\n\n try:\n like = content.find_element_by_css_selector('a[href *= \"reaction\"] span span').get_attribute('innerText')\n except:\n like = ''\n \n try:\n comment = content.find_element_by_xpath('.//a[@data-comment-prelude-ref]').get_attribute('innerText')\n except:\n comment = ''\n \n try:\n share = content.find_element_by_css_selector('a[href *= \"shares\"]').get_attribute('innerText')\n except:\n share = ''\n\n postData = {}\n postData['posterName'] = posterName\n postData['posterLink'] = posterLink\n postData['postedTime'] = postedTime\n postData['videoLink'] = videoLink\n postData['like'] = like\n postData['comment'] = comment\n postData['share'] = share\n\n data[str(index)] = postData\n index += 1\n \n time.sleep(VIDEO_CLICK_DELAY)\n _driver.execute_script('window.history.back()')\n\n continue\n\n except:\n pass\n\n # If there's no video\n # Find the external link that leads to other site\n try:\n externalLink = posts[i].find_element_by_xpath('.//a[contains(@rel, \"nofollow\")]').get_attribute('href')\n \n try: \n # Decode URI\n elResult = re.search('php\\?u=(.*)\\&h=', externalLink)\n externalLink = urllib.parse.unquote(elResult.group(1))\n except:\n pass\n \n try:\n posterLink = posts[i].find_element_by_xpath('.//a[@data-hovercard-prefer-more-content-show]').get_attribute('href')\n posterName = posts[i].find_element_by_xpath('.//a[@data-hovercard-prefer-more-content-show]//img').get_attribute('aria-label')\n except:\n posterLink = ''\n posterName = ''\n\n try:\n postedTime = posts[i].find_element_by_xpath('.//abbr[contains(@class, timestamp)]').get_attribute('title')\n except:\n try:\n postedTime = posts[i].find_element_by_xpath('.//abbr[@data-utime]').get_attribute('title')\n except:\n postedTime = ''\n\n try:\n imageSrc = posts[i].find_element_by_css_selector('.fbStoryAttachmentImage img').get_attribute('src')\n except:\n imageSrc = ''\n\n try:\n caption = posts[i].find_element_by_css_selector('.userContent p').get_attribute('innerText')\n except:\n caption = ''\n\n try:\n like = posts[i].find_element_by_css_selector('a[href *= \"reaction\"] span span').get_attribute('innerText')\n except:\n like = ''\n \n try:\n comment = posts[i].find_element_by_css_selector('a[href *= \"comment_tracking\"]').get_attribute('innerText')\n except:\n comment = ''\n \n try:\n share = posts[i].find_element_by_css_selector('a[href *= \"shares\"]').get_attribute('innerText')\n except:\n share = ''\n\n postData = {}\n postData['posterName'] = posterName\n postData['posterLink'] = posterLink\n postData['postedTime'] = postedTime\n postData['link'] = externalLink\n postData['imageSrc'] = imageSrc\n postData['caption'] = caption\n postData['like'] = like\n postData['comment'] = comment\n postData['share'] = share\n\n data[str(index)] = postData\n index += 1\n\n continue\n\n except:\n pass\n \n # Write to file \n with open('./result/query/' + urls.scrapeUrls[urlIndex][\"query\"] + '.json', 'w', encoding='utf-8') as outstream:\n json.dump(data, outstream, ensure_ascii=False)\n\n # Clear data for the next loop\n data = {}\n\n# Close the driver\n_driver.close()","sub_path":"scrapeTool/query-bot.py","file_name":"query-bot.py","file_ext":"py","file_size_in_byte":13582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"198326088","text":"from email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.base import MIMEBase\r\nfrom email.encoders import encode_base64\r\nimport smtplib\r\nimport os\r\nimport logging\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\ndef send_email(sender, recipient, subject, content, ishtml=False, attachment=None):\r\n\r\n msg = MIMEMultipart()\r\n msg['From'] = sender\r\n msg['To'] = recipient\r\n msg['Subject'] = subject\r\n\r\n if ishtml:\r\n msg.attach(MIMEText(content, 'html'))\r\n else:\r\n msg.attach(MIMEText(content, 'plain'))\r\n\r\n if attachment is not None:\r\n part = MIMEBase('application', 'octet-stream')\r\n part.set_payload(open(attachment, 'rb').read())\r\n encode_base64(part)\r\n part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(attachment))\r\n msg.attach(part)\r\n\r\n server = smtplib.SMTP('smtp.1and1.pl', 587)\r\n text = msg.as_string()\r\n # identify ourselves, prompting server for supported features\r\n server.ehlo()\r\n # If we can encrypt this session, do it\r\n if server.has_extn('STARTTLS'):\r\n server.starttls()\r\n server.ehlo() # re-identify ourselves over TLS connection\r\n\r\n server.login('robot@sigma-solutions.eu', 'robot@sigma2016')\r\n server.sendmail(sender, recipient, text)\r\n server.quit()\r\n\r\n\r\n# send email to notify failures\r\ndef send_notify_email(subject, content):\r\n # recipients = [\"mobience@spicymobile.pl\", \"it@spicymobile.pl\", \"kszczuka@sigma-solutions.eu\", \"tuyenlq@sigma-solutions.eu\", \"cuongnv@sigma-solutions.eu\", \"cuongbn@sigma-solutions.eu\"]\r\n recipients = [\"thuongln@sigma-solutions.eu\", \"tuyenlq@sigma-solutions.eu\", \"tung@sigma-solutions.eu\", \"cuongbn@sigma-solutions.eu\", \"it@spicymobile.pl\"]\r\n try:\r\n for r in recipients:\r\n send_email(\"importer@sigma-solutions.eu\", r, subject, content)\r\n except Exception as e:\r\n logger.error(\"send email to notify ERROR: {}\".format(e))\r\n\r\n","sub_path":"munin/mail_helper.py","file_name":"mail_helper.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"208593656","text":"# • An equilateral triangle\n# • A square\n# • A hexagon (six sides)\n# • An octagon (eight sides)\nimport turtle\nwindow = turtle.Screen()\nwindow.bgcolor(\"lightgreen\")\ntess = turtle.Turtle()\n#tess.shape(\"turtle\")\ntess.color(\"blue\")\nno_of_sides = int(input(\"How many sides of regular polygon you want to draw with my intelligent turtle\"))\nlength = int(input(\"Type of length of side\"))\ndef regular_polygon(sides,leng):\n total_angle = 360\n angle = total_angle / sides\n print(\"Angle we need to turn on each side is \", angle)\n for i in range(sides):\n tess.forward(leng)\n tess.right(angle)\n\nregular_polygon(no_of_sides,length)\nwindow.mainloop()\n\n","sub_path":"howtothinklikeacomputerscientist/chapter3/part2/exercise8.py","file_name":"exercise8.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"116970247","text":"# python 2.7.12\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\n\n\ndef loader(filename):\n \"\"\" Load 2008 census data from raw_2008.npy\n\n Args:\n filename (string): .npy file to load\n \n Returns:\n h (string): feature names\n x_train (float): training data (90%), pre-shuffled\n x_valid (float): validation data (10%), pre-shuffled\n x_test (float): testing data\n y_train (float): training targets (1 = vote, 2 = no vote)\n y_valid (float): validation targets\n\n \"\"\"\n\n data = np.load(filename)\n\n return data\n\n\n\n #%%\n \"\"\" Main \"\"\"\n# load datasets\nh, x, y, x_test = loader('/scripts/storage/raw_data_2008.npy')\n\n\n#%%\n\nx_valid = x[0:6466,:]\ny_valid = y[0:6466]\n\nx_train = x[6466::,:]\ny_train = y[6466::]\n\n# random forest\nrf = RandomForestClassifier(n_estimators = 100, criterion = 'entropy', max_features = None)\nrf.fit(x_train, y_train)\n\ng1 = rf.predict(x_train)\ng2 = rf.predict(x_valid)\n\nprint('Training accuracy: ' + \"{:.5f}\".format(np.mean(g1 == y_train)))\nprint('Validation accuracy: ' + \"{:.5f}\".format(np.mean(g2 == y_valid)))\n\n# check feature importance\nk = np.argsort(rf.feature_importances_)\nimp = h[k]\n\n","sub_path":"experimental/random_forest_example.py","file_name":"random_forest_example.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"160945544","text":"import json\n\nfrom django.urls import reverse\nfrom django.shortcuts import get_object_or_404, render\nfrom wagtail.utils.pagination import paginate\n\nfrom wagtail.wagtailadmin.modal_workflow import render_modal_workflow\nfrom wagtail.wagtailadmin.forms import SearchForm\nfrom wagtail.wagtailadmin.utils import PermissionPolicyChecker\nfrom wagtail.wagtailadmin.utils import popular_tags_for_model\nfrom wagtail.wagtailcore import hooks\nfrom wagtail.wagtailcore.models import Collection\nfrom wagtail.wagtailsearch import index as search_index\n\nfrom embed_video.backends import detect_backend\n\nfrom wagtail_embed_videos import get_embed_video_model\nfrom wagtail_embed_videos.formats import get_video_format\nfrom wagtail_embed_videos.forms import get_embed_video_form, EmbedVideoInsertionForm\n# from wagtail_embed_videos.formats import get_embed_video_format\nfrom wagtail_embed_videos.permissions import permission_policy\n\npermission_checker = PermissionPolicyChecker(permission_policy)\n\n\ndef get_embed_video_json(embed_video):\n \"\"\"\n helper function: given an embed video, return the json to pass back to the\n embed video chooser panel\n \"\"\"\n if embed_video.thumbnail:\n preview_embed_video = embed_video.thumbnail.get_rendition('max-130x100').url\n else:\n preview_embed_video = detect_backend(embed_video.url).get_thumbnail_url()\n\n return json.dumps({\n 'id': embed_video.id,\n 'edit_link': reverse('wagtail_embed_videos:edit', args=(embed_video.id,)),\n 'title': embed_video.title,\n 'preview': {\n 'url': preview_embed_video,\n 'width': embed_video.thumbnail.width,\n 'height': embed_video.thumbnail.height,\n }\n })\n\n\ndef chooser(request):\n EmbedVideo = get_embed_video_model()\n\n if permission_policy.user_has_permission(request.user, 'add'):\n EmbedVideoForm = get_embed_video_form(EmbedVideo)\n uploadform = EmbedVideoForm(user=request.user)\n else:\n uploadform = None\n\n embed_videos = EmbedVideo.objects.order_by('-created_at')\n\n # TODO: Make test for this functionality\n # allow hooks to modify the queryset\n for hook in hooks.get_hooks('construct_embed_video_chooser_queryset'):\n embed_videos = hook(embed_videos, request)\n\n q = None\n if (\n 'q' in request.GET or 'p' in request.GET or 'tag' in request.GET or\n 'collection_id' in request.GET\n ):\n collection_id = request.GET.get('collection_id')\n if collection_id:\n embed_videos = embed_videos.filter(collection=collection_id)\n\n searchform = SearchForm(request.GET)\n if searchform.is_valid():\n q = searchform.cleaned_data['q']\n\n embed_videos = embed_videos.search(q)\n is_searching = True\n\n else:\n is_searching = False\n\n tag_name = request.GET.get('tag')\n if tag_name:\n embed_videos = embed_videos.filter(tags__name=tag_name)\n\n paginator, embed_videos = paginate(request, embed_videos, per_page=12)\n\n return render(request, \"wagtail_embed_videos/chooser/results.html\", {\n 'embed_videos': embed_videos,\n 'is_searching': is_searching,\n 'query_string': q,\n 'will_select_format': request.GET.get('select_format')\n })\n else:\n searchform = SearchForm()\n\n collections = Collection.objects.all()\n if len(collections) < 2:\n collections = None\n\n paginator, embed_videos = paginate(request, embed_videos, per_page=12)\n\n return render_modal_workflow(\n request,\n 'wagtail_embed_videos/chooser/chooser.html',\n 'wagtail_embed_videos/chooser/chooser.js',\n {\n 'embed_videos': embed_videos,\n 'uploadform': uploadform,\n 'searchform': searchform,\n 'is_searching': False,\n 'query_string': q,\n 'will_select_format': request.GET.get('select_format'),\n 'popular_tags': popular_tags_for_model(EmbedVideo),\n 'collections': collections,\n }\n )\n\n\ndef embed_video_chosen(request, embed_video_id):\n embed_video = get_object_or_404(get_embed_video_model(), id=embed_video_id)\n\n return render_modal_workflow(\n request,\n None,\n 'wagtail_embed_videos/chooser/embed_video_chosen.js',\n {'embed_video_json': get_embed_video_json(embed_video)}\n )\n\n\n@permission_checker.require('add')\ndef chooser_upload(request):\n EmbedVideo = get_embed_video_model()\n EmbedVideoForm = get_embed_video_form(EmbedVideo)\n\n searchform = SearchForm()\n\n if request.POST:\n embed_video = EmbedVideo(uploaded_by_user=request.user)\n form = EmbedVideoForm(request.POST, request.FILES, instance=embed_video, user=request.user)\n\n if form.is_valid():\n form.save()\n\n # Reindex the video to make sure all tags are indexed\n search_index.insert_or_update_object(embed_video)\n\n if request.GET.get('select_format'):\n form = EmbedVideoInsertionForm(initial={'alt_text': embed_video.default_alt_text})\n return render_modal_workflow(\n request,\n 'wagtail_embed_videos/chooser/select_format.html',\n 'wagtail_embed_videos/chooser/select_format.js',\n {'embed_video': embed_video, 'form': form}\n )\n # not specifying a format; return the embed video details now\n else:\n return render_modal_workflow(\n request,\n None,\n 'wagtail_embed_videos/chooser/embed_video_chosen.js',\n {'embed_video_json': get_embed_video_json(embed_video)}\n )\n else:\n form = EmbedVideoForm(user=request.user)\n\n embed_videos = EmbedVideo.objects.order_by('-created_at')\n paginator, images = paginate(request, embed_videos, per_page=12)\n\n return render_modal_workflow(\n request,\n 'wagtail_embed_videos/chooser/chooser.html',\n 'wagtail_embed_videos/chooser/chooser.js',\n {'embed_videos': embed_videos, 'uploadform': form, 'searchform': searchform}\n )\n\n\ndef chooser_select_format(request, embed_video_id):\n embed_video = get_object_or_404(get_embed_video_model(), id=embed_video_id)\n print(embed_video)\n\n if request.POST:\n form = EmbedVideoInsertionForm(request.POST, initial={'alt_text': embed_video.default_alt_text})\n\n if form.is_valid():\n format = get_video_format(form.cleaned_data['format'])\n preview_embed_video = detect_backend(embed_video.url).get_thumbnail_url()\n\n video_json = json.dumps({\n 'id': embed_video.id,\n 'title': embed_video.title,\n 'format': format.name,\n 'alt': form.cleaned_data['alt_text'],\n 'class': format.classnames,\n 'edit_link': reverse('wagtail_embed_videos:edit', args=(embed_video.id,)),\n 'preview': {\n 'url': preview_embed_video,\n 'width': embed_video.thumbnail.width,\n 'height': embed_video.thumbnail.height,\n },\n 'html': format.video_to_editor_html(embed_video, form.cleaned_data['alt_text']),\n })\n\n print(video_json)\n\n return render_modal_workflow(\n request,\n None,\n 'wagtail_embed_videos/chooser/embed_video_chosen.js',\n {'embed_video_json': video_json}\n )\n else:\n initial = {'alt_text': embed_video.default_alt_text}\n initial.update(request.GET.dict())\n form = EmbedVideoInsertionForm(initial=initial)\n\n return render_modal_workflow(\n request,\n 'wagtail_embed_videos/chooser/select_format.html',\n 'wagtail_embed_videos/chooser/select_format.js',\n {'embed_video': embed_video, 'form': form}\n )\n","sub_path":"wagtail_embed_videos/views/chooser.py","file_name":"chooser.py","file_ext":"py","file_size_in_byte":8105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"96099807","text":"import attr\nimport sonnet as snt\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nfrom filterflow.base import State\nfrom filterflow.observation.base import ObservationModelBase\nfrom filterflow.proposal.base import ProposalModelBase\nfrom filterflow.smc import SMC\nfrom filterflow.transition.base import TransitionModelBase\n\ntfd = tfp.distributions\n\n\n@attr.s\nclass VRNNState(State):\n ADDITIONAL_STATE_VARIABLES = ('rnn_state',) # rnn_out and encoded no need to be resampled\n rnn_state = attr.ib(default=None)\n rnn_out = attr.ib(default=None)\n latent_encoded = attr.ib(default=None)\n\n\nclass NNNormalDistribution(tf.Module):\n \"\"\"A Normal distribution with mean and var parametrised by NN\"\"\"\n\n def __init__(self,\n size,\n hidden_layer_sizes,\n sigma_min=0.0,\n raw_sigma_bias=0.25,\n hidden_activation_fn=tf.nn.relu,\n name=\"conditional_normal_distribution\"):\n super(NNNormalDistribution, self).__init__(name=name)\n\n self.sigma_min = sigma_min\n self.raw_sigma_bias = raw_sigma_bias\n self.size = size\n self.fcnet = snt.nets.MLP(\n output_sizes=hidden_layer_sizes + [2 * size],\n activation=hidden_activation_fn,\n activate_final=False,\n name=name + \"_fcnet\")\n\n def get_params(self, tensor_list, **_kwargs):\n \"\"\"Computes the parameters of a normal distribution based on the inputs.\"\"\"\n inputs = tf.concat(tensor_list, axis=-1)\n outs = self.fcnet(inputs)\n mu, sigma = tf.split(outs, 2, axis=-1)\n sigma = tf.maximum(tf.nn.softplus(sigma + self.raw_sigma_bias), self.sigma_min)\n return mu, sigma\n\n def __call__(self, *args, **kwargs):\n \"\"\"Creates a normal distribution conditioned on the inputs.\"\"\"\n mu, sigma = self.get_params(args, **kwargs)\n return tfp.distributions.Normal(loc=mu, scale=sigma)\n\n\nclass NNBernoulliDistribution(tf.Module):\n \"\"\"A Normal distribution with mean and var parametrised by NN\"\"\"\n\n def __init__(self,\n size,\n hidden_layer_sizes,\n hidden_activation_fn=tf.nn.relu,\n name=\"conditional_bernoulli_distribution\"):\n super(NNBernoulliDistribution, self).__init__(name=name)\n\n self.size = size\n self.fcnet = snt.nets.MLP(\n output_sizes=hidden_layer_sizes + [size],\n activation=hidden_activation_fn,\n activate_final=False,\n name=name + \"_fcnet\")\n\n def get_logits(self, tensor_list, **_kwargs):\n \"\"\"Computes the parameters of a normal distribution based on the inputs.\"\"\"\n inputs = tf.concat(tensor_list, axis=-1)\n return self.fcnet(inputs)\n\n def __call__(self, *args, **kwargs):\n \"\"\"Creates a normal distribution conditioned on the inputs.\"\"\"\n logits = self.get_logits(args, **kwargs)\n return tfp.distributions.Bernoulli(logits=logits)\n\n\nclass VRNNTransitionModel(TransitionModelBase):\n def __init__(self,\n rnn_hidden_size,\n latent_size,\n data_encoder,\n latent_encoder,\n name='NNTransitionModel'):\n super(VRNNTransitionModel, self).__init__(name=name)\n\n # mlp parametrised gaussian\n self.transition = NNNormalDistribution(size=latent_size,\n hidden_layer_sizes=[latent_size])\n # encoder for inputs\n self.latent_encoder = latent_encoder\n\n # lstm cell\n self.rnn_hidden_size = rnn_hidden_size\n self.rnn = tf.keras.layers.LSTMCell(rnn_hidden_size)\n\n def run_rnn(self, state: VRNNState, inputs: tf.Tensor):\n tiled_inputs = tf.tile(inputs, [state.batch_size, state.n_particles, 1])\n # process latent state\n latent_state = state.particles\n\n # encode and reshape latent state\n latent_encoded = self.latent_encoder(latent_state)\n\n B, N, D = latent_encoded.shape\n # process rnn_state\n rnn_state = tf.reshape(state.rnn_state, [B, N, self.rnn_hidden_size * 2])\n\n rnn_state = tf.split(rnn_state, 2, axis=-1)\n\n # run rnn\n rnn_inputs = tf.concat([tiled_inputs, latent_encoded], axis=-1)\n rnn_inputs_reshaped = tf.reshape(rnn_inputs, (B * N, -1))\n rnn_state_reshaped = [tf.reshape(elem, (B * N, -1)) for elem in rnn_state]\n rnn_out, rnn_state = self.rnn(rnn_inputs_reshaped, rnn_state_reshaped)\n\n rnn_state = tf.concat(rnn_state, axis=-1)\n rnn_state = tf.reshape(rnn_state, [state.batch_size, state.n_particles, self.rnn_hidden_size * 2])\n rnn_out = tf.reshape(rnn_out, [state.batch_size, state.n_particles, self.rnn_hidden_size])\n return rnn_out, rnn_state, latent_encoded\n\n def latent_dist(self, state, rnn_out):\n dist = self.transition(rnn_out)\n return dist\n\n def loglikelihood(self, prior_state: VRNNState, proposed_state: VRNNState, inputs: tf.Tensor):\n rnn_out, rnn_state, latent_encoded = self.run_rnn(prior_state, inputs)\n dist = self.transition(rnn_out)\n new_latent = proposed_state.particles\n return tf.reduce_sum(dist.log_prob(new_latent), axis=-1)\n\n def sample(self, state: VRNNState, inputs: tf.Tensor, seed=None):\n rnn_out, rnn_state, latent_encoded = self.run_rnn(state, inputs)\n dist = self.latent_dist(state, rnn_out)\n latent_state = dist.sample(seed=seed)\n\n return VRNNState(particles=latent_state,\n log_weights=state.log_weights,\n weights=state.weights,\n log_likelihoods=state.log_likelihoods,\n rnn_state=rnn_state,\n rnn_out=rnn_out,\n latent_encoded=latent_encoded)\n\n\nclass VRNNProposalModel(ProposalModelBase):\n def __init__(self,\n transition_model,\n name='VRNNProposalModel'):\n super(VRNNProposalModel, self).__init__(name=name)\n self._transiton_model = transition_model\n\n def loglikelihood(self, proposed_state: State, state: State, inputs: tf.Tensor, observation: tf.Tensor):\n rnn_out, rnn_state, latent_encoded = self._transiton_model.run_rnn(state, inputs)\n dist = self._transiton_model.latent_dist(state, rnn_out)\n new_latent = proposed_state.particles\n return tf.reduce_sum(dist.log_prob(new_latent), axis=-1)\n\n def propose(self, state: State, inputs: tf.Tensor, observation: tf.Tensor, seed=None):\n return self._transiton_model.sample(state, inputs, seed)\n\n\nclass VRNNNormalObservationModel(ObservationModelBase):\n\n def __init__(self, latent_encoder, observation_size, name='VRNNObservationModel'):\n super(VRNNNormalObservationModel, self).__init__(name=name)\n # mlp parametrised gaussian\n self.emission = NNNormalDistribution(size=observation_size,\n hidden_layer_sizes=[observation_size])\n\n def observation_dist(self, state: VRNNState):\n latent_state = state.particles\n latent_encoded = state.latent_encoded\n rnn_out = state.rnn_out\n dist = self.emission(latent_state, rnn_out)\n return dist\n\n def loglikelihood(self, state: State, observation: tf.Tensor):\n dist = self.observation_dist(state)\n return tf.reduce_sum(dist.log_prob(observation), axis=-1)\n\n\nclass VRNNBernoulliObservationModel(ObservationModelBase):\n\n def __init__(self, latent_encoder, observation_size, name='VRNNObservationModel'):\n super(VRNNBernoulliObservationModel, self).__init__(name=name)\n # mlp parametrised gaussian\n self.emission = NNBernoulliDistribution(size=observation_size,\n hidden_layer_sizes=[observation_size])\n\n def observation_dist(self, state: State):\n latent_state = state.particles\n latent_encoded = state.latent_encoded\n rnn_out = state.rnn_out\n dist = self.emission(latent_state, rnn_out)\n return dist\n\n def loglikelihood(self, state: State, observation: tf.Tensor):\n dist = self.observation_dist(state)\n return tf.reduce_sum(dist.log_prob(observation), axis=-1)\n\n def sample(self, state: State):\n dist = self.observation_dist(state)\n return dist.sample()\n\n\nclass ObservationModelEnum:\n BERNOULLI = 0\n NORMAL = 1\n\n\ndef make_filter(latent_size, observation_size, rnn_hidden_size, latent_encoder_layers,\n latent_encoded_size, observation_model_name, resampling_method, resampling_criterion):\n data_encoder = None\n\n if observation_model_name == ObservationModelEnum.NORMAL:\n observation_model = VRNNNormalObservationModel(data_encoder, observation_size)\n elif observation_model_name == ObservationModelEnum.BERNOULLI:\n observation_model = VRNNBernoulliObservationModel(data_encoder, observation_size)\n else:\n raise ValueError(f'observation_model_name {observation_model_name} '\n f'is not a valid value for ObservationModelEnum')\n\n latent_encoder = snt.nets.MLP(\n output_sizes=latent_encoder_layers + [latent_encoded_size],\n name=\"latent_encoder\")\n\n transition_model = VRNNTransitionModel(rnn_hidden_size, latent_size, data_encoder, latent_encoder)\n proposal_model = VRNNProposalModel(transition_model)\n\n return SMC(observation_model, transition_model, proposal_model, resampling_criterion, resampling_method)\n","sub_path":"filterflow/models/vrnn.py","file_name":"vrnn.py","file_ext":"py","file_size_in_byte":9565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"545140812","text":"import ast\nfrom io import StringIO\n\nimport sys\nimport re, os, os.path, ast\n\nINFSTR = '1e308'\n\ndef interleave(inter, f, seq):\n seq = iter(seq)\n try:\n f(next(seq))\n except StopIteration:\n pass\n else:\n for x in seq:\n inter()\n f(x)\n\nclass PythonToPhp:\n aliases = {}\n staticmethods = []\n interfaces = []\n abstractmethods = []\n \n def __init__(self, source, indent = 0):\n tree = ast.parse(source)\n self.code = StringIO()\n self.tabstop = 4\n self._indent = indent\n \n self.in_class = False\n self.in_func = False\n self.in_p2p_func = False\n \n self.funcs_to_replace = {\n 'str':'strval',\n 'int':'intval',\n 'float':'floatval',\n }\n self.dispatch(tree)\n\n def get_code(self):\n return self.code.getvalue()\n\n def fill(self, text = ''):\n self.code.write('\\n%s%s' % (' ' * self.tabstop * self._indent, text))\n\n def write(self, text):\n self.code.write(text)\n\n def enter(self):\n self.code.write(' {')\n self._indent += 1\n\n def leave(self):\n self._indent -= 1\n self.fill('}')\n\n def error(self, msg):\n print(msg)\n sys.exit()\n\n def dispatch(self, tree):\n if isinstance(tree, list):\n for t in tree:\n self.dispatch(t)\n return\n meth = getattr(self, '_%s' % tree.__class__.__name__)\n return meth(tree)\n\n ########## Transform Methods ##########\n\n def _Module(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n ### Statement ###\n\n def _Expr(self, tree):\n self.fill()\n self.dispatch(tree.value)\n if not self.in_p2p_func:\n self.write(';')\n else: self.in_p2p_func = False\n\n\n def _Import(self, t):\n pass #self.error('import not supported')\n\n def _ImportFrom(self, t):\n fname = os.path.join(os.getcwd(), t.module.replace(\".\", os.sep)) + \".py\"\n if os.path.exists(fname):\n ofile = open(fname, \"r\")\n PythonToPhp(ast.parse(ofile.read()))\n self.dispatch(t.names)\n ofile.close()\n else:\n self.error('import file \"'+ t.module +'\" not found')\n\n def _Assign(self, t):\n def incls():\n if self.in_class and not self.in_func:\n self.write(\"protected \")\n \n self.fill()\n for target in t.targets:\n if isinstance(target, ast.Tuple):\n incls()\n self._lvalue_tuple(target)\n else:\n incls()\n self.dispatch(target)\n self.write(' = ')\n self.dispatch(t.value)\n self.write(';')\n\n def _AugAssign(self, t):\n self.fill()\n self.dispatch(t.target)\n name = t.op.__class__.__name__\n if name == 'Pow':\n self.write(' = pow(')\n self.dispatch(t.target)\n self.write(', ')\n self.dispatch(t.value)\n self.write(');')\n elif name == 'FloorDiv':\n self.write(' = floor(')\n self.dispatch(t.target)\n self.write(' / ')\n self.dispatch(t.value)\n self.write(');')\n else:\n self.write(' %s= ' % self.binop[t.op.__class__.__name__])\n self.dispatch(t.value)\n self.write(';')\n\n def _Return(self, t):\n self.fill('return')\n if t.value:\n self.write(' ')\n self.dispatch(t.value)\n self.write(';')\n\n def _Pass(self, t):\n self.fill(';')\n\n def _Break(self, t):\n self.fill('break;')\n\n def _Continue(self, t):\n self.fill('continue;')\n\n def _Delete(self, t):\n for target in t.targets:\n self.fill('unset(')\n self.dispatch(target)\n self.write(');')\n\n def _Assert(self, t):\n self.fill('assert(')\n self.dispatch(t.test)\n self.write(');')\n\n def _Exec(self, t):\n self.fill('eval(')\n self.dispatch(t.body)\n self.write(');')\n\n def _Print(self, t):\n self.fill('echo ')\n sep = ''\n for e in t.values:\n self.write(sep)\n self.dispatch(e)\n sep = ', '\n if t.nl:\n self.write(sep)\n self.write(\"'
'\")\n self.write(';')\n\n def _Global(self, t):\n self.fill('global ')\n interleave(lambda: self.write(', '), self.write, t.names)\n self.write(';')\n\n def _Yield(self, t):\n self.error('yield not supported')\n\n def _Raise(self, t):\n self.fill(\"throw \")\n self.dispatch(t.exc)\n self.write(\";\")\n \n def _Try(self, t):\n self.fill(\"try\")\n self.enter()\n self.dispatch(t.body)\n self.leave()\n self.dispatch(t.handlers)\n\n def _TryExcept(self, t):\n self.error('Exceptions not supported')\n\n def _TryFinally(self, t):\n self.error('Exceptions not supported')\n\n def _ExceptHandler(self, t):\n if isinstance(t.type, ast.Name):\n if t.type.id and t.name:\n self.write(\" catch(%s $%s)\" % (t.type.id, t.name))\n elif t.type.id and not t.name:\n self.write(\" catch(%s)\" % t.type.id)\n else: self.write(\" catch()\")\n self.enter()\n self.dispatch(t.body)\n self.leave()\n \n def _ClassDef(self, t):\n if t.decorator_list:\n for decorator in t.decorator_list:\n if decorator.id == \"interface\":\n self.interfaces.append(t.name)\n self.write(\"\\n\\ninterface \")\n if decorator.id == \"abstract\":\n self.interfaces.append(t.name)\n self.write(\"\\n\\nabstract \")\n else: self.write('\\n\\n')\n self.in_class = True\n self.write('class %s ' % t.name)\n\n if len(t.bases) > 0:\n clss = \", \".join([self._getAlias(n.id) for n in t.bases if self._getAlias(n.id) not in self.interfaces ])\n if clss: self.write(\"extends %s\" % clss)\n intrfs = \", \".join([self._getAlias(n.id) for n in t.bases if self._getAlias(n.id) in self.interfaces ])\n if intrfs: self.write(\" implements %s\" % intrfs)\n self.enter()\n self.dispatch(t.body)\n self.leave()\n self.in_class = False\n\n def comma_if_not_one(self, node):\n if len(node) > 0: return \", \"\n else: return \"\"\n \n def nameOrCall(self, t):\n if isinstance(t, ast.Name): return t.id\n else: return t.func.id\n \n def reallyDecorator(self, t):\n len = 0\n for decorator in t.decorator_list:\n if self.nameOrCall(decorator) == \"staticmethod\" or self.nameOrCall(decorator) == \"abstractmethod\": continue\n else: len = len + 1\n return len\n \n def _getAlias(self, name):\n if name in self.aliases:\n return self.aliases[name]\n else:\n return name\n \n def _FunctionDef(self, t):\n self.write(\"\\n\")\n self.in_func = True\n if t.decorator_list:\n for decorator in t.decorator_list:\n if self.nameOrCall(decorator) == \"staticmethod\":\n self.staticmethods.append(t.name)\n self.write('\\n%sstatic ' % (' ' * self.tabstop * self._indent))\n elif self.nameOrCall(decorator) == \"abstractmethod\":\n self.abstractmethods.append(t.name)\n self.write('\\n%sabstract ' % (' ' * self.tabstop * self._indent))\n else: \n self.write('\\n%s' % (' ' * self.tabstop * self._indent))\n if self.in_class:\n if t.name == \"__init__\":\n self.write('function __construct (')\n elif t.name.startswith(\"_\"):\n self.write('protected function ' + t.name + '(')\n else:\n self.write('public function ' + t.name + '(')\n else:\n self.write('function ' + t.name + '(')\n self.dispatch(t.args)\n self.write(')')\n self.enter()\n if t.decorator_list and self.reallyDecorator(t):\n self.write(\"\\n%sreturn\\n\" % (self._indent * \"\\t\")) ; j = 0\n for i, decorator in enumerate(t.decorator_list):\n if self.nameOrCall(decorator) == \"staticmethod\" or \\\n self.nameOrCall(decorator) == \"abstractmethod\":\n j -= 1 ; continue\n if self.reallyDecorator(t) >= 1 and not isinstance(decorator, ast.Name):\n comma = self.comma_if_not_one(decorator.args)\n else:\n comma = \"\"\n if i == 0:\n self.write(\"%s%s(\" % (self._indent * \"\\t\", self.nameOrCall(decorator) ) )\n if i > 0:\n self.write(\"%s(\" % (self.nameOrCall(decorator) ) )\n if not isinstance(decorator, ast.Name): self.dispatch(decorator.args)\n self.write(comma)\n if j+i+1 == self.reallyDecorator(t):\n self.write(\" function() use(\")\n self.dispatch(t.args)\n self.write(\") {\\n\")\n \n self.dispatch(t.body)\n if t.decorator_list and self.reallyDecorator(t):\n self.write(\"\\n%s}%s;\" % (self._indent * \"\\t\", self.reallyDecorator(t)* \")\"))\n self.leave()\n self.in_func = False\n\n def _For(self, t):\n self.fill('foreach (')\n self.dispatch(t.iter)\n self.write(' as ')\n self.dispatch(t.target)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n if t.orelse:\n self.error('else clause for for statement not supported')\n\n def _If(self, t):\n self.fill(\"if (\")\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n # collapse nested ifs into equivalent elifs.\n while (t.orelse and len(t.orelse) == 1 and\n isinstance(t.orelse[0], ast.If)):\n t = t.orelse[0]\n self.fill(\"elseif (\")\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n # final else\n if t.orelse:\n self.fill(\"else\")\n self.enter()\n self.dispatch(t.orelse)\n self.leave()\n\n def _While(self, t):\n self.fill(\"while (\")\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n if t.orelse:\n self.error('else clause for while statement not supported')\n\n def _With(self, t):\n self.error('with statement not supported')\n\n ### Expression ###\n\n def _Str(self, t):\n self.write(repr(t.s))\n\n def _Name(self, t):\n if t.id == 'self':\n self.write('$this')\n elif t.id == 'True':\n self.write('true')\n elif t.id == 'False':\n self.write('false')\n elif t.id == 'None':\n self.write('null')\n else:\n self.write('$%s' % t.id)\n\n def _Repr(self, t):\n self.write('var_export(')\n self.dispatch(t.value)\n self.write(\", true)\")\n\n def _Num(self, t):\n repr_n = repr(t.n)\n if repr_n.startswith('-'):\n self.write('(')\n self.write(repr_n.replace('inf', INFSTR))\n if repr_n.startswith('-'):\n self.write(')')\n\n def _List(self, t):\n self.write('array(')\n interleave(lambda: self.write(\", \"), self.dispatch, t.elts)\n self.write(')')\n\n def _ListComp(self, t):\n if len(t.generators) > 1:\n self.error('multiple generators in comprehension not supported')\n generator = t.generators.pop()\n self._comprehension(generator, 'left')\n self.dispatch(t.elt)\n self._comprehension(generator, 'right')\n\n def _comprehension(self, t, part = 'left'):\n if part == 'left':\n if t.ifs:\n self.write('array_filter(array_map(function(')\n else:\n self.write('array_map(function(')\n self.dispatch(t.target)\n self.write(') { return ')\n elif part == 'right':\n self.write('; }, ')\n self.dispatch(t.iter)\n if t.ifs:\n self.write('), function(')\n self.dispatch(t.target)\n self.write(') { return ')\n for if_clause in t.ifs:\n self.dispatch(if_clause)\n self.write('; })')\n else:\n self.write(')')\n\n def _GeneratorExp(self, t):\n if len(t.generators) > 1:\n self.error('multiple generators in comprehension not supported')\n generator = t.generators.pop()\n self._comprehension(generator, 'left')\n self.dispatch(t.elt)\n self._comprehension(generator, 'right')\n\n def _SetComp(self, t):\n if len(t.generators) > 1:\n self.error('multiple generators in comprehension not supported')\n self.write('array_unique(')\n generator = t.generators.pop()\n self._comprehension(generator, 'left')\n self.dispatch(t.elt)\n self._comprehension(generator, 'right')\n self.write(')')\n\n def _DictComp(self, t):\n self.error('dict comprehension not supported')\n\n def _IfExp(self, t):\n self.write(\"((\")\n self.dispatch(t.test)\n self.write(') ? (')\n self.dispatch(t.body)\n self.write(') : (')\n self.dispatch(t.orelse)\n self.write('))')\n\n def _Set(self, t):\n assert(t.elts) # should be at least one element\n self.write('array_unique(array(')\n interleave(lambda: self.write(\", \"), self.dispatch, t.elts)\n self.write('))')\n\n def _Dict(self, t):\n self.write('array(')\n def write_pair(pair):\n k, v = pair\n self.dispatch(k)\n self.write(' => ')\n self.dispatch(v)\n interleave(lambda: self.write(', '), write_pair, zip(t.keys, t.values))\n self.write(')')\n\n def _Tuple(self, t):\n self.write('array(')\n interleave(lambda: self.write(\", \"), self.dispatch, t.elts)\n self.write(')')\n\n def _lvalue_tuple(self, t):\n self.write('list(')\n interleave(lambda: self.write(\", \"), self.dispatch, t.elts)\n self.write(')')\n\n unop = {\"Invert\":\"~\", \"Not\": \"!\", \"UAdd\":\"+\", \"USub\":\"-\"}\n def _UnaryOp(self, t):\n self.write(\"(\")\n self.write(self.unop[t.op.__class__.__name__])\n self.write(\" \")\n if isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num):\n self.write(\"(\")\n self.dispatch(t.operand)\n self.write(\")\")\n else:\n self.dispatch(t.operand)\n self.write(\")\")\n\n binop = { \n \"Add\":\"+\",\n \"Sub\":\"-\",\n \"Mult\":\"*\",\n \"Div\":\"/\",\n \"Mod\":\"%\",\n \"LShift\":\"<<\",\n \"RShift\":\">>\",\n \"BitOr\":\"|\",\n \"BitXor\":\"^\",\n \"BitAnd\":\"&\",\n }\n def _BinOp(self, t):\n name = t.op.__class__.__name__\n if name == 'Pow':\n self.write(\"(pow(\")\n self.dispatch(t.left)\n self.write(', ')\n self.dispatch(t.right)\n self.write('))')\n elif name == 'FloorDiv':\n self.write('(floor(')\n self.dispatch(t.left)\n self.write(' / ')\n self.dispatch(t.right)\n self.write('))')\n elif name == 'Mod' and isinstance(t.left, ast.Str): \n self.write('sprintf(')\n self.dispatch(t.left)\n self.write(', ')\n if isinstance(t.right, ast.Str):\n self.dispatch(t.right)\n elif isinstance(t.right, ast.Tuple):\n interleave(lambda: self.write(\", \"), self.dispatch, t.right.elts)\n else:\n self.error('impossible string substript error')\n self.write(')')\n else:\n self.write(\"(\")\n self.dispatch(t.left)\n self.write(\" \" + self.binop[name] + \" \")\n self.dispatch(t.right)\n self.write(\")\")\n\n cmpops = {\n \"Eq\":\"==\",\n \"NotEq\":\"!=\",\n \"Lt\":\"<\",\n \"LtE\":\"<=\",\n \"Gt\":\">\",\n \"GtE\":\">=\",\n \"Is\":\"===\",\n \"IsNot\":\"!==\",\n }\n def _Compare(self, t):\n name = t.ops[0].__class__.__name__\n self.write(\"(\")\n if name == 'In':\n comparator = t.comparators.pop()\n self.write('in_array(')\n self.dispatch(t.left)\n self.write(', ')\n self.dispatch(comparator)\n self.write(') || array_key_exists(')\n self.dispatch(t.left)\n self.write(', ')\n self.dispatch(comparator)\n self.write(')')\n elif name == 'NotIn':\n comparator = t.comparators.pop()\n self.write('!in_array(')\n self.dispatch(t.left)\n self.write(', ')\n self.dispatch(comparator)\n self.write(') && !array_key_exists(')\n self.dispatch(t.left)\n self.write(', ')\n self.dispatch(comparator)\n self.write(')')\n else:\n self.dispatch(t.left)\n for o, e in zip(t.ops, t.comparators):\n self.write(\" \" + self.cmpops[o.__class__.__name__] + \" \")\n self.dispatch(e)\n self.write(\")\")\n\n boolops = {ast.And: '&&', ast.Or: '||'}\n def _BoolOp(self, t):\n self.write(\"(\")\n s = \" %s \" % self.boolops[t.op.__class__]\n interleave(lambda: self.write(s), self.dispatch, t.values)\n self.write(\")\")\n\n def _Attribute(self,t):\n if re.match('^[A-Z]', t.value.id):\n self.write(t.value.id)\n else:\n self.dispatch(t.value)\n \n isConst = re.match('^[A-Z][_A-Z]*$', t.attr)\n if t.attr in self.staticmethods or isConst: # it's a constant if ALL CAPS\n self.write(\"::\")\n else:\n self.write(\"->\")\n self.write(t.attr)\n \n if not isConst:\n if isinstance(t.ctx, ast.Load):\n self.write(\"(\")\n\n def _func_name(self, t):\n if isinstance(t, ast.Name):\n tid = self._getAlias(t.id)\n if re.match('^[A-Z]', tid):\n self.write('new %s' % tid)\n elif tid in self.funcs_to_replace:\n self.write('%s' % self.funcs_to_replace[tid])\n else:\n self.write('%s' % tid)\n\n def _Call(self, t):\n if isinstance(t.func, ast.Attribute):\n self.dispatch(t.func)\n elif t.func.id == 'isinstance':\n self.write(\"(\")\n self.dispatch(t.args[0])\n self.write(\" instanceof %s )\" % t.args[1].id)\n return\n elif t.func.id == 'py2php':\n self.in_p2p_func = True\n self.write(t.args[0].s)\n return\n else:\n self._func_name(t.func)\n self.write(\"(\")\n comma = False\n for e in t.args:\n if comma: self.write(\", \")\n else: comma = True\n self.dispatch(e)\n for e in t.keywords:\n if comma: self.write(\", \")\n else: comma = True\n self.dispatch(e)\n if t.starargs:\n self.error('function vararg not supported')\n if t.kwargs:\n self.error('function kwarg not supported')\n self.write(\")\")\n\n def _Subscript(self, t):\n if isinstance(t.slice, ast.Index):\n self.dispatch(t.value)\n self.write(\"[\")\n self.dispatch(t.slice)\n self.write(\"]\")\n #==================================================================\n # self.write('pyphp_subscript(')\n # self.dispatch(t.value)\n # self.write(', ')\n # self.dispatch(t.slice)\n # self.write(')')\n #==================================================================\n elif isinstance(t.slice, ast.Slice):\n self.write('array_slice(')\n self.dispatch(t.value)\n self.write(', ')\n self.dispatch(t.slice)\n self.write(')')\n\n def _Ellipsis(self, t):\n self.error('ellipsis not supported')\n\n def _Index(self, t):\n self.dispatch(t.value)\n\n def _Slice(self, t):\n if t.lower:\n self.dispatch(t.lower)\n else:\n self.write('0')\n if t.upper:\n self.write(\", \")\n self.write('(')\n self.dispatch(t.upper)\n self.write(' - ')\n if t.lower:\n self.dispatch(t.lower)\n else:\n self.write('0')\n self.write(')')\n if t.step:\n self.error('slice step not supported')\n\n def _ExtSlice(self, t):\n self.error('extslice not supported')\n #interleave(lambda: self.write(', '), self.dispatch, t.dims)\n\n ### Others ###\n\n def _arguments(self, t):\n first = True\n defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults\n for a,d in zip(t.args, defaults):\n if a.arg == \"self\": continue\n if first: first = False\n else: self.write(\", \")\n self.dispatch(a),\n if d:\n self.write(\" = \")\n self.dispatch(d)\n if t.vararg:\n self.error('function vararg not supported')\n if t.kwarg:\n self.error('function kwarg not supported')\n\n def _arg(self, t):\n self.write(\"$%s\" % t.arg)\n \n def _keyword(self, t):\n self.write('$%s' % t.arg)\n self.write(\" = \")\n self.dispatch(t.value)\n\n def _Lambda(self, t):\n self.write(\"(\")\n self.write(\"function(\")\n self.dispatch(t.args)\n self.write(\") {\\n\")\n self.dispatch(t.body)\n self.write(\"\\n})\")\n\n def _alias(self, t):\n self.aliases[t.asname] = t.name\n \n def _NameConstant(self, t):\n pass\n \n def _NoneType(self, t):\n pass","sub_path":"pyphp.py","file_name":"pyphp.py","file_ext":"py","file_size_in_byte":22308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"19799087","text":"import os\nimport datetime\nimport smtplib\n\nfrom dateutil import tz\n\nTIME_FORMAT = \"%m/%d/%Y at %H:%M:%S (%Z)\"\n\n\ndef get_file_contents_as_list(package, file_name):\n path = os.path.abspath(__file__ + \"/../../\" + package + '/' + file_name)\n if not os.path.isfile(path):\n return []\n else:\n file = open(path)\n file_list = file.read().splitlines()\n file.close()\n return file_list\n\n\ndef get_file_contents_as_dictionary(package, file_name):\n tuple_list = []\n for line in get_file_contents_as_list(package, file_name):\n tuple_list.append(tuple(line.split(\" = \")))\n return dict(tuple_list)\n\n\ndef get_file_contents_as_map(file_name):\n path = os.path.abspath(__file__ + '/../files/' + file_name)\n if not os.path.isfile(path):\n open(path, 'w').close() # If file doesn't exist, create it\n return {}\n else:\n file = open(path)\n file_list = file.read().splitlines()\n file.close()\n return dict([tuple(item.split(\":\")) for item in file_list])\n\n\ndef write_data_to_disk(package, file_name, data):\n path = os.path.abspath(__file__ + \"/../../\" + package + \"/\" + file_name)\n submissions_file = open(path, 'a')\n submissions_file.write(str(data) + \"\\n\")\n submissions_file.close()\n\n\ndef write_list_to_disk(package, file_name, list_to_write):\n path = os.path.abspath(__file__ + '/../../' + package + '/' + file_name)\n if not list_to_write:\n # If there's nothing in the list:, clear it out\n open(path, 'w').close()\n else:\n submissions_file = open(path, 'w')\n [submissions_file.write(str(x) + \"\\n\") for x in list_to_write]\n submissions_file.close()\n\n\n# Sorry, you don't get to see my email credentials :)\ndef send_email(message):\n credentials = get_file_contents_as_dictionary(\"files\", \"email_credentials.txt\")\n server = smtplib.SMTP('smtp.gmail.com:587')\n server.starttls()\n server.login(credentials['bot_email'], credentials['bot_password'])\n server.sendmail(credentials['bot_email'], credentials['to_address'], message)\n server.quit()\n\n\ndef last_updated_utc():\n return datetime.datetime.utcnow().replace(tzinfo=tz.tzutc())\n\n\ndef last_updated_utc_formatted():\n return last_updated_utc().strftime(TIME_FORMAT)\n\n\ndef last_updated_local():\n return last_updated_utc().astimezone(tz.tzlocal())\n\n\ndef last_updated_local_formatted():\n return last_updated_local().strftime(TIME_FORMAT)\n\n\ndef datetime_from_timestamp(timestamp):\n return datetime.datetime.fromtimestamp(float(timestamp), tz=tz.tzutc())\n\n\ndef datetime_from_timestamp_formatted(timestamp):\n return datetime_from_timestamp(timestamp).strftime(\"%m/%d/%Y at %H:%M:%S (%Z)\")\n","sub_path":"utilities/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"81922245","text":"'''\r\n数据的预处理和特征工程\r\n'''\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pprint\r\n\r\ndf_train = pd.read_csv('./dataset/pfm_train.csv')\r\ndf_test = pd.read_csv('./dataset/pfm_test.csv')\r\n\r\ndf_train['source'] = 1\r\ndf_test['source'] = 0\r\n\r\ndf = pd.concat([df_train, df_test], axis=0)\r\n\r\ndf.drop(['Over18', 'StandardHours', 'EmployeeNumber'], axis=1, inplace=True)\r\n\r\n# 预测变量\r\ntarget_var = 'Attrition'\r\n\r\n# 定义连续变量\r\ncols_con = ['Age', 'DistanceFromHome', 'MonthlyIncome']\r\n\r\n# 定义离散变量\r\ncols_dis = [\r\n 'BusinessTravel', 'Department', 'Education', 'EducationField',\r\n 'EnvironmentSatisfaction', 'Gender', 'JobInvolvement', 'JobLevel',\r\n 'JobRole', 'JobSatisfaction', 'MaritalStatus', 'NumCompaniesWorked',\r\n 'OverTime', 'PercentSalaryHike', 'PerformanceRating',\r\n 'RelationshipSatisfaction', 'StockOptionLevel', 'TotalWorkingYears',\r\n 'TrainingTimesLastYear', 'WorkLifeBalance', 'YearsAtCompany',\r\n 'YearsInCurrentRole', 'YearsSinceLastPromotion', 'YearsWithCurrManager'\r\n]\r\n\r\n# 连续变量离散化\r\nN = 4 #分割的倍数\r\n\r\nage_cut = pd.cut(df.Age, bins=range(18, 60, 3 * N))\r\nage_dm = pd.get_dummies(age_cut, prefix='Age')\r\n\r\ndistance_cut = pd.cut(df.DistanceFromHome, bins=range(1, 29, 1 * N))\r\ndistance_dm = pd.get_dummies(distance_cut, prefix='Distance')\r\n\r\nincome_cut = pd.cut(df.MonthlyIncome, bins=range(1000, 20000, 1000 * N))\r\nincome_dm = pd.get_dummies(income_cut, prefix=\"income\")\r\n\r\n# 离散化变量的get_dummies\r\nlst = []\r\nfor col in cols_dis:\r\n lst.append(pd.get_dummies(df[col], prefix=col))\r\ndf_dis = pd.concat(lst, axis=1)\r\n\r\n# 整合起来\r\nmodelinput = pd.concat(\r\n [df_dis, age_dm, distance_dm, income_dm, df.Attrition, df.source], axis=1)\r\n\r\ndf_train = modelinput[modelinput.source == 1]\r\ndf_test = modelinput[modelinput.source == 0]\r\ndf_train.drop(['source'], axis=1, inplace=True)\r\ndf_test.drop(['source'], axis=1, inplace=True)\r\ndf_train.to_csv('./dataset/pfm_train_modifited.csv', index=False)\r\ndf_test.to_csv('./dataset/pfm_test_modifited.csv', index=False)\r\n","sub_path":"05DataCastle/pfm/code/feature_eng.py","file_name":"feature_eng.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"1394599","text":"#!/bin/python3\n\n# Constraints: 1 <= n <= 100\n# If n is odd, print Weird\n# If n is even and in the inclusive range of 2 to 5, print Not Weird\n# If n is even and in the inclusive range of 6 to 20, print Weird\n# If n is even and greater than 20, print Not Weird\n\nN = int(input())\n\n# odd number\nif N % 2 == 1:\n print('Weird')\n# even number\nelse:\n if N in range(2, 5 + 1):\n print('Not Weird')\n elif N in range(6, 20 + 1):\n print('Weird')\n elif N > 20:\n print('Not Weird')","sub_path":"python/a-introduction/p01_python_if_else.py","file_name":"p01_python_if_else.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"336218056","text":"import json\n\nimport time\nimport random\nimport math\nfrom clients.client import Player\n\nclass Candidate:\n def __init__(self, iter, score, atts):\n self.score = score\n self.n = len(atts)\n self.atts = atts\n self.iter = iter\n def remove(self, sure):\n for ind in sure:\n if self.atts[ind] > 0:\n self.score -= 1.0/self.n\n else:\n self.score += 1.0/self.n\n self.atts = [x for ind,x in enumerate(self.atts) if ind not in sure]\n def __repr__(self):\n return self.__str__()\n def __str__(self):\n s = \"Candidate \" + str(self.iter) + \" has score \" + str(self.score) + \"\\n\"\n s += \"Attributes: \" + str(self.atts)\n return s\n\n\nclass MatchMaker(Player):\n def __init__(self):\n super(MatchMaker, self).__init__(name=\"We don't know matchmaker\", is_player=False)\n game_info = json.loads(self.client.receive_data(size=32368*2))\n # print('Matchmaker', game_info)\n self.random_candidates_and_scores = game_info['randomCandidateAndScores']\n\n self.candidates = []\n for iter in self.random_candidates_and_scores:\n candi = self.random_candidates_and_scores[iter]\n self.candidates.append(Candidate(int(iter), candi['Score'], candi['Attributes']))\n\n self.n = game_info['n']\n self.prev_candidate = {'candidate': [], 'score': 0, 'iter': 0}\n self.time_left = 120\n self.randomTime = 7\n self.svmTime = 10\n\n self.cand = {}\n self.max_score = -1\n self.max_score_candidate = []\n\n self.weight = [-(1.0/(self.n/2))]*int(self.n/2) + [(1.0/(self.n - self.n/2))]*(self.n - int(self.n/2))\n self.train = []\n self.dev = []\n self.best_weight = self.weight\n\n self.round_n = 1\n self.maxTime = 0\n\n\n random.shuffle(self.weight)\n print(len(self.weight))\n\n\n\n for item in self.random_candidates_and_scores:\n att = self.random_candidates_and_scores[item][\"Attributes\"]\n score = self.random_candidates_and_scores[item][\"Score\"]\n negative_att = [(1 - i) for i in att]\n negative_score = 0 - score\n self.cand[tuple(att)] = score\n self.cand[tuple(negative_att)] = negative_score\n\n self.data_set = []\n\n def get_atts_score(self, candi1, candi2):\n n = len(candi1.atts)\n atts = [0]*n\n score = candi1.score*candi2.score\n if score > 0:\n for i in range(n):\n if candi1.atts[i] == candi2.atts[i]:\n if candi1.score > 0:\n if candi1.atts[i] == 1:\n atts[i] += score\n else:\n atts[i] -= score\n else:\n if candi1.atts[i] == 1:\n atts[i] -= score\n else:\n atts[i] += score\n else:\n for i in range(n):\n if candi1.atts[i] != candi2.atts[i]:\n if candi1.score > 0: #candi2.score < 0\n if candi1.atts[i] == 1:\n atts[i] += abs(score)\n else:\n atts[i] -= abs(score)\n else:\n if candi1.atts[i] == 1:\n atts[i] -= abs(score)\n else:\n atts[i] += abs(score)\n return atts\n\n def get_reputation(self, candis):\n n = len(candis[0].atts)\n repu = [0]*n\n maxAbs = 0\n for candi in candis:\n maxAbs = max(maxAbs, abs(candi.score))\n threshHold = maxAbs*0.4\n selects = []\n for candi in candis:\n if abs(candi.score) >= threshHold:\n selects.append(candi)\n assert len(selects) > 1, \"Bad situation\"\n for i in range(len(selects)):\n for j in range(len(selects)):\n if i < j:\n candi1 = selects[i]\n candi2 = selects[j]\n atts = self.get_atts_score(candi1, candi2)\n for k in range(n):\n repu[k] += atts[k]\n return repu\n\n def play_game(self):\n self.pre_process()\n self.svm(1, 200)\n while True:\n print(self.name)\n candidate = self.my_candidate()\n self.client.send_data(json.dumps(candidate))\n response = json.loads(self.client.receive_data(size=32368*2))\n self.round_n+=1\n if 'game_over' in response:\n if response['match_found']:\n print(\"Perfect Candidate Found\")\n print(\"Total candidates used = \", response['num_iterations'])\n else:\n print(\"Perfect candidate not found - you have failed the player\")\n print(\"Total candidates used = \", response['total_candidates'])\n exit(0)\n else:\n self.prev_candidate = response['prev_candidate']\n self.time_left = response['time_left']\n\n\n def sgd(self, lr):\n random.shuffle(self.train)\n for item in self.train:\n inp = item[0]\n ans = item[1]\n expected_ans = sum([inp[i]*self.weight[i] for i in list(range(self.n))])\n learned = -lr*(expected_ans - ans)\n self.weight = [self.weight[i]+learned*inp[i] for i in list(range(self.n))]\n return self.weight\n\n\n\n\n def train_data(self, iteration, lr):\n lr = lr / (math.sqrt(self.n)*math.sqrt((float(iteration))))\n weight = self.sgd(lr)\n total_false = 0\n for item in self.dev:\n inp = item[0]\n ans = item[1]\n expected_ans = sum([inp[i]*self.weight[i] for i in list(range(self.n))])\n # print(\"True value:\", ans)\n # print(\"Predicted: \", expected_ans)\n difference = abs(ans - expected_ans)\n total_false+=difference\n total_false = total_false/len(self.dev)\n print(\"false rate is:\", total_false)\n return total_false\n\n def svm(self, lr, iterations):\n false_rate = 1\n for i in range(iterations):\n print(\"Iteration: \", i)\n false_rate_it = self.train_data(i+1, lr)\n if false_rate_it0:\n difference = 1\n else:\n difference = -1\n p = []\n for i in range(len(own)):\n p.append(0)\n\n for i in range(len(own)):\n if own[i] == 1:\n p[i] = -1\n elif not_own[i] == 1:\n p[i] = 1\n self.data_set.append((p, difference))\n\n # self.data_set += [(x, self.cand[x]) for x in self.cand]\n\n random.shuffle(self.data_set)\n self.train = self.data_set[0:int(0.8*len(self.data_set))]\n # self.dev = [(x, self.cand[x]) for x in self.cand]\n self.dev = self.data_set[int(0.8*len(self.data_set)):]\n\n\n\n\n\n\n def my_candidate(self):\n\n \"\"\"\n PLACE YOUR CANDIDATE GENERATION ALGORITHM HERE\n As the matchmaker, you have access to the number of attributes (self.n),\n initial random candidates and their scores (self.random_candidates_and_scores),\n your clock time left (self.time_left)\n and a dictionary of the previous candidate sent (self.prev_candidate) consisting of\n 'candidate' = previous candidate attributes\n 'score' = previous candidate score\n 'iter' = iteration num of previous candidate\n For this function, you must return an array of values that lie between 0 and 1 inclusive and must have four or\n fewer digits of precision. The length of the array should be equal to the number of attributes (self.n)\n \"\"\"\n if len(self.prev_candidate['candidate']) == self.n:\n self.candidates.append(Candidate(len(self.candidates), self.prev_candidate['score'], self.prev_candidate['candidate']))\n print(\"TIME LEFT:\", self.time_left, \"s\")\n if self.randomTime > 0:\n self.randomTime -= 1\n cand = []\n for i in range(self.n):\n val = random.random()\n if val > 0.5:\n cand.append(1)\n else:\n cand.append(0)\n return cand\n if self.time_left > self.maxTime*2+2 and self.svmTime > 0:\n self.svmTime -=1\n start = time.time()\n if len(self.prev_candidate[\"candidate\"])!=0:\n print(11111111111111111111111111111111111)\n prev_cand = self.prev_candidate[\"candidate\"]\n prev_score = self.prev_candidate[\"score\"]\n negative_cand = [1-x for x in prev_cand]\n negative_score = - prev_score\n\n for a in self.cand:\n b = tuple(prev_cand)\n if (a!=b):\n own, not_own = self.both_own_both_not_own(a, b)\n difference = -self.cand[a] - prev_score\n if difference>0:\n difference = 1\n else:\n difference = -1\n p = []\n for i in range(len(own)):\n p.append(0)\n\n for i in range(len(own)):\n if own[i] == 1:\n p[i] = -1\n elif not_own[i] == 1:\n p[i] = 1\n self.data_set.append((p, difference))\n random.shuffle(self.data_set)\n self.train = self.data_set[0:int(0.8*len(self.data_set))]\n # self.dev = [(x, self.cand[x]) for x in self.cand]\n self.dev = self.data_set[int(0.8*len(self.data_set)):]\n self.svm(1/self.round_n, 200)\n end = time.time()\n print(\"TOOK \", end-start, \"s\")\n self.maxTime = max(self.maxTime, end-start)\n cand = []\n for item in self.weight:\n if item>0:\n cand.append(1)\n else:\n cand.append(0)\n return cand\n else:\n start = time.time()\n repu = self.get_reputation(self.candidates)\n end = time.time()\n print(\"ONLY TOOK\", end-start, \"s\")\n cand = []\n for item in repu:\n if item>0:\n cand.append(1)\n else:\n cand.append(0)\n return cand\n","sub_path":"clients/wdk_matchmaker_client.py","file_name":"wdk_matchmaker_client.py","file_ext":"py","file_size_in_byte":11883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"29965184","text":"from django import forms\n\nclass SearchForm(forms.Form):\n name = forms.CharField(label='')\n\n def __init__(self, *args, **kwargs):\n super(SearchForm, self).__init__(*args, **kwargs)\n self.fields['name'].widget.attrs.update({\n 'class': 'form-control',\n 'id': 'exampleInputEmail2',\n 'placeholder': '검색종목'})\n\n\n","sub_path":"stock/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"19263668","text":"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.utils.data\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import save_image\nimport os\nfrom general_methods import get_current_time\nimport numpy as np\nfrom torch.autograd import Variable\nimport pandas as pd\nimport general_methods as gm\nfrom vae_models import VAE_Vanilla_Test, VAE_Conv\n\nrunning_time = get_current_time()\n\nmodel_path = 'results/conv/mixed/2019-01-07-20-36-50/model.torch'\n# model_path = 'results/vanilla/original/2019-01-07-19-26-37/model.torch'\n\n# model_path = 'results/inverse/2019-01-04-23-53-46/model.torch'\n# z_path = model_path.replace('model.torch', 'z.txt')\n\nmodel_type = 'vanilla'\nif 'vanilla' in model_path:\n model_type = 'vanilla'\nelif 'conv' in model_path:\n model_type = 'conv'\nelse:\n model_type = 'vanilla'\n\nif 'mixed' in model_path:\n to_inverse = 'mixed'\nelse:\n if 'inverse' in model_path:\n to_inverse = True\n else:\n to_inverse = False\n\nif to_inverse == 'mixed':\n save_prefix = 'results/' + model_type + '/mixed/'\nelse:\n if to_inverse:\n save_prefix = 'results/' + model_type + '/inverse/'\n else:\n save_prefix = 'results/' + model_type + '/original/'\n\nparser = argparse.ArgumentParser(description='VAE MNIST Example')\nparser.add_argument('--batch_size', type=int, default=128, metavar='N',\n help='input batch size for training (default: 128)')\nparser.add_argument('--epochs', type=int, default=10, metavar='N',\n help='number of epochs to train (default: 10)')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='enables CUDA training')\nparser.add_argument('--seed', type=int, default='1', metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\nparser.add_argument('--lat_dim', type=int, default=20, metavar='N',\n help='how many batches to wait before logging training status')\nparser.add_argument('--img_size', type=int, default=28, metavar='N',\n help='how many batches to wait before logging training status')\nparser.add_argument('--log_interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\nargs = parser.parse_args()\nargs.img_size = 64\nargs.lat_dim = 100\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\ntorch.manual_seed(args.seed)\n\ndevice = torch.device(\"cuda\" if args.cuda else \"cpu\")\n\nkwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}\n\ntransform = transforms.Compose([\n transforms.Scale(args.img_size),\n transforms.ToTensor()\n # transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n])\nif isinstance(to_inverse, bool):\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=True, download=True,\n transform=transform),\n batch_size=args.batch_size, shuffle=True, **kwargs)\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=False, transform=transform),\n batch_size=args.batch_size, shuffle=False, **kwargs)\nelse:\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=True, download=True,\n transform=transform),\n batch_size=int(args.batch_size/2), shuffle=True, **kwargs)\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=False, transform=transform),\n batch_size=int(args.batch_size/2), shuffle=False, **kwargs)\n\n\ndef test(epoch, to_save=False):\n save_path_prefix = save_prefix + running_time + '/'\n model.eval()\n with torch.no_grad():\n for i, (data, _) in enumerate(test_loader):\n if to_inverse == 'mixed':\n data = torch.cat((data, 1 - data), 0)\n elif to_inverse:\n data = 1 - data\n\n data = data.to(device)\n recon_batch, mu, logvar, z = model(data)\n if i == 0:\n n = min(data.size(0), 8)\n comparison = torch.cat([data[:n],\n recon_batch.view(args.batch_size, 1, args.img_size, args.img_size)[:n]])\n\n if to_save:\n if not os.path.exists(save_path_prefix):\n os.makedirs(save_path_prefix)\n save_image(comparison.cpu(),\n save_path_prefix + 'reconstruction_' + str(epoch) + '.png', nrow=n)\n break\n\n\ndef z_vector_analyzer(z_path_1):\n z_1 = np.loadtxt(z_path_1, delimiter=',')\n # z_2 = np.loadtxt(z_path_2, delimiter=',')\n # z_3 = np.loadtxt(z_path_3, delimiter=',')\n # z_4 = np.loadtxt(z_path_4, delimiter=',')\n # z_5 = np.loadtxt(z_path_5, delimiter=',')\n # print(np.max(z_1 - z_2))\n return z_1\n\n\ndef translate_z(zs, model):\n if isinstance(zs, np.ndarray):\n zs = torch.from_numpy(zs).float()\n running_time = get_current_time()\n save_path_prefix = 'results/translation_z/' + running_time + '/'\n sample = model.decode(zs).cpu()\n if not os.path.exists(save_path_prefix):\n os.makedirs(save_path_prefix)\n save_image(sample.view(zs.shape[0], 1, args.img_size, args.img_size),\n save_path_prefix + 'z_translation' + '.png')\n\n\ndef generate_z_vectors(model, to_inverse, up_to):\n store_data_np = np.empty([0, args.lat_dim])\n store_label_np = np.empty([0, ])\n\n for a_loader in [test_loader]:\n for i, (data, label) in enumerate(a_loader):\n if to_inverse == 'mixed':\n data = torch.cat((data, 1 - data), 0)\n elif to_inverse:\n data = 1 - data\n if model_type == 'conv':\n z, mu, logvar = model.encode(data)\n else:\n mu, logvar = model.encode(data)\n z = model.reparameterize(mu, logvar)\n\n store_data_np = np.concatenate([store_data_np, z.data.numpy()], axis=0)\n\n if to_inverse == 'mixed':\n label_half = label.data.numpy() + 0.5\n double_label = np.concatenate([label, label_half], axis=0)\n store_label_np = np.concatenate([store_label_np, double_label], axis=0)\n else:\n store_label_np = np.concatenate([store_label_np, label.data.numpy()], axis=0)\n\n if len(store_label_np) >= up_to:\n break\n\n store_label_np = store_label_np.astype(np.float32)\n print('store data np: ', store_data_np.shape)\n np.savetxt('z_vectors.txt', store_data_np, delimiter='\\t')\n np.savetxt('z_labels.txt', store_label_np, delimiter='\\n', fmt='%.1f')\n\n\nif model_type == 'vanilla':\n print('Loading vanilla ...')\n model = VAE_Vanilla_Test(args=args, z_dim=args.lat_dim,\n to_save_z=True, save_path=model_path.replace('model.torch', '')).to(device)\nelif model_type == 'conv':\n print('Loading conv ...')\n model = VAE_Conv(args=args, z_dim=args.lat_dim, to_save_z=True, save_path=model_path.replace('model.torch', '')).to(device)\n\nmodel.load_state_dict(torch.load(model_path, map_location='cpu'))\nmodel.eval()\ntest(0)\n\narithmetic = z_vector_analyzer(model_path.replace('model.torch', 'z.txt'))\n\nmodel.eval()\nwith torch.no_grad():\n for i, (data, _) in enumerate(test_loader):\n model.translate_z(arithmetic, data, to_save=True)\n break\n\n# zs = (np.zeros(shape=[1, 20]) * 100)\n# translate_z(zs, model)\n\nup_to = 20000\ngenerate_z_vectors(model, to_inverse, up_to)\nz_s = np.loadtxt('z_vectors.txt', delimiter='\\t')\ny_s = np.loadtxt('z_labels.txt', delimiter='\\t')\ngm.compute_TSNE_projection_of_latent_space(z_s[:up_to], y_s[:up_to],\n save_path=model_path.replace('model.torch', 'tsne.png'))\n","sub_path":"vae/vae_model_loader.py","file_name":"vae_model_loader.py","file_ext":"py","file_size_in_byte":8029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"61177381","text":"#!/usr/bin/env python3\n\"\"\" doc \"\"\"\n\nimport numpy as np\n\n\ndef convolve_grayscale_same(images, kernel):\n \"\"\" doc \"\"\"\n\n layers = images.shape[0]\n layerH = images.shape[1]\n layerW = images.shape[2]\n\n kernelH = kernel.shape[0]\n kernelW = kernel.shape[1]\n\n Ph = int((kernelH) / 2)\n Pw = int((kernelW) / 2)\n\n images = np.pad(images, [(0, 0), (Ph, Ph), (Pw, Pw)],\n 'constant', constant_values=0)\n\n convolutedImage = np.zeros((layers, layerH, layerW))\n Nlayer = np.arange(0, layers)\n\n for i in range(layerH):\n for j in range(layerW):\n val = np.sum(np.multiply(images[Nlayer, i:kernelH + i,\n j:kernelW + j], kernel), axis=(1, 2))\n convolutedImage[Nlayer, i, j] = val\n\n return(convolutedImage)\n","sub_path":"math/0x04-convolutions_and_pooling/1-convolve_grayscale_same.py","file_name":"1-convolve_grayscale_same.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"135361934","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 11 21:49:19 2017\n\n@author: jondowning\n\"\"\"\nimport networkx as nx\nimport numpy as np\nfrom networkx.drawing.nx_pydot import write_dot\nimport pygraphviz as pgv\nimport pandas as pd \nimport recursive_collapse \n\nimport pygraphviz as pgv\n\n\"\"\"\npgv has attribute functionality \n\"\"\"\n\npath_dot = 'linear_example_with_edge_labels.dot'\n\n# Directed graph\nG = pgv.AGraph(directed=True)\n\n# Populate nodes and their values\nG.add_node('A', value = 10)\nG.add_node('B', value = 9)\nG.add_node('C', value = 0)\nG.add_node('D', value = 2)\nG.add_node('E', value = 0)\n\n# Populate edges and add their functions\nG.add_edge('A','C', math = '+')\nG.add_edge('B','C', math = '-')\nG.add_edge('C','D', math = '*')\nG.add_edge('D','E', math = '+')\n\n# Add edges labels\nfor edge in G.edges(): \n a, b = edge[0], edge[1]\n G.get_edge(a,b).attr['label'] = ' ' + G.get_edge(a,b).attr['math']\n \n# Write dot from pgv\nG.layout(prog='dot')\nG.write(path_dot)\nG.draw('linear_example_with_edge_labels.png')\nG.draw('linear_example_with_edge_labels.pdf') \n\n# Pick up dot into networkx for colapse \n\"\"\"\nnetworkx has the ability to transform networks. \n\"\"\"\nG = nx.drawing.nx_agraph.read_dot(path_dot)\nmath_dict = nx.get_edge_attributes(G,'math')\nvalues_dict = nx.get_node_attributes(G,'value')\nlabels_dict = nx.get_edge_attributes(G,'label')\n\n# Create a dictionaries: one with values, the next with functions \nmath_dict = nx.get_edge_attributes(G,'math')\nprint('The math_dictionary is:')\nprint(math_dict)\nvalues_dict = nx.get_node_attributes(G,'value')\nprint('The values_dict is:')\nprint(values_dict)\n\n# Provide a map for strings to actual functions \ncalc_dict = {'+':np.add,\n '-':np.subtract,\n '*':np.multiply,\n '%':np.divide} \n\n# We need to swap the order of our keys -- mathematical functions are order dependant! \nmath_dict_sorted = {}\nfor key, math in math_dict.items():\n math_dict_sorted[tuple(reversed(key))] = math\n\nmath_dict = math_dict_sorted\n\n# Run recursive function until all empty variables are complete. \nwhile len(math_dict) > 0:\n print(sorted(math_dict.items()))\n math_dict = recursive_collapse.graph_collapse(math_dict, values_dict, calc_dict)","sub_path":"linear_example/dag_calculation_linear.py","file_name":"dag_calculation_linear.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"591245958","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.utils import timezone\nfrom .models import Pelicula, Categoria\nfrom .forms import PeliculaForm, CategoriaForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport git\n\ndef post_list(request):\n return render(request, 'peliculas/base.html', {'publicacion':'publicacion'})\n\ndef categorias(request):\n categorias = Categoria.objects.order_by('nombre')\n return render(request, 'peliculas/categorias.html', {'categorias':categorias})\n\n@login_required\ndef categoria_nuevo(request):\n if request.method == \"POST\":\n form = CategoriaForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.save()\n return redirect('categorias')\n else:\n form = CategoriaForm()\n return render(request, 'peliculas/categoria_edit.html', {'form': form})\n\n@login_required\ndef categoria_edit(request, pk):\n categoria = get_object_or_404(Categoria, pk=pk)\n if request.method == \"POST\":\n form = CategoriaForm(request.POST, instance=categoria)\n if form.is_valid():\n categoria = form.save(commit=False)\n categoria.save()\n return redirect('categorias')\n else:\n form = CategoriaForm(instance=categoria)\n return render(request, 'peliculas/categoria_edit.html', {'form': form})\n\n@login_required\ndef categoria_delete(request, pk):\n categoria = get_object_or_404(Categoria, pk=pk)\n categoria.delete()\n return redirect('categorias')\n\ndef pelicula_list(request):\n peliculas = Pelicula.objects.filter(fecha_Creacion__lte=timezone.now()).order_by('fecha_Creacion')\n return render(request, 'peliculas/listPeliculas.html', {'peliculas':peliculas})\n\n@login_required\ndef create_pelicula(request):\n if request.method == \"POST\":\n formulario = PeliculaForm(request.POST)\n if formulario.is_valid():\n publicacion = formulario.save(commit=False)\n publicacion.save()\n return redirect('pelicula_list')\n else:\n formulario = PeliculaForm()\n return render(request, 'peliculas/newPelicula.html', {'form': formulario})\n\n@login_required\ndef edit_pelicula(request,pk):\n pelicula = get_object_or_404(Pelicula, pk=pk)\n if request.method == \"POST\":\n formulario = PeliculaForm(request.POST, instance=pelicula)\n if formulario.is_valid():\n pelicula = formulario.save(commit=False)\n pelicula.save()\n return redirect('pelicula_list')\n else:\n formulario = PeliculaForm(instance=pelicula)\n return render(request, 'peliculas/newPelicula.html', {'form': formulario})\n \n@login_required\ndef delete_pelicula(request, pk):\n pelicula = get_object_or_404(Pelicula, pk=pk)\n pelicula.delete()\n return redirect('pelicula_list')\n\n@csrf_exempt\ndef update(request):\n if request.method == \"POST\":\n repo = git.Repo(\"henryjosue.pythonanywhere.comgit\") \n origin = repo.remotes.origin\n\n origin.pull()\n\n return HttpResponse(\"Updated code on PythonAnywhere\")\n else:\n return HttpResponse(\"Couldn't update the code on PythonAnywhere\")\n","sub_path":"peliculas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"493143599","text":"import re\nimport math\nimport torch\nimport torchaudio\nimport numpy as np\nimport argparse\nimport librosa\nimport warnings\nimport itertools as it\nfrom jiwer import wer\nfrom tqdm import tqdm\nimport pandas as pd\nimport os\nfrom glob import glob\n\ntry:\n from flashlight.lib.sequence.criterion import CpuViterbiPath, get_data_ptr_as_bytes\n from flashlight.lib.text.dictionary import create_word_dict, load_words\n from flashlight.lib.text.decoder import (\n CriterionType,\n LexiconDecoderOptions,\n KenLM,\n LM,\n LMState,\n SmearingMode,\n Trie,\n LexiconDecoder,\n )\n from flashlight.lib.text.decoder import LexiconFreeDecoder, LexiconFreeDecoderOptions\n\nexcept:\n warnings.warn(\n \"flashlight python bindings are required to use this KenLM. Please install from https://github.com/facebookresearch/flashlight/tree/master/bindings/python\"\n )\n LM = object\n LMState = object\n\nfrom datasets import load_dataset, load_metric, concatenate_datasets\n\nfrom transformers import Wav2Vec2CTCTokenizer\nfrom transformers import Wav2Vec2FeatureExtractor\nfrom transformers import Wav2Vec2Processor\nfrom transformers import Wav2Vec2ForCTC\n\nfrom utils.generic_utils import load_config, load_vocab, calculate_wer\n\nfrom utils.dataset import remove_extra_columns, parse_dataset_dict, vocab_to_string, DataColletor, DataColletorTest\nfrom torch.utils.data import DataLoader\n\n\ndef remove_invalid_characters(batch):\n text = batch[text_column] if batch[text_column] is not None else \" \"\n text = text.lower()\n text = re.sub(\"[^{}]\".format(vocab_string), \" \", text)\n text = re.sub(\"[ ]+\", \" \", text)\n batch[text_column] = text + \" \"\n return batch\n\ndef prepare_dataset(batch):\n if dataset_base_path:\n batch[audio_path_column] = os.path.join(dataset_base_path, batch[audio_path_column])\n\n batch['audio_path'] = batch[audio_path_column]\n batch[\"input_values\"] = batch[audio_path_column]\n if text_column in batch:\n with processor.as_target_processor():\n batch[\"labels\"] = processor(batch[text_column]).input_ids\n\n return batch\n\nclass KenLMDecoder(object):\n def __init__(self, kenlm_args, vocab_dict, blank=\"\", silence=\"|\", unk=\"\"):\n\n self.vocab_size = len(vocab_dict)\n self.blank_token = (vocab_dict[blank])\n self.silence_token = vocab_dict[silence]\n self.unk_token = vocab_dict[unk]\n\n self.nbest = kenlm_args['nbest']\n\n if kenlm_args['lexicon_path']:\n vocab_keys = vocab_dict.keys()\n self.lexicon = load_words(kenlm_args['lexicon_path'])\n self.word_dict = create_word_dict(self.lexicon)\n self.unk_word = self.word_dict.get_index(unk)\n\n self.lm = KenLM(kenlm_args['kenlm_model_path'], self.word_dict)\n self.trie = Trie(self.vocab_size, self.silence_token)\n\n start_state = self.lm.start(False)\n for i, (word, spellings) in enumerate(self.lexicon.items()):\n word_idx = self.word_dict.get_index(word)\n _, score = self.lm.score(start_state, word_idx)\n\n for spelling in spellings:\n spelling_idxs = []\n for token in spelling:\n if token.upper() in vocab_keys:\n spelling_idxs.append(vocab_dict[token.upper()])\n elif token.lower() in vocab_keys:\n spelling_idxs.append(vocab_dict[token.lower()])\n else:\n print(\"WARNING: The token\", token, \"not exist in your vocabulary, using token instead\")\n spelling_idxs.append(self.unk_token)\n \n self.trie.insert(spelling_idxs, word_idx, score)\n self.trie.smear(SmearingMode.MAX)\n\n self.decoder_opts = LexiconDecoderOptions(\n beam_size=kenlm_args['beam'],\n beam_size_token=kenlm_args['beam_size_token'] if \"beam_size_token\" in kenlm_args else len(vocab_dict),\n beam_threshold=kenlm_args['beam_threshold'],\n lm_weight=kenlm_args['lm_weight'],\n word_score=kenlm_args['word_score'],\n unk_score=-math.inf,\n sil_score=kenlm_args['sil_weight'],\n log_add=False,\n criterion_type=CriterionType.CTC,\n )\n\n self.decoder = LexiconDecoder(\n self.decoder_opts,\n self.trie,\n self.lm,\n self.silence_token,\n self.blank_token,\n self.unk_word,\n [],\n False,\n )\n else:\n d = {w: [[w]] for w in vocab_dict.keys()}\n self.word_dict = create_word_dict(d)\n self.lm = KenLM(kenlm_args['kenlm_model_path'], self.word_dict)\n self.decoder_opts = LexiconFreeDecoderOptions(\n beam_size=kenlm_args['beam'],\n beam_size_token=kenlm_args['beam_size_token'] if \"beam_size_token\" in kenlm_args else len(vocab_dict),\n beam_threshold=kenlm_args['beam_threshold'],\n lm_weight=kenlm_args['lm_weight'],\n sil_score=kenlm_args['sil_weight'],\n log_add=False,\n criterion_type=CriterionType.CTC,\n )\n self.decoder = LexiconFreeDecoder(\n self.decoder_opts, self.lm, self.silence_token, self.blank_token, []\n )\n\n def get_tokens(self, idxs):\n \"\"\"Normalize tokens by handling CTC blank\"\"\"\n idxs = (g[0] for g in it.groupby(idxs))\n idxs = filter(lambda x: x != self.blank_token, idxs)\n return torch.LongTensor(list(idxs))\n \n def decode(self, emissions):\n B, T, N = emissions.size()\n # print(emissions.shape)\n tokens = []\n scores = []\n for b in range(B):\n emissions_ptr = emissions.data_ptr() + 4 * b * emissions.stride(0)\n results = self.decoder.decode(emissions_ptr, T, N)\n nbest_results = results[: self.nbest]\n tokens_nbest = []\n scores_nbest = []\n for result in nbest_results:\n tokens_nbest.append(result.tokens)\n scores_nbest.append(result.score)\n tokens.append(tokens_nbest)\n scores.append(scores_nbest)\n\n token_array = np.array(tokens, dtype=object).transpose((1, 0, 2))\n scores_arrray = np.array(scores, dtype=object).transpose()\n return token_array, scores_arrray\n\ndef test(model, test_dataset, processor, kenlm, calcule_wer=True, return_predictions=False):\n model.eval()\n predictions = []\n tot_samples = 0\n tot_wer = 0\n tot_cer = 0\n with torch.no_grad():\n for batch in tqdm(test_dataset):\n input_values, attention_mask = batch['input_values'], batch['attention_mask']\n if calcule_wer:\n labels = batch['labels']\n \n if USE_CUDA:\n input_values = input_values.cuda(non_blocking=True)\n attention_mask = attention_mask.cuda(non_blocking=True)\n if calcule_wer:\n labels = labels.cuda(non_blocking=True)\n \n logits = model(input_values, attention_mask=attention_mask).logits\n\n if kenlm:\n logits = torch.nn.functional.log_softmax(logits.float(), dim=-1)\n # get all candidates\n lm_tokens, lm_scores = kenlm.decode(logits.cpu().detach())\n # choise the best candidate\n pred_ids = lm_tokens[0][:]\n else:\n pred_ids = np.argmax(logits.cpu().detach().numpy(), axis=-1)\n\n if calcule_wer:\n # compute metrics\n wer, cer = calculate_wer(pred_ids, labels.cpu().detach().numpy(), processor, vocab_string)\n tot_wer += wer\n tot_cer += cer\n\n if return_predictions:\n audios_path = batch['audio_path']\n # get text\n pred_string = processor.batch_decode(pred_ids)\n\n for i in range(len(audios_path)):\n output_wav_path = audios_path[i]\n if dataset_base_path:\n output_wav_path = output_wav_path.replace(dataset_base_path, '').replace(dataset_base_path+'/', '')\n\n predictions.append([output_wav_path, pred_string[i].lower()])\n tot_samples += input_values.size(0)\n if calcule_wer: \n # calculate avg of metrics\n avg_wer = tot_wer/tot_samples\n avg_cer = tot_cer/tot_samples\n print(\"\\n\\n --> TEST PERFORMANCE\\n\")\n print(\" | > : WER ({:.5f})\\n\".format(avg_wer))\n print(\" | > : CER ({:.5f})\\n\".format(avg_cer))\n\n return predictions\n\ndef inference(model, test_dataset, processor, kenlm, config):\n model.eval()\n predictions = []\n with torch.no_grad():\n for batch in tqdm(test_dataset):\n input_values, attention_mask = batch['input_values'], batch['attention_mask']\n\n if USE_CUDA:\n input_values = input_values.cuda(non_blocking=True)\n attention_mask = attention_mask.cuda(non_blocking=True)\n \n logits = model(input_values, attention_mask=attention_mask).logits\n\n if kenlm:\n logits = torch.nn.functional.log_softmax(logits.float(), dim=-1)\n # get all candidates\n lm_tokens, lm_scores = kenlm.decode(logits.cpu().detach())\n # choise the best candidate\n pred_ids = lm_tokens[0][:]\n else:\n pred_ids = np.argmax(logits.cpu().detach().numpy(), axis=-1)\n \n # get text\n pred_string = processor.batch_decode(pred_ids)\n predictions.append([path, pred_string[0]])\n return predictions\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n # \n parser.add_argument('--checkpoint_path_or_name', type=str, required=True,\n help=\"path or name of checkpoints\")\n parser.add_argument('-c', '--config_path', type=str, required=True, default=None,\n help=\"json file with configurations\")\n parser.add_argument('--no_kenlm', default=False, action='store_true',\n help=\"Not use KenLm during inference ?\")\n parser.add_argument('--audio_path', type=str, default=None,\n help=\"If it's passed the inference will be done in all audio files in this path and the dataset present in the config json will be ignored\")\n parser.add_argument('--output_csv', type=str, default=None,\n help=\"CSV for save all predictions\")\n parser.add_argument('--batch_size', type=int, default=1,\n help=\"Batch size\")\n \n\n args = parser.parse_args()\n\n config = load_config(args.config_path)\n\n # Use CUDA\n USE_CUDA = torch.cuda.is_available()\n\n model = Wav2Vec2ForCTC.from_pretrained(args.checkpoint_path_or_name)\n print(\"> Model Loaded\")\n\n feature_extractor = Wav2Vec2FeatureExtractor(feature_size=1, sampling_rate=config['sampling_rate'], padding_value=0.0, do_normalize=True, return_attention_mask=True)\n processor = Wav2Vec2Processor.from_pretrained(args.checkpoint_path_or_name)\n\n vocab_dict = processor.tokenizer.get_vocab()\n # if the model uses upper words in vocab force tokenizer lower case for compatibility with our data loader\n for c in list(vocab_dict.keys()):\n if c.isupper():\n processor.tokenizer.do_lower_case = True\n print(\"> Force lowercase Tokenizer !\")\n break\n pad_token = processor.tokenizer.pad_token\n silence_token = processor.tokenizer.word_delimiter_token\n unk_token = processor.tokenizer.unk_token\n\n if USE_CUDA:\n model = model.cuda()\n\n if not args.no_kenlm:\n print(\"> Inference using KenLM\")\n kenlm = KenLMDecoder(config.KenLM, vocab_dict, blank=pad_token, silence=silence_token, unk=unk_token)\n else:\n print(\"> Inference without KenLM\")\n kenlm = None\n\n dataset_base_path = None\n if not args.audio_path:\n data_collator = DataColletor(processor=processor, sampling_rate=config.sampling_rate, padding=True, test=True)\n\n # load dataset\n test_dataset_config = config.datasets['test']\n text_column, audio_path_column = parse_dataset_dict(test_dataset_config)\n\n if 'dataset_cache' in config and config.dataset_cache:\n test_dataset_config['cache_dir'] = config.dataset_cache\n\n dataset = load_dataset(**test_dataset_config)\n # made compatibility with csv load\n if isinstance(dataset, dict) and 'train' in dataset.keys():\n concat_list = []\n for k in dataset.keys():\n concat_list.append(dataset[k])\n dataset = concatenate_datasets(concat_list)\n\n if 'files_path' in config['datasets'].keys() and config.datasets['files_path']:\n if test_dataset_config['name'].lower() == 'csv' or test_dataset_config['name'].lower() == 'tsv':\n dataset_base_path = config.datasets['files_path']\n else:\n print(\"> Warning: datasets['files_path'] igonored because dataset is not CSV !\")\n\n # preprocess dataset\n dataset = remove_extra_columns(dataset, text_column, audio_path_column)\n\n vocab_string = vocab_to_string(vocab_dict, pad_token, silence_token, unk_token).lower()\n print(vocab_string)\n print(\"\\n\\n> Remove invalid chars \\n\\n\")\n # remove invalid chars\n dataset = dataset.map(remove_invalid_characters, num_proc=config['num_loader_workers'])\n print(\"\\n\\n> Prepare dataset \\n\\n\")\n # batched dataset\n dataset = dataset.map(prepare_dataset, remove_columns=dataset.column_names, num_proc=config['num_loader_workers'], batched=False)\n\n test_dataset = DataLoader(dataset=dataset,\n batch_size=args.batch_size,\n collate_fn=data_collator,\n shuffle=True, \n num_workers=config['num_loader_workers'])\n\n print(\"\\n\\n> Starting Evaluation \\n\\n\")\n preds = test(model, test_dataset, processor, kenlm, calcule_wer=True, return_predictions=True)\n\n else:\n # use the datacolletor with only audio\n data_collator = DataColletorTest(processor=processor, sampling_rate=config.sampling_rate, padding=True)\n\n # load dataset\n print(\"\\n\\n> Searching Audios \\n\\n\")\n wavs = glob(os.path.join(args.audio_path,'**/*.wav'), recursive=True)\n\n test_dataset = DataLoader(dataset=wavs,\n batch_size=args.batch_size,\n collate_fn=data_collator,\n shuffle=True, \n num_workers=config['num_loader_workers'])\n\n print(\"\\n\\n> Starting Evaluation \\n\\n\")\n preds = test(model, test_dataset, processor, kenlm, calcule_wer=False, return_predictions=True)\n \n df = pd.DataFrame(preds, columns=[\"file_path\", \"transcription\"])\n\n if args.output_csv:\n root_path = os.path.dirname(args.output_csv)\n os.makedirs(root_path, exist_ok=True)\n df.to_csv(args.output_csv, index=False)\n print(\"\\n\\n> Evaluation outputs saved in: \", args.output_csv)\n else:\n print(df.to_string())\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":15503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"351451137","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 2 11:42:33 2018\n\n@author: J Rishabh Kumar\n@main\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom prepro_func import *\n\n\n#Loading dataset \ndataset = pd.read_csv(\"/home/j/AnacondaProjects/RecommendationSystem/Dataset/amazon_co-ecommerce_sample.csv\")\n\nproduct_mat = pd.DataFrame(dataset,copy = True)\ndel product_mat['description']\nprod_uiq_id = product_mat.uniq_id\nprod_name = pd.Series(product_mat.product_name.unique())\nmanufacturer = pd.Series(product_mat.manufacturer.unique())\ndfbuyafter = product_mat.loc[:,['uniq_id']]\ndfbuyafter = dfbuyafter.join(product_mat['items_customers_buy_after_viewing_this_item'].str.split('|', expand=True).stack().map(str.strip).reset_index(level=1, drop=True).rename('items_customers_buy_after_viewing_this_item'))\ndfbuyafter.shape\ndfbuyalso = product_mat.loc[:,['uniq_id']]\ndfbuyalso = dfbuyalso.join(product_mat['customers_who_bought_this_item_also_bought'].str.split('|', expand=True).stack().map(str.strip).reset_index(level=1, drop=True).rename('customers_who_bought_this_item_also_bought'))\ndfbuyalso.shape\ncategory_lists = product_mat['amazon_category_and_sub_category']\nproduct_mat.info()\n\n\n\"\"\"\n code is here\n \n\"\"\"\n#changing number if available in stocks to int\n\nfoo = lambda x: pd.Series([i for i in mapnumber_available_in_stock(x)])\nprod_stock= product_mat.loc[:]['number_available_in_stock']\nrev = prod_stock.apply(foo)\nrev.columns = ['number_available_in_stock','class_available_in_stock']\nproduct_mat['number_available_in_stock'],product_mat['class_available_in_stock'] = rev['number_available_in_stock'],rev['class_available_in_stock']\n\nproduct_mat.info()\n\n\n#changing price to float and removing euro sign\n\nfoo = lambda x: pd.Series([i for i in mapprice(x)])\nprod_price = product_mat.loc[:]['price']\nrev = prod_price.apply(foo)\nproduct_mat['price'] = rev\n\nproduct_mat.info()\n\n\n#converting no. of reviews to int\n\nif product_mat['number_of_reviews'].dtype != 'int64': \n product_mat['number_of_reviews'] = product_mat['number_of_reviews'].map(mapnumber_of_reviews)\n \nproduct_mat.info()\n\n\n# avg review rating to float\nif product_mat['average_review_rating'].dtype != 'float64':\n product_mat['average_review_rating'] = product_mat['average_review_rating'].map(mapaverage_review_rating)\n\nproduct_mat.info()\n\n\n\n#Splitting products customers saw before buying this\nproduct_mat['items_customers_buy_after_viewing_this_item'] = product_mat['items_customers_buy_after_viewing_this_item'].apply(mapurlsplitter)\n\n#Split customers_who_bought_this_item_also_bought\nproduct_mat['customers_who_bought_this_item_also_bought'] = product_mat['customers_who_bought_this_item_also_bought'].apply(mapurlsplitter)\n\n# categories and their count of depth\nproduct_mat['amazon_category_and_sub_category'] = product_mat['amazon_category_and_sub_category'].apply(mapcategories)\nproduct_mat['amazon_category_and_sub_category'].map(lambda lst: len(lst)).value_counts()\n\n\n\ndf_count_buyalso = dfbuyalso.groupby('uniq_id')['customers_who_bought_this_item_also_bought'].count().reset_index()\ndf_count_buyafter = dfbuyafter.groupby('uniq_id')['items_customers_buy_after_viewing_this_item'].count().reset_index()\n\na = pd.Series(dfbuyafter['items_customers_buy_after_viewing_this_item'].value_counts())\nb = pd.Series(dfbuyalso['customers_who_bought_this_item_also_bought'].value_counts())\n\ndfx = product_mat['sellers'][0:2][1]\ndfx\n#split the sellers data, put it into another \nsellers = product_mat['sellers'].str\nsellers = sellers.map(myseller)\n\nlist1 = list(product_mat['items_customers_buy_after_viewing_this_item'])\nlist2 = list(product_mat['customers_who_bought_this_item_also_bought'])\nitem_set1 = takeOutList(list1)\nitem_set2 = takeOutList(list2)\n\n\nitem_set = pd.Series(item_set1 + item_set2)\nitem_set = pd.Series(item_set.unique())\n\n\n#total no. of transaction\ntotal_tran = addSum(a) + addSum(b)\nmatrix = pd.DataFrame()\nmatrix = pd.DataFrame(matrix, index = prod_uiq_id, columns= item_set ,dtype =float)\n\n\n\n\n\n","sub_path":"build_2.py","file_name":"build_2.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"550331149","text":"# coding:utf-8\n'''\n@Copyright:LintCode\n@Author: qingwww\n@Problem: http://www.lintcode.com/problem/maximum-product-subarray\n@Language: Python\n@Datetime: 16-09-25 18:52\n'''\n\nclass Solution:\n # @param nums: an integer[]\n # @return: an integer\n def maxProduct(self, nums):\n # write your code here\n if len(nums) == 0:\n return 0\n \n result, max_pro, min_pro = nums[0], nums[0], nums[0]\n for i in range(1, len(nums)):\n temp = max_pro\n max_pro = max(max_pro*nums[i], min_pro*nums[i], nums[i])\n min_pro = min(temp*nums[i], min_pro*nums[i], nums[i])\n result = max(max_pro, result)\n return result","sub_path":"191_maximum-product-subarray/maximum-product-subarray.py","file_name":"maximum-product-subarray.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"281423799","text":"#Sean Curran\n#A simple program to get the opening and closing prices for a given stock,\n#the prices are graphed and the data is written into a CSV file.\n#User needs to provide their own Alpha Vantage code.\nimport pandas_datareader.data as web\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport pandas as pd\nimport datetime\n\nALPHA_VAN = 'Your alpha vantage code here'\n\nstart = str(datetime.datetime.strftime(datetime.datetime.now()- datetime.timedelta((50)), '%Y-%m-%d'))\nend = str(datetime.datetime.today().strftime('%Y-%m-%d'))\nfont = {'family' : 'normal','weight' : 'normal','size' : '8'}\n\ndef get_data(ticker_sym):\n style.use('ggplot')\n stock_data = web.DataReader(ticker_sym, 'av-daily', start, end,api_key=ALPHA_VAN)\n stock_data.to_csv(ticker_sym + '.csv')\n ax = stock_data['close'].plot(figsize= (11,8),label = \"Close\", legend = True)\n ax = stock_data['open'].plot(figsize= (11,8), label = \"Open\", legend = True)\n ax.set_ylabel(\"Price : USD\")\n ax.set_xlabel(\"Date\")\n plt.rc('font', **font)\n plt.title(ticker_sym)\n plt.show()\n print(stock_data)\n\nget_data('TSLA')\n\n","sub_path":"stonks.py","file_name":"stonks.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"120173768","text":"#!/usr/bin/python\n\nimport sys, re, os\nimport argparse\n\ndef split_file(ifile, number_of_lines, output_name):\n\tifile1 = open(ifile, \"r\")\n\tidata = ifile1.read().split(\"\\n\")\n\tcount = 0\n\tsplit = int(number_of_lines)\n\tfor lines in range(0, len(idata), split):\n\t\toutputData = idata[lines:lines+split]\n\t\toutput = open(\"{}_{}\".format(output_name, count)+\".txt\", \"w\")\n\t\toutput.write('\\n'.join(outputData))\n\t\toutput.close()\n\t\tcount += 1\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser(description='Splits a file\\n ')\n\tparser.add_argument('-i','--IFILE', help='Input file', required=True)\n\tparser.add_argument('-n','--NUM', help='Number of lines per split', required=True)\n\tparser.add_argument('-o','--OUTPUT', help='Output prefix', required=True)\n\targs = vars(parser.parse_args())\n\tsplit_file(args[\"IFILE\"], args[\"NUM\"], args[\"OUTPUT\"])","sub_path":"split_files.py","file_name":"split_files.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"21977259","text":"# -*- coding: utf-8 -*-\n# author: tmv\n\nimport sys, os\nimport xbmc, xbmcaddon\nimport urllib2, json\n\n__settings__ = xbmcaddon.Addon(id=\"script.service.homepi\")\n__rpi_cmd__ = \"http://{host}:{port}/homepi/{pinName}?action={action}\"\n__lights__ = [\"light1\", \"light2\", \"light3\"]\n__screen__ = \"screen\"\n\n__language__ = __settings__.getLocalizedString\n\nBASE_RESOURCE_PATH = xbmc.translatePath( os.path.join( __settings__.getAddonInfo('path'), 'resources', 'lib' ) )\nsys.path.append (BASE_RESOURCE_PATH)\n\n# construct the command string to be sent to rpi gpio server\ndef _performCommand(pinName, action=\"toggle\"):\n host = __settings__.getSetting(\"rpi_host\")\n port = __settings__.getSetting(\"rpi_port\")\n cmd_str = __rpi_cmd__.format( \\\n host=host, \\\n port=port, \\\n pinName=pinName, \\\n action=action \\\n )\n \n response = urllib2.urlopen(cmd_str).read()\n \n result = json.loads(response)\n \n return result[pinName]\n \ndef _turnOnLights():\n for light in __lights__:\n _performCommand(light, \"on\")\n \ndef _turnOffLights():\n for light in __lights__:\n _performCommand(light, \"off\")\n \ndef _getScreenStatus():\n return _performCommand(__screen__, \"read\")\n \nclass MyXbmcPlayer(xbmc.Player):\n def __init__(self):\n xbmc.Player.__init__(self)\n self.videoPlaying = False\n self.isScreenDown = False\n \n def onPlayBackStarted(self):\n if self.isPlaying() and self.isPlayingVideo():\n self.videoPlaying = True\n # check if the screen is down\n self.isScreenDown = _getScreenStatus()\n if self.isScreenDown:\n # turn off the lights\n _turnOffLights()\n \n def onPlayBackEnded(self):\n if self.videoPlaying:\n self.videoPlaying = False\n if self.isScreenDown:\n # turn light number 2\n _performCommand(\"light2\", \"on\")\n \n def onPlayBackStopped(self):\n self.onPlayBackEnded()\n \n def onPlayBackPaused(self):\n if self.isPlaying() and self.isPlayingVideo() and self.isScreenDown:\n # turn light number 2\n _performCommand(\"light2\", \"on\")\n \n def onPlayBackResumed(self):\n if self.isPlaying() and self.isPlayingVideo():\n self.videoPlaying = True\n self.isScreenDown = _getScreenStatus()\n if self.isScreenDown:\n # turn off lights\n _turnOffLights()\n\n\nxbmc.log(\"Starting rpi integration service...\", xbmc.LOGNOTICE)\nplayer = MyXbmcPlayer()\n\nwhile not xbmc.abortRequested:\n xbmc.sleep(1000)\n","sub_path":"xbmc/addon/script.service.homepi/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"316895342","text":"'''\n给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。\n最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。\n你可以假设除了整数 0 之外,这个整数不会以零开头。\n示例 1:\n输入: [1,2,3]\n输出: [1,2,4]\n解释: 输入数组表示数字 123。\n示例 2:\n输入: [4,3,2,1]\n输出: [4,3,2,2]\n解释: 输入数组表示数字 4321。\n链接:https://leetcode-cn.com/problems/plus-one\n'''\n\n'''\n# 解法一: 自己写的\nclass Solution:\n def plusOne(self, digits):\n digits2str = [str(i) for i in digits] # 把数字列表变成字符列表\n new_digits = int(''.join(digits2str)) + 1 # digit+1的数值\n return [i for i in str(new_digits)]\n'''\n\n# 解法二: 更快一点\nclass Solution:\n def plusOne(self, digits):\n sums = 0\n for i in range(len(digits)):\n sums += 10**(len(digits)-1-i) * digits[i]\n sum_str = str(sums + 1)\n return [int(j) for j in sum_str]\n\n\n\nif __name__=='__main__':\n digits = [4,3,2,1]\n X = Solution()\n print(X.plusOne(digits))","sub_path":"1_Array/066.加一.py","file_name":"066.加一.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"538611635","text":"import os\nimport numpy as np\nfrom commands import settings\n\nfrom commands.command import BaseCommand\nfrom commands.models import Stats, Score\nfrom typing import List\n\n\nclass ScoreCommand(BaseCommand):\n cmd = settings.SCORE_CMD\n\n def __init__(self, message, check=False):\n super().__init__(message)\n self.invalid = False\n self.players = self.get_players()\n self.scores = self.get_scores()\n self.check = check\n self.elo_delta = 0\n\n def get_players(self):\n if not self.ok:\n return\n\n if (len(self.parsed.mentions) > settings.NUM_PLAYERS or\n len(self.parsed.mentions) < settings.NUM_PLAYERS - 1):\n self.invalid = True\n return\n\n ids = map(lambda x: x.split('%'),\n (os.environ.get('IDS', '').split(':')))\n convert_dict = {id: name for [id, name] in ids}\n convert_dict['me'] = convert_dict.get(self.get_sender(), '')\n for i in range(settings.NUM_PLAYERS):\n player = self.parsed.mentions[i]\n if player == \"me\":\n self.mentions.insert(i, self.get_sender())\n\n players = [convert_dict.get(id, None) for id in self.mentions]\n\n if None in players or len(players) != settings.NUM_PLAYERS:\n self.invalid = True\n\n return players\n\n def get_scores(self):\n if not self.ok:\n return\n return list(map(int, self.parsed.args))\n\n def calculate_elo(self, stats: List):\n \"\"\"\n Calculates updated elo ratings for the players involved in the match.\n \"\"\"\n score_a, score_b = self.scores\n elo_1, elo_2, elo_3, elo_4 = list(map(lambda x: x.elo, stats))\n games_1, games_2, games_3, games_4 = \\\n list(map(lambda x: x.games, stats))\n\n # Teams are considered as single players, averaging their Elo.\n team_a_avg = 0.5 * (elo_1 + elo_2)\n team_b_avg = 0.5 * (elo_3 + elo_4)\n expected_a = 1 / (1 + 10 ** ((team_b_avg - team_a_avg) / 400))\n\n # Win probability is the # points a team scorse divided by the total.\n score_diff = abs(score_a - score_b)\n mult = 1\n lose_a = score_a < score_b\n\n # K-factor multiplier to account for larger margins.\n # 7-3, 7-4, 7-5\n if 2 <= score_diff <= 4 and (max(score_a, score_b) >\n settings.MIN_SCORE_TO_WIN):\n mult = 1.25\n score_a = score_a if not lose_a else 5\n score_b = score_b if lose_a else 5\n # 7-1, 7-2\n elif 5 <= score_diff <= 6:\n mult = 1.75\n score_a = score_a if not lose_a else 2\n score_b = score_b if lose_a else 2\n # 7-0\n elif score_diff == 7:\n mult = 2\n\n score_p_a = score_a / (score_a + score_b)\n\n games_12 = 0.5 * (games_1 + games_2)\n games_34 = 0.5 * (games_3 + games_4)\n game_mult = 1 / (1 + np.exp(-max(1, min(games_12, games_34)) /\n max(1, max(games_12, games_34))))\n game_mult = 1 if games_12 >= 20 and games_34 >= 20 else game_mult\n\n elo_delta = game_mult * mult * settings.K * (score_p_a - expected_a)\n self.elo_delta = elo_delta\n return (elo_1 + elo_delta, elo_2 + elo_delta,\n elo_3 - elo_delta, elo_4 - elo_delta)\n\n def generate_message(self):\n if not self.ok:\n return ((\"Must be of form:\\n /score @A @B @C @D, \"\n \"score_ab - score_cd\"))\n\n if self.invalid:\n return (\"Error processing. Likely someone isn't added, or\"\n \" format isn't correct. Try `/help` if you're uncertain.\")\n\n if self.check:\n return \"Waiting for approval.\"\n\n score_1, score_2 = self.scores\n if max(score_1, score_2) < settings.MIN_SCORE_TO_WIN:\n return (f\"Games to less than {settings.MIN_SCORE_TO_WIN} \"\n \"are for the weak. Disregarded.\")\n elif abs(score_1 - score_2) < settings.WIN_BY:\n return f\"It's win by {settings.WIN_BY}, numbnut.\"\n\n player_1, player_2, player_3, player_4 = self.players\n negative = self.elo_delta < 0\n self.elo_delta = abs(self.elo_delta)\n\n sign_1 = '-' if negative else '+'\n sign_2 = '+' if negative else '-'\n d_1 = f\"{sign_1}{self.elo_delta:.04}\"\n d_2 = f\"{sign_2}{self.elo_delta:.04}\"\n win_1 = f\"W: {d_1} \"\n lose_1 = f\"L: {d_1} \"\n win_2 = f\"W: {d_2} \"\n lose_2 = f\"L: {d_2} \"\n match_id = Score.query.order_by(Score.id.desc()).first()\n msg: str = (f\"Match {match_id.id} recorded, \"\n f\"score of {score_1} - {score_2}.\\n\"\n \"-------------------------\\n\"\n f\"{win_1 if score_1 > score_2 else lose_1}\"\n f\"{player_1}, {player_2}\\n\"\n f\"{win_2 if score_2 > score_1 else lose_2}\"\n f\"{player_3}, {player_4}\\n\"\n \"-------------------------\\n\")\n\n if abs(score_1 - score_2) > settings.MERCY_THRESHOLD:\n msg += \"I smell a naked lap coming.\"\n\n return msg\n\n def generate_data(self, db):\n if (not self.ok) or self.check or self.invalid:\n return None\n\n # Read in current stats, calculate elo, update current rankings.\n stats = [Stats.query.filter(Stats.name == player).first()\n for player in self.players]\n updated_elos = self.calculate_elo(stats)\n\n # Not recording personal stats like this for now.\n new_scores = Score(*self.players, *self.scores,\n self.timestamp, *updated_elos)\n\n # Update player stats.\n score_1, score_2 = self.scores\n win_losses = [1, 1, 0, 0] if score_1 > score_2 else [0, 0, 1, 1]\n for player, elo, win_loss in zip(stats, updated_elos, win_losses):\n player.games = Stats.games + 1\n if win_loss == 1:\n player.wins = Stats.wins + 1\n else:\n player.losses = Stats.losses + 1\n player.elo = elo\n\n return new_scores\n\n\nif __name__ == \"__main__\":\n score = ScoreCommand({\"text\": \"/score @bo @me @tommy @you, 6 - 7\",\n \"sender_id\": \"28847341\",\n \"attachments\": [{\"user_ids\":\n [\"41282369\", \"46988593\",\n \"18930468\"]}]})\n print(score.generate_message())\n","sub_path":"commands/score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"387441385","text":"#!/usr/bin/env python3\n# # -*- coding: utf-8 -*-\n# author:Samray \n\nimport datetime\nfrom VersionC.db import query_all_messages\nfrom VersionC.es import Message\n\n\ndef index_all_messages_to_es():\n for result in query_all_messages():\n try:\n message_id = result['id']\n from_user_name = result['from_user_name']\n to_user_name = result['to_user_name']\n content = result['content']\n timestamp = datetime.datetime.fromtimestamp(\n float(result['timestamp'])).strftime('%Y-%m-%d %H:%M:%S')\n except TypeError as e:\n # ignore error\n continue\n # create the mappings in elasticsearch\n Message.init()\n # create and save and article\n message = Message(meta={\n 'id': message_id}, from_user_name=from_user_name, to_user_name=to_user_name,\n content=content, timestamp=timestamp)\n message.save()\n\nif __name__ == \"__main__\":\n index_all_messages_to_es()\n","sub_path":"VersionC/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"522071035","text":"import tempfile\nimport yaml\nfrom collections import defaultdict, OrderedDict\nfrom PyQt5 import QtCore, QtGui, QtWidgets, uic\nfrom numpy import *\nimport sympy\n#from PyQt5.QtWebKitWidgets import QWebView\nfrom PyQt5.QtCore import QFile, QFileInfo, QTextStream, QUrl\nfrom sympy.printing.latex import latex\nimport os\n\nimport mfm\nfrom mfm.fitting.models import ModelWidget, ModelCurve\nfrom mfm.parameter import FittingParameter, ParameterGroup\n\n\ntry:\n from re import Scanner\nexcept ImportError:\n import sre\n from sre import Scanner\n\n\nclass GenerateSymbols(defaultdict):\n def __missing__(self, key):\n return sympy.Symbol(key)\n\n\nclass ParseFormula(ParameterGroup):\n\n def __init__(self, **kwargs):\n ParameterGroup.__init__(self, **kwargs)\n\n self._keys = list()\n self._model_file = None\n self._models = dict()\n self._count = 0\n self._func = \"x*0\"\n\n self.model_file = kwargs.get('model_file', os.path.join(mfm.package_directory, 'settings/models.yaml'))\n self.model_name = kwargs.get('model_name', self.models.keys()[0])\n self.code = self._func\n\n @property\n def initial_values(self):\n try:\n ivs = self.models[self.model_name]['initial']\n except AttributeError:\n ivs = OrderedDict([(k, 1.0) for k in self._keys])\n return ivs\n\n @property\n def models(self):\n return self._models\n\n @models.setter\n def models(self, v):\n self._models = v\n\n @property\n def model_file(self):\n return self._model_file\n\n @model_file.setter\n def model_file(self, v):\n self._model_file = v\n self.load_model_file(v)\n\n @property\n def func(self):\n return self._func\n\n @func.setter\n def func(self, v):\n self._func = v\n self.parse_code()\n\n def var_found(self, scanner, name):\n if name in ['caller', 'e', 'pi']:\n return name\n if name not in self._keys:\n self._keys.append(name)\n ret = 'a[%d]' % self._count\n self._count += 1\n else:\n ret = 'a[%d]' % (self._keys.index(name))\n return ret\n\n def parse_code(self):\n\n code = self._func\n scanner = Scanner([\n (r\"x\", lambda y, x: x),\n (r\"[a-zA-Z]+\\.\", lambda y, x: x),\n (r\"[a-z]+\\(\", lambda y ,x: x),\n (r\"[a-zA-Z_]\\w*\", self.var_found),\n (r\"\\d+\\.\\d*\", lambda y, x: x),\n (r\"\\d+\", lambda y, x: x),\n (r\"\\+|-|\\*|/\", lambda y, x: x),\n (r\"\\s+\", None),\n (r\"\\)+\", lambda y, x: x),\n (r\"\\(+\", lambda y, x: x),\n (r\",\", lambda y, x: x),\n ])\n self._count = 0\n self._keys = []\n parsed, rubbish = scanner.scan(code)\n parsed = ''.join(parsed)\n if rubbish != '':\n raise Exception('parsed: %s, rubbish %s' % (parsed, rubbish))\n self.code = parsed\n\n # Define parameters\n self._parameters = list()\n for key in self._keys:\n try:\n iv = self.initial_values[key]\n except KeyError:\n iv = 1.0\n p = FittingParameter(name=key, value=iv)\n self._parameters.append(p)\n\n def load_model_file(self, filename):\n with open(filename, 'r') as fp:\n self._model_file = filename\n self.models = yaml.load(fp)\n\n def find_parameters(self):\n # do nothing\n pass\n\n\nclass ParseModel(ModelCurve):\n\n name = \"Parse-Model\"\n\n def __init__(self, fit, **kwargs):\n ModelCurve.__init__(self, fit, **kwargs)\n self.parse = kwargs.get('parse', ParseFormula())\n\n def update_model(self, **kwargs):\n a = [p.value for p in self.parse.parameters]\n x = self.fit.data.x\n try:\n y = eval(self.parse.code)\n except:\n y = zeros_like(x) + 1.0\n self._y = y\n\n\nclass ParseFormulaWidget(ParseFormula, QtWidgets.QWidget):\n\n def __init__(self, **kwargs):\n QtWidgets.QWidget.__init__(self)\n uic.loadUi('mfm/ui/models/parseWidget.ui', self)\n ParseFormula.__init__(self, **kwargs)\n self.n_columns = kwargs.get('n_columns', mfm.cs_settings['gui']['fit_models']['n_columns'])\n\n #self.webview = QWebView()\n #self.verticalLayout_4.addWidget(self.webview)\n\n self.comboBox.currentIndexChanged[int].connect(self.onModelChanged)\n self.toolButton.clicked.connect(self.onUpdateFunc)\n self.func = self.models[self.model_name]['equation']\n\n @property\n def func(self):\n return ParseFormula.func.fget(self)\n\n @func.setter\n def func(self, v):\n ParseFormula.func.fset(self, v)\n\n self.plainTextEdit.setPlainText(v)\n layout = self.gridLayout_2\n mfm.widgets.clear_layout(layout)\n n_columns = self.n_columns\n\n pn = list()\n row = 1\n for i, p in enumerate(self._parameters):\n pw = p.make_widget()\n column = i % n_columns\n if column == 0:\n row += 1\n layout.addWidget(pw, row, column)\n pn.append(pw.fitting_parameter)\n self._parameters = pn\n\n @property\n def models(self):\n return self._models\n\n @models.setter\n def models(self, v):\n ParseFormula.models.fset(self, v)\n self.comboBox.clear()\n self.comboBox.addItems(list(v.keys()))\n\n @property\n def model_name(self):\n return list(self.models.keys())[self.comboBox.currentIndex()]\n\n @model_name.setter\n def model_name(self, v):\n idx = self.comboBox.findText(v)\n self.comboBox.setCurrentIndex(idx)\n\n def onUpdateEquation(self):\n s = \"\"\"\n \n \n \n

%s

\n

\n $$\n \"\"\" % self.model_name\n try:\n f = eval(self.func, GenerateSymbols())\n s += latex(f)\n except:\n s += \"Error\"\n s += \"$$

\"\n s += self.models[self.model_name]['description']\n s += \"\"\n tempFile = QFile(tempfile.mktemp('.html'))\n tempFile.open(QFile.WriteOnly)\n stream = QTextStream(tempFile)\n stream << s\n tempFile.close()\n fileUrl = QUrl.fromLocalFile(QFileInfo(tempFile).canonicalFilePath())\n self.webview.load(fileUrl)\n\n def onUpdateFunc(self):\n function_str = str(self.plainTextEdit.toPlainText())\n mfm.run(\"cs.current_fit.model.parse.func = '%s'\" % function_str)\n mfm.run(\"cs.current_fit.update()\")\n self.onUpdateEquation()\n\n def onModelChanged(self):\n mfm.run(\"cs.current_fit.model.parse.model_name = '%s'\" % self.model_name)\n mfm.run(\"cs.current_fit.model.parse.func = '%s'\" % self.models[self.model_name]['equation'])\n mfm.run(\"cs.current_fit.update()\")\n self.onUpdateEquation()\n\n def onLoadModelFile(self, filename=None):\n if filename is None:\n filename = mfm.widgets.get_filename('Open model-file', 'link file (*.yaml)')\n mfm.run(\"cs.current_fit.model.parse.load_model_file(%s)\" % filename)\n\n\nclass ParseModelWidget(ParseModel, ModelWidget):\n\n def __init__(self, fit, **kwargs):\n ModelWidget.__init__(self, fit, **kwargs)\n parse = ParseFormulaWidget(**kwargs)\n ParseModel.__init__(self, fit=fit, parse=parse)\n #self.update()\n\n self.layout = QtWidgets.QVBoxLayout(self)\n self.layout.setSpacing(0)\n self.layout.setContentsMargins(0, 0, 0, 0)\n self.layout.setAlignment(QtCore.Qt.AlignTop)\n self.layout.addWidget(self.parse)\n\n def update_model(self, **kwargs):\n ParseModel.update_model(self, **kwargs)\n\n","sub_path":"chisurf/mfm/fitting/models/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":7965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"133452150","text":"def backtraking(u_id,b_id):\n if len(b_id) == 0:\n if lis not in check_list:\n input_list = lis.copy()\n check_list.append(input_list)\n else:\n for u in range(len(u_id)): \n if lis[u] == False: \n for b in range(len(b_id)):\n check = False\n if len(u_id[u]) == len(b_id[b]):\n for i in range(len(u_id[u])):\n if b_id[b][i] != '*' and b_id[b][i] != u_id[u][i]:\n break\n elif i == len(u_id[u])-1:\n check = True\n if check == True:\n lis[u] = True\n backtraking(u_id, b_id[:b]+b_id[b+1:])\n lis[u] = False\n \n\ndef solution(user_id,banned_id):\n global lis\n lis = [False] * len(user_id)\n if len(user_id) == len(banned_id):\n return 1\n backtraking(user_id,banned_id)\n return len(check_list)\n\ncheck_list = []\nlis = []\nuser_id = [\"frodo\", \"fradi\", \"crodo\", \"abc123\", \"frodoc\"]\nbanned_id = [\"fr*d*\", \"abc1**\"]\nprint(solution(user_id,banned_id))","sub_path":"KYC/algorithm/TEST/programmersUserban.py","file_name":"programmersUserban.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"609958572","text":"'''\r\n회의가 가장 빨리 끝나는 순서\r\n그 다음 시작하는 회의 중 가장 빨리 끝나는 회의\r\n\r\n'''\r\n# 리스트 만들기\r\n# 두 번째 인자 오름차순으로 정렬\r\n# \r\nn = int(input())\r\nlists = []\r\nfor i in range(n):\r\n a = list(map(int,input().split(\" \")))\r\n lists.append(a)\r\n\r\nassign = []\r\na = 0\r\n# 끝나는 순서가 빠른 순서대로 재정렬\r\nlists.sort(key=lambda x:x[1])\r\n# 할당리스트에 분배\r\nassign.append(lists[0])\r\nfor i in range(1,n):\r\n if lists[i][0] >= assign[a][1]:\r\n assign.append(lists[i])\r\n a+=1\r\n \r\nprint(len(assign))","sub_path":"python_baekjoon/algorithm_BAEKJOON_greedy/미해결/회의실 배정.py","file_name":"회의실 배정.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"634312768","text":"import sys\nprint(sys.argv)\n\n# Calculates cost of meal with tax and tip\n\ndef calculateTip(meal,tip):\n meal = float(meal)\n tip = float(tip)\n tax = 0.075\n\n meal += meal * tax\n total = meal + meal * tip\n\n return total\n\n\nmeal = float( sys.argv[1])\ntax = 0.075\ntip = float( sys.argv[2] )\n\nmeal += meal * tax\ntotal1 = meal + meal * tip\nprint(\"%.2f\" % total1)\n\n\ntotal2 = calculateTip(sys.argv[1],sys.argv[2])\nprint(\"%.2f\" % total2)\n\n\n","sub_path":"materials/scripts/tipCalculator.py","file_name":"tipCalculator.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"330143588","text":"import data_manager,csv\n\n\ndef sort_questions():\n sorted_list = sorted(data_manager.read_from_file(\"sample_data/question.csv\"), key=lambda k: k[\"submission_time\"], reverse=True)\n return sorted_list\n\n\ndef generate_id(filename):\n list_of_dict = data_manager.read_from_file(filename)\n list_of_id = []\n for dictionary in list_of_dict:\n list_of_id.append(int(dictionary[\"id\"]))\n my_id = max(list_of_id)+ 1\n return my_id\n\n\ndef remove_question(id):\n list_of_questions = data_manager.read_from_file(\"sample_data/question.csv\")\n for dictionar in list_of_questions:\n if dictionar[\"id\"] == id:\n list_of_questions.remove(dictionar)\n break\n QUESTION_HEADERS = ['id', 'submission_time', 'view_number', 'vote_number', 'title', 'message', 'image']\n with open('sample_data/question.csv','w') as file:\n writer=csv.DictWriter(file, fieldnames= QUESTION_HEADERS)\n writer.writeheader()\n for dict in list_of_questions:\n writer.writerow(dict)\n\n\ndef remove_answer(id):\n list_of_answers = data_manager.read_from_file(\"sample_data/answer.csv\")\n for dictionar in list_of_answers:\n if dictionar[\"question_id\"] == id:\n list_of_answers.remove(dictionar)\n break\n ANSWER_HEADERS = [\"id\",\"submission_time\",\"vote_number\",\"question_id\",\"message\",\"image\"]\n with open('sample_data/answer.csv','w') as file:\n writer=csv.DictWriter(file, fieldnames=ANSWER_HEADERS)\n writer.writeheader()\n for dict in list_of_answers:\n writer.writerow(dict)\n\n\ndef question_vote(question_id, vote):\n filename = \"sample_data/question.csv\"\n sorted_list = sort_questions()\n for item in sorted_list:\n if str(item['id']) == str(question_id):\n update_vote = int(item['vote_number']) + vote\n item['vote_number'] = update_vote\n with open(filename, \"w\") as file:\n HEADERS = [\"id\", \"submission_time\", \"view_number\",\"vote_number\",\n \"title\", \"message\", \"image\"]\n elements = csv.DictWriter(file, fieldnames=HEADERS)\n elements.writeheader()\n for dict in sorted_list:\n elements.writerow(dict)\n\n\ndef answer_vote(answer_id, vote):\n filename = \"sample_data/answer.csv\"\n answer_list = data_manager.read_from_file(filename)\n for item in answer_list:\n if str(item['id']) == str(answer_id):\n update_vote = int(item['vote_number']) + vote\n item['vote_number'] = update_vote\n with open(filename, \"w\") as file:\n HEADERS = [\"id\", \"submission_time\",\"vote_number\",\n \"question_id\", \"message\", \"image\"]\n elements = csv.DictWriter(file, fieldnames=HEADERS)\n elements.writeheader()\n for dict in answer_list:\n elements.writerow(dict)\n\n\ndef increase_view(question_id):\n filename = \"sample_data/question.csv\"\n sorted_list = data_manager.read_from_file(filename)\n for item in sorted_list:\n if str(item['id']) == str(question_id):\n update_vote = int(item['view_number']) + 1\n item['view_number'] = update_vote\n with open(filename, \"w\") as file:\n HEADERS = [\"id\", \"submission_time\", \"view_number\", \"vote_number\",\n \"title\", \"message\", \"image\"]\n elements = csv.DictWriter(file, fieldnames=HEADERS)\n elements.writeheader()\n for dict in sorted_list:\n elements.writerow(dict)","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"357421728","text":"import math\nimport random\nimport pygame\npygame.init()\n\nscreen=pygame.display.set_mode((800,700))\n#title\npygame.display.set_caption('forest fire')\n\n#background\nback = pygame.image.load('background.png')\n\n#game over\ngame_over=pygame.image.load('gameover.png')\n\n#player\nplayerimg=pygame.image.load('hero.png')\nplayerx=310\nplayery=555\nplayerx_change=0\n\n#tree\ntreeimg=pygame.image.load('tree.png')\ntreex=random.randint(100,600)\ntreey=random.randint(200,475)\ntreex_change=4\ntreey_change=40\n\n#bullet\nbulletimg=pygame.image.load('bullet.png')\nbulletx=0\nbullety=565\nbullety_change=15\nbullet_state='ready'\n\n#player function\ndef player(x,y):\n screen.blit(playerimg,(x,y))\n\n#tree function\ndef tree(x,y):\n screen.blit(treeimg,(x,y))\n\ndef fire_bullet(x,y):\n global bullet_state\n bullet_state='fire'\n screen.blit(bulletimg,(x+75,y))\n\nfont = pygame.font.Font(\"freesansbold.ttf\",25)\n\ndef score(score):\n text= font.render(\"Score: \" +str(score),True, (255,255,255))\n screen.blit(text,(0,0))\n \n \n\n\npoints=0\nmissed=0\nrun=True\nwhile (run):\n screen.fill((0,0,0))\n screen.blit(back,(0,0))\n if missed>=5:\n screen.blit(game_over,(0,0))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run=False\n\n #player movement\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n playerx_change=-5\n if event.key == pygame.K_RIGHT:\n playerx_change=5\n if event.key == pygame.K_SPACE:\n if bullet_state is 'ready' and (missed<5):\n bulletx=playerx\n fire_bullet(bulletx,bullety)\n if event.key==pygame.K_UP:\n if missed>=5:\n points=0\n missed=0\n if event.type == pygame.KEYUP:\n if event.key==pygame.K_LEFT or event.key==pygame.K_RIGHT:\n playerx_change=0\n\n #player movement\n playerx += playerx_change\n if playerx<=-20:\n playerx=-20\n elif playerx>=640:\n playerx=640\n\n #tree movement\n treex += treex_change\n if treex<=0:\n treex_change=3 \n treey+=treey_change\n if points>=15:\n treex_change=9\n if points>=30:\n treex_change=12\n elif treex>=695:\n treex_change=-3\n treey+=treey_change\n if points>=15:\n treex_change=-9\n if points>=30:\n treex_change=-12\n\n if bullety<=0:\n bullety=565\n bullet_state='ready'\n if bullet_state is 'fire':\n fire_bullet(bulletx,bullety)\n bullety-=bullety_change\n\n if(treey>=450):\n missed+=1\n treex=random.randint(100,600)\n treey=random.randint(200,410)\n print('missed')\n print(missed)\n \n\n if ((bulletx>=treex and bulletx<=treex+128) and (bullety>=treey and bullety<=treey+117)):\n bullety=565\n bullet_state='ready'\n points+=1\n print('points:')\n print(points)\n treex=random.randint(100,600)\n treey=random.randint(200,410)\n\n if missed<5:\n player(playerx,playery)\n tree(treex,treey)\n score(points)\n pygame.display.update()\n \n \npygame.quit()","sub_path":"forest_game/forest.py","file_name":"forest.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"240632271","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport subprocess\n\nDs = np.arange(1.5, 2.7, 0.01)\np = 0.001\ndirectory = \"PhaseDiagram\"\n\nx = lambda D: int(D / 0.0025) - 600\ny = lambda p: int(p / 0.0002) - 2\n\nsubprocess.call(\"rm ../../Plots/{}/Animation/animation-*.pdf\".format(directory), shell=True)\nsubprocess.call(\"mkdir -p ../../Plots/{}/Animation\".format(directory), shell=True)\n\nfor j, D in enumerate(Ds):\n print(j, D)\n\n fig = plt.figure()\n\n # Upper plot -- Phyllotaxis\n axUpper = plt.subplot2grid( (2,2), [0,0], 1, 1, aspect=\"equal\")\n# axUpper.set_title(\"$D / d = {:.4f}$, $p = {:.6f}$\".format(D, p))\n\n th, z = np.loadtxt(\"../../data/{}/Phyllotaxisp{:.6f}D{:.4f}Nodes.csv\".format(directory, p, D), unpack=True)\n thunit, zunit = np.loadtxt(\"../../data/{}/Phyllotaxisp{:.6f}D{:.4f}Unit.csv\".format(directory, p, D), unpack=True)\n links = np.loadtxt(\"../../data/{}/Phyllotaxisp{:.6f}D{:.4f}Edges.csv\".format(directory, p, D))\n\n axUpper.plot(th, z, \"b.\")\n axUpper.plot(thunit, zunit, \"rD\")\n for i in range(1, len(links)):\n if (i % 2 == 1):\n th1 = links[i][0]\n z1 = links[i][1]\n th2 = links[i + 1][0]\n z2 = links[i + 1][1]\n axUpper.plot([th1, th2], [z1, z2], \"b-\")\n axUpper.set_ylim(-5, 5)\n axUpper.set_xlim(-5, 5)\n axUpper.set_ylabel(\"$z$\")\n axUpper.set_xlabel(r\"$R_z \\theta$\")\n\n # Lower left plot -- PhaseDiagram\n axLeft = plt.subplot2grid( (2,2), [1,0], 1, 2 , aspect=3.5)\n\n param = np.loadtxt(\"../../data/{}/MeanArea.txt\".format(directory), unpack=True)\n\n plt.imshow(param.T, origin=\"lower\", interpolation=\"nearest\", cmap=\"terrain\", aspect=3)\n plt.yticks(np.arange(-2, 98)[::25], np.arange(0, 0.02, 0.0002)[::25])\n plt.ylabel(\"pressure $p$\")\n plt.xticks(np.arange(0, 481)[::100], np.arange(1.5, 2.7, 0.0025)[::100])\n plt.xlabel(\"diameter ratio $D / d$\")\n\n fsizeUniform = 3\n axLeft.text(30, 20, r\"zigzag\", fontsize=6)\n axLeft.text(145, 5, r\"twisted\" + \"\\n\" + \"zigzag\", fontsize=fsizeUniform)\n axLeft.text(50, 70, r\"straight\" + \"\\n\" + \"zigzag\", fontsize=fsizeUniform)\n axLeft.text(110, 60, r\"$(2, 2, 0)$\" + \"\\n\" + \"uniform\", fontsize=fsizeUniform, color=\"white\")\n axLeft.text(160, 60, r\"$(3, 2, 1)$\" + \"\\n\" + \"uniform\", fontsize=fsizeUniform, color=\"white\")\n axLeft.text(217, 50, r\"$(3, 3, 0)$\" + \"\\n\" + \"uniform\", fontsize=fsizeUniform, color=\"white\")\n axLeft.text(248, 60, r\"$(4, 2, 2)$\" + \"\\n\" + \"uniform\", fontsize=fsizeUniform, color=\"white\")\n axLeft.text(275, 80, r\"$(4, 3, 1)$\" + \"\\n\" + \"uniform\", fontsize=fsizeUniform, color=\"white\")\n axLeft.text(320, 70, r\"$(4, 4, 0)$\" + \"\\n\" + \"uniform\", fontsize=fsizeUniform, color=\"white\")\n axLeft.text(353, 80, r\"$(5, 3, 2)$\" + \"\\n\" + \"uniform\", fontsize=fsizeUniform, color=\"white\")\n axLeft.text(390, 70, r\"$(5, 4, 1)$\" + \"\\n\" + \"uniform\", fontsize=fsizeUniform, color=\"white\")\n axLeft.text(440, 70, r\"$(5, 5, 0)$\" + \"\\n\" + \"uniform\", fontsize=fsizeUniform, color=\"white\")\n\n axLeft.plot(x(D), y(p), \"ro\")\n\n axRight = plt.subplot2grid( (2,2), [0,1], 1, 1 , aspect=\"auto\")\n\n Enthalpy = np.loadtxt(\"../../data/{}/EnthalpyMin.txt\".format(directory))\n D_zs = np.arange(1.5, 2.7, 0.0025)\n axRight.plot(D_zs, Enthalpy[:, y(p)], \".\")\n axRight.plot(D, Enthalpy[x(D), y(p)], \"ro\")\n axRight.set_ylabel(\"Enthalpy $h$\")\n axRight.set_xlabel(\"Diameter ratio $D / d$\")\n\n fig.savefig(\"../../Plots/{}/Animation/animation-{:d}.png\".format(directory, j), dpi=1000)\n plt.close()\n","sub_path":"ConstPressure/Scripts/PlotScripts/animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"175887097","text":"from bazaar_scraper import *\r\n\r\ndef update_auction_status (auction_id, wait=0):\r\n\r\n char_url = root_url + '&page=details&auctionid=' + auction_id\r\n print(f'Parsing auction #{auction_id} ', end='', flush=True)\r\n\r\n req = requests.get(char_url, headers=request_headers)\r\n if req.status_code == 200:\r\n\r\n print(f'successful request: collecting data... ', end='', flush=True)\r\n char_html = HTML(html=req.text)\r\n cb_table = char_html.find('.CurrentBid')\r\n if len(cb_table) > 0:\r\n auction_status = cb_table[0].text\r\n print(f'done! New status: {auction_status}.', end='\\n', flush=True)\r\n else:\r\n print(f'FAILED! Auction missing!', end='\\n', flush=True)\r\n return None\r\n\r\n time.sleep(wait)\r\n return auction_status\r\n\r\n else:\r\n\r\n return None","sub_path":"auction_tools.py","file_name":"auction_tools.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"250331094","text":"import turtle\nt = turtle.Turtle()\nt.shape('turtle')\n\nNumber = 100\nStep = 5\n\n\ndef circle(Number, Step):\n for step in range(Number):\n t.forward(Step)\n t.left(360/Number)\n for step in range(Number):\n t.forward(Step)\n t.right(360/Number)\n \n\nfor _ in range(3):\n circle(Number, Step)\n t.left(60)\n","sub_path":"turtle_new/упр 10.py","file_name":"упр 10.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"196127818","text":"#!/usr/bin/env python3.5\n# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\nfrom os.path import join, dirname\n\nPACKAGE = \"BayrellCommon\"\nabout = __import__(PACKAGE)\n\n\nsetup(\n\tname = about.__name__,\n\tversion = about.__version__,\n\tdescription = about.__description__,\n\tlong_description = open(join(dirname(__file__), 'README.rst')).read(),\n\tauthor = about.__author__,\n\tauthor_email = about.__email__,\n\tlicense = about.__license__,\n\turl = about.__url__,\n\tpackages=find_packages(),\n\tinclude_package_data = True,\n\tscripts=[\n\t\t#'scripts/bayrell'\n\t],\n\tinstall_requires=[\n\t],\n\tclassifiers=[\n\t\t'Development Status :: 1 - Planning',\n\t\t'Environment :: Console',\n\t\t'Environment :: Web Environment',\n\t\t'Intended Audience :: Developers',\n\t\t'License :: OSI Approved :: Apache Software License',\n\t\t'Operating System :: OS Independent',\n\t\t'Programming Language :: Python',\n\t\t'Programming Language :: Python :: 3.5',\n\t\t'Topic :: Internet',\n\t\t'Topic :: Software Development :: Interpreters',\n\t\t'Topic :: Software Development :: Libraries',\n\t],\n)","sub_path":"pypi_install_script/bayrell-common-0.0.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"112012942","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.signal import fftconvolve\n\nfrom src.blend import composite_paper\nfrom src.draw_map import get_dmap\nfrom src.edge import get_edge_img\nfrom src.multi_res import get_mr_img_from_rgb_img\nfrom src.stroke import get_stroke_img\nfrom src.utilities import show_img\nfrom src.multi_res_lic import get_mrl\n\nimg_path = \"../images/flower.jpeg\"\nimg = cv2.imread(img_path)\nbg_img = cv2.imread(\"paper.jpg\")\nimg = cv2.resize(img, None, fx=2 , fy=2)\n\n# if img_path == \"../images/castle.jpeg\":\n# print(img.shape)\n# img = cv2.resize(img, None, fx=2.0, fy=2.0)\n# elif img_path == \"../images/udata.png\":\n# print(img.shape)\n# img = cv2.resize(img, None, fx=2.0, fy=2.0)\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\ns_map, _, _, d_map = get_dmap(img)\n\nmr_img = get_mr_img_from_rgb_img(img)\n_, _, edge_img = get_edge_img(mr_img, thresh=130, thresh2=0.3)\nmrl_img = get_mrl(img)\nstrk_img = get_stroke_img(edge_img, mrl_img)\nout = composite_paper(strk_img, bg_img,0.1)\n\nedge_img = edge_img.astype(np.uint8)\nshow_img(img, splt=321,gray=False, title=\"Input\")\nshow_img(mr_img, splt=322, title=\"Multi Resolution Image\")\nshow_img(edge_img, splt=323, title=\"Edge Image\")\nshow_img(mrl_img, splt=324, title=\"Multi-resolution LIC Image\")\nshow_img(strk_img, splt=325, title=\"Stroke Image\")\nshow_img(out, splt=326, title=\"Output\")\nplt.show()\nplt.figure()\nplt.suptitle(\"Final Output\")\nshow_img(img, splt=121, title=\"Input\")\nshow_img(out, splt=122, title=\"Output\")\nplt.show()\nplt.figure()\nfor ind, i in enumerate(range(3,9)):\n out = composite_paper(strk_img, bg_img, alpha=i/10)\n show_img(out, splt=321+ind)\nplt.show()\nplt.figure()\nshow_img(mr_img, title=\"M\")\nplt.figure()\nshow_img(img, splt=131, title=\"Input Image\")\nshow_img(s_map, splt=132, title=\"Saliency Map\")\nshow_img(d_map, splt=133, title=\"Draw Map\")\n\nplt.show()\n# plt.figure()\n# show_img(s_map, splt=121, title=\"Saliency Map\")\n# show_img(d_map, splt=122, title=\"Draw Map\")\n# plt.show()\n\n# plt.show()","sub_path":"src/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"299239484","text":"# Aaron Fuller\r\n# Period 1\r\n# Dice Roller\r\n\r\n# Imports\r\nimport random\r\n# Variables\r\ns1 = 0\r\ns2 = 0\r\ns3 = 0\r\ns4 = 0\r\ns5 = 0\r\ns6 = 0\r\n# List\r\nx = 1\r\nprint(\"Welcome to the Dice Roller\")\r\n# Main Loop\r\nwhile x <= s:\r\n\ts = int(input(\"How many numbers would you like:\"))\r\n\tprint(random.randint(1,6))\r\n\tx += 1\r\n\tif s == \"0\":\r\n\t\tprint(\"Thanks for rolling\")\r\n\t\tbreak\r\n\tprint(\"Total Rolls:\"+ str(s))\r\n\tprint(\"1s:\" + str(s1))\r\n\tprint(\"2s:\" + str(s2))\r\n\tprint(\"3s:\" + str(s3))\r\n\tprint(\"4s:\" + str(s4))\r\n\tprint(\"5s:\" + str(s5))\r\n\tprint(\"6s:\" + str(s6))\r\n\r\n\tif diceRoll == \"1\":\r\n\t\ts1 += 1\r\n\r\n\telif diceRoll == \"2\":\r\n\t\ts2 += 1\r\n\r\n\telif diceRoll == \"3\":\r\n\t\ts3 += 1\r\n\r\n\telif diceRoll == \"4\":\r\n\t\ts4 += 1\r\n\r\n\telif diceRoll == \"5\":\r\n\t\ts5 += 1\r\n\r\n\telif diceRoll == \"6\":\r\n\t\ts6 += 1\r\n","sub_path":"diceGame.py","file_name":"diceGame.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"607053286","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: yk\n\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport subprocess\n\n\ndef submit_mothur(infa, taxdb, tax, mothur, threads):\n '''物种分类\n 参数:\n infa: 输入fasta文件\n taxdb: mothur数据库\n tax: mothur数据库分类文件\n mothur: mothur路径\n threads: 进程数\n 返回:\n 无\n '''\n cmd = mothur\n cmd = cmd + ' \"#classify.seqs(fasta='\n cmd = cmd + infa + ',template='\n cmd = cmd + taxdb + ',taxonomy='\n cmd = cmd + tax + ',processors='\n cmd = cmd + str(threads) + ')\"'\n logging.info(' %s' % cmd)\n try:\n status = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE)\n print(status)\n except Exception as e:\n logging.info(' %s' % cmd)\n\n\nif __name__ == '__main__':\n db_dir = '/Bioinfo/Database/Silva_132_v3/mothur/'\n parser = argparse.ArgumentParser(\n description='this is for taxonomy of fasta using mothur classify.seqs',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-i', '--in_fasta',\n help='input fasta file',\n required=True)\n parser.add_argument('-db', '--taxdb',\n help='tax database fasta file',\n default=os.path.join(db_dir, 'silva_132_v3.fa'))\n parser.add_argument('-tax', '--tax',\n help='tax database tax file',\n default=os.path.join(db_dir, 'silva_132_v3.2.tax'))\n parser.add_argument('-t', '--threads',\n help='threads for bowtie.',\n default=1, type=int)\n parser.add_argument('-path', '--mothur_path',\n help='mothur absolute path',\n default='/Bioinfo/bin/mothur')\n args = parser.parse_args()\n logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.INFO)\n submit_mothur(args.in_fasta, args.taxdb, args.tax, args.mothur_path, args.threads)\n","sub_path":"script/submit_mothur.py","file_name":"submit_mothur.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"273475389","text":"#!/usr/bin/env python\n# encoding: utf-8\n# --------------------------------------------------------------------------\n\nfrom django.conf.urls import patterns, url\nfrom apps.front.decorators import has_logged\nfrom .views import ServiceList, ServiceDetail\n\n\nurlpatterns = patterns(\n '',\n\n url(r'^detail/'\n r'(?P[0-9]+)/$',\n has_logged(ServiceDetail.as_view()),\n name='front_service'),\n\n url(r'^list/$',\n has_logged(ServiceList.as_view()),\n name='front_service_list'),\n)\n","sub_path":"src/apps/front/mods/service/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"29051035","text":"# Problem Link: https://leetcode.com/problems/range-sum-of-bst/\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def traverse(self, node, low, high):\n if node == None:\n return 0\n sum = 0\n if node.val >= low and node.val <= high:\n sum += node.val\n if low < node.val:\n sum += self.traverse(node.left, low, high)\n if high > node.val:\n sum += self.traverse(node.right, low, high)\n return sum\n \n \n def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:\n return self.traverse(root, low, high)\n","sub_path":"Leetcode/938. Range Sum of BST.py","file_name":"938. Range Sum of BST.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"395937103","text":"import walkSearch\n\n\ndef writeList(mylist, myfile):\n f = open(myfile, 'w', encoding='utf-8')\n for i in mylist:\n for j in i:\n j = str(j)\n f.write(j + \"\\n\")\n f.close()\n\n\nif __name__ == '__main__':\n f = open(\"C:/核心资料/肖伟祥/会计杂项参数2018-1-19.txt\", \"r\")\n # f = open(\"E:/aaa.txt\", \"r\", encoding='utf-8')\n lines = f.readlines() # 读取全部内容\n b = []\n i = 0\n myfile = \"E:/ccc.txt\"\n for line in lines:\n print(line)\n i += 1\n line = str(line).strip()\n a = walkSearch.detect_walk(line, myfile, \"C:/core-local/frw_user_apps/apps/onl/modules\")\n # print(a)\n if len(a)>0:\n b.append(a)\n print(\"len(b)=\"+str(len(b)))\n print(\"i=\"+str(i))\n myfile1 = \"E:/bbb.txt\"\n writeList(b, myfile1)\n # print(len(b))\n f.close()\n","sub_path":"thirdSearch.py","file_name":"thirdSearch.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"546005151","text":"from tkinter import *\nfrom YouTube import *\nfrom bs4 import BeautifulSoup as soup\nimport urllib.parse\nfrom PIL import Image, ImageTk\nimport io\nimport os\n\nroot = Tk()\nroot.geometry('1000x580')\n\nphoto = PhotoImage(file=\"./logo.png\")\nroot.iconphoto(False,photo)\n\nroot.title(\"YouTube Play Music\")\n\nimage1 = PhotoImage(file=\"./banner.png\")\nlabel_for_image = Label(root,image=image1)\nlabel_for_image.place(x=170, y=-1)\n\nSearchVar = StringVar()\nos.system(\"cls\")\n\ndef Search():\n def PlayAudio(argument):\n vidlink = argument[0]\n duration = argument[1]\n Audio(vidlink,duration)\n \n def PlayVideo(argument):\n vidlink = argument[0]\n duration = argument[1]\n Video(vidlink,duration)\n \n search=SearchVar.get()\n SearchData = list(SearchKeywords(search))\n\n Title = SearchData[2]\n ThumbURL = SearchData[3]\n Channel = SearchData[4]\n Duration = SearchData[5]\n Views = SearchData[6]\n\n raw_data1 = urllib.request.urlopen(ThumbURL[0]).read()\n im1 = Image.open(io.BytesIO(raw_data1))\n im1 = im1.resize((170,100))\n thumimage1 = ImageTk.PhotoImage(im1)\n label1 = Label(root, image=thumimage1)\n label1.place(x=30,y=200)\n Title1 = f'''{Title[0][0:75:]}\\n{Title[0][75::]}'''\n Label(root,text=Title1,font=(\"ArialBlack\",14),justify=LEFT).place(x=210,y=200)\n Label(root,text=Channel[0][0:25:]+\" | \",font=(\"ArialBold\",12)).place(x=210,y=250)\n Label(root,text=Views[0],font=(\"ArialBold\",12)).place(x=400,y=250)\n Label(root,text=\"Video Length: \"+Duration[0],font=(\"ArialBold\",12)).place(x=210,y=275)\n argument1 = list((SearchData[1][0],Duration[0]))\n Button(root,text=\"Play Audio\",font=(\"ArialBlack\",15),bd=5,command=lambda: PlayAudio(argument1)).place(x=620,y=240)\n Button(root,text=\"Play Video\",font=(\"ArialBlack\",15),bd=5,command=lambda: PlayVideo(argument1)).place(x=780,y=240)\n \n raw_data2 = urllib.request.urlopen(ThumbURL[1]).read()\n im2 = Image.open(io.BytesIO(raw_data2))\n im2 = im2.resize((170,100))\n thumimage2 = ImageTk.PhotoImage(im2)\n label2 = Label(root, image=thumimage2)\n label2.place(x=30,y=320)\n Title2 = f'''{Title[1][0:75:]}\\n{Title[1][75::]}'''\n Label(root,text=Title2,font=(\"ArialBlack\",14),justify=LEFT).place(x=210,y=320)\n Label(root,text=Channel[1][0:25:]+\" | \",font=(\"ArialBold\",12)).place(x=210,y=370)\n Label(root,text=Views[1],font=(\"ArialBold\",12)).place(x=400,y=370)\n Label(root,text=\"Video Length: \"+Duration[1],font=(\"ArialBold\",12)).place(x=210,y=395)\n argument2 = list((SearchData[1][1],Duration[1]))\n Button(root,text=\"Play Audio\",font=(\"ArialBlack\",15),bd=5,command=lambda: PlayAudio(argument2)).place(x=620,y=360)\n Button(root,text=\"Play Video\",font=(\"ArialBlack\",15),bd=5,command=lambda: PlayVideo(argument2)).place(x=780,y=360)\n \n raw_data3 = urllib.request.urlopen(ThumbURL[2]).read()\n im3 = Image.open(io.BytesIO(raw_data3))\n im3 = im3.resize((170,100))\n thumimage3 = ImageTk.PhotoImage(im3)\n label3 = Label(root, image=thumimage3)\n label3.place(x=30,y=440)\n Title3 = f'''{Title[2][0:75:]}\\n{Title[2][75::]}'''\n Label(root,text=Title3,font=(\"ArialBlack\",14),justify=LEFT).place(x=210,y=440)\n Label(root,text=Channel[2][0:25:]+\" | \",font=(\"ArialBold\",12)).place(x=210,y=490)\n Label(root,text=Views[2],font=(\"ArialBold\",12)).place(x=400,y=490)\n Label(root,text=\"Video Length: \"+Duration[2],font=(\"ArialBold\",12)).place(x=210,y=515)\n argument3 = list((SearchData[1][2],Duration[2]))\n Button(root,text=\"Play Audio\",font=(\"ArialBlack\",15),bd=5,command=lambda: PlayAudio(argument3)).place(x=620,y=480)\n Button(root,text=\"Play Video\",font=(\"ArialBlack\",15),bd=5,command=lambda: PlayVideo(argument3)).place(x=780,y=480)\n root.mainloop()\n\nLabel(root,text=\"Search Keywords:\",font=(\"ArialBlack\",15)).place(x=50,y=90)\ne1 = Entry(root,font=(\"ArialBlack\",20),width=50,bd=5,textvariable=SearchVar)\ne1.focus()\nSearchVar.set(\"Laung Lachi\")\ne1.place(x=50,y=120)\nButton(root,text=\"Search\",font=(\"ArialBlack\",20),bd=5,command=Search).place(x=840,y=110)\n\nroot.mainloop()","sub_path":"Search-and-Play-YouTube-Video/Search and Play YouTube Video/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"313222399","text":"'''\nA string S consisting of the letters A,B,C and D is given. The string can be transformed by removing a letter A together with an adjacent letter B or by removing a letter C together with an adjacent letter D. Write a function:\n\tdef solution(S)\nthat, given a string S consisting of N characters, return any string that:\n\t* can be obtained from S by repeatedly applying the described transformation and\n\t* can not further be transformed\n\nIf at some point there is more than 1 possible way to transform the string, any of the valid transformations may be chosen.\n\nExamples:\n\n1. Given S = \"CBACD\", the function may return \"C\", because one of the possible sequences of the operations is as follow:\n\tCBACD -> CBA -> C\n\n2. S = \"CABABD\", function may return empty string.\n\tCABABD -> CABD -> CD -> []\n\n3. S = \"ACBDACBD\" function return \"ACBDCBD\"\n\nWrite an efficient algorithm for the following assumption.\n * the length of S is within range 0 -> 250000\n * string S consists only of the following characters \"A\", \"B\", \"C\" or \"D\"\n \n'''\n\nclass Solution:\n\tdef transform(self, s):\n\t\tans = []\n\t\tfor char in s:\n\t\t\tif ans and ans[-1] + char in [\"DC\", \"CD\", \"AB\", \"BA\"]:\n\t\t\t\tans.pop()\n\t\t\telse:\n\t\t\t\tans.append(char)\n\t\treturn \"\".join(ans)\n\t\t\n\nprint(Solution().transform(\"CBACD\") == \"C\")\nprint(Solution().transform(\"DACADCBABD\") == \"DA\")\nprint(Solution().transform(\"CABABD\") == \"\")\nprint(Solution().transform(\"ACBDACBD\") == \"ACBDACBD\")\n\t\t\t\t\n","sub_path":"Interview Prep-2021/Microsoft/microsoft_oa_sep_21.py","file_name":"microsoft_oa_sep_21.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"67250469","text":"# pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103\n\nfrom __future__ import absolute_import, division, print_function\n\nimport pytest\nimport matplotlib.pyplot as plt\nfrom mock import MagicMock, patch\n\nfrom glue.external.qt.QtCore import Qt\nfrom glue.external.qt import QtGui\nfrom glue.core import Data, Subset\nfrom glue.config import data_factory\nfrom glue.clients.layer_artist import RGBImageLayerArtist\n\nfrom .. import qtutil\nfrom ..qtutil import GlueDataDialog\nfrom ..qtutil import pretty_number, PythonListModel, update_combobox\n\n\ndef test_glue_action_button():\n a = QtGui.QAction(None)\n a.setToolTip(\"testtooltip\")\n a.setWhatsThis(\"testwhatsthis\")\n a.setIcon(QtGui.QIcon(\"dummy_file\"))\n a.setText('testtext')\n b = qtutil.GlueActionButton()\n b.set_action(a)\n\n # assert b.icon() == a.icon() icons are copied, apparently\n assert b.text() == a.text()\n assert b.toolTip() == a.toolTip()\n assert b.whatsThis() == a.whatsThis()\n\n #stays in sync\n a.setText('test2')\n assert b.text() == 'test2'\n\n\n@data_factory('testing_factory', identifier=lambda *args: True, priority=-999)\ndef dummy_factory(filename):\n result = Data()\n result.made_with_dummy_factory = True\n return result\ndummy_factory_member = [f for f in data_factory.members\n if f[0] is dummy_factory][0]\n\n\nclass TestGlueDataDialog(object):\n\n def test_factory(self):\n \"\"\"Factory method should always match with filter\"\"\"\n fd = GlueDataDialog()\n assert len(fd.filters) > 0\n for k, v in fd.filters:\n fd._fd.selectNameFilter(v)\n assert fd.factory() is k\n\n def test_load_data_cancel(self):\n \"\"\"Return None if user cancels operation\"\"\"\n fd = GlueDataDialog()\n mock_file_exec(fd, cancel=True)\n assert fd.load_data() == []\n\n def test_load_data_normal(self):\n \"\"\"normal load_data dispatches path to factory\"\"\"\n fd = GlueDataDialog()\n mock_file_exec(fd, cancel=False, path='ld_data_nrml',\n factory=dummy_factory_member)\n d = fd.load_data()\n assert len(d) == 1\n d = d[0]\n assert d.label == 'ld_data_nrml'\n assert d.made_with_dummy_factory is True\n\n def test_filters(self):\n \"\"\"Should build filter list from data_factories env var\"\"\"\n fd = GlueDataDialog()\n assert len(fd.filters) == len([x for x in data_factory.members if not x.deprecated])\n\n def test_load_multiple(self):\n fd = GlueDataDialog()\n mock_file_exec(fd, cancel=False, path=['a.fits', 'b.fits'],\n factory=dummy_factory_member)\n ds = fd.load_data()\n assert len(ds) == 2\n for d, label in zip(ds, 'ab'):\n assert d.label == label\n assert d.made_with_dummy_factory is True\n\n\ndef mock_file_exec(fd, cancel=False, path='junk',\n factory=dummy_factory_member):\n if not isinstance(path, list):\n path = [path]\n\n fd._fd.exec_ = MagicMock()\n fd._fd.exec_.return_value = 1 - cancel\n fd.factory = MagicMock()\n fd.factory.return_value = factory\n fd.paths = MagicMock()\n fd.paths.return_value = path\n\n\ndef test_data_wizard_cancel():\n \"\"\"Returns empty list if user cancel's dialog\"\"\"\n with patch('glue.qt.qtutil.GlueDataDialog') as mock:\n mock().load_data.return_value = []\n assert qtutil.data_wizard() == []\n\n\ndef test_data_wizard_normal():\n \"\"\"Returns data list if successful\"\"\"\n with patch('glue.qt.qtutil.GlueDataDialog') as mock:\n mock().load_data.return_value = [1]\n assert qtutil.data_wizard() == [1]\n\n\ndef test_data_wizard_error_cancel():\n \"\"\"Returns empty list of error generated and then canceled\"\"\"\n with patch('glue.qt.qtutil.GlueDataDialog') as mock:\n mock().load_data.side_effect = Exception\n with patch('glue.qt.qtutil.QMessageBox') as qmb:\n qmb().exec_.return_value = 0\n assert qtutil.data_wizard() == []\n\n\nclass TestPrettyNumber(object):\n\n def test_single(self):\n assert pretty_number([1]) == ['1']\n assert pretty_number([0]) == ['0']\n assert pretty_number([-1]) == ['-1']\n assert pretty_number([1.0001]) == ['1']\n assert pretty_number([1.01]) == ['1.01']\n assert pretty_number([1e-5]) == ['1.000e-05']\n assert pretty_number([1e5]) == ['1.000e+05']\n assert pretty_number([3.3]) == ['3.3']\n\n def test_list(self):\n assert pretty_number([1, 2, 3.3, 1e5]) == ['1', '2', '3.3',\n '1.000e+05']\n\n\ndef test_qt4_to_mpl_color():\n assert qtutil.qt4_to_mpl_color(QtGui.QColor(255, 0, 0)) == '#ff0000'\n assert qtutil.qt4_to_mpl_color(QtGui.QColor(255, 255, 255)) == '#ffffff'\n\n\ndef test_edit_color():\n with patch('glue.qt.qtutil.QtGui.QColorDialog') as d:\n d.getColor.return_value = QtGui.QColor(0, 1, 0)\n d.isValid.return_value = True\n s = Subset(None)\n qtutil.edit_layer_color(s)\n assert s.style.color == '#000100'\n\n\ndef test_edit_color_cancel():\n with patch('glue.qt.qtutil.QtGui.QColorDialog') as d:\n d.getColor.return_value = QtGui.QColor(0, -1, 0)\n s = Subset(None)\n qtutil.edit_layer_color(s)\n\n\ndef test_edit_symbol():\n with patch('glue.qt.qtutil.QtGui.QInputDialog') as d:\n d.getItem.return_value = ('*', True)\n s = Subset(None)\n qtutil.edit_layer_symbol(s)\n assert s.style.marker == '*'\n\n\ndef test_edit_symbol_cancel():\n with patch('glue.qt.qtutil.QtGui.QInputDialog') as d:\n d.getItem.return_value = ('*', False)\n s = Subset(None)\n qtutil.edit_layer_symbol(s)\n assert s.style.marker != '*'\n\n\ndef test_edit_point_size():\n with patch('glue.qt.qtutil.QtGui.QInputDialog') as d:\n d.getInt.return_value = 123, True\n s = Subset(None)\n qtutil.edit_layer_point_size(s)\n assert s.style.markersize == 123\n\n\ndef test_edit_point_size_cancel():\n with patch('glue.qt.qtutil.QtGui.QInputDialog') as d:\n d.getInt.return_value = 123, False\n s = Subset(None)\n qtutil.edit_layer_point_size(s)\n assert s.style.markersize != 123\n\n\ndef test_edit_layer_label():\n with patch('glue.qt.qtutil.QtGui.QInputDialog') as d:\n d.getText.return_value = ('accepted label', True)\n s = Subset(None)\n qtutil.edit_layer_label(s)\n assert s.label == 'accepted label'\n\n\ndef test_edit_layer_label_cancel():\n with patch('glue.qt.qtutil.QtGui.QInputDialog') as d:\n d.getText.return_value = ('rejected label', False)\n s = Subset(None)\n qtutil.edit_layer_label(s)\n assert s.label != 'rejected label'\n\n\ndef test_pick_item():\n items = ['a', 'b', 'c']\n labels = ['1', '2', '3']\n with patch('glue.qt.qtutil.QtGui.QInputDialog') as d:\n d.getItem.return_value = '1', True\n assert qtutil.pick_item(items, labels) == 'a'\n d.getItem.return_value = '2', True\n assert qtutil.pick_item(items, labels) == 'b'\n d.getItem.return_value = '3', True\n assert qtutil.pick_item(items, labels) == 'c'\n d.getItem.return_value = '3', False\n assert qtutil.pick_item(items, labels) is None\n\n\ndef test_pick_class():\n class Foo:\n pass\n\n class Bar:\n pass\n Bar.LABEL = 'Baz'\n with patch('glue.qt.qtutil.pick_item') as d:\n qtutil.pick_class([Foo, Bar])\n d.assert_called_once_with([Foo, Bar], ['Foo', 'Baz'])\n\n\ndef test_get_text():\n with patch('glue.qt.qtutil.QtGui.QInputDialog') as d:\n d.getText.return_value = 'abc', True\n assert qtutil.get_text() == 'abc'\n\n d.getText.return_value = 'abc', False\n assert qtutil.get_text() is None\n\n\nclass TestGlueListWidget(object):\n\n def setup_method(self, method):\n self.w = qtutil.GlueListWidget()\n\n def test_mime_type(self):\n assert self.w.mimeTypes() == [qtutil.LAYERS_MIME_TYPE]\n\n def test_mime_data(self):\n self.w.set_data(3, 'test data')\n self.w.set_data(4, 'do not pick')\n mime = self.w.mimeData([3])\n mime.data(qtutil.LAYERS_MIME_TYPE) == ['test data']\n\n def test_mime_data_multiselect(self):\n self.w.set_data(3, 'test data')\n self.w.set_data(4, 'also pick')\n mime = self.w.mimeData([3, 4])\n mime.data(qtutil.LAYERS_MIME_TYPE) == ['test data', 'also pick']\n\n\nclass TestRGBEdit(object):\n\n def setup_method(self, method):\n d = Data()\n self.fig = plt.figure()\n self.ax = self.fig.add_subplot(1, 1, 1)\n self.artist = RGBImageLayerArtist(d, self.ax)\n self.w = qtutil.RGBEdit(artist=self.artist)\n\n def teardown_method(self, method):\n plt.close(self.fig)\n\n def test_update_visible(self):\n for color in ['red', 'green', 'blue']:\n state = self.artist.layer_visible[color]\n self.w.vis[color].click()\n assert self.artist.layer_visible[color] != state\n\n def test_update_current(self):\n for color in ['red', 'green', 'blue']:\n self.w.current[color].click()\n assert self.artist.contrast_layer == color\n\n\nclass TestListModel(object):\n\n def test_row_count(self):\n assert PythonListModel([]).rowCount() == 0\n assert PythonListModel([1]).rowCount() == 1\n assert PythonListModel([1, 2]).rowCount() == 2\n\n def test_data_display(self):\n m = PythonListModel([1, 'a'])\n i = m.index(0)\n assert m.data(i, role=Qt.DisplayRole) == '1'\n\n i = m.index(1)\n assert m.data(i, role=Qt.DisplayRole) == 'a'\n\n def test_data_edit(self):\n m = PythonListModel([1, 'a'])\n i = m.index(0)\n assert m.data(i, role=Qt.EditRole) == '1'\n\n i = m.index(1)\n assert m.data(i, role=Qt.EditRole) == 'a'\n\n def test_data_user(self):\n m = PythonListModel([1, 'a'])\n i = m.index(0)\n assert m.data(i, role=Qt.UserRole) == 1\n\n i = m.index(1)\n assert m.data(i, role=Qt.UserRole) == 'a'\n\n def test_itemget(self):\n m = PythonListModel([1, 'a'])\n assert m[0] == 1\n assert m[1] == 'a'\n\n def test_itemset(self):\n m = PythonListModel([1, 'a'])\n m[0] = 'b'\n assert m[0] == 'b'\n\n @pytest.mark.parametrize('items', ([], [1, 2, 3], [1]))\n def test_len(self, items):\n assert len(PythonListModel(items)) == len(items)\n\n def test_pop(self):\n m = PythonListModel([1, 2, 3])\n assert m.pop() == 3\n assert len(m) == 2\n assert m.pop(0) == 1\n assert len(m) == 1\n assert m[0] == 2\n\n def test_append(self):\n m = PythonListModel([])\n m.append(2)\n assert m[0] == 2\n m.append(3)\n assert m[1] == 3\n m.pop()\n m.append(4)\n assert m[1] == 4\n\n def test_extend(self):\n m = PythonListModel([])\n m.extend([2, 3])\n assert m[0] == 2\n assert m[1] == 3\n\n def test_insert(self):\n m = PythonListModel([1, 2, 3])\n m.insert(1, 5)\n assert m[1] == 5\n\n def test_iter(self):\n m = PythonListModel([1, 2, 3])\n assert list(m) == [1, 2, 3]\n\n\ndef test_update_combobox():\n combo = QtGui.QComboBox()\n update_combobox(combo, [('a', 1), ('b', 2)])\n update_combobox(combo, [('c', 3)])\n\n\ndef test_update_combobox_indexchanged():\n # Regression test for bug that caused currentIndexChanged to not be\n # emitted if the new index happened to be the same as the old one but the\n # label data was different.\n\n class MyComboBox(QtGui.QComboBox):\n\n def __init__(self, *args, **kwargs):\n self.change_count = 0\n super(MyComboBox, self).__init__(*args, **kwargs)\n self.currentIndexChanged.connect(self.changed)\n\n def changed(self):\n self.change_count += 1\n\n combo = MyComboBox()\n update_combobox(combo, [('a', 1), ('b', 2)])\n update_combobox(combo, [('c', 3)])\n\n assert combo.change_count == 2\n assert combo.currentIndex() == 0\n\n combo = MyComboBox()\n update_combobox(combo, [('a', 1), ('b', 2)])\n update_combobox(combo, [('a', 1), ('b', 3)])\n update_combobox(combo, [('a', 3), ('b', 1)])\n\n assert combo.change_count == 3\n assert combo.currentIndex() == 1\n","sub_path":"glue/qt/tests/test_qtutil.py","file_name":"test_qtutil.py","file_ext":"py","file_size_in_byte":12273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"94514970","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\n'''\r\npip install pywin32 安装pywin32\r\n'''\r\n\r\nfrom win32com.client import gencache\r\nfrom win32com.client import constants, gencache\r\n\r\ndef createPdf(wordPath, pdfPath):\r\n \"\"\"\r\n word转pdf\r\n :param wordPath: word文件路径\r\n :param pdfPath: 生成pdf文件路径\r\n \"\"\"\r\n word = gencache.EnsureDispatch('Word.Application')\r\n doc = word.Documents.Open(wordPath, ReadOnly=1)\r\n doc.ExportAsFixedFormat(pdfPath,\r\n constants.wdExportFormatPDF,\r\n Item=constants.wdExportDocumentWithMarkup,\r\n CreateBookmarks=constants.wdExportCreateHeadingBookmarks)\r\n word.Quit(constants.wdDoNotSaveChanges)\r\n\r\nwordPath = r'H:\\python3\\project\\test\\0413\\20210413_RNA_PBK_42_肺泡灌洗液-DNA(RNA_PBK_42)_PRI-seq纳米孔测序病原宏基因组学检测报告.docx'\r\npdfPath = r'H:\\python3\\project\\test\\0413\\20210413_RNA_PBK_42_肺泡灌洗液-DNA(RNA_PBK_42)_PRI-seq纳米孔测序病原宏基因组学检测报告.pdf'\r\n\r\ncreatePdf(wordPath,pdfPath)\r\n","sub_path":"common_use/word2pdf.py","file_name":"word2pdf.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"247439889","text":"\"\"\"Change examination paths to file ids.\n\nRevision ID: 4a3debf40b72\nRevises: adbd033b0dcd\nCreate Date: 2018-03-11 21:32:04.522634\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\nfrom app import hashfs\nfrom app.models.base_model import BaseEntity\nfrom app.enums import FileCategory\n\nimport os\nimport re\n\n# revision identifiers, used by Alembic.\nrevision = '4a3debf40b72'\ndown_revision = 'adbd033b0dcd'\n\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, relationship\n\nBase = declarative_base()\ndb = sa\ndb.Model = Base\ndb.relationship = relationship\n\n\n\nclass File(db.Model, BaseEntity):\n __tablename__ = 'file'\n\n hash = db.Column(db.String(200), nullable=False)\n extension = db.Column(db.String(20), nullable=False)\n\n category = db.Column(db.Enum(FileCategory, name='file_category'),\n nullable=False)\n display_name = db.Column(db.String(200))\n\n\nclass IntermediateExamination(db.Model, BaseEntity):\n __tablename__ = 'examination'\n\n examination_file_id = db.Column(db.Integer, db.ForeignKey('file.id'),\n nullable=False)\n answers_file_id = db.Column(db.Integer, db.ForeignKey('file.id'))\n\n examination_file = db.relationship(\n File, foreign_keys=[examination_file_id], lazy='joined')\n answers_file = db.relationship(\n File, foreign_keys=[answers_file_id], lazy='joined')\n\n path = db.Column(db.String(256))\n answer_path = db.Column(db.String(256))\n\n\nfilename_regex = re.compile(r'(.+)\\.([^\\s.]+)')\n\n\ndef migrate_single_file(path, fn):\n if not os.path.isfile(path):\n if fn != '1':\n print(\"File does not exist:\", path)\n return None\n\n with open(path, 'rb') as file_reader:\n address = hashfs.put(file_reader)\n\n f = File()\n\n f.category = FileCategory.EXAMINATION\n f.hash = address.id\n\n m = filename_regex.match(fn)\n if m is not None:\n f.extension = m.group(2).lower()\n else:\n f.extension = \"\"\n\n db.session.add(f)\n return f\n\n\ndef migrate_files():\n print(\"Migrating all examination files to HashFS\")\n\n exams = db.session.query(IntermediateExamination).all()\n exams_dir = 'app/static/uploads/examinations'\n\n total = len(exams)\n stepsize = 40\n\n has_invalid_exams = False\n\n dummy_file = File()\n dummy_file.hash = '0' * 64\n dummy_file.extension = 'pdf'\n dummy_file.category = FileCategory.EXAMINATION\n db.session.add(dummy_file)\n\n for i, exam in enumerate(exams):\n if (i + 1) % stepsize == 0:\n print(\"{}/{}\".format(i + 1, total))\n\n if exam.path is None:\n continue\n\n path = os.path.join(exams_dir, exam.path)\n\n examination_file = migrate_single_file(path, exam.path)\n\n if examination_file is None:\n has_invalid_exams = True\n examination_file = dummy_file\n print(\"Setting file of exam {} to dummy file\".format(\n exam.id))\n\n exam.examination_file = examination_file\n\n if exam.answer_path:\n answers_path = os.path.join(exams_dir, exam.answer_path)\n answers_file = migrate_single_file(answers_path, exam.answer_path)\n\n if answers_file:\n exam.answers_file = answers_file\n\n if not has_invalid_exams:\n db.session.expunge(dummy_file)\n\n db.session.commit()\n\n\ndef upgrade():\n connection = op.get_bind()\n Session = sa.orm.sessionmaker()\n session = Session(bind=connection)\n\n db.session = session\n\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('examination', sa.Column('answers_file_id', sa.Integer(), nullable=True))\n op.add_column('examination', sa.Column('examination_file_id', sa.Integer(), nullable=False))\n\n try:\n migrate_files()\n except Exception as e:\n op.drop_column('examination', 'examination_file_id')\n op.drop_column('examination', 'answers_file_id')\n raise e\n\n op.create_foreign_key(op.f('fk_examination_examination_file_id_file'), 'examination', 'file', ['examination_file_id'], ['id'])\n op.create_foreign_key(op.f('fk_examination_answers_file_id_file'), 'examination', 'file', ['answers_file_id'], ['id'])\n op.drop_column('examination', 'path')\n op.drop_column('examination', 'answer_path')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n raise Exception(\"Undoing this migration is impossible\")\n\n # op.add_column('examination', sa.Column('answer_path', mysql.VARCHAR(length=256), nullable=True))\n # op.add_column('examination', sa.Column('path', mysql.VARCHAR(length=256), nullable=True))\n # op.drop_constraint(op.f('fk_examination_answers_file_id_file'), 'examination', type_='foreignkey')\n # op.drop_constraint(op.f('fk_examination_examination_file_id_file'), 'examination', type_='foreignkey')\n # op.drop_column('examination', 'examination_file_id')\n # op.drop_column('examination', 'answers_file_id')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/2018_03_11_4a3debf40b72_change_examination_paths_to_file_ids.py","file_name":"2018_03_11_4a3debf40b72_change_examination_paths_to_file_ids.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"433290803","text":"\"\"\"\nTrain the simplest model. Mostly Use this script for testing\nMeant to be run from the parent directory\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nimport os\nimport sys\nimport pickle\nfrom AngryTops.features import *\nfrom AngryTops.ModelTraining.models import models\nfrom AngryTops.ModelTraining.plotting_helper import plot_history\nfrom AngryTops.ModelTraining.FormatInputOutput import get_input_output\nfrom AngryTops.ModelTraining.custom_loss import *\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.backend import manual_variable_initialization\nmanual_variable_initialization(True)\n\nprint(tf.__version__)\nprint(tf.test.gpu_device_name())\n\n\ndef train_model(model_name, train_dir, csv_file, log_training=True, load_model=False, **kwargs):\n \"\"\"\n Trains a DNN model.\n ============================================================================\n INPUTS:\n Model_name: The name of the mode in models.py\n train_dir: Name of the folder to save the training info + model\n csv_file: The csv file to read data from.\n EPOCHES: # of EPOCHES to train\n scaling: Choose between 'standard' or 'minmax' scaling of input and outputs\n rep: The representation of the data. ie. pxpypz vs ptetaphiM vs ...\n sort_jets: True or False. Sort jets by first btag, then Mass.\n shuffle: If in kwargs.keys, will shuffle the training/testing data.\n weights: The weights for the weighted MSE. Defaults to [1,1,1,1,1,1]\n custom_loss: A custom loss function particle: If you want to test on a specific particle, specify\n \"\"\"\n # CONSTANTS\n if 'retrain' in kwargs.keys():\n train_dir = \"PostTraining_Analysis/models/{0}\".format(train_dir)\n checkpoint_dir = \"{}/checkpoints\".format(train_dir)\n else:\n train_dir = \"../CheckPoints/{}\".format(train_dir)\n checkpoint_dir = \"{}/checkpoints\".format(train_dir)\n checkpoint_path = tf.train.latest_checkpoint(checkpoint_dir)\n EPOCHES = kwargs[\"EPOCHES\"]\n BATCH_SIZE = 32\n print(\"Saving files in: {}\".format(train_dir))\n print(\"Checkpoint Path: \", checkpoint_path)\n\n ###########################################################################\n # LOGGING\n try:\n log = open(\"{}/log.txt\".format(train_dir), 'w')\n except Exception as e:\n os.mkdir(train_dir)\n log = open(\"{}/log.txt\".format(train_dir), 'w')\n if log_training:\n sys.stdout = log\n\n ###########################################################################\n # LOADING / PRE-PROCESSING DATA\n (training_input, training_output), (testing_input, testing_output), \\\n (jets_scalar, lep_scalar, output_scalar), (event_training, event_testing) \\\n = get_input_output(input_filename=csv_file, **kwargs)\n print(\"Shape of training events: \", training_input.shape)\n print(\"Shape of testing events: \", testing_output.shape)\n\n ###########################################################################\n # BUILDING / TRAINING MODEL\n # For the weighted mean square error metric\n if 'weights' in kwargs.keys():\n weights = kwargs['weights']\n print(\"Weights for Weighted MSE:\", weights)\n # Updated the metrics/losses imported from custom_loss.py\n weighted_mse = weighted_MSE(weights)\n custom_metrics[\"Weighted_MSE\"] = weighted_mse\n losses[\"Weighted_MSE\"] = weighted_mse\n metrics.append(weighted_mse)\n if 'custom_loss' in kwargs.keys():\n print(\"Loss Function: \", kwargs['custom_loss'])\n else:\n print(\"Loss Function: mse\")\n metrices = ['mse', 'mae']\n losses = losses = {\"mse\":\"mse\"}\n model = models[model_name](metrics, losses, **kwargs)\n\n # Load previously trained model if it exists\n if load_model:\n try:\n model = tf.keras.models.load_model(\"%s/simple_model.h5\" % train_dir,\n custom_objects=custom_metrics)\n print(\"Loaded weights from previous session\")\n print(\"Loaded weights from previous session\", file=sys.stderr)\n except Exception as e:\n print(e)\n print(e, file=sys.stderr)\n\n print(model.summary())\n\n # Checkpoint saving / Model training\n filepath = checkpoint_dir + \"/weights-improvement-{epoch:02d}.ckpt\"\n print(\"Checkpoints saved in: \", filepath)\n cp_callback = ModelCheckpoint(filepath, monitor='val_loss', save_weights_only=False, verbose=1)\n early_stopping = EarlyStopping(monitor='val_loss', patience=3)\n try:\n history = model.fit(training_input, training_output, epochs=EPOCHES,\n batch_size=BATCH_SIZE, validation_split=0.1,\n callbacks = []\n )\n except KeyboardInterrupt:\n print(\"Training_inerrupted\")\n print(\"Training_inerrupted\", file=sys.stderr)\n history = None\n\n ###########################################################################\n # SAVING MODEL, TRAINING HISTORY AND SCALARS\n model.save('%s/simple_model.h5' % train_dir)\n model.save_weights('%s/model_weights.h5' % train_dir)\n plot_model(model, to_file='%s/model.png' % train_dir, show_shapes=True, expand_nested=False)\n\n scaler_filename = \"{}/scalers.pkl\".format(train_dir)\n with open( scaler_filename, \"wb\" ) as file_scaler:\n pickle.dump(jets_scalar, file_scaler, protocol=2)\n pickle.dump(lep_scalar, file_scaler, protocol=2)\n pickle.dump(output_scalar, file_scaler, protocol=2)\n print(\"INFO: scalers saved to file:\", scaler_filename)\n print(\"INFO: scalers saved to file:\", scaler_filename, file=sys.stderr)\n\n ###########################################################################\n # EVALUATING MODEL\n try:\n test_acc = model.evaluate(testing_input, testing_output)\n print('\\nTest accuracy:', test_acc)\n print('\\nTest accuracy:', test_acc, file=sys.stderr)\n except Exception as e:\n print(e)\n\n ###########################################################################\n # MAKE AND SAVE PREDICTIONS\n # Try to roll back model by 1 epoche to the least overfit version\n # Might fail if EPOCHES == 1.\n try:\n model.load_weights('checkpoints/weights-improvement-0%i.ckpt' % history.epoch.size)\n model.save('%s/best_model.h5' % train_dir)\n model.save_weights('%s/best_weights.h5' % train_dir)\n except Exception as e:\n print(\"Failed to roll model back by 1 EPOCHE\")\n print(e)\n\n predictions = model.predict(testing_input)\n np.savez(\"{}/predictions\".format(train_dir), input=testing_input,\n true=testing_output, pred=predictions, events=event_testing)\n\n ###########################################################################\n # SAVE TRAINING HISTORY\n if history is not None:\n for key in history.history.keys():\n np.savez(\"{0}/{1}.npz\".format(train_dir, key),\n epoches=history.epoch, loss=history.history[key])\n print(\"Keys: \", history.history.keys())\n plot_history(history, train_dir)\n\n # for layer in model.layers:\n # g=layer.get_config()\n # h=layer.get_weights()\n # print (g)\n # print (h)\n sys.stdout = sys.__stdout__\n log.close()\n\nif __name__ == \"__main__\":\n print(\"Compiled\")\n","sub_path":"AngryTops/ModelTraining/train_simple_model2.py","file_name":"train_simple_model2.py","file_ext":"py","file_size_in_byte":7421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"141188560","text":"from selenium import webdriver\nimport conftest\nimport time\n\n#link = \" http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\n\n\ndef test_guest_should_see_login_link(browser):\n time.sleep(1)\n browser_text=browser\n print(browser,'$$$$$')\n link = f\"http://selenium1py.pythonanywhere.com/{browser}/catalogue/coders-at-work_207/\"\n browser = webdriver.Chrome()\n browser.get(link)\n time.sleep(6)\n # //*[@id=\"add_to_basket_form\"]/button\n #browser.find_element_by_xpath('//*[@id=\"add_to_basket_form\"]/button')\n rest_text=browser.find_element_by_xpath('//*[@id=\"add_to_basket_form\"]/button')\n bit_text=rest_text.text\n print(bit_text,' <:-)',browser_text)\n assert rest_text==rest_text\n browser.find_element_by_css_selector(\"#login_link\")\n browser.quit()\n## pytest -s -v --language=ru test_parser.py\n# pytest -s -v --language=de test_parser.py\n\n","sub_path":"test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"125523528","text":"\"\"\"Module for the TriggerReact cog.\"\"\"\r\nimport os\r\nfrom unicodedata import lookup\r\nimport logging\r\nimport discord\r\nfrom discord.ext import commands\r\nfrom cogs.utils import checks\r\nfrom cogs.utils.dataIO import dataIO\r\nfrom cogs.utils.chat_formatting import pagify\r\n\r\n_LOGGER = logging.getLogger(\"red.triggerreact\")\r\nFOLDER_PATH = \"data/triggerreact\"\r\nTRIGGERS_PATH = FOLDER_PATH + \"/triggers.json\"\r\nDEFAULT_SETTINGS = {\r\n \"text_triggers\": {},\r\n \"user_triggers\": {}\r\n}\r\n\r\nclass TriggerReact:\r\n \"\"\"React to messages based on user-defined triggers.\"\"\"\r\n\r\n def __init__(self, bot: commands.Bot):\r\n self.bot = bot\r\n self.triggers = _load()\r\n\r\n async def trigger_reactions(self, message):\r\n \"\"\"Fires when the bot sees a message being sent, and\r\n triggers any reactions.\r\n \"\"\"\r\n if message.author == self.bot.user or message.channel.is_private:\r\n return\r\n\r\n def _triggered_reactions():\r\n for text, emoji_list in self.triggers['text_triggers'].items():\r\n if text in message.content.lower():\r\n for emoji in emoji_list:\r\n yield self._lookup_emoji(emoji)\r\n for user, emoji_list in self.triggers['user_triggers'].items():\r\n if user == message.author.id:\r\n for emoji in emoji_list:\r\n yield self._lookup_emoji(emoji)\r\n\r\n for emoji in _triggered_reactions():\r\n try:\r\n await self.bot.add_reaction(message, emoji)\r\n except (discord.errors.ClientException, discord.errors.HTTPException):\r\n pass\r\n\r\n @commands.group(name=\"triggerreact\", aliases=[\"treact\"], pass_context=True)\r\n @checks.is_owner()\r\n async def trigger_set(self, ctx: commands.Context):\r\n \"\"\"Manage the triggers for reactions. These are global, unless the reaction\r\n is a server emoji.\r\n\r\n To delete a trigger, reset the trigger with no reaction.\r\n \"\"\"\r\n if ctx.invoked_subcommand is None:\r\n await self.bot.send_cmd_help(ctx)\r\n\r\n @trigger_set.command(name=\"text\", pass_context=True)\r\n async def trigger_set_text(self, ctx: commands.Context, *,\r\n text: str):\r\n \"\"\"Trigger if a message contains a word or phrase.\r\n\r\n This text is not case sensitive and strips the message of leading\r\n or trailing whitespace.\r\n \"\"\"\r\n text = text.strip().lower()\r\n emojis = await self._get_trigger_emojis(ctx)\r\n if emojis:\r\n self.triggers[\"text_triggers\"][text] = emojis\r\n _save(self.triggers)\r\n emojis_str = \" \".join(str(self._lookup_emoji(emoji)) for emoji in emojis)\r\n await self.bot.say(\"Done - I will now react to messages containing `{text}` with\"\r\n \" {emojis}.\".format(text=text,\r\n emojis=emojis_str))\r\n elif text in self.triggers['text_triggers']:\r\n del self.triggers['text_triggers'][text]\r\n _save(self.triggers)\r\n await self.bot.say(\"Done - I will no longer react to messages containing `{text}`.\"\r\n \"\".format(text=text))\r\n else:\r\n await self.bot.say(\"Done - no triggers were changed.\")\r\n\r\n @trigger_set.command(name=\"user\", pass_context=True)\r\n async def trigger_set_user(self, ctx: commands.Context,\r\n user: discord.User):\r\n \"\"\"Trigger if a message is from some user.\"\"\"\r\n emojis = await self._get_trigger_emojis(ctx)\r\n if emojis:\r\n self.triggers[\"user_triggers\"][user.id] = emojis\r\n _save(self.triggers)\r\n emojis_str = \" \".join(str(self._lookup_emoji(emoji)) for emoji in emojis)\r\n await self.bot.say(\"Done - I will now react to messages from `{user}` with\"\r\n \" {emojis}.\".format(user=str(user),\r\n emojis=emojis_str))\r\n elif user.id in self.triggers['user_triggers']:\r\n del self.triggers['user_triggers'][user.id]\r\n _save(self.triggers)\r\n await self.bot.say(\"Done - I will no longer react to messages from `{user}`.\"\r\n \"\".format(user=str(user)))\r\n else:\r\n await self.bot.say(\"Done - no triggers were changed.\")\r\n\r\n @trigger_set.command(name=\"list\")\r\n async def trigger_set_list(self):\r\n \"\"\"List all active triggers.\"\"\"\r\n msg = ''\r\n if not (self.triggers['text_triggers'] or self.triggers['user_triggers']):\r\n await self.bot.say('There are no active triggers.')\r\n return\r\n if self.triggers['text_triggers']:\r\n msg += 'These are the active text triggers:\\n'\r\n for text, emojis in self.triggers['text_triggers'].items():\r\n emojis_str = \" \".join(str(self._lookup_emoji(emoji)) for emoji in emojis)\r\n if not emojis_str:\r\n continue\r\n msg += '`{text}`: {emojis}\\n'.format(text=text, emojis=emojis_str)\r\n if self.triggers['user_triggers']:\r\n msg += 'These are the active user triggers:\\n'\r\n for user_id, emojis in self.triggers['user_triggers'].items():\r\n user = discord.utils.get(self.bot.get_all_members(), id=user_id)\r\n emojis_str = \" \".join(str(self._lookup_emoji(emoji)) for emoji in emojis)\r\n if user is None or not emojis_str:\r\n continue\r\n msg += '`{user}`: {emojis}\\n'.format(user=str(user), emojis=emojis_str)\r\n for page in pagify(msg):\r\n await self.bot.say(page)\r\n\r\n async def _get_trigger_emojis(self, ctx: commands.Context):\r\n msg = await self.bot.say(\"React to my message with the new trigger's emojis,\"\r\n \" and type `done` when finished.\")\r\n response = await self.bot.wait_for_message(90.0, author=ctx.message.author,\r\n check=lambda m: 'done' in m.content.lower())\r\n if response is not None:\r\n msg = discord.utils.get(self.bot.messages, id=msg.id)\r\n if msg and msg.reactions:\r\n emojis = list(_create_emoji_list(msg.reactions))\r\n return emojis\r\n\r\n def _lookup_emoji(self, emoji_name):\r\n emoji = discord.utils.get(self.bot.get_all_emojis(), name=emoji_name)\r\n if emoji is not None:\r\n return emoji\r\n return emoji_name\r\n\r\ndef _create_emoji_list(reactions):\r\n for reaction in reactions:\r\n emoji = reaction.emoji\r\n if isinstance(emoji, discord.Emoji):\r\n emoji = emoji.name\r\n yield emoji\r\n\r\ndef _load():\r\n return dataIO.load_json(TRIGGERS_PATH)\r\n\r\ndef _save(settings):\r\n dataIO.save_json(TRIGGERS_PATH, settings)\r\n\r\ndef _check_folders():\r\n if not os.path.exists(FOLDER_PATH):\r\n _LOGGER.info(\"Creating \" + FOLDER_PATH + \" folder...\")\r\n os.makedirs(FOLDER_PATH)\r\n\r\ndef _check_files():\r\n if not dataIO.is_valid_json(TRIGGERS_PATH):\r\n _LOGGER.info(\"Creating json: \" + TRIGGERS_PATH)\r\n dataIO.save_json(TRIGGERS_PATH, DEFAULT_SETTINGS)\r\n else: # Backwards compatibility check\r\n triggers = dataIO.load_json(TRIGGERS_PATH)\r\n for text, emoji_list in triggers['text_triggers'].items():\r\n for idx, emoji in enumerate(emoji_list):\r\n try:\r\n emoji = lookup(emoji)\r\n except KeyError:\r\n pass\r\n else:\r\n emoji_list[idx] = emoji\r\n triggers['text_triggers'][text] = emoji_list\r\n for user, emoji_list in triggers['user_triggers'].items():\r\n for idx, emoji in enumerate(emoji_list):\r\n try:\r\n emoji = lookup(emoji)\r\n except KeyError:\r\n pass\r\n else:\r\n emoji_list[idx] = emoji\r\n triggers['user_triggers'][user] = emoji_list\r\n dataIO.save_json(TRIGGERS_PATH, triggers)\r\n\r\ndef setup(bot: commands.Bot):\r\n \"\"\"Load this cog.\"\"\"\r\n _check_folders()\r\n _check_files()\r\n cog = TriggerReact(bot)\r\n bot.add_listener(cog.trigger_reactions, \"on_message\")\r\n bot.add_cog(cog)\r\n","sub_path":"cogs/triggerreact.py","file_name":"triggerreact.py","file_ext":"py","file_size_in_byte":8402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"14878751","text":"# Echo client program\nimport socket\nimport time\nHOST = 'localhost' # The remote host\nPORT = 50007 # The same port as used by the server\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nwhile True:\n print(\"Introdueix informacio\")\n dato = raw_input()\n\n s.sendto(dato, (HOST,PORT))\n if dato in \"bye\":\n time.sleep(1)\n break\ns.close()\n","sub_path":"M5M9_XavierSanchez/UF3/XaviSanchez_Exercici1/client-speak.py","file_name":"client-speak.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"610137466","text":"import pygame as pg\r\n\r\n#Classe représentant une balle\r\nclass Balle:\r\n\r\n # Constructeur\r\n def __init__(self, WIN_HEIGHT, WIN_WIDTH):\r\n\r\n self.hauteur = 20\r\n self.largeur = 20\r\n self.directionX = 1\r\n self.directionY = 0\r\n self.time = pg.time.get_ticks()\r\n self.barre = pg.Rect(WIN_WIDTH / 2, WIN_HEIGHT/2, self.largeur, self.hauteur)\r\n\r\n # retourne le rectangle de la balle\r\n def getBarre(self):\r\n return self.barre\r\n\r\n #deplace la balle sur l'écran\r\n def deplace(self, vitesse):\r\n if self.time +10 <= pg.time.get_ticks():\r\n self.time = pg.time.get_ticks()\r\n if self.directionX == 0:\r\n self.barre.x += vitesse\r\n else:\r\n self.barre.x -= vitesse\r\n \r\n if self.directionY == 0:\r\n self.barre.y += vitesse\r\n else:\r\n self.barre.y -= vitesse\r\n \r\n #Vérifie que la balle ne sort pas de l'écran\r\n def checkPos(self, WIN_WIDTH, WIN_HEIGHT, j1, j2):\r\n\r\n touche = False # vrai si une raquette est touchée par la balle\r\n\r\n if self.barre.colliderect(j1.getBarre()):\r\n self.directionX = 0\r\n touche = True\r\n if self.directionY == 0:\r\n self.directionY = 1\r\n else :\r\n self.directionY = 0\r\n if self.barre.colliderect(j2.getBarre()):\r\n self.directionX = 1\r\n touche = True\r\n if self.directionY == 0:\r\n self.directionY = 1\r\n else :\r\n self.directionY = 0\r\n\r\n if self.barre.y <= 0:\r\n self.directionY = 0\r\n if self.barre.y + self.hauteur >= WIN_HEIGHT:\r\n self.directionY = 1\r\n \r\n if self.barre.x <= 0:\r\n self.directionX = 0\r\n j2.addPt(1)\r\n return True, touche\r\n if self.barre.x + self.largeur >= WIN_WIDTH:\r\n self.directionX = 1\r\n j1.addPt(1)\r\n return True, touche\r\n\r\n return False, touche","sub_path":"Pong/Balle.py","file_name":"Balle.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"125536070","text":"from __future__ import division\nimport Tkinter\nimport collections\n\ndef analyse(): \n output_text.delete(\"1.0\", Tkinter.END) \n # get the parameters \n dna = dna_entry.get() \n kmer_length = int(kmer_length_entry.get()) \n threshold = float(threshold_entry.get()) \n \n all_kmers = [] \n \n for start in range(len(dna) - kmer_length + 1): \n kmer = dna[start:start+kmer_length] \n all_kmers.append(kmer) \n \n kmer_counts = collections.Counter(all_kmers) \n total_count = len(all_kmers) \n \n for kmer, count in kmer_counts.items(): \n proportion = count / total_count \n if proportion > threshold: \n line = kmer + \",\" + str(count) + \",\" + str(proportion) + \"\\n\" \n output_text.insert(Tkinter.END, line)\n\nwindow = Tkinter.Tk()\n\ndna_label = Tkinter.Label(window, text=\"Enter DNA sequence:\")\ndna_label.pack()\ndna_entry = Tkinter.Entry(window)\ndna_entry.pack()\n\nkmer_length_label = Tkinter.Label(window, text=\"Enter kmer length:\") \nkmer_length_label.pack() \nkmer_length_entry = Tkinter.Spinbox(window, from_=1, to=20)\nkmer_length_entry.pack() \n \nthreshold_label = Tkinter.Label(window, text=\"Enter threshold:\") \nthreshold_label.pack() \nthreshold_entry = Tkinter.Scale(\n window, \n from_=0, \n to=1, \n orient=Tkinter.HORIZONTAL, \n resolution=0.01)\nthreshold_entry.pack()\n\nanalyse_button = Tkinter.Button(window, text=\"Analyse\", width=10, command=analyse) \nanalyse_button.pack() \n\noutput_text = Tkinter.Text(window, height=10, width=25)\noutput_text.pack()\n\nwindow.mainloop()","sub_path":"Effective Python Development for Biologists/interfaces/find_kmers_tkinter_polished.py","file_name":"find_kmers_tkinter_polished.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"280967492","text":"import os, sys, requests, unittest\ndir = os.path.dirname(os.path.dirname(__file__))\nsys.path.append(dir)\nfrom db_fixture import test_data\nfrom my_unit import MyUnit\nfrom parameterized import parameterized\nclass SearchGuestTest(MyUnit):\n '''嘉宾查询测试'''\n def setUp(self):\n self.base_url = 'http://127.0.0.1:8000/api/get_guest_list_sec/'\n\n\n @parameterized.expand([('eid_null', '', '', 10021, 'eid cannot be empty'),\n ('eid_notnull_phone_null_fail', '3', '', 10022, 'result is empty'),\n ('eid_notnull_phone_null_success', '1', '', 200, 'success'),\n ('eid_notnull_phone_notnull_fail', '1', '13511001105', 10022, 'result is empty'),\n ('eid_notnull_phone_null_success', '1', '13511001101', 200, 'success')])\n def test_search_guest(self, name, eid, phone, status, message):\n data = {'eid': eid, 'phone': phone, 'time': self.get_client_time, 'sign': self.get_client_sign}\n auth_data = ('admin', 'admin123456')\n r = requests.request('get', url=self.base_url, params=data, auth=auth_data)\n self.result = r.json()\n self.assertEqual(self.result['status'], status)\n self.assertIn(message, self.result['message'])\n\n def tearDown(self):\n print(self.result)\n\nif __name__ == '__main__':\n test_data.init_data()\n unittest.main()","sub_path":"pyrequests/interface_sec/search_guest_test.py","file_name":"search_guest_test.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"530413628","text":"'''\n블루레이에는 총 N개의 레슨이 들어가는데, 블루레이를 녹화할 때, 레슨의 순서가 바뀌면 안 된다\nM개의 블루레이, M개의 블루레이는 모두 같은 크기\n가능한 블루레이의 크기 중 최소를 구하는 프로그램\n\n풀이 법:\n최대치를 제시했을 때 이것이 가능한지 판단 하는 법.\nex ) M=3 이고 답을 15을 제시\n1부터 차례대로 더해나가다가 다음수를 더했을 때 15가 넘어가는 지점에서 중단\n1 2 3 4 5/ 6 7 / 8 / 9 => 4개 나오므로 불가 => 최대치를 올림\n\nex ) M=3 이고 답을 20을 제시\n1 2 3 4 5 / 6 7 / 8 9 => 3개 나오므로 가능 => 최대치를 내림.\n\n혹시 count 가 많아 최대치를 내리려던 중 레슨 시간을 초과하는게 있다면 그 블루레이의 용량의 크기가 최소이다.\n# '''\n\n# N,M = map(int,input().split())\n# les = list(map(int,input().split()))\n\n# lo = 0\n# hi = sum(les)\n\n# while lo+1 mid:\n# hi=max(les)\n# break\n# total=0\n# count=1\n# for i in range(len(les)-1):\n# total += les[i]\n# if total + les[i+1] > mid:\n# count+=1\n# total=0\n# # print('lo : {}, hi : {}, mid : {}, count = {}'.format(lo,hi,mid,count))\n# if count > M:\n# lo = mid\n# else:\n# hi = mid\n\n# print(hi)\n\nimport sys\ninput = sys.stdin.readline\n\ndef record(mid):\n count = 1\n temp = 0\n for i in L:\n temp += i\n if temp > mid:\n temp = i\n count += 1\n return count\n\n\nN, M = map(int, input().split())\nL = list(map(int, input().split()))\nans = 0\nlo = max(L)\nhi = sum(L)\nwhile lo <= hi:\n mid = (lo + hi) // 2\n if M >= record(mid):\n ans = mid\n hi = mid-1\n else:\n lo = mid+1\nprint(ans)","sub_path":"백준/Python/카테고리/이분탐색(Binary Search)/2343(기타 레슨).py","file_name":"2343(기��� 레슨).py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"407008507","text":"import json\nimport os\nfrom jsonmerge import merge\n\ndef save_json_data(filepath, data):\n \"\"\"\n Save JSON data to a file\n \"\"\"\n if not os.path.exists(filepath):\n with open(filepath, 'w+') as outfile:\n json.dump(data, outfile, indent=4, sort_keys=True)\n else:\n loaded_data = {}\n with open(filepath) as data_file:\n loaded_data = json.load(data_file)\n compiled_data = merge(data, loaded_data)\n\n with open(filepath, 'w+') as outfile:\n json.dump(compiled_data, outfile, indent=4, sort_keys=True)\n","sub_path":"SUASSystem/SUASSystem/utils/data_functions.py","file_name":"data_functions.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"292748077","text":"import sys\nimport csv\nimport optparse\n\nsheet = csv.DictReader(open('aggregation-input.csv'))\n\n\ndef readData() : \n for row in sheet : \n photo_url = row['url']\n mode_rating = row['mode_rating']\n if mode_rating == \"1\":\n \tprint(photo_url)\n\nreadData();\n","sub_path":"Dummy Data/aggregation_module.py","file_name":"aggregation_module.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"649159069","text":"'''\n Implementation of Priority Queue Data Structure using Unsorted Array\n Priority Queue returns the Highest Priority element on Dequeue Operation\n Assume higher value of queue element have higher priority represent '\n \n Example \n If Queue contains 2,3,1,45,6,23,33\n then dequeue operation return 45\n'''\n\nclass Priority_Queue:\n \"\"\"Class to implement Priority Queue Data Structure using Unsorted Array\"\"\"\n def __init__(self):\n \"\"\"\n constructing a queue \n \"\"\"\n self.items=[]\n \n def __str__(self):\n \"\"\"\n for printing the Priority Queue elemetns\n \"\"\"\n return self.display()\n\n def __repr__(self):\n \"\"\"\n for representaions of Priority Queue elemetns\n \"\"\"\n return self.display()\n\n def __len__(self):\n \"\"\"\n for length of Priority Queue object\n \"\"\" \n return self.size() \n\n def __iter__(self): \n \"\"\"\n queue elements Priority Queue from front to rear\n \"\"\"\n if self.is_empty():\n raise IndexError(\"Priority Queue object is not iterable Because Queue is empty\") \n i = 0\n while True:\n if i >= len(self.items):\n raise StopIteration\n yield self.items[i]\n i += 1 \n\n\n def size(self):\n \"\"\" \n return the size of Priority Queue \n Syntax: size() \n Time Complexity: O(1) \n \"\"\" \n return len(self.items) \n\n def peek(self):\n \"\"\"\n function to return the front element value\n Syntax: peek() \n Time Complexity: O(1) \n \"\"\"\n if self.is_empty():\n raise IndexError(\"Front element doesnot exixts Because Priority Queue is empty\")\n return self.items[0]\n\n def is_empty(self):\n \"\"\" \n return the true if Priority Queue is empty\n Syntax: is_empty() \n Time Complexity: O(1) \n \"\"\" \n return self.items == []\n \n def display(self):\n \"\"\" \n function to display the Priority Queue elements\n Syntax: display() \n Time Complexity: O(1) \n \"\"\" \n #if Priority Queue is empty\n if(len(self.items)<=0):\n print(\"Priority Queue is Empty \",end='')\n return str() #for representaion purpose\n # otherwise\n else:\n print('-'*11,'Priority Queue','-'*11)\n print('Front : '+str(self.items[0]))\n print('Rear : '+str(self.items[-1]))\n print('Elements : '+str(self.items))\n print('Size : '+str(len(self.items)))\n print('-'*30)\n return str() #for representaion purpose\n\n def enqueue(self,item):\n \"\"\" \n function to insert a given element in the Priority Queue\n Syntax: enqueue(item) \n Time Complexity: O(1) \n \"\"\"\n #since we are using unsorted array so we do not have to worry about the inserted item postion in the Priority Queue items\n self.items.append(item) #adding the new element at the end of Priority Queue\n\n\n def dequeue(self):\n \"\"\" \n function to delete highest priority element from Priority Queue\n Syntax: dequeue(item) \n Time Complexity: O(n) \n \"\"\" \n #if Priority Queue is empty\n if self.is_empty():\n raise IndexError(\"Deletion is not Possible Because Priority Queue is Empty\")\n else:\n \t#since we are using unsorted array so we have to loop through items to find highest priority element\n \t#find the element with highest priority and delete it from Priority Queue\n highest=self.items[0]\n index=0\n for i in range(len(self.items)):\n \tif self.items[i]>highest:\n \t\thighest=self.items[i]\n \t\tindex=i\n\n del self.items[index] # deleting highest priority element\n return highest \n\n\n\n\nif __name__ == '__main__':\n obj=Priority_Queue()\n while(1):\n print(\"\\n------------------------------------\")\n print(\"Priority Queue Menu\")\n print(\"1.Enqueue\")\n print(\"2.Dequeue\")\n print(\"3.Peek\")\n print(\"4.Display\")\n print(\"5.Exit\")\n print(\"------------------------------------\")\n choice=int(input(\"\\nEnter your choice : \"))\n if(choice==1):\n item=int(input(\"\\nEnter the element you want to insert in Priority Queue : \"))\n obj.enqueue(item)\n elif(choice==2):\n item=obj.dequeue()\n print(\"\\nThe deleted element is : \",item)\n elif(choice==3):\n item=obj.peek()\n print(\"\\nThe Front element is : \",item) \n elif(choice==4):\n obj.display() \n elif(choice==5):\n print(\"\\nExiting ......\")\n break\n else:\n continue\n ","sub_path":"Queue/Priority Queue Using Unsorted Array.py","file_name":"Priority Queue Using Unsorted Array.py","file_ext":"py","file_size_in_byte":4869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"101808362","text":"import sys\n\nwith open(sys.argv[1]) as f:\n\tlines = f.readlines()\n\tIDs = []\n\tcounties = []\n\tinjuries = []\n\tcolTimes = []\n\tlats = []\n\tlngs = []\n\tfor line in lines[1:]:\n\t\tfields = line.split(',')\n\t\tIDs.append(fields[0])\n\t\tlats.append(fields[1])\n\t\tlngs.append(fields[2])\n\t\tcounties.append(fields[3])\n\t\tinjuries.append(fields[5] == 'Vehicle Crash w/injuries')\n\t\tcolTimes.append(fields[6].strip())\n\n\tlatLngsJS = 'var latLngs = ['\n\tfor lat, lng in zip(lats, lngs):\n\t\tlatLngsJS = latLngsJS + 'new google.maps.LatLng(' + lat + ',' + lng + '),'\n\tlatLngsJS = latLngsJS[:-1] + '];'\n\tprint(latLngsJS)\n\n\tIDsJS = 'var IDs = ['\n\tfor ID in IDs:\n\t\tIDsJS = IDsJS + \"'\" + ID + \"'\" + ','\n\tIDsJS = IDsJS[:-1] + ']'\n\tprint(IDsJS)\n\n\tcountiesJS = 'var counties = ['\n\tfor c in counties:\n\t\tcountiesJS = countiesJS + \"'\" + c + \"'\" + ','\n\tcountiesJS = countiesJS[:-1] + '];'\n\tprint(countiesJS)\n\n\tinjuriesJS = 'var injuries = ['\n\tfor i in injuries:\n\t\tinjuriesJS = injuriesJS + \"'\" + str(i) + \"'\" + ','\n\tinjuriesJS = injuriesJS[:-1] + '];'\n\tprint(injuriesJS)\n\n\tcolTimesJS = 'var colTimes = ['\n\tfor ct in colTimes:\n\t\tcolTimesJS = colTimesJS + \"'\" + ct + \"'\" + ','\n\tcolTimesJS = colTimesJS[:-1] + '];'\n\tprint(colTimesJS)","sub_path":"att_florida_collector/googleMaps/CSV2JS.py","file_name":"CSV2JS.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"360844629","text":"# Copyright (c) 2021, Xilinx, Inc.\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without \n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, \n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright \n# notice, this list of conditions and the following disclaimer in the \n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its \n# contributors may be used to endorse or promote products derived from \n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, \n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR \n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR \n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, \n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nimport os\nimport glob\nimport re\nimport cffi\nfrom collections import defaultdict\n\n\n__author__ = \"Yun Rock Qu\"\n__copyright__ = \"Copyright 2021, Xilinx\"\n__email__ = \"pynq_support@xilinx.com\"\n\n\nboard = os.environ['BOARD']\nif board == \"ZCU111\":\n _iic_channel = 12\nelif board == \"RFSoC2x2\":\n _iic_channel = 7\nelse:\n raise ValueError(\"Board {} is not supported.\".format(board))\n\n\n_ffi = cffi.FFI()\n_ffi.cdef(\"int clearInt(int IicNum);\"\n \"int writeLmx2594Regs(int IicNum, unsigned int RegVals[113]);\"\n \"int writeLmk04208Regs(int IicNum, unsigned int RegVals[26]);\"\n \"int writeLmk04832Regs(int IicNum, unsigned int RegVals[125]);\")\n_lib = _ffi.dlopen(os.path.join(os.path.dirname(__file__), 'libxrfclk.so'))\n\n\n_lmx2594Config = defaultdict(list)\n_lmk04208Config = defaultdict(list)\n_lmk04832Config = defaultdict(list)\n\n\ndef _safe_wrapper(name, *args, **kwargs):\n \"\"\"Wrapper function for FFI function calls.\n\n \"\"\"\n if not hasattr(_lib, name):\n raise RuntimeError(\"Function {} not in library.\".format(name))\n if getattr(_lib, name)(*args, **kwargs):\n raise RuntimeError(\"Function {} call failed.\".format(name))\n\n\ndef clear_int():\n \"\"\"Clear the interrupts.\n\n \"\"\"\n _safe_wrapper(\"clearInt\", _iic_channel)\n\n\ndef write_lmk04208_regs(reg_vals):\n \"\"\"Write values to the LMK04208 registers.\n\n This is an internal function.\n\n Parameters\n ----------\n reg_vals: list\n A list of 26 32-bit register values.\n\n \"\"\"\n _safe_wrapper(\"writeLmk04208Regs\", _iic_channel, reg_vals)\n\n\ndef write_lmk04832_regs(reg_vals):\n \"\"\"Write values to the LMK04832 registers.\n\n This is an internal function.\n\n Parameters\n ----------\n reg_vals: list\n A list of 125 24-bit register values.\n\n \"\"\"\n _safe_wrapper(\"writeLmk04832Regs\", _iic_channel, reg_vals)\n\n\ndef write_lmx2594_regs(reg_vals):\n \"\"\"Write values to the LMX2594 registers.\n\n This is an internal function.\n\n Parameters\n ----------\n reg_vals: list\n A list of 113 32-bit register values.\n\n \"\"\"\n _safe_wrapper(\"writeLmx2594Regs\", _iic_channel, reg_vals)\n\n\ndef set_ref_clks(lmk_freq=122.88, lmx_freq=409.6):\n \"\"\"Set all RF data converter tile reference clocks to a given frequency.\n\n LMX chips are downstream so make sure LMK chips are enabled first.\n\n Parameters\n ----------\n lmk_freq: float\n The frequency for the LMK clock generation chip.\n lmx_freq: float\n The frequency for the LMX PLL chip.\n\n \"\"\"\n if board == \"ZCU111\":\n read_tics_output()\n set_lmk04208_clks(lmk_freq)\n set_lmx2594_clks(lmx_freq)\n\n elif board == \"RFSoC2x2\":\n read_tics_output()\n set_lmk04832_clks(lmk_freq)\n set_lmx2594_clks(lmx_freq)\n\n\ndef read_tics_output():\n \"\"\"Read all the TICS register values from all the txt files.\n\n Reading all the configurations from the current directory. We assume the\n file has a format `CHIPNAME_frequency.txt`.\n\n \"\"\"\n dir_path = os.path.dirname(os.path.realpath(__file__))\n all_txt = glob.glob(os.path.join(dir_path, '*.txt'))\n for s in all_txt:\n chip, freq = s.lower().split('/')[-1].strip('.txt').split('_')\n config = eval('_{}Config'.format(chip))\n with open(s, 'r') as f:\n lines = [l.rstrip(\"\\n\") for l in f]\n for i in lines:\n m = re.search('[\\t]*(0x[0-9A-F]*)', i)\n config[float(freq)] += int(m.group(1), 16),\n\n\ndef set_lmx2594_clks(lmx_freq):\n \"\"\"Set LMX chip frequency.\n\n Parameters\n ----------\n lmx_freq: float\n The frequency for the LMX PLL chip.\n\n \"\"\"\n if lmx_freq not in _lmx2594Config:\n raise RuntimeError(\"Frequency {} MHz is not valid.\".format(lmx_freq))\n else:\n write_lmx2594_regs(_lmx2594Config[lmx_freq])\n\n\ndef set_lmk04832_clks(lmk_freq):\n \"\"\"Set LMK chip frequency.\n\n Parameters\n ----------\n lmk_freq: float\n The frequency for the LMK clock generation chip.\n\n \"\"\"\n if lmk_freq not in _lmk04832Config:\n raise RuntimeError(\"Frequency {} MHz is not valid.\".format(lmx_freq))\n else:\n write_lmk04832_regs(_lmk04832Config[lmk_freq])\n\n\ndef set_lmk04208_clks(lmk_freq):\n \"\"\"Set LMK chip frequency.\n\n Parameters\n ----------\n lmk_freq: float\n The frequency for the LMK clock generation chip.\n\n \"\"\"\n if lmk_freq not in _lmk04208Config:\n raise RuntimeError(\"Frequency {} MHz is not valid.\".format(lmx_freq))\n else:\n write_lmk04208_regs(_lmk04208Config[lmk_freq])\n","sub_path":"board/RFSoC2x2/packages/xrfclk/package/xrfclk/xrfclk.py","file_name":"xrfclk.py","file_ext":"py","file_size_in_byte":6163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"523582334","text":"# ------------------------------\n# 496. Next Greater Element I\n# \n# Description:\n# You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.\n# The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.\n# Example 1:\n# Input: nums1 = [4,1,2], nums2 = [1,3,4,2].\n# Output: [-1,3,-1]\n# Explanation:\n# For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.\n# For number 1 in the first array, the next greater number for it in the second array is 3.\n# For number 2 in the first array, there is no next greater number for it in the second array, so output -1.\n# \n# Example 2:\n# Input: nums1 = [2,4], nums2 = [1,2,3,4].\n# Output: [3,-1]\n# Explanation:\n# For number 2 in the first array, the next greater number for it in the second array is 3.\n# For number 4 in the first array, there is no next greater number for it in the second array, so output -1.\n# \n# Note:\n# All elements in nums1 and nums2 are unique.\n# The length of both nums1 and nums2 would not exceed 1000.\n# \n# Version: 1.0\n# 07/10/18 by Jianfa\n# ------------------------------\n\nclass Solution(object):\n def nextGreaterElement(self, findNums, nums):\n \"\"\"\n :type findNums: List[int]\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n res = []\n indexFound = False\n for i in findNums:\n index = nums.index(i)\n for j in nums[index+1:]:\n if j > i:\n res.append(j)\n indexFound = True\n break\n \n if indexFound:\n indexFound = False\n \n else:\n res.append(-1)\n \n return res\n\n# Used for testing\nif __name__ == \"__main__\":\n test = Solution()\n\n# ------------------------------\n# Summary:\n# ","sub_path":"Easy/496.py","file_name":"496.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"627868110","text":"import datetime as dt\nimport random\n\nfrom clowder.storage import cluster_state\nfrom clowder.storage import event_log\nfrom clowder.storage import event_types\n\n\nasync def get_gossip_host(app):\n return app['config']['gossip_host']\n\n\nasync def get_gossip_port(app):\n return app['config']['gossip_port']\n\n\nasync def get_random_peer(app):\n peer_ids = await cluster_state.get_peer_ids(app)\n if not peer_ids:\n return None\n\n random_id = random.sample(peer_ids, 1)[0]\n return await cluster_state.get_peer(app, random_id)\n\n\nasync def get_peer_by_host_and_port(app, host, port):\n peers = await cluster_state.get_peers(app)\n\n for p in peers:\n if p['gossip_host'] == host and p['gossip_port'] == port:\n return p\n\n return None\n\n\nasync def get_namespace_peers(app, namespace_name):\n peers = await cluster_state.get_peers(app)\n return [peer for peer in peers if namespace_name in peer['namespaces']]\n\n\nasync def add_peer(app, peer_name, gossip_host, gossip_port, web_host, web_port, namespaces, event_time):\n if await cluster_state.peer_exists(app, peer_name):\n return None\n\n peer = await cluster_state.add_peer(\n app, peer_name, gossip_host, gossip_port, web_host, web_port, namespaces, event_time\n )\n\n await event_log.add_event(\n app, await get_gossip_host(app), await get_gossip_port(app),\n event_types.PEER_JOINED, peer, event_time\n )\n\n\nasync def add_peer_namespace(app, peer_name, new_namespace, event_time):\n peer = await cluster_state.get_peer(peer_name)\n namespaces = peer['namespaces']\n if new_namespace in namespaces:\n return\n\n namespaces.append(new_namespace)\n await cluster_state.update_peer_namespaces(app, peer_name, namespaces, event_time)\n\n await event_log.add_event(\n app, peer['gossip_host'], await peer['gossip_port'],\n event_types.NAMESPACE_CREATED, new_namespace, event_time\n )\n\n\nasync def get_peers(app):\n return await cluster_state.get_peers(app)\n\n\nasync def update_peer_ping_time(app, peer_name, new_ping_time):\n return await cluster_state.update_peer_ping_time(app, peer_name, new_ping_time)\n\n\nasync def remove_peer(app, peer_name):\n if not await cluster_state.peer_exists(app, peer_name):\n return\n\n await cluster_state.remove_peer(app, peer_name)\n await event_log.add_event(\n app, await get_gossip_host(app), await get_gossip_port(app),\n event_types.PEER_LEFT, peer_name, str(dt.datetime.utcnow())\n )","sub_path":"clowder/service/cluster_state.py","file_name":"cluster_state.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"224004575","text":"# !/usr/bin/env python3\n# coding: utf8\n\"\"\"Модуль используемый для тестирования GUI\n\"\"\"\nfrom pywinauto import Application\nfrom pywinauto.controls.uia_controls import ListViewWrapper\nfrom pywinauto.controls.uia_controls import ListItemWrapper\nfrom pywinauto import mouse\n\nclass Testing:\n \"\"\"Класс предназначенный для тестирования GUI\n \"\"\"\n\n def __init__(self, path):\n self.shortcut_name = \"StarLine-Master\"\n self.application_name = \"explorer.exe\"\n self.application_path = path\n self.title = \"Мастер\"\n self.application = None\n\n def start_testing(self):\n self.start_application()\n pass\n\n def start_application(self):\n Application().start('%s \"%s\"' % (self.application_name, self.application_path))\n self.application = Application(backend=\"uia\").connect(path=self.application_name, title=self.title)\n scroll = self.application['Dialog']\n scroll.print_control_identifiers()\n listBox = self.application['Dialog']['ListBox - Просмотр элементов']\n listBox.set_focus()\n wrapper = listBox.wrapper_object()\n while not self.find_exe(wrapper):\n scroll(10)\n listBox = self.application['Dialog']['ListBox - Просмотр элементов']\n wrapper = listBox.wrapper_object()\n\n def find_exe(self, wrapper):\n items = wrapper.items()\n for item in items:\n if item._element_info.rich_text == self.shortcut_name:\n return True\n return False\n","sub_path":"source/Testing.py","file_name":"Testing.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"427770278","text":"\"\"\"Constants used by the OpenMediaVault integration.\"\"\"\n\nDOMAIN = \"openmediavault\"\nDEFAULT_NAME = \"OpenMediaVault\"\nDATA_CLIENT = \"client\"\nATTRIBUTION = \"Data provided by OpenMediaVault integration\"\n\nDEFAULT_HOST = \"10.0.0.1\"\nDEFAULT_USERNAME = \"admin\"\nDEFAULT_PASSWORD = \"openmediavault\"\n\nDEFAULT_DEVICE_NAME = \"OMV\"\nDEFAULT_SSL = False\nDEFAULT_SSL_VERIFY = True\n\nATTR_ICON = \"icon\"\nATTR_LABEL = \"label\"\nATTR_UNIT = \"unit\"\nATTR_UNIT_ATTR = \"unit_attr\"\nATTR_GROUP = \"group\"\nATTR_PATH = \"data_path\"\nATTR_ATTR = \"data_attr\"\n\nBINARY_SENSOR_TYPES = {\n \"system_pkgUpdatesAvailable\": {\n ATTR_LABEL: \"Update available\",\n ATTR_GROUP: \"System\",\n ATTR_PATH: \"hwinfo\",\n ATTR_ATTR: \"pkgUpdatesAvailable\",\n },\n \"system_rebootRequired\": {\n ATTR_LABEL: \"Reboot pending\",\n ATTR_GROUP: \"System\",\n ATTR_PATH: \"hwinfo\",\n ATTR_ATTR: \"rebootRequired\",\n },\n \"system_configDirty\": {\n ATTR_LABEL: \"Config dirty\",\n ATTR_GROUP: \"System\",\n ATTR_PATH: \"hwinfo\",\n ATTR_ATTR: \"configDirty\",\n },\n}\n\nSENSOR_TYPES = {\n \"system_cpuUsage\": {\n ATTR_ICON: \"mdi:speedometer\",\n ATTR_LABEL: \"CPU load\",\n ATTR_UNIT: \"%\",\n ATTR_GROUP: \"System\",\n ATTR_PATH: \"hwinfo\",\n ATTR_ATTR: \"cpuUsage\",\n },\n \"system_memUsage\": {\n ATTR_ICON: \"mdi:memory\",\n ATTR_LABEL: \"Memory\",\n ATTR_UNIT: \"%\",\n ATTR_GROUP: \"System\",\n ATTR_PATH: \"hwinfo\",\n ATTR_ATTR: \"memUsage\",\n },\n \"system_uptimeEpoch\": {\n ATTR_ICON: \"mdi:clock-outline\",\n ATTR_LABEL: \"Uptime\",\n ATTR_UNIT: \"hours\",\n ATTR_GROUP: \"System\",\n ATTR_PATH: \"hwinfo\",\n ATTR_ATTR: \"uptimeEpoch\",\n },\n}\n\nDEVICE_ATTRIBUTES_FS = [\n \"size\",\n \"available\",\n \"type\",\n \"mountpoint\",\n \"_readonly\",\n \"_used\",\n]\n\nDEVICE_ATTRIBUTES_DISK = [\n \"canonicaldevicefile\",\n \"size\",\n \"israid\",\n \"isroot\",\n \"devicemodel\",\n \"serialnumber\",\n \"firmwareversion\",\n \"sectorsize\",\n \"rotationrate\",\n \"writecacheis\",\n \"smartsupportis\",\n \"Raw_Read_Error_Rate\",\n \"Spin_Up_Time\",\n \"Start_Stop_Count\",\n \"Reallocated_Sector_Ct\",\n \"Seek_Error_Rate\",\n \"Load_Cycle_Count\",\n \"UDMA_CRC_Error_Count\",\n \"Multi_Zone_Error_Rate\",\n]\n","sub_path":"custom_components/openmediavault/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"459479621","text":"#!/usr/bin/env python\n\n#------------------------------------------------------------------------------\n# Copyright (c) 2020, Andres A. \n# All rights reserved.\n#\n# Distributed under BSD license.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# 3. All advertising materials mentioning features or use of this software\n# must display the following acknowledgement:\n# This product includes software developed by the .\n# 4. Neither the name of the nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY\n# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# \n# Created by:\n# andres.arboleda AT gmail DOT com, (jun/2020)\n# Modified by:\n# andres.arboleda AT gmail DOT com, (nov/2020)\n#------------------------------------------------------------------------------\n\n\nimport rospy\nfrom geometry_msgs.msg import PoseStamped\nfrom nav_msgs.msg import Path\nimport actionlib\nimport move_base_msgs.msg\nfrom std_srvs.srv import Empty\nfrom vva_msgs.msg import OdomCorrectionStatus\nfrom vva_msgs.msg import NavCorrectionStatus\n\n\n\n# Intermediate module between a goal client and move_base, in charge of implementing improvement actions when\n# a goal fails. For example, put an intermediate closer goal which is in the same path of the original goal\n# to unstuck the robot\nclass NavigationCorrection:\n def __init__(self):\n rospy.init_node('vva_navigation_correction')\n \n # Subscribed topics\n self.simple_goal_sub = rospy.Subscriber('vva_navigation_simple/goal', PoseStamped, self.simple_goal_callback)\n self.global_path_sub = rospy.Subscriber('move_base/GlobalPlanner/plan', Path, self.global_path_callback)\n self.odom_c_status_sub = rospy.Subscriber('vva_odom_correction/status', OdomCorrectionStatus, self.odom_c_status_callback)\n \n # Published topics\n self.nav_corr_status_pub = rospy.Publisher('vva_navigation_correction/status', NavCorrectionStatus, queue_size=10)\n \n # Published services\n self.cancel_goal_srv = rospy.Service('~cancel_goal', Empty, self.cancel_goal_srv_callback)\n\n # Parameters\n self.rate = rospy.get_param('~rate', 10)\n self.closer_goal_path_poses = rospy.get_param('~closer_goal_path_poses', 40)\n self.clear_costmaps_service_name = rospy.get_param('~clear_costmaps_service_name', \"/move_base/clear_costmaps\")\n self.use_odom_correction_status = rospy.get_param('~use_odom_correction_status', True)\n self.using_hw_rplidar = rospy.get_param('~using_hw_rplidar', True)\n self.stop_lidar_service_name = rospy.get_param('~stop_lidar_service_name', \"/stop_motor\")\n self.start_lidar_service_name = rospy.get_param('~start_lidar_service_name', \"/start_motor\")\n self.rplidar_idle_time = rospy.get_param('~rplidar_idle_time', 30)\n \n # Global variables for subscribed topics\n self.original_simple_goal = None # Type: geometry_msgs/PoseStamped\n self.global_path = None # Type: geometry_msgs/PoseStamped[]\n self.odom_c_status = OdomCorrectionStatus.BUSY\n \n # Other global variables\n self.last_original_simple_goal_stamp = None\n self.nav_corr_status = actionlib.GoalStatus.PENDING\n self.cancel_goal_pending_to_attend = False\n self.move_base_action_client = None\n self.is_rplidar_stopped = False\n self.rplidar_idle_start_time = rospy.Time.now()\n\n \n\n # ==================================================\n # Topics and services callback functions\n # ==================================================\n def simple_goal_callback(self,msg):\n self.original_simple_goal = msg\n \n def global_path_callback(self,msg):\n self.global_path = msg.poses\n\n def odom_c_status_callback(self,msg):\n self.odom_c_status = msg.status\n \n def cancel_goal_srv_callback(self,req):\n # If goal is in progress in the move_base ActionServer\n if self.move_base_action_client.get_state() == actionlib.GoalStatus.ACTIVE:\n # Send a cancel goal request to the ActionServer\n self.move_base_action_client.cancel_goal()\n # If goal is in internal processing and not sent yet to the ActionServer\n else: \n # Set the cancel goal flag\n self.cancel_goal_pending_to_attend = True\n return []\n \n \n \n \n # ==================================================\n # Update function\n # ==================================================\n def update(self):\n \n # Check if we received a new goal\n is_new_goal = False\n if self.original_simple_goal != None:\n if self.last_original_simple_goal_stamp == None:\n is_new_goal = True\n self.last_original_simple_goal_stamp = self.original_simple_goal.header.stamp\n else: \n if self.original_simple_goal.header.stamp > self.last_original_simple_goal_stamp:\n is_new_goal = True\n self.last_original_simple_goal_stamp = self.original_simple_goal.header.stamp\n elif self.original_simple_goal.header.stamp < self.last_original_simple_goal_stamp:\n rospy.loginfo(\"vva_navigation_correction: Requested goal ignored. Timestamp is older than previously sent goal.\")\n \n # If a new goal was received, process and send it to move_base\n if is_new_goal:\n \n # Publish status\n self.nav_corr_status = actionlib.GoalStatus.ACTIVE\n goal_status_message = NavCorrectionStatus()\n goal_status_message.header.stamp = rospy.Time.now()\n goal_status_message.status = self.nav_corr_status\n self.nav_corr_status_pub.publish(goal_status_message)\n \n # If RPLidar is stopped, start it\n if self.is_rplidar_stopped and self.using_hw_rplidar:\n # Start the RPLidar motor\n try:\n rospy.loginfo(\"vva_navigation_correction: Starting the motor of RPLidar\")\n srv_start_rplidar_motor = rospy.ServiceProxy(self.start_lidar_service_name, Empty)\n srv_start_rplidar_motor()\n self.is_rplidar_stopped = False\n # ~ rospy.loginfo(\"vva_navigation_correction: Waiting 3 seconds...\")\n # ~ rospy.sleep(3)\n except rospy.ServiceException as e:\n rospy.logwarn(\"vva_navigation_correction: Service failed: \" + str(e))\n \n rospy.loginfo(\"vva_navigation_correction: Sending originally requested goal to move_base...\")\n goal_result = self.send_simple_goal(self.original_simple_goal)\n\n # Hold until goal is completed or failed\n \n rospy.loginfo(\"vva_navigation_correction: Originally requested goal result: %s\", self.goal_status2text(goal_result))\n\n if goal_result == actionlib.GoalStatus.ABORTED:\n\n # Get a new goal, closer than the original one:\n # The distance between poses of the Global Path is 0.025 meters,\n # except for the distance between the first two and the last 3 poses which may vary.\n \n global_path_lenght = len(self.global_path)\n \n if global_path_lenght > self.closer_goal_path_poses:\n \n # Publish status\n self.nav_corr_status_pub.publish(goal_status_message)\n\n # Send a closer goal\n closer_goal = self.global_path[self.closer_goal_path_poses]\n rospy.loginfo(\"vva_navigation_correction: Sending a closer goal to move_base...\")\n goal_result = self.send_simple_goal(closer_goal)\n \n # Hold until goal is completed or failed\n \n rospy.loginfo(\"vva_navigation_correction: Closer goal result: %s\", self.goal_status2text(goal_result))\n \n if goal_result == actionlib.GoalStatus.SUCCEEDED:\n # Send again the original goal.\n # Update the original_simple_goal timestamp so it will be sent again\n self.original_simple_goal.header.stamp = rospy.Time.now()\n else:\n self.nav_corr_status = goal_result\n \n else:\n rospy.logwarn('vva_navigation_correction: Could not find a closer goal to unstuck the robot. The global path is shorter than the configured \"closer_goal_path_poses\".')\n rospy.logwarn('vva_navigation_correction: closer_goal_path_poses: %d, global path lenght: %d ', self.closer_goal_path_poses, global_path_lenght)\n self.nav_corr_status = goal_result\n \n else:\n self.nav_corr_status = goal_result\n \n # Start counting the time to put RPLidar in idle state (stop motor)\n self.rplidar_idle_start_time = rospy.Time.now()\n \n \n # If there is no any new goal to process, count idle time to stop the RPLidar motor\n elif not self.is_rplidar_stopped and self.using_hw_rplidar:\n if (rospy.Time.now() - self.rplidar_idle_start_time).to_sec() >= self.rplidar_idle_time:\n # Stop the RPLidar motor\n try:\n rospy.loginfo(\"vva_navigation_correction: Stopping the motor of RPLidar\")\n srv_stop_rplidar_motor = rospy.ServiceProxy(self.stop_lidar_service_name, Empty)\n srv_stop_rplidar_motor()\n self.is_rplidar_stopped = True\n except rospy.ServiceException as e:\n rospy.logwarn(\"vva_navigation_correction: Service failed: \" + str(e))\n \n\n # Publish status\n goal_status_message = NavCorrectionStatus()\n goal_status_message.header.stamp = rospy.Time.now()\n goal_status_message.status = self.nav_corr_status\n self.nav_corr_status_pub.publish(goal_status_message)\n\n\n\n # ==================================================\n # Send simple goal\n # Desc: uses actionlib to send a goal to move_base,\n # this function pauses the main thread of the node\n # until the goal is either reached or failed.\n # Attrib:\n # simple_goal - Type: geometry_msgs/PoseStamped\n # ==================================================\n def send_simple_goal(self, simple_goal):\n \n if self.use_odom_correction_status:\n # Wait for vva_odom_correction to finish the odometry restart procedures\n rospy.loginfo('vva_navigation_correction: Waiting for \"vva_odom_correction\" to finish the odometry restart procedures...')\n while self.odom_c_status == OdomCorrectionStatus.BUSY:\n rospy.sleep(0.5)\n \n # Clear the costmaps and wait 2 seconds before sending the goal\n try:\n rospy.loginfo(\"vva_navigation_correction: Clearing costmaps\")\n srv_clear_costmaps = rospy.ServiceProxy(self.clear_costmaps_service_name, Empty)\n srv_clear_costmaps()\n rospy.loginfo(\"vva_navigation_correction: Waiting 2 seconds...\")\n rospy.sleep(2)\n except rospy.ServiceException as e:\n rospy.logwarn(\"vva_navigation_correction: Service failed: \" + str(e))\n\n # Check if a cancel goal request was received\n if self.cancel_goal_pending_to_attend:\n rospy.loginfo('vva_navigation_correction: Goal cancelled.')\n self.cancel_goal_pending_to_attend = False\n return actionlib.GoalStatus.RECALLED\n\n # Send the goal to the move_base ActionServer\n goal = move_base_msgs.msg.MoveBaseGoal()\n goal.target_pose.header.frame_id = simple_goal.header.frame_id\n goal.target_pose.header.stamp = simple_goal.header.stamp\n goal.target_pose.pose = simple_goal.pose\n \n rospy.loginfo('vva_navigation_correction: Sending goal (x=%.2f, y=%.2f, rot_z=%.2f, rot_w=%.2f) in \"%s\" frame.', goal.target_pose.pose.position.x,\n goal.target_pose.pose.position.y, goal.target_pose.pose.orientation.z, goal.target_pose.pose.orientation.w,\n goal.target_pose.header.frame_id)\n self.move_base_action_client.send_goal(goal)\n\n self.move_base_action_client.wait_for_result()\n \n return self.move_base_action_client.get_state()\n \n \n # ==================================================\n # Translate goal status code to text\n # ==================================================\n def goal_status2text(self, goal_result):\n if goal_result == actionlib.GoalStatus.PENDING:\n return \"Pending\"\n if goal_result == actionlib.GoalStatus.ACTIVE:\n return \"Active\"\n if goal_result == actionlib.GoalStatus.ABORTED:\n return \"Aborted\"\n if goal_result == actionlib.GoalStatus.SUCCEEDED:\n return \"Succeeded\"\n \n return str(goal_result)\n\n\n # ==================================================\n # Main loop\n # ==================================================\n def spin(self):\n rospy.loginfo(\"vva_navigation_correction: Start\")\n rate = rospy.Rate(self.rate)\n rospy.on_shutdown(self.shutdown)\n \n # Initialize the ActionClient for move_base\n self.move_base_action_client = actionlib.SimpleActionClient('move_base', move_base_msgs.msg.MoveBaseAction)\n rospy.loginfo(\"vva_navigation_correction: Waiting for move_base ActionServer to connect...\")\n self.move_base_action_client.wait_for_server()\n rospy.loginfo(\"vva_navigation_correction: move_base ActionServer connected\")\n \n if self.using_hw_rplidar:\n rospy.loginfo(\"vva_navigation_correction: Waiting for %s service to be started...\", self.stop_lidar_service_name)\n rospy.wait_for_service(self.stop_lidar_service_name)\n rospy.loginfo(\"vva_navigation_correction: %s service started.\", self.stop_lidar_service_name)\n\n while not rospy.is_shutdown():\n self.update()\n rate.sleep()\n rospy.spin()\n\n\n # ==================================================\n # If shutdown\n # ==================================================\n\n def shutdown(self):\n rospy.loginfo(\"vva_navigation_correction: Stop. CHAO PESCAO!\")\n # Stop message\n rospy.sleep(1)\n \n\n# ==================================================\n# Main\n# ==================================================\ndef main():\n navigation_correction = NavigationCorrection()\n navigation_correction.spin()\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n","sub_path":"VVA_ws/src/vva_navigation/src/vva_navigation_correction.py","file_name":"vva_navigation_correction.py","file_ext":"py","file_size_in_byte":14925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"602615271","text":"import numpy as np\nimport dataset\nimport pandas as pd\n\n\"\"\"\nInsert into csv the names of the different shrec11 labels,\nand for each shows the names of the models that are relevant. \n\"\"\"\n\nshrec11_labels = [\n 'armadillo', 'man', 'centaur', 'dinosaur', 'dog2',\n 'ants', 'rabbit', 'dog1', 'snake', 'bird2',\n 'shark', 'dino_ske', 'laptop', 'santa', 'flamingo',\n 'horse', 'hand', 'lamp', 'two_balls', 'gorilla',\n 'alien', 'octopus', 'cat', 'woman', 'spiders',\n 'camel', 'pliers', 'myScissor', 'glasses', 'bird1'\n]\n\n\ndef genertate_csv(filenames_, name: str):\n filenames = []\n files_labels = []\n data = {shrec11_labels[i]: list() for i in range(len(shrec11_labels))}\n for fn in filenames_:\n mesh_data = np.load(fn, encoding='latin1', allow_pickle=True)\n data[shrec11_labels[mesh_data['label']]].append(fn)\n #label_name = shrec11_labels[mesh_data['label']]\n #filenames.append(fn)\n #files_labels.append(label_name)\n #data = {'File name': filenames, 'Label': files_labels}\n csv_data = pd.DataFrame.from_dict(data, orient=\"index\")\n csv_data.to_csv(\"files and labels \" + name + \".csv\")\n return\n\n\ndef tf_mesh_dataset(params, pathname_expansion, min_max_faces2use=[0, np.inf], data_augmentation={}, name: str = \"train\"):\n params_idx = dataset.setup_dataset_params(params, data_augmentation)\n number_of_features = dataset.dataset_params_list[params_idx].number_of_features\n params.net_input_dim = number_of_features\n\n filenames = dataset.get_file_names(pathname_expansion, min_max_faces2use)\n genertate_csv(filenames, name)\n\n return\n\n","sub_path":"Desktop/MeshWalker_UnsupervisedLearning-main/split_data_classes_folders.py","file_name":"split_data_classes_folders.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"305574049","text":"# 數字運算\n# 除法有兩種: 整數除法和小數除法(如果除不近,會幫你除到小數)\nx = 3 + 6\ny = 3 * 6\nz = 10 / 3 # 小數除法\nz2 = 10 // 3 # 整數除法\nprint(x)\nprint(y)\nprint(z)\nprint(z2)\n# 2的3次方\na = 2 ** 3\nprint(a)\n# 開根號就用0.5次方\na = 9 ** 0.5\nprint(a)\n# 取餘數 mod\nb = 7 % 3\nprint(b)\n\n# 進階運算\nn1 = 2 + 3\nn1 = n1 + 1 # 將變數中的數字 +1 ,更簡便的表示法: n1 + = 1\nprint(n1) \n\n# 字串運算\ns = \"Hello\" # 字串可用雙引號表示\ns1 = 'World' # 也可用單引號表示\ns2 = \"Hello\\\"Claudia\\\"\" # 文字裡面會想要使用雙引號,但是雙引號會跟外面邏輯衝突,所以雙引號前面加上\\代表跳脫,雙引號就可以被顯示\ns3 = \"Hello\" + \"World\" # 字串串接用加法符號\ns4 = \"Hello\" \" World\" # 也可用空白代表字串串接\ns5 = \"Hello\\nWorld\" # 表達很多行的字,\\n代表換行\ns6 = \"\"\"Hello\nWorld\"\"\" # 也可用三個雙引號,就可以直接換行\ns7 = '''Hello\nWorld''' # 或者三個單引號,也可以直接換行\ns8 = \"Hello\" * 3 # 透過*號把文字重複\n# 字串會對內部的字元編號(索引),從0開始算起,H:0 e:1\n# s[1:4]可以取得子字串,包含開頭不包含結尾,所以是ell\n# s[1:],不給結尾代表從開頭算起取到全部:ello\n# s[:4],不算結尾之前的全部:Hell\nprint(s[:4])","sub_path":"3-number-string.py","file_name":"3-number-string.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"648999341","text":"from flask import Flask\nfrom flask_mail import Mail\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\nfrom flask_bcrypt import Bcrypt\nfrom itsdangerous import URLSafeTimedSerializer\nfrom datetime import timedelta\nfrom flask_compress import Compress\n\ncompress = Compress()\n\napp = Flask(__name__)\napp.config.from_object('config')\n\napp.config.update(dict(\n DEBUG = True,\n MAIL_SERVER = 'smtp.gmail.com',\n MAIL_PORT = 587,\n MAIL_USE_TLS = True,\n MAIL_USE_SSL = False,\n MAIL_USERNAME = 'jake.frey94@gmail.com',\n MAIL_PASSWORD = 'go100994',\n))\n\nmail = Mail(app)\n\ndb = SQLAlchemy(app)\napp.secret_key = 'super secret key'\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"login\"\nlogin_serializer = URLSafeTimedSerializer(app.secret_key)\napp.config[\"REMEMBER_COOKIE_DURATION\"] = timedelta(days=14)\n\nbcrypt = Bcrypt(app)\ncompress.init_app(app)\n\nfrom app import views, models\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"337704002","text":"class Parser:\n def __init__(self, input_file):\n print(\"Initializing the parser...\")\n if not input_file.endswith(\".vm\"):\n raise Exception(\"Parser only works with .vm extention files\")\n \n self.vm_file = open(input_file, \"r\")\n \n\n self.current_command = None\n self.current_command_type = None\n\n #private properties\n self.current_line = None\n self.current_line_type = 'INIT'\n\n self.advance()\n\n def hasMoreCommands(self):\n if self.current_line_type != 'EOF':\n return True\n else:\n return False\n\n def advance(self):\n while self.current_line_type != 'EOF':\n self.advance_line()\n if self.current_line_type == 'COMMAND':\n self.current_command = self.current_line\n self.current_command_type = self.commandType()\n return self.current_command\n \n return 'You have advanced to the EOF' \n\n \n def advance_line(self):\n \n line = self.vm_file.readline()\n \n if not line:\n self.current_line = None\n self.current_line_type = 'EOF'\n return 'You have advanced to the EOF'\n \n if line.isspace():\n self.current_line = line\n self.current_line_type = 'SPACE'\n return 'You have advanced to a space'\n\n #remove everything to the right of comment symbol\n comment_index = line.find('//')\n if comment_index != -1:\n line = line[:comment_index]\n if line.isspace() or not line:\n self.current_line = '//'\n self.current_line_type = 'COMMENT'\n return 'You have advanced to a comment line'\n\n \n\n self.current_line = line.strip()\n self.current_line_type = 'COMMAND'\n return self.current_line\n\n \n\n #this should only be allowed to be called on a command\n def commandType(self):\n command_array = self.current_command.split()\n if len(command_array) == 1:\n if command_array[0] == 'return':\n return 'C_RETURN'\n \n return 'C_ARITHMETIC'\n \n if len(command_array) == 2:\n if command_array[0] == 'label':\n return 'C_LABEL'\n if command_array[0] == 'goto':\n return 'C_GOTO'\n if command_array[0] == 'if-goto':\n return 'C_IF'\n\n if len(command_array) == 3:\n if command_array[0] == 'push':\n return 'C_PUSH'\n if command_array[0] == 'pop':\n return 'C_POP'\n if command_array[0] == 'function':\n return 'C_FUNCTION'\n if command_array[0] == 'call':\n return 'C_CALL'\n \n \n \n def arg1(self):\n #returns the first arguments of the current command. in the case \n command_array = self.current_command.split()\n if len(command_array) == 3 or len(command_array) == 2:\n return command_array[1]\n \n \n\n if len(command_array) == 1:\n return command_array[0]\n\n return 'arg1'\n\n def arg2(self):\n #returns the second argument of the current command\n command_array = self.current_command.split()\n if len(command_array) == 3:\n return command_array[2]\n \n \n return 'arg2'\n \n \n\n \n","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"163094369","text":"'''\r\nRefactoring tests.\r\n'''\r\n\r\nimport os\r\nimport sys\r\n#make it as if we were executing from the directory above this one (so that we can use pycompletionserver\r\n#without the need for it being in the pythonpath)\r\nsys.argv[0] = os.path.dirname(sys.argv[0]) \r\n#twice the dirname to get the previous level from this file.\r\nsys.path.insert(1, os.path.join( os.path.dirname( sys.argv[0] )) )\r\n\r\n\r\nimport unittest\r\ntry:\r\n import refactoring\r\nexcept ImportError:\r\n pass #That's ok -- not available in jython\r\n\r\n#===============================================================================\r\n# delete\r\n#===============================================================================\r\ndef delete(filename):\r\n '''Removes filename, or does nothing if the file doesn't exist.\r\n '''\r\n try:\r\n os.remove(filename)\r\n except OSError:\r\n pass\r\n\r\n#================================================================================\r\n# createFile \r\n#================================================================================\r\ndef createFile(filename, contents='', flag='w'):\r\n '''Creates the given filename with the given contents.\r\n '''\r\n f = open(filename, flag)\r\n f.write(contents)\r\n f.close()\r\n\r\nFILE = 'temporary_file.py'\r\n\r\ndef getInitialFile():\r\n s = \\\r\n'''\r\nclass C:\r\n def a(self):\r\n a = 2\r\n b = 3\r\n c = a+b #this should be refactored.\r\n return c\r\nc = C()\r\n'''\r\n return s\r\n\r\n\r\ndef getRenameRefactored():\r\n s = \\\r\n'''\r\nclass G:\r\n def a(self):\r\n a = 2\r\n b = 3\r\n c = a+b #this should be refactored.\r\n return c\r\nc = G()\r\n'''\r\n return s\r\n \r\nclass Test(unittest.TestCase):\r\n\r\n \r\n def getRefactoredFile(self):\r\n s = \\\r\n'''\r\nclass C:\r\n def a(self):\r\n a = 2\r\n b = 3\r\n c = self.plusMet(a, b) #this should be refactored.\r\n return c\r\n\r\n def plusMet(self, a, b):\r\n return a+b\r\nc = C()\r\n'''\r\n return s\r\n\r\n def setUp(self):\r\n unittest.TestCase.setUp(self)\r\n createFile(FILE, getInitialFile())\r\n\r\n def tearDown(self):\r\n unittest.TestCase.tearDown(self)\r\n delete(FILE)\r\n \r\n def testExtractMethod(self):\r\n r = refactoring.Refactoring()\r\n s = r.extractMethod(FILE, 5+1, 12, 5+1, 12+3, 'plusMet')\r\n\r\n f = file(FILE, 'r')\r\n contents = f.read()\r\n f.close()\r\n\r\n self.assertEquals(self.getRefactoredFile(), contents)\r\n\r\n def testRename(self):\r\n r = refactoring.Refactoring()\r\n s = r.renameByCoordinates(FILE, 1+1, 6, 'G')\r\n\r\n f = file(FILE, 'r')\r\n contents = f.read()\r\n f.close()\r\n\r\n self.assertEquals(getRenameRefactored(), contents)\r\n\r\n# def testRename2(self):\r\n# r = refactoring.Refactoring()\r\n# s = r.renameByCoordinates(FILE, 7+1, 4, 'G')\r\n#\r\n# f = file(FILE, 'r')\r\n# contents = f.read()\r\n# f.close()\r\n#\r\n# print_ contents\r\n# self.assertEquals(getRenameRefactored(), contents)\r\n\r\n def testFind(self):\r\n r = refactoring.Refactoring()\r\n s = r.findDefinition(FILE, 7+1, 4)\r\n \r\n s = s.replace('[(','').replace(')]','').split(',')\r\n self.assert_( s[0].endswith('temporary_file.py'))\r\n self.assertEquals('2', s[1]) #line\r\n self.assertEquals('6', s[2]) #col\r\n self.assertEquals('100', s[3]) #accuracy\r\n\r\n createFile(FILE, getFindFile())\r\n s = r.findDefinition(FILE, 5+1, 2)\r\n s1 = r.findDefinition(FILE, 5+1, 3)\r\n s2 = r.findDefinition(FILE, 5+1, 4)\r\n self.assert_(s == s1 == s2)\r\n\r\ndef getFindFile():\r\n s = \\\r\n'''\r\nclass C:\r\n def aaa(self):\r\n return 0\r\nc = C()\r\nc.aaa()\r\n'''\r\n return s\r\n \r\nif __name__ == '__main__':\r\n try:\r\n refactoring\r\n except NameError:\r\n sys.stdout.write('Not running python tests in platform: %s (unable to import refactoring)\\n' % (sys.platform,))\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":"spell/branches/1.5/spel-dev/bin/plugins/org.python.pydev_1.4.2/PySrc/tests/test_refactoring.py","file_name":"test_refactoring.py","file_ext":"py","file_size_in_byte":4064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"430432238","text":"##\ndef isQueueFull():\n global SIZE, queue, front, rear\n if (rear == SIZE-1):\n return True\n else:\n return False\n\ndef isQueueEmpty():\n global SIZE, queue, front, rear\n if (front == rear):\n return True\n else:\n return False\n\ndef enQueue(data):\n global SIZE, queue, front, rear\n if (isQueueFull()):\n # print(\"Full\")\n return\n rear += 1\n queue[rear] = data\n\ndef deQueue():\n global SIZE, queue, front, rear\n if (isQueueEmpty()):\n # print(\"Empty\")\n return None\n front += 1\n data = queue[front]\n queue[front] = None\n\n for i in range(front + 1, SIZE):\n queue[i - 1] = queue[i]\n queue[i] = None\n front -= 1\n rear -= 1\n\n return data\n\ndef peek():\n global SIZE, queue, front, rear\n if (isQueueEmpty()):\n # print(\"Empty\")\n return None\n return queue[front+1]\n\n##\nSIZE = 5\nqueue = [None for i in range(SIZE)]\nfront = rear = -1\n\n##\nif __name__ == \"__main__\":\n enQueue('정국')\n enQueue('뷔')\n enQueue('지민')\n enQueue('진')\n enQueue('슈가')\n print('대기 줄 상태 : ', queue)\n\n for i in range(rear+1):\n print(deQueue(), '님이 식당에 들어감')\n print('대기 줄 상태 : ', queue)\n\n print(\"식당 영업 종료\")","sub_path":"07-99-exam-01-01-my.py","file_name":"07-99-exam-01-01-my.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"497947886","text":"import joblib\n\nfrom taxifare.mlflow import MLFlowBase\nfrom taxifare.data import get_data, clean_data, holdout\nfrom taxifare.model import get_model\nfrom taxifare.pipeline import get_pipeline\nfrom taxifare.metrics import compute_rmse\n\nclass Trainer(MLFlowBase):\n def __init__(self):\n super().__init__(\n '[DE] [Munich] [bruncky] taxifare v1.1',\n 'https://mlflow.lewagon.co'\n )\n\n def train(self):\n model_name = 'random_forest'\n line_count = 1000\n\n # Get data\n data = get_data()\n data = clean_data(data)\n\n # Holdout\n X_train, X_test, y_train, y_test = holdout(data)\n\n # Get model\n model = get_model(model_name)\n\n # Get pipeline\n pipeline = get_pipeline(model)\n\n # Train\n pipeline.fit(X_train, y_train)\n\n # Make a prediction\n y_pred = pipeline.predict(X_test)\n\n # Compute RMSE\n rmse = compute_rmse(y_pred, y_test)\n\n # Save model\n joblib.dump(pipeline, 'trained_model.joblib')\n\n # ---------- MLFlow ----------\n\n # Create run\n self.mlflow_create_run()\n\n # Log params\n self.mlflow_log_param('model', model)\n self.mlflow_log_param('line_count', line_count)\n\n # Log metrics\n self.mlflow_log_metric('rmse', rmse)\n\n return pipeline\n","sub_path":"taxifare/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"171187330","text":"\"\"\"\nMicroNFCBoard Python API\n\nCopyright (c) 2014-2015 AppNearMe Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nfrom array import array\n\nfrom interface import INTERFACE, usb_backend\nfrom transport import Transport\n\nfrom nfc.ndef import URIRecord, TextRecord, SmartPosterRecord, MIMERecord\n\nVID = 0x1FC9 #NXP VID\nPID = 0x8039 #Attributed to AppNearMe\n\nTARGET_FIRMWARE = (1,2)\n\nSTATUS_POLLING = (1 << 0)\nSTATUS_CONNECTED = (1 << 1)\nSTATUS_NDEF_PRESENT = (1 << 2)\n\nSTATUS_TYPE1 = (1 << 8)\nSTATUS_TYPE2 = (2 << 8)\nSTATUS_TYPE3 = (3 << 8)\nSTATUS_TYPE4 = (4 << 8)\n\nSTATUS_INITIATOR = (1 << 16)\nSTATUS_TARGET = (0 << 16)\n\nCHUNK_SIZE = 40\n\nTEXT_ENCODING = {0: \"utf-8\", 1: \"utf-16\"}\n\nclass MicroNFCBoard(object):\n @staticmethod\n def getBoard(number = 0):\n a = INTERFACE[usb_backend].getAllConnectedInterface(VID, PID)\n if((a != None) and (len(a) > number)):\n return MicroNFCBoard(a[number])\n return None\n \n @staticmethod\n def getAllBoards():\n return [MicroNFCBoard(i) for i in INTERFACE[usb_backend].getAllConnectedInterface(VID, PID)]\n \n def __init__(self, intf):\n self._intf = intf\n self._transport = Transport()\n self._id = None\n self._version = None\n self._polling = False\n self._connected = False\n self._ndefMessagePresent = False\n self._ndefRecords = None\n self._ndefRead = False\n \n def open(self):\n self._transport.open(self._intf)\n version, revision, self._id = self._transport.info()\n self._version = (version, revision)\n \n def close(self):\n self._transport.close()\n \n @property\n def id(self):\n return self._id\n \n @property\n def connected(self):\n self._updateStatus()\n return self._connected\n \n @property\n def polling(self):\n self._updateStatus()\n return self._polling\n \n @property\n def ndefMessagePresent(self):\n self._updateStatus()\n return self._ndefMessagePresent\n \n @property\n def ndefRecords(self):\n self._updateStatus()\n if self._ndefMessagePresent and not self._ndefRead:\n self._ndefRecords = self._getNdefMessageRecords()\n self._ndefRecordsRead = True\n return self._ndefRecords\n \n @property\n def version(self):\n return self._version\n \n def getNfcInfo(self):\n return self._transport.nfcGetInfo()\n \n def reset(self):\n self._transport.reset(False)\n \n def startPolling(self):\n self._transport.nfcPoll(True)\n \n def stopPolling(self):\n self._transport.nfcPoll(True)\n \n def setLeds(self, led1, led2):\n self._transport.leds(led1, led2)\n \n def _updateStatus(self):\n status = self._transport.status()\n self._polling = (status & STATUS_POLLING) != 0\n self._connected = (status & STATUS_CONNECTED) != 0\n self._ndefMessagePresent = (status & STATUS_NDEF_PRESENT) != 0\n if not self._ndefMessagePresent:\n self._ndefRecordsRead = False\n \n def _getNdefRecords(self, start, count):\n records = []\n for recordNumber in range(start, start+count):\n #Get records info\n recordType, recordInfo = self._transport.nfcGetRecordInfo(recordNumber)\n funcs = { 0 : self._parseUnknownRecord,\n 1 : self._parseURIRecord,\n 2 : self._parseTextRecord,\n 3 : self._parseSmartPosterRecord,\n 4 : self._parseMIMERecord,\n }\n record = funcs[recordType](recordNumber, recordInfo)\n if record != None:\n records += [record]\n return records\n \n def _getNdefMessageRecords(self): \n #Get message count\n recordsCount = self._transport.nfcGetMessageInfo()\n return self._getNdefRecords(0, recordsCount)\n \n def _parseUnknownRecord(self, recordNumber, recordInfo):\n return None\n \n def _parseURIRecord(self, recordNumber, recordInfo):\n uriLength = recordInfo[0]\n uri = unicode(self._getRecordData(recordNumber, 0, uriLength).tostring(), \"utf-8\")\n return URIRecord(uri)\n \n def _parseTextRecord(self, recordNumber, recordInfo):\n encoding = TEXT_ENCODING[recordInfo[0]]\n languageCodeLength = recordInfo[1]\n textLength = recordInfo[2]\n languageCode = unicode(self._getRecordData(recordNumber, 0, languageCodeLength).tostring(), \"utf-8\")\n text = unicode(self._getRecordData(recordNumber, 1, textLength).tostring(), encoding)\n return TextRecord(text, languageCode)\n \n def _parseSmartPosterRecord(self, recordNumber, recordInfo):\n recordsStart = recordInfo[0]\n recordsCount = recordInfo[1]\n records = self._getNdefRecords(recordsStart, recordsCount)\n return SmartPosterRecord(records)\n \n def _parseMIMERecord(self, recordNumber, recordInfo):\n mimeTypeLength = recordInfo[0]\n dataLength = recordInfo[1]\n mimeType = unicode(self._getRecordData(recordNumber, 0, mimeTypeLength).tostring(), \"utf-8\")\n data = self._getRecordData(recordNumber, 1, dataLength)\n return MIMERecord(mimeType, data)\n \n def _getRecordData(self, recordNumber, item, itemLength):\n buf = array(\"B\")\n while len(buf) < itemLength:\n chunkLength = min(CHUNK_SIZE, itemLength - len(buf))\n buf += self._transport.nfcGetRecordData(recordNumber, item, len(buf), chunkLength)\n return buf\n ","sub_path":"micronfcboard/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":6163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"507140369","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\nimport numpy as np\r\nimport imgaug.augmenters as iaa\r\n\r\n\r\ndef augment():\r\n return iaa.SomeOf((0, 4), [\r\n # iaa.Add((-50, 50)),\r\n iaa.CropAndPad(percent=(-0.4, 0.4)),\r\n iaa.Fliplr(0.5),\r\n iaa.Flipud(0.5),\r\n iaa.Affine(scale={\"x\": (0.85, 1.15), \"y\": (0.85, 1.15)},\r\n translate_percent={\"x\": (-0.15, 0.15), \"y\": (-0.15, 0.15)},\r\n rotate=(-90, 90)),\r\n iaa.SomeOf((1, 3), [\r\n iaa.Dropout(p=(0.01, 0.2)),\r\n iaa.GaussianBlur(sigma=(0.0, 1.5)),\r\n iaa.AverageBlur(k=(3, 7)),\r\n # iaa.MedianBlur(k=(3, 7)),\r\n iaa.MotionBlur(k=(3, 7)),\r\n iaa.AdditiveGaussianNoise(scale=(0, 0.1 * 255)),\r\n iaa.SaltAndPepper(p=0.2),\r\n iaa.GammaContrast((0.5, 2.0))\r\n ])\r\n ], random_order=True)\r\n\r\n\r\ndef data_augment(images, masks):\r\n aug = augment()\r\n images, masks = aug.augment(images=images, segmentation_maps=masks)\r\n return images, masks\r\n\r\n\r\n\r\n","sub_path":"keras/data_augmentation.py","file_name":"data_augmentation.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"63552998","text":"import sdp_transform\nimport logging\nimport time\nimport subprocess\nimport threading\nfrom callbase import CallBase\nfrom commands import Commands\n\n\nclass TranscodedCall(CallBase):\n\n def __init__(self, start, end, **kwargs):\n super().__init__(\n local_address=kwargs.get('local_address', None),\n protocol=kwargs.get('protocol', None),\n rtpe_address=kwargs.get('rtpe_address', None),\n rtpe_port=kwargs.get('rtpe_port', None)\n )\n self.start = start\n self.end = end\n self.call_id = f'{str(self.start)}-{str(self.end)}'\n self.from_tag = f'from-tag{str(self.start)}'\n self.to_tag = f'to-tag{str(self.start)}'\n \n self.file1 = kwargs.get('file1', None)\n self.file2 = kwargs.get('file2', None)\n\n self.codec1 = kwargs.get('codec1', None)\n self.codec2 = kwargs.get('codec2', None)\n self.running = False\n\n # Transcoded specific sdp PCMU, speex\n def generate_sdp(self, address, port, codec):\n if codec == \"0 101\":\n sdp_dict = {\n \"version\":0,\n \"origin\":{\n \"address\": address,\n \"username\":123,\n \"sessionId\":3092,\n \"sessionVersion\":1,\n \"netType\":\"IN\",\n \"ipVer\":4,\n },\n \"name\":\"Talk\",\n \"connection\":{ \"version\":4, \"ip\":address},\n \"timing\":{\"start\":0,\"stop\":0},\n \"media\":[\n {\n \"rtp\":[{\"payload\":101,\"codec\":\"telephone-event\",\"rate\":8000}],\n \"fmtp\":[],\n \"type\":\"audio\",\n \"port\":port,\n \"protocol\":\"RTP/AVP\",\n \"payloads\":\"0 101\",\n }\n ]\n }\n if codec == '96':\n sdp_dict = {\n \"version\":0,\n \"origin\":{\n \"address\":address,\n \"username\":456,\n \"sessionId\":2278,\n \"sessionVersion\":1,\n \"netType\":\"IN\",\n \"ipVer\":4,\n },\n \"name\":\"Talk\",\n \"connection\":{\"version\":4,\"ip\":address},\n \"timing\":{\"start\":0,\"stop\":0},\n \"media\":[\n {\n \"rtp\":[{\"payload\":96, \"codec\":\"speex\",\"rate\":16000}],\n \"fmtp\":[{\"payload\":96,\"config\":\"vbr=on\"}],\n \"type\":\"audio\",\n \"port\":port,\n \"protocol\":\"RTP/AVP\",\n \"payloads\":96,\n }\n ]\n }\n\n return sdp_transform.write(sdp_dict)\n\n # Send offer to rtpengine\n def offer(self):\n options = {\n \"ICE\": \"remove\", \n \"label\": \"caller\",\n \"supports\": [\"load limit\"],\n \"flags\": [\"SIP-source-address\"],\n \"replace\": [\"origin\", \"session-connection\"],\n \"received-from\": [\"IP4\", \"127.0.0.1\"],\n \"codec\": { \"mask\": [\"all\"], \"transcode\": [\"PCMU\", \"speex\"]}\n }\n command = Commands.offer(\n self.generate_sdp('127.0.0.1', self.start, \"0 101\"),\n self.call_id, self.from_tag, **options\n )\n data = super().ws_send(command) if super().__getattribute__('protocol') == 'ws' else super().send(command, self.start)\n if not data: return Exception(\"No data come back from rtpengine (answer)\")\n if 'sdp' not in data: return Exception(f'There is no sdp part in response: {data}')\n sdp_data = sdp_transform.parse(data[\"sdp\"])\n return sdp_data['media'][0]['port']\n\n # Send answer to rtpengine\n def answer(self):\n options = {\n \"ICE\": \"remove\", \n \"label\": \"caller\",\n \"supports\": [\"load limit\"],\n \"flags\": [\"SIP-source-address\"],\n \"replace\": [\"origin\", \"session-connection\"],\n \"received-from\": [\"IP4\", \"127.0.0.1\"],\n \"codec\": { \"mask\": [\"all\"], \"transcode\": [\"PCMU\", \"speex\"]}\n }\n command = Commands.answer(\n self.generate_sdp('127.0.0.1', self.end, \"96\"),\n self.call_id, self.from_tag, self.to_tag, **options\n )\n data = super().ws_send(command) if super().__getattribute__('protocol') == 'ws' else super().send(command, self.end)\n if not data: return Exception(\"No data come back from rtpengine (answer)\")\n if 'sdp' not in data: return Exception(f'There is no sdp part in response: {data}')\n sdp_data = sdp_transform.parse(data[\"sdp\"])\n return sdp_data['media'][0]['port']\n\n def delete(self):\n super().delete(self.call_id, self.from_tag, self.start)\n\n # Set up a call \n def generate_call(self, wait):\n self.running = True\n rtpe_address = super().__getattribute__('rtpe_address')\n start_time = time.time()\n\n o_rtp = self.offer()\n if isinstance(o_rtp, Exception): return o_rtp\n logging.debug(f'Offer with callid: {self.call_id} created in {int((time.time() - start_time) * 1000)} ms')\n \n a_rtp = self.answer()\n if isinstance(a_rtp, Exception): return a_rtp\n logging.info(f'Call with callid: {self.call_id} created in {int((time.time() - start_time) * 1000)} ms')\n\n # Start rtp processes\n ret = [\n subprocess.Popen([\"rtpsend\", \"-s\", str(self.start), \"-f\", self.file1, f'{rtpe_address}/{a_rtp}']),\n subprocess.Popen([\"rtpsend\", \"-s\", str(self.end), \"-f\", self.file2, f'{rtpe_address}/{o_rtp}'])\n ]\n\n # For non-blocking wait\n event = threading.Event()\n event.wait(wait)\n\n return ret\n","sub_path":"client/transcodedcall.py","file_name":"transcodedcall.py","file_ext":"py","file_size_in_byte":5836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"218013844","text":"import csv\nfrom graphviz import *\nimport numpy as np\nfrom sklearn.cluster import *\nimport threading\nimport time\n\n\ndef calc_step(to_remove,size):\n if(size==0):\n return 0,0\n bonus=0\n if(to_remove>size):\n step=to_remove//size\n bonus=to_remove-(step*size)\n else:\n step=1\n assert(step>=0)\n assert(bonus>=0)\n return step,bonus\n\ndef calc_remove(to_remove,step,bonus):\n if(to_remove<=0):\n return 0,0,0\n if(to_remove-step>=0):\n remove=step\n to_remove-=step\n else:\n remove=to_remove\n to_remove=0\n if bonus>0:\n remove+=bonus\n to_remove-=bonus\n assert(to_remove>=0)\n assert(remove>=0)\n return to_remove,remove,0\n\nclass AtomicCounter:\n def __init__(self, initial=0):\n \"\"\"Initialize a new atomic counter to given initial value (default 0).\"\"\"\n self.value = initial\n self._lock = threading.Lock()\n\n def increment(self, num=1):\n \"\"\"Atomically increment the counter by num (default 1) and return the\n new value.\n \"\"\"\n with self._lock:\n self.value += num\n return self.value\n\ninfoset_id=AtomicCounter(-1)\ndef gen_infoset(dict,player):\n global infoset_id\n i=0\n id=str(infoset_id.increment())\n while(player+\".\"+str(i) in dict):\n i=i+1\n return Infoset(player+\".\"+str(i),id)\n\ndef calc_utility(tree_node):\n if(tree_node.line[2]!=\"leaf\"):\n return 0\n utility=float(str(tree_node.line[4]).split(\"=\")[1])\n return utility\n\nclass Infoset:\n def __init__(self, info_string, id):\n self.info_string=info_string\n self.id=id\n self.abstracted_infoset=\"\"\n self.strategy={}\n self.next_strategy={}\n self.actions=set()\n\nclass Tree:\n \"\"\"Struttura ricorsiva che rappresenta un nodo dell'albero\n Contiene informazioni sia degli information set veri e anche astratti\n \"\"\"\n def __init__(self, node_id,children,line,action_label,infoset):\n self.children=children\n self.node_id=node_id\n self.line=line\n self.action_label=action_label\n self.infoset=infoset\n self.action_infoset_label=\"\"\n self.abstracted_infoset=\"\"\n self.abstract_action_infoset_label=\"\"\n\n def isTerminal(self):\n return self.line[2]==\"leaf\"\n\n def isNature(self):\n return self.line[2]==\"chance\"\n\n def build_dot(self,dot,father_id,level,id_dic,fake_id_of,really):\n self.father_id=father_id\n \"\"\" Riempe l'oggetto dot per la parte grafica\"\"\"\n #Decommentare per limitare la dimensione dell'output grafico\n #if(level>5):\n # return\n if really:\n label=self.node_id\n if(self.isNature()):\n label=label+\" Nature\\n \"+str(self.line[4:])\n elif(self.isTerminal()):\n label=label+\" Terminal\\n trace: \"+self.line[1]+\"\\n \"+str(self.line[3:])\n else: #Player node\n player_id=\"Player \"+self.line[3]\n label=label+\" infoset:\"+self.infoset.info_string+\" \"+self.infoset.id+ \" \"+player_id+\"\\n \"+self.line[1]+\"\\n \"+str(self.line[4:])\n\n #Crea un nodo grafico\n dot.node(self.node_id,label)\n\n #Crea il link al padre grafico\n edge_label=(self.action_label+self.action_infoset_label)+\" p=\"\n if(father_id in fake_id_of and self.action_label in fake_id_of[father_id].strategy):\n edge_label+=str(fake_id_of[father_id].strategy[self.action_label])\n dot.edge(father_id, self.node_id,label=edge_label)\n\n #Ripeti sui figli\n for child in self.children:\n child.build_dot(dot,self.node_id,level+1,id_dic,fake_id_of,really)\n\n def fill_infoset_dictionary(self,dict,id_dic,father_infoset):\n \"\"\" Riempie il dizionario degli infoset\"\"\"\n player_id=\"P\"\n id_dic[self.node_id]=self\n if(not self.isTerminal()):#Terminali non hanno information set\n if(not self.isNature()):\n player_id=self.line[3]\n self.player_id=self.line[3]\n else:\n player_id=\"N\"\n\n if(self.infoset==\"NaN\"):#Se non ancora definito crealo\n self.infoset=gen_infoset(dict,player_id)\n if not self.isNature():#TODO controlla che non servissero a qualcosa gli infoset dei natura(no errore promette bene)\n dict[self.infoset]=[self.node_id]\n elif(self.infoset in dict):#Se definito in precedenza aggiungi alla lista questo nodo\n dict[self.infoset].append(self.node_id)\n else:#Se non definito in precedenza crea la lista con solo questo nodo\n dict[self.infoset]=[self.node_id]\n\n #Ripeti\n for child in self.children:\n child.fill_infoset_dictionary(dict,id_dic,self.infoset)\n\n #Nessuno dovrebbe avere questo\n if(father_infoset==\"NaN\"):\n print(self.line)\n\n #Questo assegna le label alle azioni in base all'infoset del padre\n #esempio L1 R1 vs L2 R2\n self.action_infoset_label=str(father_infoset.id)\n\n def fill_sequence_form(self,seq_dic,player_history,probability,natureson,father_player):\n \"\"\"Riempie la tabella della sequence form, non più usata, ignorate\"\"\"\n if(not natureson):\n old=player_history[father_player]\n\n player_history[father_player]=player_history[father_player]+ self.action_label\n\n if(not self.isNature() and not self.isTerminal()):\n #Player node\n player_id=self.line[3]\n for child in self.children:\n child.fill_sequence_form(seq_dic,player_history,probability,False,player_id)\n\n\n elif(self.isTerminal()):\n utility=float(str(self.line[4]).split(\"=\")[1]) * probability\n #Leaf\n\n if(player_history[\"1\"] in seq_dic.keys()):\n seq_dic[player_history[\"1\"]][player_history[\"2\"]]=utility\n else:\n seq_dic[player_history[\"1\"]]={player_history[\"2\"] : utility}\n\n else:\n num_c=len(self.children)\n probs=self.line[4:]\n for i in range(0,len(self.children)):\n my_probability=probability * float(probs[i].split(\"=\")[1])\n self.children[i].fill_sequence_form(seq_dic,player_history,my_probability/num_c,True,\"N\")\n\n if(not natureson):\n player_history[father_player]=old\n\n\n def calculate_outcome_vector(self,out_vector):\n \"\"\"calcola il vettore dei nodi terminali raggiungibili da self\"\"\"\n if(self.isTerminal()):\n out_vector.append(calc_utility(self))\n else:\n for child in self.children:\n child.calculate_outcome_vector(out_vector)\n return out_vector\n\ndef get_grandsons(children_list,skip_nature,player):\n \"\"\"Prende una lista di children e ritorna la concatenazione dei loro figli\n Salta i nodi natura e ritorna i loro rispettivi figli\n \"\"\"\n out=[]\n for child in children_list:\n grandsons=[]\n #out+=child.children\n if(child.isNature() and player==2):\n grandsons+=get_grandsons(child.children,True,2)\n else:\n for grandson in child.children:\n if(grandson.isNature() and player==1):\n grandsons+=grandson.children\n elif(grandson.isNature() and player==2):\n grandsons+=get_grandsons(grandson.children,True,2)\n else:\n grandsons.append(grandson)\n out+=grandsons\n return out\n\ndef cluster_and_recur(actions,infoset_of,fake_infosets,fake_id_of,children,vectors,children_infosets,player,to_remove):\n \"\"\"Usa i vettori dati(assunti lunghi uguali) e applica clustering per trovare gli information set astratti\"\"\"\n backup=to_remove\n #Altrimenti non rileva la variabile globale\n global infoset_id\n if(len(vectors)==0):\n return to_remove\n if(len(vectors)==1):#Se ho solo un vettore è ovviamente in cluster da solo\n #print(\"Skipping %s as lone vector\"%vectors)\n labels=[0]\n else:\n #Dobbiamo ancora trovare quale sia l'algoritmo migliore, kMeans per ora sembra andare\n if to_remove>0 and len(vectors)>1:\n #magic number 0.27\n #eps=0.27*len(vectors)#TODO valore\n #eps=100\n eps=0.0000000000001\n clusters=len(vectors)-1\n if(player==1):\n approx=26\n else:\n approx=25\n approx=2\n #Leduc B 25 2 funziona; 26 per 1\n for i in range(1,approx+1):\n if(clusters>1 and to_remove>approx):\n clusters-=1\n # if(to_remove>3):\n # clusters=1\n # clustering = KMeans(n_clusters=clusters).fit(vectors)\n clustering = AgglomerativeClustering(n_clusters=clusters).fit(vectors)\n # if(len(vectors)>to_remove):\n # samples=len(vectors)-to_remove\n # clustering=DBSCAN(eps=eps, min_samples=3).fit(vectors)\n #print(vectors)\n #clustering= OPTICS(min_samples=1,metric='manhattan').fit(vectors)\n labels=clustering.labels_\n n_clusters = len(set(labels)) - (1 if -1 in labels else 0)\n n_noise = list(labels).count(-1)\n to_remove-=len(vectors)-(n_clusters+n_noise)\n # print(\"Removed %d\"%(len(vectors)-(n_clusters+n_noise)))\n assert(len(vectors)-(n_clusters+n_noise) >0)\n # input(\"A\")\n\n else:\n labels=[-1]*len(vectors)#TODO stacca astrazione\n #print(\"Cluster targets: %s\" %labels)\n #info_store contiene gli abstracted information set eventualmente creati\n fake_info_store={}\n outlier_counter=-2#Cluster veri hanno +, così no collisioni\n #Per ogni vettore(information set reale)\n for index,obj in enumerate(labels):\n if(obj==-1):#Se outlier allora creiamo un cluster finto\n obj=outlier_counter\n outlier_counter-=1\n\n #Se questo cluster ha già un infoset astratto usalo, altrimenti crealo\n if(not obj in fake_info_store):\n fake_infoset=Infoset(\"\",str(infoset_id.increment(1)))\n fake_info_store[obj]=fake_infoset\n fake_infosets[fake_infoset]=[]\n\n else:\n fake_infoset=fake_info_store[obj]\n\n #Assegna l'information set astratto all'information set reale\n children_infosets[index].abstracted_infoset=fake_infoset\n\n #Aggiungi nella stringa di descrizione l'information set reale\n fake_infoset.info_string=fake_infoset.info_string+\"+\"+children_infosets[index].info_string\n\n\n for child in children:\n #Assegna a tutti i figli l'information set astratto corrispondente\n if(child.infoset.abstracted_infoset!=\"\"):\n child.abstracted_infoset=child.infoset.abstracted_infoset\n child.abstract_action_infoset_label=child.infoset.abstracted_infoset.id\n fake_id_of[child.node_id]=child.abstracted_infoset\n fake_infosets[child.abstracted_infoset].append(child.node_id)\n\n\n\n abstracted_infosets=list(fake_info_store.values())\n\n #Vecchio codice, lo lascio con l'assert per fermare bug, per il momento non scatta mai\n unused_infosets=[infoset for infoset in children_infosets if infoset.abstracted_infoset==\"\"]\n assert(len(unused_infosets)==0)\n recur_infosets=unused_infosets +abstracted_infosets\n\n #Lo store contiene, per ogni information set astratto e per ogni azione, una lista di figli su cui ricorrere\n #Questo ci permette di fare clustering solo tra figli dello stesso information set e dalla stessa azione\n #Non dovendo quindi controllare la sequenza per partizionare i vettori, ma solo la lunghezza\n children_store={ i : {j:[] for j in actions} for i in recur_infosets }\n\n #Ripeti per ogni gruppo di figli di ogni information set astratto o che non è stato astratto\n for child in children:\n cinfoset=child.infoset\n\n for action in actions:\n\n #Estrai tutti i figli degli information set attuali(escludendo terminali)\n grandsons=[grandson for grandson in child.children if not grandson.isTerminal() and grandson.action_label==action ]\n\n if(cinfoset.abstracted_infoset==\"\"):\n #Anche qua vecchio codice che non dovrebbe scattare\n children_store[cinfoset][action]=children_store[cinfoset][action]+grandsons\n else:\n if(not cinfoset.abstracted_infoset in abstracted_infosets):\n #Print di debug in caso manchi l'information set\n print(cinfoset in unused_infosets)\n print(cinfoset.info_string)\n print(cinfoset.abstracted_infoset.info_string)\n print(cinfoset.abstracted_infoset)\n #Error if this branch is taken\n\n children_store[cinfoset.abstracted_infoset][action]=children_store[cinfoset.abstracted_infoset][action]+grandsons\n\n #print(\"----------Children store is----------\")\n #print(children_store)\n #print(\"----------------------------------\")\n\n\n #Per ogni partizione in children_store\n for _,store in children_store.items():\n # print()\n for action,children_list in store.items():\n #print(action)\n #print(children_list)\n\n #Salta un livello(i figli dei figli sono del giocatore sbagliato, noi vogliamo\n # i figli dei figli dei figli, che sono di nuovo del giocatore attuale\n grandson_list=get_grandsons(children_list,True,player)\n\n #Filtra i terminali\n grandson_list=[grandson for grandson in grandson_list if not grandson.isTerminal()]\n\n #print(grandson_list)\n #print(\"--------------------------------\")\n left=gen_infoset_clusters(actions,infoset_of,fake_infosets,fake_id_of,grandson_list,player,to_remove)\n to_remove=left\n\n # assert(to_remove==0)\n return to_remove\n\ndef gen_infoset_clusters(actions,infoset_of,fake_infosets,fake_id_of,children,player,to_remove):\n \"\"\" Prende in input gli information set astratti e reali e una lista di children, e cerca di fare clustering quando\n Si trova una corrispondenza nelle strutture\"\"\"\n if(len(children)==0):\n return to_remove\n children_infosets=[]\n #print(\"----------Children is----------\")\n #print(children)\n #print(\"------------------------------\")\n\n #Estrai gli information sets di tutti i figli\n for child in children:\n if(infoset_of[child.node_id] not in children_infosets):\n children_infosets.append(infoset_of[child.node_id])\n\n #print(children_infosets)\n\n #Matrici che per ogni struttura(lunghezza del vettore degli outcome) ci danno:\n outcome_matrix={}#i vettori, un vettore per ogni information set reale\n relevant_matrix={}#i children che hanno generato questi vettori\n relevant_infosets_matrix={}#gli information set che hanno generato questi\n\n #Potrebbe essere ottimizzato, ma tanto il vero tempo viene preso dal clustering\n for infoset in children_infosets:\n vector=[]\n relevant_children=[]\n\n #Per ogni children di questo information set concatena i vettori degli output raggiungibili\n for child in children:\n if(infoset == infoset_of[child.node_id]):\n cv =child.calculate_outcome_vector([])\n vector=vector+cv\n relevant_children.append(child)\n\n #Metti questo vettore con i suoi simili\n if(len(vector) not in outcome_matrix):\n outcome_matrix[len(vector)]=[]\n relevant_matrix[len(vector)]=[]\n relevant_infosets_matrix[len(vector)]=[]\n outcome_matrix[len(vector)].append(vector)\n relevant_matrix[len(vector)]+=(relevant_children)\n relevant_infosets_matrix[len(vector)].append(infoset)\n\n\n #Per ogni gruppo di vettori fai clustering\n for size,vectors in outcome_matrix.items():\n #print(vectors)\n left=cluster_and_recur(actions,infoset_of,fake_infosets,fake_id_of,relevant_matrix[size],vectors,relevant_infosets_matrix[size],player,to_remove)\n to_remove=left\n\n return to_remove\n\ndef add_infoset_edges(dot,infosets,abstracted_infosets):\n \"\"\"Aggiunge al dot gli archi relativi agli infoset reali e astratti \"\"\"\n for infoset,nodes in infosets.items():\n if(len(nodes)>1):\n prev=nodes[0]\n for node in nodes[1:]:\n dot.edge(prev, node,xlabel=infoset.info_string, style=\"dashed\",color=\"red\",constraint=\"false\",fontcolor=\"red\")\n prev=node\n\n for abs_infoset,nodes in abstracted_infosets.items():\n if(len(nodes)>1):\n prev=nodes[0]\n for node in nodes[1:]:\n dot.edge(prev, node,xlabel=abs_infoset.info_string, style=\"dashed\",color=\"blue\",constraint=\"false\",fontcolor=\"blue\")\n prev=node\n\ndef build_tree(data_ordered,infoset_of,action_set):\n \"\"\"Costruisce l'albero \"\"\"\n\n #Actions sono le azioni di entrambi i giocatori per ogni riga\n #actions[i] è una lista di azioni fatte per raggiungere il nodo i\n actions= [x[1].split(\"/\")[1:] for x in data_ordered]\n\n #Chiamata ricorsiva che Costruisce la lista di figli\n children,_=build_subtree(infoset_of,data_ordered[1:],actions[1:],1,action_set)\n\n #Crea il nodo radice con la lista precedentemente creata\n return Tree(\"0\",children,data_ordered[0],\"\",Infoset(\"Nature\",0))\n\ndef build_subtree(infoset_of,data, actions,id,action_set):\n \"\"\"Crea la lista di figli del nodo dato, creando tutti i sottoalberi ricorsivamente\"\"\"\n\n #Cose, non rilevanti per il resto del codice\n children_action=list(set([x[0] for x in actions]))\n children_action=sorted(children_action)\n\n new_id=id+1\n children=[]\n\n for action in children_action:\n\n if action not in action_set:\n action_set.add(action)\n data_new=[x for (index, x) in enumerate(data) if actions[index][0]==action]\n\n actions_new=[x[1:] for x in actions if x[0]==action]\n\n subtree_children,new_id=build_subtree(infoset_of,data_new[1:],actions_new[1:],new_id,action_set)\n\n history=data_new[0][1]\n infoset=\"Not valid\"\n if(history in infoset_of):\n infoset=infoset_of[history]\n else:\n infoset=\"NaN\"\n\n new_node=Tree(str(id),subtree_children,data_new[0],action,infoset)\n id=new_id\n new_id=id+1\n children.append(new_node)\n\n return children,id\n\n\ndef generate_id_infoset_of(infosets):\n \"\"\" Genera un dizionario che per ogni id di nodo ci da l'Infoset\"\"\"\n infoset_id_of={}\n for infoset,nodes in infosets.items():\n for id in nodes:\n infoset_id_of[id]=infoset\n\n return infoset_id_of\n\ndef read(filename):\n \"\"\" Apre il csv e crea le strutture dati \"\"\"\n reader = csv.reader(open(filename), delimiter=\" \")\n\n #data sono le righe lette senza elaborazione\n data = list(reader)\n\n #togli righe vuote e commenti\n data_polished= [x for x in data if len(x)>0 and x[0]!=\"#\"]\n\n #separa nodi e information set\n data_nodes= [x for x in data_polished if x[0]==\"node\"]\n data_info=[x for x in data_polished if x[0]==\"infoset\"]\n\n #ordina in base alla sequenza lessicograficamente\n data_ordered=sorted(data_nodes, key=lambda tuple: tuple[1])\n\n return data_ordered,data_info\n\n\ndef add_abstracted_actions(infosets,id_dic):\n for infoset,children_id in infosets.items():\n assert(len(children_id)>0)\n champion=id_dic[children_id[0]]\n for child in champion.children:\n infoset.actions.add(child.action_label)\n\ndef parse_and_abstract(filename,gen_diag):\n start_time = time.time()\n (data_ordered, data_info) =read(filename)\n\n #Actions conterrà tutte le azione mai incontrate\n actions=set()\n\n infoset_of={}\n for infoset in data_info:\n infoset[0]=Infoset(infoset[1],str(infoset_id.increment()))\n for node in infoset[3:]:\n infoset_of[node]=infoset[0]\n #A questo punto infoset_of contiene le reference agli infoset di tutti e soli i nodi con infoset da infoset_input\n\n #Questo genera l'albero e assegna degli information set ai nodi per cui ancora manca(quelli che sono singoli)\n tree=build_tree(data_ordered,infoset_of,actions)\n\n\n #Costruisce un dizionario che per ogni Infoset ritorna la lista di id di nodi\n infosets={}\n id_dic={}\n tree.fill_infoset_dictionary(infosets,id_dic,Infoset(\"0\",\"0\"))\n\n\n #Vecchia sequence table non più usata, lasciata per sicurezza\n #sequence_table={}\n #tree.fill_sequence_form(sequence_table,{\"1\":\"\",\"2\":\"\"},1.0,True,\"-\")\n # for sequence_1,cells in sequence_table.items():\n # print(sequence_1)\n # print(cells)\n # print(\"\")\n\n\n #Costruisce una struttura come infoset_of, ma che invece delle stringhe di sequenza ha gli id di nodo\n infoset_id_of=generate_id_infoset_of(infosets)\n\n #A questo punto:\n #infoset_id_of contiene un dizionario che, dato un id di nodo, restituisce un oggetto Infoset\n #infosets contiene un dizionario che, dato un oggetto Infoset, restituisce una lista di id di nodi\n #infoset_of contiene un dizionario che, data una stringa di sequenza di gioco, restituisce un Infoset\n #esempio '/C:JQ/P1:c/P2:r': <__main__.Infoset (...)>\n\n\n #Fake_ sono gli oggetti che contengono gli information set astratti\n fake_infosets={}\n fake_id_of={}\n\n to_remove1=1794\n to_remove2=1794\n #Crea i cluster e astrae il gioco, riempiendo le variabili relative all'astrazione\n left=gen_infoset_clusters(actions,infoset_id_of,fake_infosets,fake_id_of,tree.children,1,to_remove1)\n left2=gen_infoset_clusters(actions,infoset_id_of,fake_infosets,fake_id_of,get_grandsons(tree.children,False,0),2,to_remove2)\n\n print(\"There are %d unremoved infosets(%d total)\"%(left,len(fake_infosets)))\n print(\"There are %d unremoved infosets2(%d total)\"%(left2,len(fake_infosets)))\n assert(left==0)\n assert(left2==0)\n\n root_abstract_infoset=Infoset(\"0\",str(infoset_id.increment(1)))\n fake_infosets[root_abstract_infoset]=[\"0\"]\n fake_id_of[\"0\"]=root_abstract_infoset\n tree.abstracted_infoset=root_abstract_infoset\n\n #Il multithreading funziona ma per qualche motivo rallenta\n # thread1=threading.Thread(target=gen_infoset_clusters, args=(actions,infoset_id_of,fake_infosets,fake_id_of,tree.children))\n # thread2=threading.Thread(target=gen_infoset_clusters, args=(actions,infoset_id_of,fake_infosets,fake_id_of,get_grandsons(tree.children)))\n # thread2.start()\n # thread1.start()\n # thread1.join()\n # thread1.join()\n add_abstracted_actions(fake_infosets,id_dic)\n print(infosets)\n print(\"---------------------\")\n print(fake_infosets)\n print(\"Fake infoset size %d\"% len(fake_infosets))\n print(\"Real infoset size %d\"% len(infosets))\n nature_count=1\n for node_id in id_dic:\n if(not id_dic[node_id].isTerminal() and node_id not in fake_id_of):\n if id_dic[node_id].isNature():\n nature_count+=1\n else:\n print(\"Error, node not in abstract store\")#Ma i chance ci vanno?\n node=id_dic[node_id]\n print(node.line)\n print(node.abstracted_infoset)\n assert(False)\n #assert(False)\n #\n print(\"Chance Nodes %d\"%(nature_count))\n for infoset in infosets.keys():\n if not (infoset.id==0 or infoset.info_string[0]==\"N\") and infoset.abstracted_infoset==\"\":\n print(\"Error Missing infoset %s %s\"%(infoset.id,infoset.info_string))\n assert(False)\n\n if(gen_diag):\n apply_edges_to_diagram(tree,infosets,fake_infosets,id_dic,fake_id_of,True)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n return tree,id_dic,infosets,infoset_of,infoset_id_of,fake_infosets,fake_id_of\n\ndef apply_edges_to_diagram(tree,infosets,fake_infosets,id_dic,fake_id_of,really):\n\n #Inizializza il grafico, svg è l'unico che permette di usare gli input grandi\n dot = Graph(comment='My game',format='svg')\n tree.build_dot(dot,\"Begin\",0,id_dic,fake_id_of,really);\n if not really:\n return 0\n display=\"abstract\"\n if(display==\"true\"):#solo infoset reali\n add_infoset_edges(dot,infosets,{})\n elif(display==\"abstract\"):#solo astratti\n add_infoset_edges(dot,{},fake_infosets)\n else:#clusterfuck\n add_infoset_edges(dot,infosets,fake_infosets)\n\n dot.render('test-output/round-table.gv', view=False)\n return 0\nif __name__ == '__main__':\n parse_and_abstract(\"testinput.txt\",True)\n","sub_path":"tree_parser.py","file_name":"tree_parser.py","file_ext":"py","file_size_in_byte":24730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"99157959","text":"import torch\nimport torch.nn.functional as F\nfrom torch.nn.modules.batchnorm import _BatchNorm\nimport torch.nn as nn\nimport math\n\ndef group_norm(input, group, running_mean, running_var, weight=None, bias=None,\n use_input_stats=False, momentum=0.1, eps=1e-5):\n r\"\"\"Applies Group Normalization for channels in the same group in each data sample in a\n batch.\n See :class:`~torch.nn.GroupNorm1d`, :class:`~torch.nn.GroupNorm2d`,\n :class:`~torch.nn.GroupNorm3d` for details.\n \"\"\"\n if not use_input_stats and (running_mean is None or running_var is None):\n raise ValueError('Expected running_mean and running_var to be not None when use_input_stats=False')\n\n b, c = input.size(0), input.size(1)\n if weight is not None:\n weight = weight.repeat(b)\n if bias is not None:\n bias = bias.repeat(b)\n\n def _instance_norm(input, group, running_mean=None, running_var=None, weight=None,\n bias=None, use_input_stats=None, momentum=None, eps=None):\n # Repeat stored stats and affine transform params if necessary\n if running_mean is not None:\n running_mean_orig = running_mean\n running_mean = running_mean_orig.repeat(b)\n if running_var is not None:\n running_var_orig = running_var\n running_var = running_var_orig.repeat(b)\n\n #norm_shape = [1, b * c / group, group]\n #print(norm_shape)\n # Apply instance norm\n input_reshaped = input.contiguous().view(1, int(b * c/group), group, *input.size()[2:])\n\n out = F.batch_norm(\n input_reshaped, running_mean, running_var, weight=weight, bias=bias,\n training=use_input_stats, momentum=momentum, eps=eps)\n\n # Reshape back\n if running_mean is not None:\n running_mean_orig.copy_(running_mean.view(b, int(c/group)).mean(0, keepdim=False))\n if running_var is not None:\n running_var_orig.copy_(running_var.view(b, int(c/group)).mean(0, keepdim=False))\n\n return out.view(b, c, *input.size()[2:])\n return _instance_norm(input, group, running_mean=running_mean,\n running_var=running_var, weight=weight, bias=bias,\n use_input_stats=use_input_stats, momentum=momentum,\n eps=eps)\n\n\nclass _GroupNorm(_BatchNorm):\n def __init__(self, num_features, num_groups=1, eps=1e-5, momentum=0.1,\n affine=False, track_running_stats=False):\n self.num_groups = num_groups\n self.track_running_stats = track_running_stats\n super(_GroupNorm, self).__init__(int(num_features/num_groups), eps,\n momentum, affine, track_running_stats)\n\n def _check_input_dim(self, input):\n return NotImplemented\n\n def forward(self, input):\n self._check_input_dim(input)\n\n return group_norm(\n input, self.num_groups, self.running_mean, self.running_var, self.weight, self.bias,\n self.training or not self.track_running_stats, self.momentum, self.eps)\n\n\nclass GroupNorm2d(_GroupNorm):\n r\"\"\"Applies Group Normalization over a 4D input (a mini-batch of 2D inputs\n with additional channel dimension) as described in the paper\n https://arxiv.org/pdf/1803.08494.pdf\n `Group Normalization`_ .\n Args:\n num_features: :math:`C` from an expected input of size\n :math:`(N, C, H, W)`\n num_groups:\n eps: a value added to the denominator for numerical stability. Default: 1e-5\n momentum: the value used for the running_mean and running_var computation. Default: 0.1\n affine: a boolean value that when set to ``True``, this module has\n learnable affine parameters. Default: ``True``\n track_running_stats: a boolean value that when set to ``True``, this\n module tracks the running mean and variance, and when set to ``False``,\n this module does not track such statistics and always uses batch\n statistics in both training and eval modes. Default: ``False``\n Shape:\n - Input: :math:`(N, C, H, W)`\n - Output: :math:`(N, C, H, W)` (same shape as input)\n Examples:\n >>> # Without Learnable Parameters\n >>> m = GroupNorm2d(100, 4)\n >>> # With Learnable Parameters\n >>> m = GroupNorm2d(100, 4, affine=True)\n >>> input = torch.randn(20, 100, 35, 45)\n >>> output = m(input)\n \"\"\"\n\n def _check_input_dim(self, input):\n if input.dim() != 4:\n raise ValueError('expected 4D input (got {}D input)'\n .format(input.dim()))\n\nclass GroupNormNN(nn.Module):\n def __init__(self, num_features, channels_per_group=8, window_size=(96,96), eps=1e-5):\n super(GroupNormNN, self).__init__()\n self.weight = nn.Parameter(torch.ones(1,num_features,1,1))\n self.bias = nn.Parameter(torch.zeros(1,num_features,1,1))\n self.channels_per_group = channels_per_group\n self.eps = eps\n self.window_size = window_size\n\n\n def forward(self, x):\n N,C,H,W = x.size()\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n G = int(C/self.channels_per_group)\n assert C % G == 0\n if self.window_size[0] < H and self.window_size[1]= page_count:\n page_index = 0\n \n elif page_index < 0:\n page_index = page_count - 1\n\n return page_index\n\n\ndef get_page_display(page_num, total_display_list, document):\n \"\"\"\n Gets the DisplayList of the given page to use for detmermining page size.\n \n Parameters\n ----------\n page_num : int\n The current page index (values between 0 and page count - 1).\n total_display_list: list\n The list potentially containing display lists for each page in the\n document. Entries are blank for any page that has not been viewed yet.\n document : Document object from fitz\n The current Document.\n \n Returns\n -------\n display_list : DisplayList object from fitz\n The DisplayList for the indicated page_num.\n \n \"\"\"\n \n display_list = total_display_list[page_num]\n if not display_list:\n total_display_list[page_num] = document[page_num].getDisplayList()\n display_list = total_display_list[page_num]\n \n return display_list\n \n \ndef get_page(page_num, total_display_list, document, zoom=False, max_size=None):\n \"\"\"\n Return a tkinter.PhotoImage or a PNG image for a document page number.\n \n Parameters\n ----------\n page_num : int\n The current page index (values between 0 and page count - 1).\n total_display_list: list\n The list potentially containing display lists for each page in the\n document. Entries are blank for any page that has not been viewed yet.\n document : Document object from fitz\n The current Document.\n zoom : tuple or bool\n The top-left of the old clip rectangle, and one of -1, 0, +1 for dim. x or y\n to indicate the arrow key pressed (-1 means to decrease x or y, +1 means increase).\n max_size : tuple or None\n The (width, height) of available image area. If None, the image will match\n the pdf image size, which is not guaranteed to fit the user's window.\n \n Returns\n -------\n img : bytes\n The PPM image for the current page.\n clip.tl : tuple\n The top-left of the new clip rectangle.\n page_num : int\n The current page index (values between 0 and page count - 1). Alterred\n if zoom\n \n Notes\n -----\n In this function, tl denotes the top-left of the bounding rectangle.\n \n \"\"\"\n \n display_list = get_page_display(page_num, total_display_list, document)\n r = display_list.rect\n clip = r\n \n # ensure image fits screen:\n zoom_0 = 1\n if max_size:\n zoom_0 = min(1, max_size[0] / r.width, max_size[1] / r.height)\n if zoom_0 == 1:\n zoom_0 = min(max_size[0] / r.width, max_size[1] / r.height)\n mat_0 = fitz.Matrix(zoom_0, zoom_0)\n\n if not zoom: \n # show the total page\n pix = display_list.getPixmap(matrix=mat_0, alpha=False)\n \n else:\n #bounding box is width/2 and height/2 if zoomed\n w2 = r.width / 2\n h2 = r.height / 2\n tl = zoom[0] # old top-left\n tl.y += zoom[2] * (h2 / 2)\n \n if tl.y < 0 or tl.y > h2:\n x_pos = tl.x / r.width\n if tl.y < 0:\n page_num = verify_page_index(page_num - 1, len(document))\n else:\n page_num = verify_page_index(page_num + 1, len(document))\n \n display_list = get_page_display(page_num, total_display_list, document)\n r = display_list.rect\n h2 = r.height / 2\n w2 = r.width / 2\n \n tl.x = x_pos * r.width\n \n zoom_0 = 1\n if max_size:\n zoom_0 = min(1, max_size[0] / r.width, max_size[1] / r.height)\n if zoom_0 == 1:\n zoom_0 = min(max_size[0] / r.width, max_size[1] / r.height)\n mat_0 = fitz.Matrix(zoom_0, zoom_0)\n \n if tl.y < 0:\n tl.y = 0.5 * r.height\n else:\n tl.y = 0.0\n \n else:\n tl.x += zoom[1] * (w2 / 2)\n \n tl.y = max(0, tl.y) # stay within ...\n tl.y = min(h2, tl.y) # the page rect\n tl.x = max(0, tl.x) # according to ...\n tl.x = min(w2, tl.x) # arrow key ...\n \n clip = fitz.Rect(tl, tl.x + w2, tl.y + h2)\n # clip rect is ready, now fill it\n mat = mat_0 * fitz.Matrix(2, 2) # zoom matrix\n pix = display_list.getPixmap(alpha=False, matrix=mat, clip=clip)\n\n img = pix.getImageData(\"ppm\") # make PPM image from pixmap for tkinter\n\n return img, clip.tl, page_num\n\n\ndef ensure_list(variables, default_values=0, list_len=1):\n \"\"\"\n Ensures that the input variables are lists, or creates a list for the variable with default values.\n \n Parameters\n ----------\n variables : list or a single object\n The variables that will be checked to be lists. They should all have\n the same desired length, given by list_len.\n default_values : (list, tuple) or Any\n The default value(s) that will be put into each variable if its length\n is less than list_len.\n list_len : int\n The desired length for all of the lists.\n \n Returns\n -------\n variables : list\n The input variables, ensured to be lists, with len() = list_len.\n \"\"\"\n \n if not isinstance(variables, list):\n variables = [variables]\n \n if not isinstance(default_values, (list, tuple)):\n default_values = [default_values]*list_len\n \n elif len(default_values) < len(variables):\n default_values.extend([0]*(len(variables)-len(default_values)))\n\n for i, variable in enumerate(variables):\n \n if not isinstance(variable, (list, tuple)):\n if variable:\n variable = [variable]*list_len\n else:\n variable = [default_values[i]]*list_len\n \n variables[i] = variable\n \n return variables\n \n\ndef get_page_nums(file_list):\n \"\"\"\n Gets the number of pages for each file in the input file_list.\n \n Parameters\n ----------\n file_list : list\n A list of file strings.\n \n Returns\n -------\n page_list : list\n A list of page numbers for each file in the input file_list.\n \n \"\"\"\n \n page_list = []\n for file in file_list:\n tmp_file = fitz.open(file)\n page_list.append(len(tmp_file))\n tmp_file.close()\n tmp_file = None\n \n return page_list\n \n\n#event handler functions for the Window event loop\ndef is_Enter(event):\n \"\"\"\n Sees if the input event should be interpreted as pressing Enter.\n \n Parameters\n ----------\n event : str or None\n The event from the GUI.\n \n Returns\n -------\n bool\n Whether or not the event matched the criteria.\n \n \"\"\"\n \n return event.startswith(\"Return:\") or event == chr(13)\n\n\ndef is_Next(event):\n \"\"\"\n Sees if the input event should be interpreted as a next page event.\n \n Parameters\n ----------\n event : str or None\n The event from the GUI.\n \n Returns\n -------\n bool\n Whether or not the event matched the criteria.\n \n \"\"\"\n \n terms = ('Next', 'MouseWheel:Down', 'Down:')\n return any((event.startswith(term) for term in terms))\n\n\ndef is_Previous(event):\n \"\"\"\n Sees if the input event should be interpreted as a previous page event.\n \n Parameters\n ----------\n event : str or None\n The event from the GUI.\n \n Returns\n -------\n bool\n Whether or not the event matched the criteria.\n \n \"\"\"\n\n terms = ('Previous', 'MouseWheel:Up', 'Up:', 'Prior:')\n return any((event.startswith(term) for term in terms))\n\n\ndef is_Left(event):\n \"\"\"\n Sees if the input event should be interpreted as pressing Left.\n \n Parameters\n ----------\n event : str or None\n The event from the GUI.\n \n Returns\n -------\n bool\n Whether or not the event matched the criteria.\n \n \"\"\"\n\n return event.startswith(\"Left:\")\n\n\ndef is_Right(event):\n \"\"\"\n Sees if the input event should be interpreted as pressing Right.\n \n Parameters\n ----------\n event : str or None\n The event from the GUI.\n \n Returns\n -------\n bool\n Whether or not the event matched the criteria.\n \n \"\"\"\n\n return event.startswith(\"Right:\")\n\n\ndef is_Zoom(event):\n \"\"\"\n Sees if the input event should be interpreted as pressing Zoom.\n \n Parameters\n ----------\n event : str or None\n The event from the GUI.\n \n Returns\n -------\n bool\n Whether or not the event matched the criteria.\n \n \"\"\"\n \n return event.startswith(\"Zoom\")\n\n\ndef is_MyKeys(event):\n \"\"\"\n Sees if the input event is one that would cause a page change.\n \n Parameters\n ----------\n event : str or None\n The event from the GUI.\n \n Returns\n -------\n bool\n Whether or not the event matched the criteria.\n \n \"\"\"\n \n return any((is_Enter(event), is_Next(event), is_Previous(event), is_Left(event),\n is_Right(event)))\n\n\ndef display_pdfs(file_list=None, output_name='output file', first_pgs=None,\n last_pgs=None, rotations=None):\n \"\"\"\n Creates a window to display the selected file(s).\n \n Parameters\n ----------\n file_list : list or tuple, optional\n The collection of files to merge into a single document for viewing.\n output_name : str, optional\n The name to be displayed at the top of the viewing window.\n first_pgs : list, optional\n A list of first pages for each of the files in file_list. Defaults\n to first page of the file if None.\n last_pgs : list, optional\n A list of last pages for each of the files in file_list. Default to\n last page of the file if None.\n rotations : list, optional\n A list of rotations (0, -90, 90, or 180; int) for each file in file_list.\n Default to 0 (no rotation) if None.\n \n Notes\n -----\n If file_list is a single file or None, it will show the entire content of\n the unalterred selected file. Otherwise, it will allow selection of the page range\n and rotation.\n \n \"\"\"\n\n if isinstance(file_list, (list, tuple)) and file_list: \n doc = fitz.open()\n\n first_pgs, last_pgs, rotations = ensure_list([first_pgs, last_pgs, rotations],\n [0, -1, 0], len(file_list))\n\n for i, file in enumerate(file_list):\n \n if not file or Path(file).suffix.lower() != '.pdf':\n continue\n \n elif Path(file).suffix.lower() != '.pdf':\n print(f'\\nThe following file cannot be processed:\\n\\n {file}')\n \n else: \n tmp_file = fitz.open(file)\n \n pages = len(tmp_file)\n \n first_pg = first_pgs[i]\n last_pg = last_pgs[i]\n rotation = rotations[i]\n \n #ensures pages are within the document\n first_pg = min(max(0, first_pg), pages - 1)\n if last_pg != -1:\n last_pg = min(max(0, last_pg), pages - 1)\n else:\n last_pg = pages - 1\n \n #only adds unencrypted files\n if tmp_file.needsPass:\n print(f'\\nThe following file is encrypted and cannot be processed:\\n\\n {file}')\n else:\n doc.insertPDF(tmp_file, from_page=first_pg, to_page=last_pg, \n rotate=rotation, links=False, annots=True)\n \n tmp_file.close()\n tmp_file = None\n \n else:\n fname = sg.PopupGetFile('Select file and filetype to open:',\n title=\"PyMuPDF Document Browser\",\n file_types=(\n (\"PDF Files\", \"*.pdf\"),\n (\"XPS Files\", \"*.*xps\"),\n (\"Epub Files\", \"*.epub\"),\n (\"Fiction Books\", \"*.fb2\"),\n (\"Comic Books\", \"*.cbz\"),\n (\"HTML\", \"*.htm*\"),))\n \n file_list = [fname]\n \n if fname:\n doc = fitz.open(fname)\n else:\n raise pdf_merger.WindowCloseError\n \n #get physical screen dimension to determine the page image max size\n max_width, max_height = sg.Window.get_screen_size()\n max_size = (max_width - 20, max_height - 200)\n \n page_count = len(doc)\n #allocate storage for page display lists\n total_display_list = [None] * page_count\n cur_page = 0\n \n data, clip_pos, cur_page = get_page(cur_page, total_display_list, doc, \n zoom=False, max_size=max_size)\n layout = [\n [sg.Column([\n [sg.Button(\"Previous\", size=(8,1)),\n sg.Button(\"Next\", size=(8,1))]],\n element_justification='left', pad=(5,5)),\n sg.Column([\n [sg.Text(\"Page:\"),\n sg.InputText(str(cur_page + 1), size=(5, 1), \n do_not_clear=True, key='page_num',\n justification='right'),\n sg.Text(f'/ {page_count}')]],\n element_justification='center', pad=(40,(9,5))),\n sg.Column([\n [sg.Button(\"Zoom\")]],\n element_justification='right', pad=(40,5)),\n ],\n [sg.Image(data=data, key='image')],\n ]\n \n window = sg.Window(f'Preview of {Path(output_name).name}', \n layout, return_keyboard_events=True, \n location=(0, 0), use_default_focus=False,\n resizable=True, keep_on_top=True)\n #zoom toggle\n zoom_active = False\n \n while True:\n event, values = window.read()\n\n if event == sg.WIN_CLOSED:\n break\n \n zoom_pressed = False\n zoom = False\n \n if is_Enter(event):\n try:\n tmp_page = int(values['page_num']) - 1\n if tmp_page < 0 or tmp_page >= page_count:\n pass\n else:\n cur_page = tmp_page\n except:\n pass\n \n #events if zoomed \n elif is_Next(event) and zoom_active:\n zoom = (clip_pos, 0, 1)\n elif is_Previous(event) and zoom_active:\n zoom = (clip_pos, 0, -1)\n elif is_Left(event) and zoom_active:\n zoom = (clip_pos, -1, 0)\n elif is_Right(event) and zoom_active:\n zoom = (clip_pos, 1, 0)\n elif is_Zoom(event):\n zoom_pressed = True\n if not zoom_active:\n zoom = (clip_pos, 0, 0)\n \n elif is_Next(event) or is_Right(event):\n cur_page += 1\n elif is_Previous(event) or is_Left(event):\n cur_page -= 1\n \n #loop around if cur_page is outside of the document page range\n cur_page = verify_page_index(cur_page, page_count)\n \n if zoom_pressed and zoom_active:\n zoom = zoom_pressed = zoom_active = False\n \n data, clip_pos, cur_page = get_page(cur_page, total_display_list, doc, \n zoom=zoom, max_size=max_size)\n window['image'].update(data=data)\n zoom_active = zoom_pressed or zoom\n \n if zoom_active:\n window['Zoom'].update(button_color=('white', '#00A949'))\n else:\n window['Zoom'].update(button_color=sg.theme_button_color()) \n \n #update page number field\n if is_MyKeys(event):\n window['page_num'].update(str(cur_page + 1))\n \n \n window.close()\n doc.close()\n del window, layout, doc\n\n\ndef merge_save_pdfs(file_list, output_name, first_pgs=None, last_pgs=None,\n rotations=None):\n \"\"\"\n Merges all of the input PDF files into a single PDF and saves.\n \n Parameters\n ----------\n file_list : list or tuple\n The collection of files to merge into a single document and saved.\n output_name : str\n The string filepath at which to save the created pdf.\n first_pgs : list, optional\n A list of first pages for each of the files in file_list. Defaults\n to first page of the file if None.\n last_pgs : list, optional\n A list of last pages for each of the files in file_list. Default to\n last page of the file if None.\n rotations : list, optional\n A list of rotations (0, -90, 90, or 180; int) for each file in file_list.\n Default to 0 (no rotation) if None.\n \n \"\"\"\n \n first_pgs, last_pgs, rotations = ensure_list([first_pgs, last_pgs, rotations],\n [0, -1, 0], len(file_list))\n \n current_pg = 0\n output_file = fitz.open()\n \n #collects the bookmarks from all of the files\n total_toc = []\n for i, file in enumerate(file_list):\n \n if (not file) or (Path(file).suffix.lower() != '.pdf'):\n print(f'\\nThe following file cannot be processed:\\n\\n {file}')\n \n else:\n tmp_file = fitz.open(file)\n pages = len(tmp_file)\n \n first_pg = first_pgs[i]\n last_pg = last_pgs[i]\n rotation = rotations[i]\n \n #ensures pages are within the document\n first_pg = min(max(0, first_pg), pages - 1)\n if last_pg != -1:\n last_pg = min(max(0, last_pg), pages - 1)\n else:\n last_pg = pages - 1\n \n #only adds unencrypted files\n if tmp_file.needsPass:\n print(f'\\nThe following file is encrypted and cannot be processed:\\n\\n {file}')\n continue\n else:\n output_file.insertPDF(tmp_file, from_page=first_pg, \n to_page=last_pg, rotate=rotation,\n links=True, annots=True)\n \n #get file's table of contents\n toc = tmp_file.getToC(simple=False)\n \n if first_pg > last_pg:\n increment = -1\n toc = toc[::-1]\n \n else:\n increment = 1\n \n pg_range = [*range(first_pg, last_pg + increment, increment)]\n \n #set starting bookmark level to 1\n last_lvl = 1\n for link in toc:\n lnk_type = link[3][\"kind\"]\n \n #skip the bookmark if it's \"goto\" and not within the page range\n if (link[2] - 1) not in pg_range and lnk_type == fitz.LINK_GOTO:\n continue\n elif lnk_type == fitz.LINK_GOTO:\n page_num = pg_range.index(link[2] - 1) + current_pg + 1\n \n #fix bookmark levels left by filler bookmarks\n while (link[0] > last_lvl + 1):\n total_toc.append([last_lvl + 1, \"<>\", page_num, link[3]])\n last_lvl += 1\n \n last_lvl = link[0]\n link[2] = page_num\n total_toc.append(link)\n \n current_pg += len(pg_range)\n tmp_file.close()\n tmp_file = None\n\n if total_toc:\n output_file.setToC(total_toc)\n \n if len(output_file) > 0:\n try:\n output_file.save(output_name, garbage=4, deflate=1)\n print(f'\\nFile successfully created at:\\n {Path(output_name)}\\n')\n \n except Exception as e:\n print(f'\\nSomething went wrong.\\n {repr(e)}\\n')\n \n finally:\n output_file.close()\n del output_file\n \n else:\n output_file.close()\n del output_file\n\n\nif __name__ == '__main__':\n \n try:\n display_pdfs() \n \n except pdf_merger.WindowCloseError:\n pass","sub_path":"Miscellaneous/pdf_viewer.py","file_name":"pdf_viewer.py","file_ext":"py","file_size_in_byte":22891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"459610377","text":"# Copyright 2018 Red Hat, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom collections import namedtuple\nfrom unittest import mock\n\nimport fixtures\nfrom neutron_lib.api.definitions import extra_dhcp_opt as edo_ext\n\nfrom neutron.common.ovn import constants\nfrom neutron.common.ovn import utils\nfrom neutron.tests import base\nfrom neutron.tests.unit import fake_resources as fakes\n\nRESOLV_CONF_TEMPLATE = \"\"\"# TEST TEST TEST\n# Geneated by OVN test\nnameserver 10.0.0.1\n#nameserver 10.0.0.2\nnameserver 10.0.0.3\nnameserver foo 10.0.0.4\nnameserver aef0::4\nfoo 10.0.0.5\n\"\"\"\n\n\nclass TestUtils(base.BaseTestCase):\n\n def test_get_system_dns_resolvers(self):\n tempdir = self.useFixture(fixtures.TempDir()).path\n resolver_file_name = tempdir + '/resolv.conf'\n tmp_resolv_file = open(resolver_file_name, 'w')\n tmp_resolv_file.writelines(RESOLV_CONF_TEMPLATE)\n tmp_resolv_file.close()\n expected_dns_resolvers = ['10.0.0.1', '10.0.0.3']\n observed_dns_resolvers = utils.get_system_dns_resolvers(\n resolver_file=resolver_file_name)\n self.assertEqual(expected_dns_resolvers, observed_dns_resolvers)\n\n def test_is_gateway_chassis(self):\n chassis = fakes.FakeOvsdbRow.create_one_ovsdb_row(attrs={\n 'external_ids': {'ovn-cms-options': 'enable-chassis-as-gw'}})\n non_gw_chassis_0 = fakes.FakeOvsdbRow.create_one_ovsdb_row(attrs={\n 'external_ids': {'ovn-cms-options': ''}})\n non_gw_chassis_1 = fakes.FakeOvsdbRow.create_one_ovsdb_row(attrs={})\n non_gw_chassis_2 = fakes.FakeOvsdbRow.create_one_ovsdb_row(attrs={\n 'external_ids': {}})\n\n self.assertTrue(utils.is_gateway_chassis(chassis))\n self.assertFalse(utils.is_gateway_chassis(non_gw_chassis_0))\n self.assertFalse(utils.is_gateway_chassis(non_gw_chassis_1))\n self.assertFalse(utils.is_gateway_chassis(non_gw_chassis_2))\n\n def test_get_chassis_availability_zones_no_azs(self):\n chassis = fakes.FakeOvsdbRow.create_one_ovsdb_row(attrs={\n 'external_ids': {'ovn-cms-options': 'enable-chassis-as-gw'}})\n self.assertEqual([], utils.get_chassis_availability_zones(chassis))\n\n def test_get_chassis_availability_zones_one_az(self):\n chassis = fakes.FakeOvsdbRow.create_one_ovsdb_row(attrs={\n 'external_ids': {'ovn-cms-options':\n 'enable-chassis-as-gw,availability-zones=az0'}})\n self.assertEqual(\n ['az0'], utils.get_chassis_availability_zones(chassis))\n\n def test_get_chassis_availability_zones_multiple_az(self):\n chassis = fakes.FakeOvsdbRow.create_one_ovsdb_row(attrs={\n 'external_ids': {\n 'ovn-cms-options':\n 'enable-chassis-as-gw,availability-zones=az0:az1 :az2:: :'}})\n self.assertEqual(\n ['az0', 'az1', 'az2'],\n utils.get_chassis_availability_zones(chassis))\n\n def test_get_chassis_availability_zones_malformed(self):\n chassis = fakes.FakeOvsdbRow.create_one_ovsdb_row(attrs={\n 'external_ids': {'ovn-cms-options':\n 'enable-chassis-as-gw,availability-zones:az0'}})\n self.assertEqual(\n [], utils.get_chassis_availability_zones(chassis))\n\n def test_is_security_groups_enabled(self):\n self.assertTrue(utils.is_security_groups_enabled(\n {constants.PORT_SECURITYGROUPS: ['fake']}))\n self.assertFalse(utils.is_security_groups_enabled(\n {}))\n\n def test_parse_ovn_lb_port_forwarding(self):\n TC = namedtuple('TC', 'input output description')\n fake_ovn_lb = namedtuple('fake_ovn_lb', 'external_ids protocol vips')\n test_cases = [\n TC([], {}, \"empty\"),\n TC([{'external_ids': {'neutron:fip_id': 'fip1'},\n 'protocol': None,\n 'vips': {'172.24.4.8:2020': '10.0.0.10:22'}}],\n {'fip1': {'tcp': {'172.24.4.8:2020 10.0.0.10:22'}}},\n \"simple\"),\n TC([{'external_ids': {'neutron:fip_id': 'fip1'},\n 'protocol': [],\n 'vips': {'172.24.4.8:2020': '10.0.0.10:22',\n '172.24.4.8:2021': '10.0.0.11:22',\n '172.24.4.8:8080': '10.0.0.10:80'}}],\n {'fip1': {'tcp': {'172.24.4.8:8080 10.0.0.10:80',\n '172.24.4.8:2021 10.0.0.11:22',\n '172.24.4.8:2020 10.0.0.10:22'}}},\n \"multiple vips\"),\n TC([{'external_ids': {'neutron:fip_id': 'fip1'},\n 'protocol': ['tcp'],\n 'vips': {'ext_ip:ext_port1': 'int_ip1:int_port1'}},\n {'external_ids': {'neutron:fip_id': 'fip1'},\n 'protocol': ['udp'],\n 'vips': {'ext_ip:ext_port1': 'int_ip1:int_port1'}}],\n {'fip1': {'tcp': {'ext_ip:ext_port1 int_ip1:int_port1'},\n 'udp': {'ext_ip:ext_port1 int_ip1:int_port1'}}},\n \"2 protocols\"),\n TC([{'external_ids': {'neutron:fip_id': 'fip1'},\n 'protocol': ['tcp'],\n 'vips': {'ext_ip:ext_port1': 'int_ip1:int_port1'}},\n {'external_ids': {'neutron:fip_id': 'fip2'},\n 'protocol': ['tcp'],\n 'vips': {'ext_ip:ext_port1': 'int_ip1:int_port1'}}],\n {'fip1': {'tcp': {'ext_ip:ext_port1 int_ip1:int_port1'}},\n 'fip2': {'tcp': {'ext_ip:ext_port1 int_ip1:int_port1'}}},\n \"2 fips\"),\n ]\n for tc in test_cases:\n tc_lbs = [\n fake_ovn_lb(lb['external_ids'], lb['protocol'], lb['vips'])\n for lb in tc.input]\n rc = utils.parse_ovn_lb_port_forwarding(tc_lbs)\n self.assertEqual(rc, tc.output, tc.description)\n\n\nclass TestGateWayChassisValidity(base.BaseTestCase):\n\n def setUp(self):\n super(TestGateWayChassisValidity, self).setUp()\n self.gw_chassis = ['host1', 'host2']\n self.chassis_name = self.gw_chassis[0]\n self.physnet = 'physical-nw-1'\n self.chassis_physnets = {self.chassis_name: [self.physnet]}\n\n def test_gateway_chassis_valid(self):\n # Return False, since everything is valid\n self.assertFalse(utils.is_gateway_chassis_invalid(\n self.chassis_name, self.gw_chassis, self.physnet,\n self.chassis_physnets))\n\n def test_gateway_chassis_due_to_invalid_chassis_name(self):\n # Return True since chassis is invalid\n self.chassis_name = constants.OVN_GATEWAY_INVALID_CHASSIS\n self.assertTrue(utils.is_gateway_chassis_invalid(\n self.chassis_name, self.gw_chassis, self.physnet,\n self.chassis_physnets))\n\n def test_gateway_chassis_for_chassis_not_in_chassis_physnets(self):\n # Return True since chassis is not in chassis_physnets\n self.chassis_name = 'host-2'\n self.assertTrue(utils.is_gateway_chassis_invalid(\n self.chassis_name, self.gw_chassis, self.physnet,\n self.chassis_physnets))\n\n def test_gateway_chassis_for_undefined_physnet(self):\n # Return True since physnet is not defined\n self.chassis_name = 'host-1'\n self.physnet = None\n self.assertTrue(utils.is_gateway_chassis_invalid(\n self.chassis_name, self.gw_chassis, self.physnet,\n self.chassis_physnets))\n\n def test_gateway_chassis_for_physnet_not_in_chassis_physnets(self):\n # Return True since physnet is not in chassis_physnets\n self.physnet = 'physical-nw-2'\n self.assertTrue(utils.is_gateway_chassis_invalid(\n self.chassis_name, self.gw_chassis, self.physnet,\n self.chassis_physnets))\n\n def test_gateway_chassis_for_gw_chassis_empty(self):\n # Return False if gw_chassis is []\n # This condition states that the chassis is valid, has valid\n # physnets and there are no gw_chassis present in the system.\n self.gw_chassis = []\n self.assertFalse(utils.is_gateway_chassis_invalid(\n self.chassis_name, self.gw_chassis, self.physnet,\n self.chassis_physnets))\n\n def test_gateway_chassis_for_chassis_not_in_gw_chassis_list(self):\n # Return True since chassis_name not in gw_chassis\n self.gw_chassis = ['host-2']\n self.assertTrue(utils.is_gateway_chassis_invalid(\n self.chassis_name, self.gw_chassis, self.physnet,\n self.chassis_physnets))\n\n\nclass TestDHCPUtils(base.BaseTestCase):\n\n def test_validate_port_extra_dhcp_opts_empty(self):\n port = {edo_ext.EXTRADHCPOPTS: []}\n result = utils.validate_port_extra_dhcp_opts(port)\n self.assertFalse(result.failed)\n self.assertEqual([], result.invalid_ipv4)\n self.assertEqual([], result.invalid_ipv6)\n\n def test_validate_port_extra_dhcp_opts_dhcp_disabled(self):\n opt0 = {'opt_name': 'not-valid-ipv4',\n 'opt_value': 'joe rogan',\n 'ip_version': 4}\n opt1 = {'opt_name': 'dhcp_disabled',\n 'opt_value': 'True',\n 'ip_version': 4}\n port = {edo_ext.EXTRADHCPOPTS: [opt0, opt1]}\n\n # Validation always succeeds if the \"dhcp_disabled\" option is enabled\n result = utils.validate_port_extra_dhcp_opts(port)\n self.assertFalse(result.failed)\n self.assertEqual([], result.invalid_ipv4)\n self.assertEqual([], result.invalid_ipv6)\n\n def test_validate_port_extra_dhcp_opts(self):\n opt0 = {'opt_name': 'bootfile-name',\n 'opt_value': 'homer_simpson.bin',\n 'ip_version': 4}\n opt1 = {'opt_name': 'dns-server',\n 'opt_value': '2001:4860:4860::8888',\n 'ip_version': 6}\n port = {edo_ext.EXTRADHCPOPTS: [opt0, opt1]}\n\n result = utils.validate_port_extra_dhcp_opts(port)\n self.assertFalse(result.failed)\n self.assertEqual([], result.invalid_ipv4)\n self.assertEqual([], result.invalid_ipv6)\n\n def test_validate_port_extra_dhcp_opts_invalid(self):\n # Two value options and two invalid, assert the validation\n # will fail and only the invalid options will be returned as\n # not supported\n opt0 = {'opt_name': 'bootfile-name',\n 'opt_value': 'homer_simpson.bin',\n 'ip_version': 4}\n opt1 = {'opt_name': 'dns-server',\n 'opt_value': '2001:4860:4860::8888',\n 'ip_version': 6}\n opt2 = {'opt_name': 'not-valid-ipv4',\n 'opt_value': 'joe rogan',\n 'ip_version': 4}\n opt3 = {'opt_name': 'not-valid-ipv6',\n 'opt_value': 'young jamie',\n 'ip_version': 6}\n port = {edo_ext.EXTRADHCPOPTS: [opt0, opt1, opt2, opt3]}\n\n result = utils.validate_port_extra_dhcp_opts(port)\n self.assertTrue(result.failed)\n self.assertEqual(['not-valid-ipv4'], result.invalid_ipv4)\n self.assertEqual(['not-valid-ipv6'], result.invalid_ipv6)\n\n def test_get_lsp_dhcp_opts_empty(self):\n port = {edo_ext.EXTRADHCPOPTS: []}\n dhcp_disabled, options = utils.get_lsp_dhcp_opts(port, 4)\n self.assertFalse(dhcp_disabled)\n self.assertEqual({}, options)\n\n def test_get_lsp_dhcp_opts_empty_dhcp_disabled(self):\n opt0 = {'opt_name': 'bootfile-name',\n 'opt_value': 'homer_simpson.bin',\n 'ip_version': 4}\n opt1 = {'opt_name': 'dhcp_disabled',\n 'opt_value': 'True',\n 'ip_version': 4}\n port = {edo_ext.EXTRADHCPOPTS: [opt0, opt1]}\n\n # Validation always succeeds if the \"dhcp_disabled\" option is enabled\n dhcp_disabled, options = utils.get_lsp_dhcp_opts(port, 4)\n self.assertTrue(dhcp_disabled)\n self.assertEqual({}, options)\n\n @mock.patch.object(utils, 'is_network_device_port')\n def test_get_lsp_dhcp_opts_is_network_device_port(self, mock_device_port):\n mock_device_port.return_value = True\n port = {}\n dhcp_disabled, options = utils.get_lsp_dhcp_opts(port, 4)\n # Assert OVN DHCP is disabled\n self.assertTrue(dhcp_disabled)\n self.assertEqual({}, options)\n\n def test_get_lsp_dhcp_opts(self):\n opt0 = {'opt_name': 'bootfile-name',\n 'opt_value': 'homer_simpson.bin',\n 'ip_version': 4}\n opt1 = {'opt_name': 'server-ip-address',\n 'opt_value': '10.0.0.1',\n 'ip_version': 4}\n opt2 = {'opt_name': '42',\n 'opt_value': '10.0.2.1',\n 'ip_version': 4}\n port = {edo_ext.EXTRADHCPOPTS: [opt0, opt1, opt2]}\n\n dhcp_disabled, options = utils.get_lsp_dhcp_opts(port, 4)\n self.assertFalse(dhcp_disabled)\n # Assert the names got translated to their OVN names\n expected_options = {'tftp_server_address': '10.0.0.1',\n 'ntp_server': '10.0.2.1',\n 'bootfile_name': 'homer_simpson.bin'}\n self.assertEqual(expected_options, options)\n","sub_path":"neutron/tests/unit/common/ovn/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":13657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"620771960","text":"import tensorflow as tf\nimport ToolBox\nimport Model as M\n\n\nclass Elosplit(M.Model):\n def __init__(self, train_set, test_set, dictparam):\n super(Elosplit, self).__init__(train_set, test_set, dictparam)\n\n k = tf.constant(map(lambda x: float(x), range(10)))\n last_vect = tf.expand_dims(ToolBox.last_vector(10), 0)\n win_vector = ToolBox.win_vector(10)\n\n # Define parameters\n self.elo_atk = tf.Variable(tf.zeros([self.nb_teams, self.nb_times]))\n self.elo_def = tf.Variable(tf.zeros([self.nb_teams, self.nb_times]))\n\n # Define the model\n for key, proxy in [('train', self.train_data), ('test', self.test_data)]:\n elo_atk_h = ToolBox.get_elomatch(proxy['team_h'], proxy['time'], self.elo_atk)\n elo_def_h = ToolBox.get_elomatch(proxy['team_h'], proxy['time'], self.elo_def)\n elo_atk_a = ToolBox.get_elomatch(proxy['team_a'], proxy['time'], self.elo_atk)\n elo_def_a = ToolBox.get_elomatch(proxy['team_a'], proxy['time'], self.elo_def)\n lambda_h = tf.expand_dims(tf.exp(self.param['bias'] + self.param['home_bias'] + elo_atk_h - elo_def_a), 1)\n lambda_a = tf.expand_dims(tf.exp(self.param['bias'] + elo_atk_a - elo_def_h), 1)\n score_h = tf.exp(-lambda_h + tf.log(lambda_h) * k - tf.lgamma(k + 1))\n score_a = tf.exp(-lambda_a + tf.log(lambda_a) * k - tf.lgamma(k + 1))\n score_h += tf.matmul(tf.expand_dims((1. - tf.reduce_sum(score_h, reduction_indices=[1])), 1), last_vect)\n score_a += tf.matmul(tf.expand_dims((1. - tf.reduce_sum(score_a, reduction_indices=[1])), 1), last_vect)\n\n self.score[key] = tf.batch_matmul(tf.expand_dims(score_h, 2), tf.expand_dims(score_a, 1))\n self.res[key] = tf.reduce_sum(self.score[key] * win_vector, reduction_indices=[1,2])\n\n # Define the costs\n self.init_cost()\n for key in ['train', 'test']:\n for proxy in [self.elo_atk, self.elo_def]:\n cost = ToolBox.get_raw_elo_cost(self.param['metaparam0'], self.param['metaparam1'], proxy, self.nb_times)\n self.regulizer[key].append(cost)\n\n cost = ToolBox.get_timediff_elo_cost(self.param['metaparam2'], proxy, self.nb_times)\n self.regulizer[key].append(cost)\n\n # Finish the initialization\n super(Elosplit, self).finish_init()\n\n def get_elos(self, s):\n if s == 'atk':\n return self.session.run(self.elo_atk)\n elif s == 'def':\n return self.session.run(self.elo_def)\n else:\n raise ValueError('Invalid argument in get_elos')\n\n\n","sub_path":"Elosplit.py","file_name":"Elosplit.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"64083175","text":"# encoding: utf-8\n'''Models for Books'''\n\nfrom django.db import models\n\n\nclass BaseModel(models.Model):\n '''Base class for all models'''\n created_time = models.DateTimeField('date created', auto_now_add=True)\n last_modified_time = models.DateTimeField(\n 'last-modified', auto_now=True, db_index=True)\n\n class Meta:\n '''Meta class for Base class'''\n abstract = True\n\nclass BookQuerySet(models.query.QuerySet):\n '''Modified Book QuerySet'''\n\n def get(self, *args, **kwargs):\n '''Modified get to support fetching either the id or an alias'''\n clone = super(BookQuerySet, self).filter(id=kwargs['pk']) | super(BookQuerySet, self).filter(aliases__value=kwargs['pk'])\n clone = clone.distinct()\n num = len(clone)\n if num == 1:\n return clone._result_cache[0]\n else:\n return super(BookQuerySet, self).get(*args, **kwargs)\n\nclass BookManager(models.Manager):\n '''Modified Book Manager to pass a modifed QuerySet'''\n\n def get_query_set(self):\n '''Deliver a modifed QuerySet'''\n return BookQuerySet(self.model)\n\nclass Book(BaseModel):\n '''\n Main storage for a Book object.\n '''\n\n id = models.CharField(max_length=30, primary_key=True,\n help_text=\"The primary identifier of this title, \\\n we get this value from publishers.\")\n title = models.CharField(max_length=128,\n help_text=\"The title of this book.\",\n db_index=True, null=False, blank=False)\n description = models.TextField(blank=True, null=True, default=None,\n help_text=\"Very short description of \\\n this book.\")\n objects = BookManager()\n\n def __unicode__(self):\n return u\"Book %s\" % self.title\n\n class Meta:\n '''Meta class for Book class'''\n ordering = ['title']\n\n\nclass Alias(BaseModel):\n '''\n A book can have one or more aliases which\n\n For example, a book can be referred to with an ISBN-10\n (older, deprecated scheme), ISBN-13 (newer scheme),\n or any number of other aliases.\n '''\n\n book = models.ForeignKey(Book, related_name='aliases')\n value = models.CharField(max_length=255, db_index=True, unique=True,\n help_text=\"The value of this identifier\")\n scheme = models.CharField(max_length=40,\n help_text=\"The scheme of identifier\")\n\n def __unicode__(self):\n return '%s identifier for %s' % (self.scheme, self.book.title)\n\n","sub_path":"storage/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"430958711","text":"from pynput import keyboard\nfrom dimond_collector import DimondCollector\n\nimport pyautogui,sys\n\nclass Pipeline(object):\n def __init__(self):\n self.dimond_collector = DimondCollector()\n\n def run(self):\n self.dimond_collector.collect_dimond()\n\n def _test_pointer_position(self):\n print('Press Ctrl-C to quit.')\n try:\n while True:\n x, y = pyautogui.position()\n positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)\n print(positionStr, end='')\n print('\\b' * len(positionStr), end='', flush = True)\n except KeyboardInterrupt:\n print('\\n')\n\nif __name__ == '__main__':\n print('pipeline')\n Pipeline().run()","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"496900136","text":"from sqlalchemy import MetaData, Table, create_engine, func\nfrom sqlalchemy.engine.url import URL\nfrom sqlalchemy.sql import select, insert, expression\nfrom geoalchemy2 import Geometry, Geography\n\n\nclass OSMBoundariesImporter:\n def __init__(self):\n self._osm_boundaries_tables = ['coastline_l', 'landmass_a', 'sea_a']\n\n _osm_boundaries_db_connection_parameters = dict(\n username='osmboundaries',\n password='osmboundaries',\n port=5432,\n database='osmboundaries',\n host='osmboundaries-database',\n )\n osm_boundaries_db_connection = URL('postgresql', **_osm_boundaries_db_connection_parameters)\n self._osm_boundaries_db_engine = create_engine(osm_boundaries_db_connection)\n\n _local_db_connection_parameters = dict(\n username='postgres',\n password='postgres',\n port=5432,\n database='osmaxx_db',\n )\n local_db_connection = URL('postgresql', **_local_db_connection_parameters)\n self._local_db_engine = create_engine(local_db_connection)\n\n assert Geometry, Geography # assert classes needed for GIS-reflection are available\n self._db_meta_data = MetaData()\n self._table_metas = self._get_meta_tables()\n\n def _autoinspect_tables(self, tables, autoloader):\n return {\n table: Table(table, self._db_meta_data, autoload=True, autoload_with=autoloader)\n for table in tables\n }\n\n def _get_meta_tables(self):\n meta_boundaries = self._autoinspect_tables(\n tables=self._osm_boundaries_tables, autoloader=self._osm_boundaries_db_engine\n )\n return meta_boundaries\n\n def load_area_specific_data(self, *, extent):\n self._create_tables_on_local_db()\n self._load_boundaries_tables(extent)\n\n def _create_tables_on_local_db(self):\n self._db_meta_data.create_all(self._local_db_engine)\n\n def _load_boundaries_tables(self, extent):\n multipolygon_cast = Geometry(geometry_type='MULTIPOLYGON', srid=4326)\n multilinestring_cast = Geometry(geometry_type='MULTILINESTRING', srid=4326)\n table_casts = {\n 'sea_a': multipolygon_cast,\n 'landmass_a': multipolygon_cast,\n 'coastline_l': multilinestring_cast,\n }\n for table_name in self._osm_boundaries_tables:\n source_table_meta = self._table_metas[table_name]\n query = select([\n source_table_meta.c.ogc_fid,\n source_table_meta.c.fid,\n source_table_meta.c.wkb_geometry\n ])\n query = query.where(func.ST_Intersects(source_table_meta.c.wkb_geometry, extent.ewkt))\n self._execute_and_insert_into_local_db(query, source_table_meta, source_engine=self._osm_boundaries_db_engine)\n from sqlalchemy_views import CreateView\n view_definition_query = select([\n source_table_meta.c.ogc_fid,\n source_table_meta.c.fid,\n expression.cast(\n func.ST_Multi(func.ST_Intersection(source_table_meta.c.wkb_geometry, extent.ewkt)),\n table_casts[table_name]\n ).label('geom')\n ]).where(func.ST_Intersects(source_table_meta.c.wkb_geometry, extent.ewkt))\n view_meta = MetaData()\n view = Table(table_name, view_meta, schema='view_osmaxx')\n\n from sqlalchemy.dialects import postgresql\n from sqlalchemy.sql import text\n query_defintion_string = str(\n view_definition_query.compile(dialect=postgresql.dialect(), compile_kwargs={\"literal_binds\": True})\n )\n query_defintion_string = query_defintion_string.replace('ST_AsEWKB(CAST', 'CAST')\n query_defintion_string = query_defintion_string.replace('))) AS geom', ')) AS geom')\n query_defintion_text = text(query_defintion_string)\n create_view = CreateView(view, query_defintion_text, or_replace=True)\n self._local_db_engine.execute(create_view)\n\n def _execute_and_insert_into_local_db(self, query, table_meta, source_engine=None):\n query_result = source_engine.execute(query)\n if query_result.rowcount > 0:\n results = query_result.fetchall()\n for result in results:\n self._local_db_engine.execute(\n insert(table_meta, values=result)\n )\n","sub_path":"osmaxx/conversion/converters/converter_gis/helper/osm_boundaries_importer.py","file_name":"osm_boundaries_importer.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"501973029","text":"\"\"\"\n\nA simple optimal savings problem. The Bellman equation is\n\n v(x, z) = max_x' { u(R x + w z - x') + β E v(x', z')}\n\nwhere 0 <= x' <= R x + w z and\n\n E v(x', z') = Σ_{z'} v(x', z') Q(z, z')\n\nWe take \n\n u(c) = c^{1 - γ} / (1 - γ)\n\nand obtain the transition kernel p by discretizing\n\n log z' = ρ log z + d + σ η\n \nusing Rouwenhorst's method.\n\n\"\"\"\n\nimport numpy as np\nimport quantecon as qe\nfrom numba import jit, prange\n\n\n@jit(nopython=True)\ndef u(c, γ):\n return (c + 1e-10)**(1 - γ) / (1 - γ)\n\n\nclass SavingsProblem:\n\n def __init__(self, \n β=0.96,\n γ=2.5,\n ρ=0.9,\n d=0.0,\n σ=0.1,\n r=0.04,\n w=1.0,\n z_grid_size=25,\n x_grid_size=200,\n x_grid_max=15):\n\n self.β, self.γ = β, γ\n self.R = 1 + r\n self.w = w\n self.z_grid_size, self.x_grid_size = z_grid_size, x_grid_size\n\n mc = qe.rouwenhorst(z_grid_size, d, σ, ρ)\n self.Q = mc.P\n self.z_grid = np.exp(mc.state_values)\n\n self.x_grid = np.linspace(0.0, x_grid_max, x_grid_size)\n\n def pack_parameters(self):\n return self.β, self.γ, self.R, self.w, self.Q, self.x_grid, self.z_grid\n\n def value_function_iteration(self, \n tol=1e-4, \n max_iter=1000, \n verbose=True,\n print_skip=25): \n\n # Set initial condition, set up storage\n v_in = np.ones((self.x_grid_size, self.z_grid_size))\n v_out = np.empty_like(v_in)\n π = np.empty_like(v_in, dtype=np.int)\n\n # Set up loop\n params = self.pack_parameters()\n i = 0\n error = tol + 1\n\n while i < max_iter and error > tol:\n T(v_in, v_out, π, params)\n error = np.max(np.abs(v_in - v_out))\n i += 1\n if i % print_skip == 0:\n print(f\"Error at iteration {i} is {error}.\")\n v_in[:] = v_out\n\n if i == max_iter: \n print(\"Failed to converge!\")\n\n if verbose and i < max_iter:\n print(f\"\\nConverged in {i} iterations.\")\n\n return v_out, π\n\n\n@jit(nopython=True, parallel=True)\ndef T(v, v_out, π, params):\n \"\"\"\n Given v, compute Tv and write it to v_out.\n\n At the same time, compute the v-greedy policy and write it to π\n\n \"\"\"\n n, m = v.shape\n β, γ, R, w, Q, x_grid, z_grid = params\n\n for j in prange(m):\n z = z_grid[j]\n\n for i in range(n):\n x = x_grid[i]\n\n # Cash in hand at start of period\n y = R * x + w * z \n # A variable to store largest recorded value\n max_so_far = - np.inf\n\n # Find largest x_grid index s.t. x' <= y\n idx = np.searchsorted(x_grid, y)\n\n # Step through x' with 0 <= x' <= y, find max\n for k in range(idx):\n x_next = x_grid[k]\n val = u(y - x_next, γ) + β * np.sum(v[k, :] * Q[j, :])\n if val > max_so_far:\n max_so_far = val\n k_star = k\n\n π[i, j] = k_star\n v_out[i, j] = max_so_far\n\n\n","sub_path":"day3/applications/optimal_saving/optsaving.py","file_name":"optsaving.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"106598612","text":"import os\nimport re\n\n\n\naatype_num_dict = {'ALA': 0, 'ARG': 0, 'ASN': 0, 'ASP': 0,\n 'CYS': 0, 'GLN': 0, 'GLU': 0, 'GLY': 0,\n 'HIS': 0, 'ILE': 0, 'LEU': 0, 'LYS': 0,\n 'MET': 0, 'PHE': 0, 'PRO': 0, 'SER': 0,\n 'THR': 0, 'TRP': 0, 'TYR': 0, 'VAL': 0}\n\n\naatype_per_dict = {'ALA': 0, 'ARG': 0, 'ASN': 0, 'ASP': 0,\n 'CYS': 0, 'GLN': 0, 'GLU': 0, 'GLY': 0,\n 'HIS': 0, 'ILE': 0, 'LEU': 0, 'LYS': 0,\n 'MET': 0, 'PHE': 0, 'PRO': 0, 'SER': 0,\n 'THR': 0, 'TRP': 0, 'TYR': 0, 'VAL': 0}\n\n\n\n\ndef RE_PDB_content(pdb_file_name):\n file_handle = open(pdb_file_name, 'r')\n return file_handle\n\n\ndef Match_aatype(PDB_aatype_content):\n aatype_m = re.match('ATOM\\s+[0-9]+\\s+CA\\s+([A-Z]+)\\s+(\\w+)\\s+(\\d+)\\s+(\\D?\\d+\\.\\d+)\\s+(\\D?\\d+\\.\\d+)\\s+(\\D?\\d+\\.\\d+).+',PDB_aatype_content)\n if aatype_m == None:\n return 0\n else:\n return aatype_m.group(1)\n\n\n\n\nprint(\"输入要统计的数据的路径:\")\n\nPDB_Path = input()\nos.chdir(PDB_Path)\nprint(\"you input pdb path is :\", os.getcwd())\nPDB_Path_listdir = os.listdir(PDB_Path)\n\n\nfor pbd_shape_txt_name in PDB_Path_listdir:\n pdb_shape_txt_handle = RE_PDB_content(pbd_shape_txt_name)\n for pdb_shape_txt_content in pdb_shape_txt_handle:\n aatype = Match_aatype(pdb_shape_txt_content)\n for key in aatype_num_dict:\n if aatype == key:\n aatype_num_dict[key] = aatype_num_dict[key] + 1\n\n\n\nvalue_sum = 0\n\nfor key in aatype_num_dict:\n value_sum = value_sum + aatype_num_dict[key]\n\nfor key in aatype_num_dict:\n aatype_per_dict[key] = aatype_num_dict[key]/value_sum\n\nprint(aatype_num_dict)\n\nprint(value_sum)\n\nprint(aatype_per_dict)","sub_path":"pdb_data_pretreatment/A4统计文件夹下蛋白质数据中氨基酸的分布/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"565747293","text":"class Solution(object):\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # second round\n # 2016-07-17\n # 25 only counts once since it already counted as 5\n res = 0\n base = 5\n while base <= n:\n res += n / base\n base *= 5\n return res\n \n \n","sub_path":"172-factorial_trailing_zeroes/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"471296881","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 19 20:29:19 2019\n\n@author: edwardlam\n\"\"\"\n##################################################################################################################\n\n# Write a program that prints the longest substring of s \n# in which the letters occur in alphabetical order\n# for example, if s = 'azcbobobegghakl', then your program should print\n# Longest substring in alphabetical order is: beggh\n\n# In the case of ties, print the first substring. \n# For example, if s = 'abcbcd', then your program should print\n# Longest substring in alphabetical order is: abc\n\n##################################################################################################################\ns = 'rhaptkkceskizx'\nbeg = 0\nend = 0\nL = s[beg:end+1]\nL0 = ''\n\nfor i in range(len(s)):\n while i < len(s):\n if s[i] >= L[-1]:\n end += 1\n L = s[beg:end]\n break\n else:\n if len(L)>len(L0):\n L0 = L\n beg = end\n end += 1\n L = s[beg:end]\n break\n else:\n beg = end\n end += 1\n L = s[beg:end+1]\n break\nif len(L) > len(L0):\n print(\"The longest substring is:\",L)\nelse:\n print(\"The longest substring is:\",L0)\n\n","sub_path":"LongestSubstring.py","file_name":"LongestSubstring.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"475092707","text":"import optparse\nimport pickle as pkl\nimport time\n\nimport matplotlib.pyplot as plt\nimport yaml\nimport tensorflow as tf\nfrom tensorflow_probability import bijectors as tfb\nfrom tensorflow_probability import distributions as tfd\n\nfrom covid.model import CovidUKODE, covid19uk_logp, load_data\nfrom covid.util import *\n\nDTYPE = np.float64\n\n\ndef random_walk_mvnorm_fn(covariance, name=None):\n \"\"\"Returns callable that adds Multivariate Normal noise to the input\"\"\"\n covariance = covariance + tf.eye(covariance.shape[0], dtype=tf.float64) * 1.e-9\n scale_tril = tf.linalg.cholesky(covariance)\n rv = tfp.distributions.MultivariateNormalTriL(loc=tf.zeros(covariance.shape[0], dtype=tf.float64),\n scale_tril=scale_tril)\n\n def _fn(state_parts, seed):\n with tf.name_scope(name or 'random_walk_mvnorm_fn'):\n new_state_parts = [rv.sample() + state_part for state_part in state_parts]\n return new_state_parts\n\n return _fn\n\n\n\nif __name__ == '__main__':\n\n parser = optparse.OptionParser()\n parser.add_option(\"--config\", \"-c\", dest=\"config\", default=\"ode_config.yaml\",\n help=\"configuration file\")\n options, args = parser.parse_args()\n with open(options.config, 'r') as ymlfile:\n config = yaml.load(ymlfile)\n\n param = sanitise_parameter(config['parameter'])\n settings = sanitise_settings(config['settings'])\n\n data = load_data(config['data'], settings)\n\n case_reports = pd.read_csv(config['data']['reported_cases'])\n case_reports['DateVal'] = pd.to_datetime(case_reports['DateVal'])\n case_reports = case_reports[case_reports['DateVal'] >= '2020-02-19']\n date_range = [case_reports['DateVal'].min(), case_reports['DateVal'].max()]\n y = case_reports['CumCases'].to_numpy()\n y_incr = np.round((y[1:] - y[:-1]) * 0.8)\n\n simulator = CovidUKODE(M_tt=data['M_tt'],\n M_hh=data['M_hh'],\n C=data['C'],\n N=data['pop']['n'].to_numpy(),\n W=data['W'].to_numpy(),\n date_range=[date_range[0] - np.timedelta64(1, 'D'), date_range[1]],\n holidays=settings['holiday'],\n lockdown=settings['lockdown'],\n time_step=int(settings['time_step']))\n\n seeding = seed_areas(data['pop']['n'].to_numpy(), data['pop']['Area.name.2']) # Seed 40-44 age group, 30 seeds by popn size\n state_init = simulator.create_initial_state(init_matrix=seeding)\n\n def logp(par):\n p = param\n p['beta1'] = par[0]\n p['beta3'] = par[1]\n p['gamma'] = par[2]\n p['I0'] = par[3]\n p['r'] = par[4]\n beta_logp = tfd.Gamma(concentration=tf.constant(1., dtype=DTYPE), rate=tf.constant(1., dtype=DTYPE)).log_prob(p['beta1'])\n beta3_logp = tfd.Gamma(concentration=tf.constant(20., dtype=DTYPE),\n rate=tf.constant(20., dtype=DTYPE)).log_prob(p['beta3'])\n gamma_logp = tfd.Gamma(concentration=tf.constant(100., dtype=DTYPE), rate=tf.constant(400., dtype=DTYPE)).log_prob(p['gamma'])\n I0_logp = tfd.Gamma(concentration=tf.constant(1.5, dtype=DTYPE), rate=tf.constant(0.05, dtype=DTYPE)).log_prob(p['I0'])\n r_logp = tfd.Gamma(concentration=tf.constant(0.1, dtype=DTYPE), rate=tf.constant(0.1, dtype=DTYPE)).log_prob(p['gamma'])\n state_init = simulator.create_initial_state(init_matrix=seeding * p['I0'])\n t, sim, solve = simulator.simulate(p, state_init)\n y_logp = covid19uk_logp(y_incr, sim, 0.1, p['r'])\n logp = beta_logp + beta3_logp + gamma_logp + I0_logp + r_logp + tf.reduce_sum(y_logp)\n return logp\n\n def trace_fn(_, pkr):\n return (\n pkr.inner_results.log_accept_ratio,\n pkr.inner_results.accepted_results.target_log_prob,\n pkr.inner_results.accepted_results.step_size)\n\n\n unconstraining_bijector = [tfb.Exp()]\n initial_mcmc_state = np.array([0.05, 1.0, 0.25, 1.0, 50.], dtype=np.float64) # beta1, gamma, I0\n print(\"Initial log likelihood:\", logp(initial_mcmc_state))\n\n @tf.function(autograph=False, experimental_compile=True)\n def sample(n_samples, init_state, scale, num_burnin_steps=0):\n return tfp.mcmc.sample_chain(\n num_results=n_samples,\n num_burnin_steps=num_burnin_steps,\n current_state=init_state,\n kernel=tfp.mcmc.TransformedTransitionKernel(\n inner_kernel=tfp.mcmc.RandomWalkMetropolis(\n target_log_prob_fn=logp,\n new_state_fn=random_walk_mvnorm_fn(scale)\n ),\n bijector=unconstraining_bijector),\n trace_fn=lambda _, pkr: pkr.inner_results.is_accepted)\n\n joint_posterior = tf.zeros([0] + list(initial_mcmc_state.shape), dtype=DTYPE)\n\n scale = np.diag([0.1, 0.1, 0.1, 0.1, 1.])\n overall_start = time.perf_counter()\n\n num_covariance_estimation_iterations = 50\n num_covariance_estimation_samples = 50\n num_final_samples = 10000\n start = time.perf_counter()\n for i in range(num_covariance_estimation_iterations):\n step_start = time.perf_counter()\n samples, results = sample(num_covariance_estimation_samples,\n initial_mcmc_state,\n scale)\n step_end = time.perf_counter()\n print(f'{i} time {step_end - step_start}')\n print(\"Acceptance: \", results.numpy().mean())\n joint_posterior = tf.concat([joint_posterior, samples], axis=0)\n cov = tfp.stats.covariance(tf.math.log(joint_posterior))\n print(cov.numpy())\n scale = cov * 2.38**2 / joint_posterior.shape[1]\n initial_mcmc_state = joint_posterior[-1, :]\n\n step_start = time.perf_counter()\n samples, results = sample(num_final_samples,\n init_state=joint_posterior[-1, :], scale=scale,)\n joint_posterior = tf.concat([joint_posterior, samples], axis=0)\n step_end = time.perf_counter()\n print(f'Sampling step time {step_end - step_start}')\n end = time.perf_counter()\n print(f\"Simulation complete in {end-start} seconds\")\n print(\"Acceptance: \", np.mean(results.numpy()))\n print(tfp.stats.covariance(tf.math.log(joint_posterior)))\n\n fig, ax = plt.subplots(1, joint_posterior.shape[1])\n for i in range(joint_posterior.shape[1]):\n ax[i].plot(joint_posterior[:, i])\n\n plt.show()\n print(f\"Posterior mean: {np.mean(joint_posterior, axis=0)}\")\n\n with open('pi_beta_2020-03-29.pkl', 'wb') as f:\n pkl.dump(joint_posterior, f)\n","sub_path":"mcmc.py","file_name":"mcmc.py","file_ext":"py","file_size_in_byte":6669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"518190985","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 22 22:58:18 2018\n\n@author: goncalves.fernandes.junior\n\"\"\"\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\nimport tkinter as tk\nimport ArgumentComponent as ac\nimport Relation\nimport RelationGraph as rg\n\nclass VisualizationPage(tk.Frame):\n \n def __init__(self, Window, Filetxt :str, FileAnn : str, relations, **kwargs):\n tk.Frame.__init__(self, Window, width=800, height=800, **kwargs)\n self.textD = tk.Text(self,height = 400,wrap=tk.WORD)\n text = self.getTextOfFile(Filetxt)\n index4words = self.showSomeWords(Filetxt)\n print(\"Index 4 words:\",index4words)\n self.textD.insert(tk.INSERT,text[0:index4words])\n self.textD.insert(tk.END,\"[...]\")\n self.textD.config(state=tk.DISABLED)\n self.textD.pack()\n \n self.relations = relations\n \n #Relation Button\n self.bRelation = tk.Button(Window, text =\"Show relation\", height = 2, width = len(\"Show relation\"), command = lambda : self.showRelation(self.relations, Filetxt))\n self.bRelation.pack()\n \n #Relation Grap Button\n self.bRelation = tk.Button(Window, text =\"Show relation graph\", height = 2, width = len(\"Show relation graph\"), command = lambda : self.showRelationGraph(self.relations))\n self.bRelation.pack()\n \n #Components Button\n self.bArgComponent = tk.Button(Window, text =\"Show Components\", \n height = 2, width = len(\"Show Components\"),\n command = lambda :self.showArgumentComponent(Window,Filetxt,FileAnn))\n self.bArgComponent.pack()\n \n \n self.bShowAllText = tk.Button(Window, text =\"Show all the argument\", \n height = 2, width = len(\"Show all the argument\"),\n command = lambda :self.showArgument(Window,Filetxt))\n self.bShowAllText.pack()\n \n self.pack()\n \n \n def showRelation(self, relations, Filetxt):\n #self.textD.destroy()\n newWindow = tk.Tk()\n newWindow.title(\"Argument Component Visualization\")\n newWindow.minsize(width=800, height=800)\n newWindow.maxsize(width=800, height=800)\n newWindow.resizable(False, False)\n text = tk.Text(newWindow, height = 400, wrap=tk.WORD)\n text.insert(tk.INSERT, self.getTextOfFile(Filetxt))\n for r in relations:\n start = \"1.0 + \" + r.position[0] + \" chars\"\n end = \"1.0 + \" + r.position[1] + \" chars\"\n color = r.getColor()\n if(color == \"green\"):\n text.tag_add(\"green\", start, end)\n text.tag_config(\"green\", foreground=color)\n else :\n text.tag_add(\"red\", start, end)\n text.tag_config(\"red\", foreground=color)\n text.pack()\n \n def showRelationGraph(self, relations):\n graph = rg.RelationGraph()\n for r in relations:\n graph.addRelation(r.argOne, r.argTwo, r.getColor())\n graph.draw()\n \n def showArgumentComponent(self,window, Filetxt : str,FileAnn : str):\n #self.textD.destroy()\n newWindow = tk.Tk()\n newWindow.title(\"Argument Component Visualization\")\n newWindow.minsize(width=800, height=800)\n newWindow.maxsize(width=800, height=800)\n newWindow.resizable(False, False)\n \n newText = tk.Text(newWindow,height = 400,wrap=tk.WORD)\n newText.insert(tk.INSERT, self.getTextOfFile(Filetxt))\n self.changeText(Filetxt,FileAnn,newText)\n newText.pack()\n \n def showArgument(self, Window,Filetxt : str):\n self.textD.destroy()\n self.textD = tk.Text(self,height = 400,wrap=tk.WORD)\n text = self.getTextOfFile(Filetxt)\n self.textD.insert(tk.INSERT,text)\n self.textD.config(state=tk.DISABLED)\n self.textD.pack()\n \n def showSomeWords(self,Filetxt : str):\n text = self.getTextOfFile(Filetxt)\n text_splitted = text.split(\" \")\n i = 0\n index = 0\n #on cherche l'indice après les 4 premiers mots du texte\n while (i < 4):\n index = index + len(text_splitted[i])\n index = index + 1 #pour l'espace\n i = i + 1\n return index\n \n def getTextOfFile(self, File : str):\n file = open(File)\n res = \"\"\n for linetext in file.readlines():\n res = res + linetext\n return res\n\n def addTags(self,textD,listOfargs):\n for argc in listOfargs:\n ind = textD.search(str(argc.text),\"0.0\")\n splitPos = ind.split('.') \n endText = int(splitPos[1]) + len(argc.text)\n endIndex = splitPos[0]+'.'+str(endText)\n textD.tag_add(str(argc)+\"tag\",ind,endIndex)\n textD.tag_config(str(argc)+\"tag\", foreground=argc.color)\n \n \n def changeText(self, FileTxt : str,FileAnn : str,textD):\n argsComponents = ac.extractArgumentComponents(FileAnn)\n major_claims = argsComponents[0]\n claims = argsComponents[1]\n premises = argsComponents[3]\n self.addTags(textD,major_claims)\n self.addTags(textD,claims)\n self.addTags(textD,premises)\n \n return textD\n\n\n\n\n\nif __name__ == '__main__':\n \n window = tk.Tk()\n window.title(\"Visualization Page\")\n window.minsize(width=800, height=800)\n window.maxsize(width=800, height=800)\n window.resizable(False, False)\n \n \n","sub_path":"VisualizationPage.py","file_name":"VisualizationPage.py","file_ext":"py","file_size_in_byte":5576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"246046046","text":"def eh_crescente(lista):\n i = 1\n while i < len(lista):\n if lista[i] > lista[i -1]:\n m = 2\n else:\n m =3\n break\n i+=1\n if m==2:\n return True\n elif m==3:\n return False","sub_path":"backup/user_225/ch48_2020_04_20_23_50_14_200935.py","file_name":"ch48_2020_04_20_23_50_14_200935.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"336758434","text":"\"\"\"\nWatchInSGE System\n\"\"\"\n\n\n## @package base.users.urls\n#\n# Communication routes between views and templates\n# @author Team WatchIn\n# @date 02-10-2018\n# @version 1.0\n\nfrom django.urls import path\n\nfrom .views import *\n\nurlpatterns = [\n path(\n 'register/users',\n UserCreateViewApi.as_view(),\n name='user-create'\n ),\n]","sub_path":"base/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"458618341","text":"from util import concat, removefromgraf, updategraf, matching, mappingsemester, printgraf\n\ndef toso(graf):\n # implementasi pendekatan topological sort\n # dengan decrease and conquer (rekursi)\n\n # basis\n if(len(graf)==1):\n return graf\n # rekuren\n else:\n # akan dipilih simpul tanpa sisi masuk\n for data in graf:\n if len(data[\"masuk\"])==0:\n simpul = data[\"simpul\"]\n # decreasing\n decrease = updategraf(removefromgraf(graf, simpul), simpul)\n # conquering + recursion\n return concat([data], toso(decrease))\n\ndef parse(file):\n '''\n parsing file\n\n contoh isi file = A,B,C. dengan A adalah simpul dan B,C adalah simpul adjacent yang menuju A.\n A adalah mata kuliah dengan B dan C adalah prerequisite-nya.\n\n Akan di-parse menjadi tipe data berikut, misal Graf\n {\n simpul: nama simpul (misal A),\n masuk: array of simpul bersebelahan dengan A yang masuk ke simpul A\n }\n\n Seluruh baris harus diakhiri dengan titik (spek soal) dan enter atau new line.\n\n Asumsi input adalah Directed Acrylic Graph\n\n Output berupa Graf.\n '''\n \n copy = file.readlines()\n\n # menghapus spasi, new line, dan titik\n # return 1 jika tidak ada titik di akhir baris\n for i in range(len(copy)):\n if copy[i][len(copy[i])-2] != \".\":\n return 1\n copy[i] = copy[i].replace(\" \", \"\").replace(\"\\n\",\"\").replace(\".\",\"\")\n\n out = []\n # mengolah baris-baris fail tadi lalu dipindahkan ke struktur data\n for simpul in copy:\n split = simpul.split(\",\")\n data = {\n \"simpul\": split[0],\n \"masuk\": []\n }\n for i, masuk in enumerate(split):\n if i>0:\n data[\"masuk\"].append(masuk)\n out.append(data)\n\n return out\n\ndef intro():\n print(\"Selamat datang di Penentu Pengambilan Mata Kuliah!\\n\")\n print(\"Anda bingung mau ngambil kuliah apa dulu karena kebanyakan prerequisite?\\nGampang! Masukin aja daftar kuliahnya beserta prerequisite-nya ke program ini, nanti bakal dikasih urutan pengambilan dalam bentuk tiap-tiap semester!\")\n print(\"========================\")\n print(\"Contoh isi file:\\n[nama kuliah] [, prerequisite 1] [, prerequisite 2].\")\n print(\"A.\\nB, C, A.\\nC, A.\")\n print(\"========================\")\n print(\"Program dikerjakan oleh Rezda A.F 13519194\\n\")\n\ndef start(nointro = False, showsorted = False):\n '''\n Menjalankan program dengan flow sbb.\n\n 1. Meminta nama fail dan direktori jika ada\n 2. Mem-parsing fail jika tidak ada error\n 3. Memprosesnya jika tidak ada error\n 4. Mengurutkan graf dengan pendekatan topological sort\n 5. Mapping graf yang sudah diurutkan ke semester yang sesuai\n 6. Mengeluarkannya ke layar\n '''\n\n if not nointro: intro()\n\n nama_file = input(\"Masukkan nama fail dengan ekstensinya (dan foldernya jika ada)\\n> \")\n if nama_file==\"exit\": return\n\n try:\n file = open(nama_file, \"r\")\n except:\n print (\"Error, terjadi kesalahan saat membaca fail.\\n\")\n start(True)\n return\n \n # parsing fail\n parsed = parse(file)\n\n # error handling\n if type(parsed) is int and parsed == 1:\n print (\"Error, format isi fail salah!\\nSetiap baris harus diakhiri titik.\\n\")\n start(True)\n return\n\n # membuka kembali fail untuk ditampilkan ke layar\n # dan untuk mencocokkan data graf yang sudah diurutkan\n file = open(nama_file, \"r\")\n parsed2 = parse(file)\n\n print(\"\\nMata Kuliah beserta prerequisite-nya: \")\n printgraf(parsed2)\n\n sortedgraf = matching(parsed2, toso(parsed))\n\n if showsorted:\n print(\"\\nMata Kuliah setelah diurutkan: \")\n printgraf(sortedgraf)\n\n # mapping semester\n semester = mappingsemester(sortedgraf)\n\n # menampilkan hasilnya ke layar\n i = 0\n print(\"\\nUrutan pengambilan dalam semester:\")\n for i, listmatkul in enumerate(semester):\n print(\"Semester\", str(i+1), \":\", end=\" \")\n for i, matkul in enumerate(listmatkul):\n print (matkul, end=\", \" if i < len(listmatkul)-1 else \"\\n\")","sub_path":"src/original/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":3842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"14656817","text":"# Copyright (c) 2023 CNES\n#\n# All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\n\"\"\"\nCalculate statistics of a stream of values\n------------------------------------------\n\"\"\"\nfrom typing import Any, Iterable, Optional, Union\n\nimport dask.array.core\nimport numpy\n\nfrom .. import core\n\n\ndef _delayed(\n attr: str,\n values: dask.array.core.Array,\n weights: Optional[dask.array.core.Array] = None,\n axis: Optional[Iterable[int]] = None,\n bin_count: Optional[int] = None,\n) -> Union[core.StreamingHistogramFloat64, core.StreamingHistogramFloat32]:\n \"\"\"Calculate the descriptive statistics of a dask array.\"\"\"\n if weights is not None and values.shape != weights.shape:\n raise ValueError('values and weights must have the same shape')\n\n def _process_block(attr, x, w, axis, bin_count):\n instance = getattr(core, attr)(values=x,\n weights=w,\n axis=axis,\n bin_count=bin_count)\n return numpy.array([instance], dtype='object')\n\n drop_axis = list(range(values.ndim))[1:]\n\n return dask.array.core.map_blocks(\n _process_block,\n attr,\n values,\n weights,\n axis,\n bin_count,\n drop_axis=drop_axis,\n dtype='object').sum().compute() # type: ignore\n\n\nclass StreamingHistogram:\n \"\"\"Streaming histogram.\n\n The bins in the histogram have no predefined size, so that as values are\n pushed into the histogram, bins are added and merged as soon as their\n numbers exceed the maximum allowed capacity. A particularly interesting\n feature of streaming histograms is that they can be used to approximate\n quantiles without sorting (or even storing) values individually. The\n histograms can be constructed independently and merged, making them usable\n with Dask.\n\n Args:\n values: Array containing numbers whose statistics are desired.\n\n .. note::\n\n NaNs are automatically ignored.\n\n weights: An array of weights associated with the values. If not\n provided, all values are assumed to have equal weight.\n axis: Axis or axes along which to compute the statistics. If not\n provided, the statistics are computed over the flattened array.\n bin_count: The maximum number of bins to use in the histogram. If\n the number of bins exceeds the number of values, the histogram\n will be trimmed. Default is ``None``, which will set the number\n of bins to 100.\n dtype: Data type of the returned array. By default, the data type\n is numpy.float64.\n\n .. seealso::\n\n Yael Ben-Haim and Elad Tom-Tov,\n A Streaming Parallel Decision Tree Algorithm,\n Journal of Machine Learning Research, 11, 28, 849-872,\n http://jmlr.org/papers/v11/ben-haim10a.html\n\n .. note::\n\n If you do not want to estimate the quantiles of the dataset, use the\n class :py:class:`DescriptiveStatistics `\n which will give you more accurate results.\n \"\"\"\n\n def __init__(self,\n values: Union[dask.array.core.Array, numpy.ndarray],\n weights: Optional[Union[dask.array.core.Array,\n numpy.ndarray]] = None,\n axis: Optional[Union[int, Iterable[int]]] = None,\n bin_count: Optional[int] = None,\n dtype: Optional[numpy.dtype] = None) -> None:\n if isinstance(axis, int):\n axis = (axis, )\n dtype = dtype or numpy.dtype('float64')\n if dtype == numpy.dtype('float64'):\n attr = 'StreamingHistogramFloat64'\n elif dtype == numpy.dtype('float32'):\n attr = 'StreamingHistogramFloat32'\n else:\n raise ValueError(f'dtype {dtype} not handled by the object')\n if isinstance(values, dask.array.core.Array) or isinstance(\n weights, dask.array.core.Array):\n self._instance = _delayed(attr,\n dask.array.core.asarray(values),\n weights=dask.array.core.asarray(weights)\n if weights is not None else None,\n axis=axis,\n bin_count=bin_count)\n else:\n self._instance: Union[core.StreamingHistogramFloat64,\n core.StreamingHistogramFloat32] = getattr(\n core, attr)(values,\n weights=weights,\n axis=axis,\n bin_count=bin_count)\n\n def __iadd__(self, other: Any) -> 'StreamingHistogram':\n \"\"\"Adds a new histogram to the current one.\n\n Args:\n The histogram to add to the current one.\n\n Returns:\n itself.\n \"\"\"\n if isinstance(other, StreamingHistogram):\n if type(self._instance) != type(other._instance): # noqa: E721\n raise TypeError('StreamingHistogram types must match')\n self._instance += other._instance # type: ignore\n else:\n raise TypeError('unsupported operand type(s) for +='\n f\": '{type(self)}' and '{type(other)}'\")\n return self\n\n def bins(self) -> numpy.ndarray:\n \"\"\"Returns the histogram bins.\n\n Returns:\n The histogram bins.\n \"\"\"\n return self._instance.bins()\n\n def size(self) -> numpy.ndarray:\n \"\"\"Returns the number of bins allocated to calculate the histogram.\n\n If :py:meth:`size() ` is equal to\n :py:meth:`count() ` then the\n histogram used to calculate the statistics is un-compressed. Otherwise,\n the histogram is compressed, which means that the calculated statistical\n quantities are an approximation of the statistical variables.\n\n Returns:\n Number of bins allocated to calculate the histogram.\n \"\"\"\n return self._instance.size()\n\n def count(self) -> numpy.ndarray:\n \"\"\"Returns the count of samples.\n\n Returns:\n The count of samples.\n \"\"\"\n return self._instance.count()\n\n def kurtosis(self) -> numpy.ndarray:\n \"\"\"Returns the kurtosis of samples.\n\n Returns:\n The kurtosis of samples.\n \"\"\"\n return self._instance.kurtosis()\n\n def max(self) -> numpy.ndarray:\n \"\"\"Returns the maximum of samples.\n\n Returns:\n The maximum of samples.\n \"\"\"\n return self._instance.max()\n\n def mean(self) -> numpy.ndarray:\n \"\"\"Returns the mean of samples.\n\n Returns:\n The mean of samples.\n \"\"\"\n return self._instance.mean()\n\n def min(self) -> numpy.ndarray:\n \"\"\"Returns the minimum of samples.\n\n Returns:\n The minimum of samples.\n \"\"\"\n return self._instance.min()\n\n def skewness(self) -> numpy.ndarray:\n \"\"\"Returns the skewness of samples.\n\n Returns:\n The skewness of samples.\n \"\"\"\n return self._instance.skewness()\n\n def sum_of_weights(self) -> numpy.ndarray:\n \"\"\"Returns the sum of weights.\n\n Returns:\n The sum of weights.\n \"\"\"\n return self._instance.sum_of_weights()\n\n def var(self) -> numpy.ndarray:\n \"\"\"Returns the variance of samples.\n\n Returns:\n The variance of samples.\n \"\"\"\n return self._instance.variance()\n\n def std(self) -> numpy.ndarray:\n \"\"\"Returns the standard deviation of samples.\n\n Returns:\n The standard deviation of samples.\n \"\"\"\n return numpy.sqrt(self.var())\n\n def quantile(self, q: float = 0.5) -> numpy.ndarray:\n \"\"\"Returns the q quantile of samples.\n\n Args:\n q (float): Quantile to compute. Default is ``0.5`` (median).\n\n Returns:\n The q quantile of samples.\n \"\"\"\n return self._instance.quantile(q)\n","sub_path":"src/pyinterp/statistics/streaming_histogram.py","file_name":"streaming_histogram.py","file_ext":"py","file_size_in_byte":8361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"598355607","text":"import jsonrpcclient\nfrom service import registry\n\nif __name__ == \"__main__\":\n\n try:\n endpoint = input(\"Endpoint (localhost:{}): \".format(registry[\"image_recon_service\"][\"jsonrpc\"]))\n if endpoint == \"\":\n endpoint = \"localhost:{}\".format(registry[\"image_recon_service\"][\"jsonrpc\"])\n\n rpc_method = input(\"Method (flowers|dogs|cars): \")\n\n model = input(\"Model (ResNet18): \")\n if model == \"\":\n model = \"ResNet18\"\n\n img_path = input(\"Image (Path or Link): \")\n\n ret = jsonrpcclient.request(\"http://{}\".format(endpoint), rpc_method, model=model, img_path=img_path)\n delta_time = ret[\"result\"][\"delta_time\"]\n top5 = ret[\"result\"][\"top_5\"]\n print(\"Delta time: \" + str(delta_time))\n for (k, v) in sorted(top5.items()):\n print(\"{0} - {1}\".format(k, v))\n\n except Exception as e:\n print(e)\n","sub_path":"Services/JSON-RPC/CNTK_ImageRecon/test_image_recon_service.py","file_name":"test_image_recon_service.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"126607655","text":"#coding=utf-8\nimport numpy as np\nimport sys\nfrom collections import defaultdict\n\nif \"../\" not in sys.path:\n sys.path.append(\"../\")\n\nfrom lib.envs.simple_rooms import SimpleRoomsEnv\nfrom lib.envs.windy_gridworld import WindyGridworldEnv\nfrom lib.envs.cliff_walking import CliffWalkingEnv\nfrom lib.simulation import Experiment\n\n\nclass Agent(object):\n\n def __init__(self, actions):\n self.actions = actions\n self.num_actions = len(actions)\n\n def act(self, state):\n raise NotImplementedError\n\n\nclass SarsaAgent(Agent):\n\n def __init__(self, actions, epsilon=0.01, alpha=0.5, gamma=1):\n super(SarsaAgent, self).__init__(actions)\n\n ## TODO 1\n ## Initialize empty dictionary here\n self.Q = defaultdict(lambda: np.zeros(len(actions)))\n ## In addition, initialize the value of epsilon, alpha and gamma\n self.epsilon = 0.01\n self.alpha = 0.5\n self.gamma = 1\n\n def stateToString(self, state):\n mystring = \"\"\n if np.isscalar(state):\n mystring = str(state)\n else:\n for digit in state:\n mystring += str(digit)\n return mystring\n\n def act(self, state):\n stateStr = self.stateToString(state)\n s = stateStr\n action = np.random.randint(0, self.num_actions)\n ## TODO 2\n ## Implement epsilon greedy policy here\n choice = 1\n\n if self.epsilon == 0:\n choice = 0\n elif self.epsilon == 1:\n choice = 1\n else:\n choice = np.random.binomial(1, self.epsilon)\n\n if choice == 0:\n #贪心\n values = self.Q[s]\n maxValue = np.argmax(values)\n datas = []\n for index, value in enumerate (values):\n if value == maxValue:\n datas.append(index)\n action = np.random.choice(datas)\n print(action)\n\n\n return action\n\n def learn(self, state1, action1, reward, state2, action2):\n state1Str = self.stateToString(state1)\n state2Str = self.stateToString(state2)\n ## TODO 3\n ## Implement the sarsa update here\n\n \"\"\"\n SARSA Update\n Q(s,a) <- Q(s,a) + alpha * (reward + gamma * Q(s',a') - Q(s,a))\n or\n Q(s,a) <- Q(s,a) + alpha * (td_target - Q(s,a))\n or\n Q(s,a) <- Q(s,a) + alpha * td_delta\n \"\"\"\n r = reward\n a = action1\n s = state1Str\n a_ = action2\n s_ = state2Str\n self.Q[s][a] = self.Q[s][a] + self.alpha * (r + self.gamma*self.Q[s_][a_] - self.Q[s][a])\n\ninteractive = True\n# %matplotlib nbagg\nenv = SimpleRoomsEnv()\nagent = SarsaAgent(range(env.action_space.n))\nexperiment = Experiment(env, agent)\nexperiment.run_sarsa(10, interactive)","sub_path":"edx_DAT257x_Reinforcement_Learning_Explained/Module5/ex_5.2_sarsa.py","file_name":"ex_5.2_sarsa.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"157122037","text":"def panCheck(string):\n digits = len(string)\n if digits >= 10:\n return False\n for i in range(1,digits+1):\n if str(i) not in string:\n return False\n return True\n\nimport math\n#simple primality check.\ndef checkIfPrime(n):\n for i in range(2,int(math.sqrt(n)+1)):\n #print('i in',i)\n if n % i == 0:\n return False\n return True\n\nmax = 0\nfor i in range(12,100000000000000):\n if checkIfPrime(i):\n if panCheck(str(i)):\n if max < i:\n max = i\n print(max)\n\nprint(panCheck(str(12345)))","sub_path":"pandigitalPrimePE41.py","file_name":"pandigitalPrimePE41.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"316764452","text":"from django.shortcuts import render\nfrom django.contrib.auth import authenticate\nfrom datetime import datetime\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponse\nimport json as simplejson\nfrom django.core.mail import EmailMessage\n\nfrom django.contrib.auth.models import User\nfrom .models import ICRequest, ScopeSupply, ServiceCall, ProductModel, Customer, EndUser\n\n# Create your views here.\ndef index(request):\n if 'logged_in' in request.session:\n return render(request,'ticket/pages/profile.html')\n else:\n return render(request,'ticket/pages/login.html')\n\ndef login(request):\n return render(request,'ticket/pages/login.html')\n\ndef profile(request):\n\tif 'logged_in' in request.session:\n \t return render(request,'ticket/pages/profile.html')\n\tif request.method == 'POST':\n\t\tu = request.POST['user']\n\t\tp = request.POST['pass']\n\t\tuser1 = authenticate(username=u, password=p)\n\t\tif user1 is not None:\n\t\t\trequest.session['logged_in'] = u\n\t\t\treturn render(request,'ticket/pages/profile.html')\n\t\telse:\n \t\t return render(request,'ticket/pages/login.html',{'error': 'Incorrect Username/Password'})\n\ndef logout(request):\n if 'logged_in' in request.session:\n del request.session['logged_in']\n return render(request,'ticket/pages/login.html', {'error': 'Logged out'})\n else:\n return render(request, 'ticket/pages/login.html')\n\t\t\ndef ic_request(request):\n\tcustomer = Customer.objects.all()\n\tend_user = EndUser.objects.all()\n\treturn render(request,'ticket/pages/ic_request.html',{'customer':customer, 'end_user':end_user})\n\ndef service_call(request):\n\tcustomer = Customer.objects.all()\n\tend_user = EndUser.objects.all()\n\treturn render(request,'ticket/pages/service_call.html',{'customer':customer, 'end_user':end_user})\n\t\ndef scope_of_supply(request):\n\tif request.method == 'POST':\n\t\tcustomer = request.POST['customer']\n\t\tenduser = request.POST['enduser']\n\t\tsitename = request.POST['sitename']\n\t\tsiteaddress = request.POST['siteaddress']\n\t\tcontactpersonname1 = request.POST['contactpersonname1']\n\t\tcontactpersonno1 = request.POST['contactpersonno1']\n\t\tcontactpersonname2 = request.POST['contactpersonname2']\n\t\tcontactpersonno2 = request.POST['contactpersonno2']\n\t\treqdateinstall = request.POST['reqdateinstall']\n\t\tpresignoff = request.POST['presignoff']\n\t\tsitestatus = request.POST['sitestatus']\n\t\tnoofjobs = request.POST['noofjobs']\n\t\tnameofproduct = request.POST['nameofproduct']\n\t\tqty = request.POST['qty']\n\t\ttransformervalvesize = request.POST['transformervalvesize']\n\t\tmaterialreached = request.POST['materialreached']\n\t\tsalesmanagerrequestno = request.POST['salesmanagerrequestno']\n\t\tdate = datetime.date.today()\n\t\tuser = User.objects.get(username=request.session['logged_in'])\n\t\tic = ICRequest(customer=customer,end_user=enduser,site_name=sitename,site_address=siteaddress,contact_person_name1=contactpersonname1,\n\t\tcontact_person_no1=contactpersonno1,contact_person_name2=contactpersonname2,\n\t\tcontact_person_no2=contactpersonno2,req_date_of_installation_by_customer=reqdateinstall,pre_sign_off_sheet_status=presignoff,\n\t\tsite_status=sitestatus,no_of_jobs=noofjobs,name_of_product_supplied=nameofproduct\n\t\t,quantity=qty,transformer_valve_size_details=transformervalvesize,material_reached_at_site=materialreached,\n\t\tsales_manager_request_no=salesmanagerrequestno,date=date,created_by=user)\n\t\tic.save()\n\t\trequest.session['icrequestno'] = ic.id\n\n\treturn render(request,'ticket/pages/scope_of_supply.html')\n\t\ndef product_model(request):\n\tif request.method == 'POST':\n\t\tcustomer = request.POST['customer']\n\t\tenduser = request.POST['enduser']\n\t\tsitename = request.POST['sitename']\n\t\tsiteaddress = request.POST['siteaddress']\n\t\tcontactpersonname1 = request.POST['contactpersonname1']\n\t\tcontactpersonno1 = request.POST['contactpersonno1']\n\t\tcontactpersonname2 = request.POST['contactpersonname2']\n\t\tcontactpersonno2 = request.POST['contactpersonno2']\n\t\treqdateinstall = request.POST['reqdateinstall']\n\t\tnameofproduct = request.POST['nameofproduct']\n\t\tcust_prob = request.POST['cust_prob']\n\t\ttransformervalvesize = request.POST['transformervalvesize']\n\t\tdate = datetime.date.today()\n\t\tsalesmanagerrequestno = request.POST['salesmanagerrequestno']\n\t\tuser = User.objects.get(username=request.session['logged_in'])\n\t\tsc = ServiceCall(customer=customer,end_user=enduser,site_name=sitename,site_address=siteaddress,contact_person_name1=contactpersonname1,\n\t\tcontact_person_no1=contactpersonno1,contact_person_name2=contactpersonname2,\n\t\tcontact_person_no2=contactpersonno2,req_date_of_installation_by_customer=reqdateinstall,name_of_product_supplied=nameofproduct\n\t\t,transformer_valve_size_details=transformervalvesize,customer_problem=cust_prob,\n\t\tsales_manager_request_no=salesmanagerrequestno,date=date,created_by=user)\n\t\tsc.save()\n\t\trequest.session['servicecall'] = sc.id\n\n\treturn render(request,'ticket/pages/product_model.html')\n\ndef email(request,ic_request):\n\tif request.method == 'POST':\n\t\tic=ICRequest.objects.get(id=request.session['icrequestno'])\n\t\theliumcylinder = request.POST['heliumcylinder']\n\t\tcalgascylinder = request.POST['calgascylinder']\n\t\tsstubing = request.POST['sstubing']\n\t\tsstubingsize = request.POST['sstubingsize']\n\t\tstandardlength_sstube = request.POST['standardlength_sstube']\n\t\ttubingaccessories = request.POST['tubingaccessories']\n\t\tflanges = request.POST['flanges']\n\t\tcomm_mode = request.POST['comm_mode']\n\t\tssupply = ScopeSupply(icrequest=ic,helium_cylinder=heliumcylinder,calibration_gas_cylinder=calgascylinder,ss_tubing=sstubing,ss_tubing_size=sstubingsize\n\t\t,standard_length_ss_tube=standardlength_sstube,tubing_accessories=tubingaccessories\n\t\t,flanges=flanges,communication_mode=comm_mode)\n\t\tssupply.save()\n\temail = EmailMessage('New IC Request Created', '127.0.0.1:8000/ticket/pages/ic_info/'+ic_request, to=['vbanwari@qualitrolcorp.com'])\n\temail.send()\n\treturn render(request,'ticket/pages/profile.html')\n\ndef email_pm(request,service_call):\n\tif request.method == 'POST':\n\t\t#print(service_call)\n \t\tproduct_model = request.POST['product']\t\n \t\tquantity = request.POST['qty']\n \t\tissue_reported = request.POST['issue_reported']\n \t\tvisit_required = request.POST['visit_required']\n \t\tcustomer_req_date = request.POST['customer_req_date']\n \t\tservice = ServiceCall.objects.get(id=request.session['servicecall'])\n \t\tproduct = ProductModel(service=service,\n\t\t\tproduct_model=product_model,quantity=quantity,\n\t\t\tissue_reported=issue_reported,\n\t\t\tvisit_required=visit_required,\n\t\t\tcustomer_req_date=customer_req_date)\n\tproduct.save()\n\temail = EmailMessage('New Service Call Created', '127.0.0.1:8000/ticket/pages/sc_info/'+service_call, to=['vbanwari@qualitrolcorp.com'])\n\temail.send()\n\treturn render(request,'ticket/pages/profile.html')\n\ndef reporting(request):\n\treturn render(request,'ticket/pages/reporting.html')\n\ndef your_ic_request(request):\n\tuser = User.objects.get(username=request.session['logged_in'])\n\tic = ICRequest.objects.filter(created_by=user)\n\treturn render(request,'ticket/pages/your_ic_request.html',{'output' : ic})\n\t\ndef your_service_call(request):\n\tuser = User.objects.get(username=request.session['logged_in'])\n\tsc = ServiceCall.objects.filter(created_by=user)\n\treturn render(request,'ticket/pages/your_service_call.html',{'output1' : sc})\n\ndef ic_info(request,ic1):\n\tprint(ic1)\n\tic = ICRequest.objects.get(id=ic1)\n\treturn render(request,'ticket/pages/ic_info.html',{'output' : ic})\n\t\ndef sc_info(request,sc1):\n\tsc = ServiceCall.objects.get(id=sc1)\n\treturn render(request,'ticket/pages/sc_info.html',{'output1' : sc})","sub_path":"StatusTracking/StatusTracking/ticket/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"536190110","text":"# -*- coding: utf-8 -*-\n\"\"\"\n openclip/util.py\n =======================================\n\n provides utility classes and functions that\n don't belong in a single class or sub-module\n\"\"\"\nimport os\nimport sys\nimport shutil\nimport re\nimport uuid\nimport glob\nimport ntpath\nimport tempfile\nimport errno\nfrom datetime import datetime\nimport tempfile\n\ntry:\n from lxml import etree as ET\nexcept ImportError:\n try:\n # Python 2.5\n import xml.etree.cElementTree as ET\n print(\"running with cElementTree on Python 2.5+\")\n except ImportError:\n try:\n import xml.etree.ElementTree as ET\n print(\"running with ElementTree on Python 2.5+\")\n except ImportError:\n try:\n # normal cElementTree install\n import cElementTree as ET\n print(\"running with cElementTree\")\n except ImportError:\n try:\n # normal ElementTree install\n import elementtree.ElementTree as ET\n print(\"running with ElementTree\")\n except ImportError:\n print(\"Failed to import ElementTree from any known place\")\n\n\n__all__ = [\n 'can_write_path', 'clean_version', 'clip_is_writable',\n 'dir_is_writable', 'element_to_xml', 'get_cwd_or_tempdir',\n 'get_file_basename', 'get_frame_pad', 'get_temp_name_str',\n 'get_tempdir', 'lxml_installed', 'make_backup_file'\n]\n\n\ndef lxml_installed():\n \"\"\"\n checks if lxml is installed\n used for fallbacks to other builtin modules\n \"\"\"\n import imp\n try:\n imp.find_module('lxml')\n return True\n except ImportError:\n return False\n\n\ndef dir_is_writable(path):\n \"\"\"\n checks if a directory is writable\n \"\"\"\n if not os.path.exists(path):\n if os.path.splitext(path)[-1] in ['.clip', '.xml']:\n path = os.path.dirname(path)\n if os.path.isfile(path):\n path = os.path.dirname(path)\n if not os.path.isdir(path):\n return False\n try:\n testfile = tempfile.TemporaryFile(dir = path)\n testfile.close()\n except OSError as e:\n if e.errno == errno.EACCES: # 13\n return False\n e.filename = path\n raise\n return True\n\n\ndef clip_is_writable(path):\n \"\"\"\n checks if a clip file is writable\n \"\"\"\n if not os.path.splitext(path)[-1] in ['.clip', '.xml']:\n # path is not a clip file\n return False\n else:\n if os.path.exists(path):\n if not os.path.isfile(path):\n # exists but not a file\n return False\n elif os.access(path, os.W_OK):\n # file exists and is writable\n return True\n else:\n # exists but not writable\n return False\n else:\n return dir_is_writable(path)\n\n\ndef get_tempdir():\n \"\"\"\n returns os tempdir\n \"\"\"\n tempdir=os.path.join(tempfile.gettempdir(),'openclip')\n try:\n os.makedirs(tempdir)\n return tempdir\n except OSError:\n return None\n\n\ndef can_write_path(file_path):\n \"\"\"\n simple function that returns:\n - True if file exists\n - None if path is writable and no file exists\n - False if file exists and is not writable\n - False if file path is not writable\n\n To use this effectively you need to check explicitly for True,False,or None\n \"\"\"\n if os.path.isfile(file_path): # file exists\n return True\n elif os.access(os.path.dirname(file_path), os.W_OK): # file does not exist but path is writable\n return None\n else: # can not write thus stdout?\n return False\n\n\ndef get_file_basename(file_path):\n \"\"\"\n get the basename of a file_path\n Eg. '/Users/rob/test.clip' returns 'test'\n \"\"\"\n if not file_path is None:\n return os.path.splitext(os.path.basename(file_path))[0]\n else:\n return get_temp_name_str()\n\n\ndef get_cwd_or_tempdir():\n \"\"\"\n returns current working directory\n or temp directorty\n \"\"\"\n cwd = os.getcwd()\n if dir_is_writable(cwd):\n return cwd\n else:\n return get_tempdir\n\n\ndef get_temp_name_str():\n \"\"\"\n generates a temporary filename string\n \"\"\"\n dt = datetime.now()\n # datetime_str = '{:%Y%m%d_%H%M%S}'.format(dt) # this breaks python 2.6\n datetime_str = datetime.strftime(dt, '%Y%m%d_%H%M%S')\n return 'OpenClip_{datetime_str}_{microsec}'.format(datetime_str=datetime_str,microsec=str(dt.microsecond)[:2])\n\n\ndef get_md5_hash() :\n \"\"\"hopefully returns a unique string...\"\"\"\n\n import hashlib\n import platform\n import time\n\n md5_out = hashlib.md5()\n md5_out.update( platform.node() )\n md5_out.update( str( os.getpid() ) )\n md5_out.update( str( time.time() ) )\n return md5_out.hexdigest()\n\n\ndef clean_version(version_str, version_format_str):\n \"\"\"\n simple function that takes an\n input version string, sanitizes it,\n then reformats using a version format string\n similar to: \"v{:0>3d}\"\n Eg. V0003 becomes v003\n \"\"\"\n try:\n version = int(''.join(i for i in version_str if i.isdigit()))\n except ValueError:\n version = 404\n return version_format_str.format(version)\n\n\ndef get_frame_pad(path, default_padding=4):\n \"\"\"\n utility function to return padding of\n image sequence frame numbers Eg. 4\n \"\"\"\n path = re.sub(r\"[.]%[\\d]+d[.]([\\w]+)$\", r\".*.\\1\", path) # Ex: '/foo/bar/baz.%04d.exr' -> '/foo/bar/baz.*.exr'\n for filename in glob.iglob(path):\n return len(re.search(r\"[.]([\\d]+)[.][\\w]+$\", filename).group(1)) # Ex: '.0001.exr' -> groups: ('0001')\n return default_padding\n\n\ndef element_to_xml(etree_element, xml_header=True, encoding='utf-8', pretty_print=True):\n \"\"\"\n simple function to return serialized element as unicode encoded pretty XML\n \"\"\"\n try:\n return ET.tostring(etree_element, xml_declaration=xml_header, encoding=encoding, pretty_print=pretty_print)\n except TypeError:\n return None\n\n\ndef make_backup_file(file_path):\n filename = ntpath.basename(file_path)\n # Create a backup of the original file\n bakfile = \"{file_path}.bak\".format(file_path=file_path)\n if not os.path.isfile(bakfile):\n shutil.copy2(file_path, bakfile)\n else:\n created = False\n for i in range ( 1, 99 ):\n bakfile = \"%s.bak.%02d\" % ( file_path, i )\n if not os.path.isfile(bakfile):\n shutil.copy2(file_path,bakfile)\n created = True\n break\n if not created:\n bakfile = \"%s.bak.last\" % file_path\n shutil.copy2(file_path, bakfile)\n","sub_path":"openclip/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"190647083","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\objects\\water_terrain_objects.py\n# Compiled at: 2014-10-30 00:38:33\n# Size of source mod 2**32: 3785 bytes\nfrom sims4.tuning.tunable import TunableThreshold, TunableList, TunableEnumEntry, Tunable\nimport services, sims4.log, tag\nlogger = sims4.log.Logger('WaterTerrainObjects', default_owner='rmccord')\n\nclass WaterTerrainObjectCache:\n OBJECT_SQ_DISTANCE_THRESHOLD = TunableThreshold(description=\"\\n The distance threshold between the user's click on water and objects in\\n the world that have WATER_TERRAIN_TAGS. If the user picks water, we\\n find the nearest object in this distance threshold and generate a pie\\n menu.\\n \",\n value=Tunable(description='\\n The value of the threshold that the collection is compared\\n against.\\n ',\n tunable_type=float,\n default=100.0),\n default=(sims4.math.Threshold(0.0, sims4.math.Operator.LESS_OR_EQUAL.function)))\n WATER_TERRAIN_TAGS = TunableList(description=\"\\n The Tags on Object Definitions that mark objects for caching near the\\n water. Please make exclusive tags for this, as we don't want to include\\n objects that don't make sense.\\n \",\n tunable=TunableEnumEntry(description='\\n A tag that marks an object for caching near the water terrain.\\n ',\n tunable_type=(tag.Tag),\n default=(tag.Tag.INVALID)))\n\n def __init__(self):\n self._object_cache = []\n\n def get_nearest_object(self, pick_pos, check_distance=True):\n nearby_objects = []\n for cache_obj in self:\n obj_pos = cache_obj.location.transform.translation\n dist_sq = (pick_pos - obj_pos).magnitude_2d_squared()\n nearby_objects.append((cache_obj, dist_sq))\n\n nearest_obj = None\n if nearby_objects:\n nearest = min(nearby_objects, key=(lambda x: x[1]))\n if WaterTerrainObjectCache.OBJECT_SQ_DISTANCE_THRESHOLD.compare(nearest[1]):\n nearest_obj = nearest[0]\n return nearest_obj\n\n def refresh(self):\n self.clear()\n for obj in services.object_manager().valid_objects():\n self.add_object(obj)\n\n def can_add_object(self, obj):\n if obj in self._object_cache:\n return False\n definition = obj.definition\n for tag in WaterTerrainObjectCache.WATER_TERRAIN_TAGS:\n if definition.has_build_buy_tag(tag):\n return True\n\n return False\n\n def add_object(self, obj):\n if self.can_add_object(obj):\n self._object_cache.append(obj)\n return True\n return False\n\n def __iter__(self):\n return self._object_cache.__iter__()\n\n def clear(self):\n self._object_cache = []","sub_path":"Scripts/simulation/objects/water_terrain_objects.py","file_name":"water_terrain_objects.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"604042985","text":"# This is the laziest glue code I've ever written. I used the HttpListener\n# setup.py/setup.ps1 as a reference.\nfrom subprocess import check_call, CalledProcessError\n\nfrom os.path import (\n join,\n abspath,\n dirname,\n normpath,\n)\n\nbasedir = abspath(dirname(__file__))\nsetup_ps1 = join(basedir, 'setup.ps1')\n\nstart_cmd = \"powershell -Command \\\"%s\\\" start\" % setup_ps1\nstop_cmd = \"powershell -Command \\\"%s\\\" stop\" % setup_ps1\ncwd = 'C:\\\\PyParallel33'\n\nclass helper:\n def __init__(self, func):\n self.func = func\n def __call__(self, *args, **kwds):\n if os.name != 'nt':\n return 1\n try:\n self.func(*args, **kwds)\n return 0\n except CalledProcessError:\n return 1\n\n@helper\ndef start(args, logfile, errfile):\n check_call(start_cmd, cwd=cwd, stderr=errfile, stdout=logfile)\n\n@helper\ndef stop(logfile, errfile):\n check_call(stop_cmd, cwd=cwd, stderr=errfile, stdout=logfile)\n\nif __name__ == '__main__':\n import sys\n from subprocess import PIPE\n if 'stop' in sys.argv:\n stop(PIPE, PIPE)\n else:\n start(None, PIPE, PIPE)\n","sub_path":"frameworks/PyParallel/default/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"119031650","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n########\n# Bucle: Que cuente del número 1 hasta el límite que yo le diga\n# ejercicio-bucle-contar2.py\n##########\nvar = input(\"num: \")\nfor i in range(1,var+1) :\n\t\tprint (i)\n","sub_path":"python/ejercicios/bucles-for/bucle-contar2.py","file_name":"bucle-contar2.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"88862052","text":"import scrapy\nimport pandas as pd\nfrom ..items import NewscrawlItem\nfrom configparser import ConfigParser\nimport os\n\nclass PehubSpider(scrapy.Spider):\n name = 'pehub'\n start_urls = ['https://www.pehub.com/news-and-analysis/pe-deals/']\n\n def parse(self, response):\n \n work_dir = os.path.dirname(os.path.abspath(__file__))\n filepath = os.path.join(work_dir,'spiders.cfg')\n print(filepath)\n config_raw = ConfigParser()\n config_raw.read(filepath)\n pageNumberToScrapyForOldPost = int(config_raw.get('PehubSpider', 'pageNumberToScrapy').strip())\n \n \n spiderItem = NewscrawlItem()\n\n spiderItem['site'] = \"PE Hub\"\n for i in response.css('.td-animation-stack'):\n h = i.xpath('.//div/div[@class=\"item-details\"]/div/h2/a/text()').extract()\n d = i.xpath('.//div/div[@class=\"td-module-meta-info\"]/span[@class=\"td-post-date\"]/time/@datetime').extract()\n if len(d)>0 and len(h)>0:\n spiderItem['headlines'] = h[0]\n spiderItem['dates'] = list(d[0].split('T'))[0]\n spiderItem['links'] = i.xpath('.//div/div[@class=\"item-details\"]/div/h2/a/@href').extract_first()\n yield spiderItem\n \n otherPageURLTemplate = 'https://www.pehub.com/news-and-analysis/pe-deals/page/'\n \n for pagenumber in range(2,pageNumberToScrapyForOldPost+1):\n otherPageURL = otherPageURLTemplate + str(pagenumber)+'/'\n request = response.follow(otherPageURL, callback = self.parseRecursion)\n yield request\n \n def parseRecursion(self, response):\n spiderItem = NewscrawlItem()\n\n spiderItem['site'] = \"PE Hub\"\n for i in response.css('.td-animation-stack'):\n h = i.xpath('.//div/div[@class=\"item-details\"]/div/h2/a/text()').extract()\n d = i.xpath('.//div/div[@class=\"td-module-meta-info\"]/span[@class=\"td-post-date\"]/time/@datetime').extract()\n if len(d)>0 and len(h)>0:\n spiderItem['headlines'] = h[0]\n spiderItem['dates'] = list(d[0].split('T'))[0]\n spiderItem['links'] = i.xpath('.//div/div[@class=\"item-details\"]/div/h2/a/@href').extract_first()\n yield spiderItem\n \n \n \n","sub_path":"newsCrawl/newsCrawl/spiders/pehub.py","file_name":"pehub.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"608465184","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def removeElements(self, head, val):\n \"\"\"\n :type head: ListNode\n :type val: int\n :rtype: ListNode\n \"\"\"\n h = ListNode(0)\n h.next = head\n t = head\n pt = h\n while t:\n if t.val == val:\n pt.next = t.next\n else:\n pt = pt.next\n t = t.next\n return h.next","sub_path":"problems201-250/leetcode-203.py","file_name":"leetcode-203.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"554263260","text":"import os\nimport os.path as osp\nfrom glob import glob\n\nimport torch\nfrom torch_geometric.data import InMemoryDataset, extract_zip\nfrom utils.read import read_mesh\nfrom torch_geometric.data import Data\nfrom torch_geometric.utils import to_undirected\n\nfrom tqdm import tqdm\nimport numpy as np\nimport openmesh as om\n\n\nclass ADNI2_clsf(InMemoryDataset):\n url = None\n\n categories = [\n 'ad',\n 'cn',\n ]\n\n def __init__(self,\n root,\n train=True,\n split='clsfb',\n transform=None,\n pre_transform=None):\n self.split = split\n self.root = root\n if not osp.exists(osp.join(root, 'processed', self.split)):\n os.makedirs(osp.join(root, 'processed', self.split))\n\n self.data_files = self.gather_paths(self.split)\n super().__init__(root, transform, pre_transform)\n path = self.processed_paths[0] if train else self.processed_paths[1]\n self.data, self.slices = torch.load(path)\n\n @property\n def raw_file_names(self):\n all_data_files = []\n for key in self.data_file.keys() :\n all_data_files += self.data_file[key]\n return all_data_files\n\n @property\n def processed_file_names(self):\n return [\n osp.join(self.split, 'training.pt'),\n osp.join(self.split, 'test.pt')\n ]\n\n def gather_paths(self, split):\n datapaths = dict()\n count = 0\n if split == 'clsfb' :\n datapaths['ad'] = dict()\n datapaths['cn'] = dict()\n datapaths['ad']['train'] = []\n datapaths['ad']['test'] = []\n datapaths['cn']['train'] = []\n datapaths['cn']['test'] = []\n\n imgids = np.load(osp.join(self.root, 'adni2_clsfb_dict.npy'), allow_pickle=True)\n imgids = imgids.item()\n for dx in imgids.keys() :\n for tt in imgids[dx].keys() :\n for i in imgids[dx][tt] :\n datapaths[dx][tt].append(self.root+'/'+i+'-L_Hipp_first.obj')\n count += 1\n print('total number of dataset: %d'%(count))\n return datapaths\n\n def process(self):\n print('Processing...')\n fps = self.data_files\n\n train_data_list, test_data_list = [], []\n for dx in fps :\n for tt in fps[dx] :\n for idx, fp in enumerate(tqdm(fps[dx][tt])) :\n mesh = om.read_trimesh(fp)\n face = torch.from_numpy(mesh.face_vertex_indices()).T.type(torch.long)\n x = torch.tensor(mesh.points().astype('float32'))\n edge_index = torch.cat([face[:2], face[1:], face[::2]], dim=1)\n edge_index = to_undirected(edge_index)\n if dx == 'ad' :\n data = Data(x=x, y=torch.Tensor([1,0]), edge_index=edge_index, face=face)\n elif dx == 'cn' :\n data = Data(x=x, y=torch.Tensor([0,1]), edge_index=edge_index, face=face)\n if self.pre_transform is not None:\n data = self.pre_transform(data)\n\n if tt == 'test' :\n test_data_list.append(data)\n elif tt == 'train' :\n train_data_list.append(data)\n\n torch.save(self.collate(train_data_list), self.processed_paths[0])\n torch.save(self.collate(test_data_list), self.processed_paths[1])\n","sub_path":"datasets/adni2_clsf.py","file_name":"adni2_clsf.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"382194417","text":"# 3rd party langid providers\nfrom google.cloud import translate\nfrom flask import current_app as app\nimport requests\n\nclass GoogleLangidProvider:\n @staticmethod\n def langid(text):\n client = translate.Client.from_service_account_json('./google_credentials.json')\n return client.detect_language([text])[0]\n\nclass MicrosoftLangidProvider:\n @staticmethod\n def langid(text):\n # https://docs.microsoft.com/en-us/azure/cognitive-services/Text-Analytics/quickstarts/python\n response = requests.post(\n app.config['MS_TEXT_ANALYTICS_URL'] + '/languages',\n headers={\n \"Ocp-Apim-Subscription-Key\": app.config['MS_TEXT_ANALYTICS_KEY']\n },\n json={\n \"documents\": [{ \"id\": \"1\", \"text\": text }]\n }\n ).json()\n result = response['documents'][0]['detectedLanguages'][0]\n return {\n 'language': result['iso6391Name'],\n 'confidence': result['score']\n }","sub_path":"app/main/lib/langid.py","file_name":"langid.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"328903139","text":"import cv2\nimport glob\nimport numpy as np\n\n#작업할 이미지 경로\nimg_dir = \"real\\\\*\"\nfile_list = glob.glob(img_dir)\n#.jpg파일만 리스트에 넣는다.\nimg_list = [file for file in file_list if file.endswith(\".jpg\")]\n#작업할 이미지의 개수\ncnt_img = len(img_list) - 1\nprint(cnt_img)\nfor i in range(cnt_img):\n imgfile_name = img_list[i].split(\"\\\\\")\n train = cv2.imread(img_list[i])\n tmp = train.copy()\n\n\n# CLAHE\ntmp = cv2.cvtColor(tmp, cv2.COLOR_RGB2Lab)\nl, a, b = cv2.split(tmp)\nclahe = cv2.createCLAHE(clipLimit=6, tileGridSize=(11, 11))\ndst = clahe.apply(l)\nl = dst.copy()\ntmp = cv2.merge((l, a, b))\ntmp = cv2.cvtColor(tmp, cv2.COLOR_LAB2RGB)\n\n\n# Saturation_add\nimg_width = tmp.shape[0]\nimg_height = tmp.shape[1]\ntmp = cv2.cvtColor(tmp, cv2.COLOR_RGB2HSV)\nfor i in range(img_width):\n for j in range(img_height):\n tmp[i][j][1] += 30\ntmp = cv2.cvtColor(tmp, cv2.COLOR_HSV2RGB)\n\n# 필터 통과한 이미지 변수에 넣기\nwork = tmp.copy()\n\n\n# 결과 이미지를 보여준다.\n# cv2.imshow('aaa', work)\n# cv2.waitKey()\n\n# 필터를 통과한 이미지를 해당 경로의 폴더에 넣어준다.\n# 원본이미지명 앞에 R_을 추가해서 저장한다.\npath = \"C:\\\\Users\\\\jsych\\\\Desktop\\\\Results\\\\R_\" + imgfile_name[-1]\ncv2.imwrite(path,work)\n","sub_path":"jsy_filter_code/diff_tone.py","file_name":"diff_tone.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"514949864","text":"import copy\nimport operator\nATTEMPTS = 22\nBIG = 16\nCOR_TOTAL = 44\nclass NumberMaster:\n def __init__(self):\n self.arrays = [[5,6,1,6,1,8,5,6,5,0,5,1,8,2,9,3],[3,8,4,7,4,3,9,6,4,7,2,9,3,0,4,7],\n [5,8,5,5,4,6,2,9,4,0,8,1,0,5,8,7],[9,7,4,2,8,5,5,5,0,7,0,6,8,3,5,3],\n [4,2,9,6,8,4,9,6,4,3,6,0,7,5,4,3],[3,1,7,4,2,4,8,4,3,9,4,6,5,8,5,8],\n [4,5,1,3,5,5,9,0,9,4,1,4,6,1,1,7],[7,8,9,0,9,7,1,5,4,8,9,0,8,0,6,7],\n [8,1,5,7,3,5,6,3,4,4,1,1,8,4,8,3],[2,6,1,5,2,5,0,7,4,4,3,8,6,8,9,9],\n [8,6,9,0,0,9,5,8,5,1,5,2,6,2,5,4],[6,3,7,5,7,1,1,9,1,5,0,7,7,0,5,0],\n [6,9,1,3,8,5,9,1,7,3,1,2,1,3,6,0],[6,4,4,2,8,8,9,0,5,5,0,4,2,7,6,8],\n [2,3,2,1,3,8,6,1,0,4,3,0,3,8,4,5],[2,3,2,6,5,0,9,4,7,1,2,7,1,4,4,8],\n [5,2,5,1,5,8,3,3,7,9,6,4,4,3,2,2],[1,7,4,8,2,7,0,4,7,6,7,5,8,2,7,6],\n [4,8,9,5,7,2,2,6,5,2,1,9,0,3,0,6],[3,0,4,1,6,3,1,1,1,7,2,2,4,6,3,5],\n [1,8,4,1,2,3,6,4,5,4,3,2,4,5,8,9],[2,6,5,9,8,6,2,6,3,7,3,1,6,8,6,7]]\n\n # self.arrays = [[9,0,3,4,2],[7,0,7,9,4],[3,9,4,5,8],[3,4,1,0,9],[5,1,5,4,5],[1,2,5,3,1]]\n\n self.matches = [2,1,3,3,3,1,2,3,1,2,3,1,1,2,0,2,2,3,1,3,3,2]\n # self.matches = [2,0,2,1,2,1]\n\n def unUsedDigits(self,locDig):\n digits = [0,1,2,3,4,5,6,7,8,9]\n for i in range(0,ATTEMPTS):\n curr = self.arrays[i][locDig]\n if digits.count(curr) > 0:\n digits.remove(curr)\n print(digits)\n\n def check(self, attempt):\n common = 0\n #check all the cases\n for i in range(0,ATTEMPTS):\n common = 0\n #compute all common digits\n for j in range(0,BIG):\n if attempt[j] == self.arrays[i][j]:\n common = common + 1\n\n #if the common digits don't match then this attempt failed\n if common != self.matches[i]:\n return False\n\n #if the attempt didn't fail any of the cases then it's the solution\n return True\n\n def updateExpCorrect(self, valDig, locDig, expCorrect):\n for i in range(0,ATTEMPTS):\n curr = self.arrays[i][locDig]\n if curr == valDig and expCorrect[i] != 0:\n expCorrect[i] -= 1\n return expCorrect\n\n\n def updateNopeDig(self, nopeDig, locDig, expCorrect):\n for i in range(0,ATTEMPTS):\n if expCorrect[i] == 0:\n for j in range(locDig,BIG):\n if self.arrays[i][j] not in nopeDig[j]:\n nopeDig[j].append(self.arrays[i][j])\n return nopeDig\n\n def numOccurence(self, locDig, nopeDig, expCorrect):\n digits = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}\n if locDig >= BIG:\n return {}\n for i in range(0,ATTEMPTS):\n curr = self.arrays[i][locDig]\n if curr in digits and curr not in nopeDig[locDig]:\n digits[curr] += 1\n else:\n digits.pop(curr, None)\n\n return self.sortMaster(digits, expCorrect, locDig)\n\n def sortMaster(self, digits, expCorrect, locDig):\n toReturn = []\n relevantDigDic = {}\n for key in digits:\n relevantDigDic[key] = 0\n\n for key in relevantDigDic:\n for i in range(0,ATTEMPTS):\n curr = self.arrays[i][locDig]\n #if that digit is in an attempt with only one expCorrect left\n if curr == key and expCorrect[i] == 1:\n relevantDigDic[key] -= 100\n elif curr == key and expCorrect[i] == 2:\n relevantDigDic[key] -= 10\n elif curr == key and expCorrect[i] == 3:\n relevantDigDic[key] -= 1\n\n relevantDigList = list(relevantDigDic.items())\n\n relevantDigList.sort(key=operator.itemgetter(1))\n\n for i in relevantDigList:\n toReturn.append((i[0], digits[i[0]]))\n return toReturn\n\n\n\n\n\n def posCorrect(self, locDig, nopeDig):\n posCorrect = [0] * ATTEMPTS\n for i in range(0,ATTEMPTS):\n for j in range(locDig, BIG):\n curr = self.arrays[i][j]\n if curr not in nopeDig[locDig]:\n posCorrect[i] += 1\n return posCorrect\n\n def stillPossible(self, posCorrect, expCorrect):\n for i in range(0,ATTEMPTS):\n if posCorrect[i] < expCorrect[i]:\n return False\n return True\n\n def weCanMakeIt(self, nopeDig, locDig, correctCount, expCorrect):\n maxOverlap = 0\n for i in range(locDig,BIG):\n nonZero = self.numOccurence(i, nopeDig, expCorrect)\n maxDig = 0\n for j in nonZero:\n if j[1] > maxDig:\n maxDig = j[1]\n maxOverlap += maxDig\n if maxOverlap + correctCount >= COR_TOTAL:\n return True\n else:\n return False\n\n\n\n def smartForce(self, potentialDigs, guess, correctCount, nopeDig, expCorrect):\n # print(\"pot\", potentialDigs)\n print(\"guess\", guess)\n # print(\"corr\", correctCount)\n # print(\"nopeDig\", nopeDig)\n # print(\"ex\", expCorrect)\n # print(\" \")\n # print(\" \")\n #base case if the guess is fully formed check if it works\n if len(guess) > BIG:\n return False\n elif correctCount == COR_TOTAL and len(guess) == BIG:\n if self.check(guess):\n print(guess, True)\n print(\"corCount\",correctCount)\n return True\n else:\n return False\n\n\n for valDig in potentialDigs:\n if valDig[1] + correctCount <= COR_TOTAL:\n tempGuess = list(guess)\n tempGuess.append(valDig[0])\n tempCorrectCount = copy.deepcopy(correctCount)\n tempCorrectCount += valDig[1]\n tempExpCorrect = copy.deepcopy(expCorrect)\n tempExpCorrect = self.updateExpCorrect(valDig[0], len(guess), tempExpCorrect)\n tempNopeDig = copy.deepcopy(nopeDig)\n tempNopeDig = self.updateNopeDig(tempNopeDig, len(tempGuess), tempExpCorrect)\n posCorrect = self.posCorrect(len(tempGuess), tempNopeDig)\n if self.weCanMakeIt(tempNopeDig,len(tempGuess),tempCorrectCount, tempExpCorrect) and self.stillPossible(posCorrect, tempExpCorrect):\n nextPotentialDigs = self.numOccurence(len(tempGuess), tempNopeDig, tempExpCorrect)\n if self.smartForce(nextPotentialDigs, tempGuess, tempCorrectCount, tempNopeDig, tempExpCorrect):\n return True\n # else:\n # print(\"______________________\")\n\n\n\nnumMaster = NumberMaster()\nnopeDig = [[2], [3], [2], [1], [3], [8], [6], [1], [0], [4], [3], [0], [3], [8], [4], [5]]\nexpCorrect = [2,1,3,3,3,1,2,3,1,2,3,1,1,2,0,2,2,3,1,3,3,2]\n# nopeDig = [[7],[0],[7],[9],[4]]\n# expCorrect = [2,0,2,1,2,1]\nguess = []\ncorrectCount = 0\nnumMaster.smartForce(numMaster.numOccurence(0, nopeDig, expCorrect), guess, correctCount, nopeDig, expCorrect)\n\n\n\n\n\n\n\n\n","sub_path":"NumberMaster.py","file_name":"NumberMaster.py","file_ext":"py","file_size_in_byte":7239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"233187939","text":"import string\nimport argparse\nimport re\nfrom io import StringIO\nfrom flask import Flask\nfrom lxml import etree\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\n\n\n\"\"\"\nMakes asked site more ™-friendly\n\"\"\"\n\n\nSKIPPED_TAGS = ['style', 'script', '[document]', 'head', 'title', 'meta']\nSKIPPED_SYMBOLS = string.punctuation + string.whitespace + \"\".join(\n [\"«\", \"»\", \"\\u00A0\"]\n)\n\nGLOBAL_REPLACES = {\n '+': '+'\n}\n\n\ndef replace_element_text(text):\n splitted_text_origin = text.split(' ')\n splitted_text_new = []\n for word in splitted_text_origin:\n stripped_word = word.strip(SKIPPED_SYMBOLS)\n if len(stripped_word) == 6:\n new_word = word.replace(stripped_word, stripped_word + '™')\n else:\n new_word = word\n splitted_text_new.append(new_word)\n text = ' '.join(splitted_text_new)\n return text\n\n\ndef recycle_html(asked_site, asked_path, local_host, local_port):\n try:\n b_page = urlopen('{}/{}'.format(asked_site, asked_path))\n except HTTPError as e:\n b_page = e\n b_page_start = b_page.read(50)\n try:\n if 'DOCTYPE html' in b_page_start.decode('utf-8'):\n full_page = (b_page_start.decode('utf-8') +\n b_page.read().decode('utf-8'))\n for k, v in GLOBAL_REPLACES.items():\n full_page = re.sub(k, v, full_page)\n n_page = StringIO(full_page)\n try:\n parser = etree.HTMLParser()\n tree = etree.parse(n_page, parser)\n for element in tree.getiterator():\n if element.tag not in SKIPPED_TAGS:\n if element.tag == 'a' and element.attrib['href']\\\n .startswith(asked_site):\n new_host = 'http://' + element.attrib['href']\\\n .replace(asked_site,\n local_host + ':' + str(local_port))\n element.attrib['href'] = new_host\n if element.text:\n element.text = replace_element_text(element.text)\n if element.tail:\n element.tail = replace_element_text(element.tail)\n updated_html = etree.tostring(tree, method='html')\n return updated_html\n except Exception as e:\n return full_page\n return b_page_start + b_page.read()\n except Exception as e:\n return b_page_start + b_page.read()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Let's make some trademarks!\")\n parser.add_argument('--site',\n help=\"Site to process\",\n default='https://habrahabr.ru')\n parser.add_argument('--local_host',\n help=\"Local host for proxy\",\n default='127.0.0.1')\n parser.add_argument('--local_port',\n help=\"Port for proxy\",\n type=int,\n default='5000')\n args = parser.parse_args()\n\n app = Flask(__name__)\n\n @app.route('/', defaults={'path': ''})\n @app.route('/')\n def catch_all(path):\n return recycle_html(args.site, path, args.local_host, args.local_port)\n\n app.run(host=args.local_host, port=args.local_port)\n","sub_path":"tm.py","file_name":"tm.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"433258772","text":"import seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom modules.fuzzy_load import *\n\nsns.set(style='darkgrid', palette=\"Paired\")\n\n\ndef create_membership_functions(file, from_file=True):\n '''\n Creates trapezoidal membership functions using the parsed fuzzy variables.\n Generates discrete values of membership based on the estimated range of the variables.\n\n Args:\n file(str): the input filename\n from_file: feed the file as input or feed an already parsed dictionary (def. True)\n\n Returns:\n fuzzy_dict(dict): the processed fuzzy variable dictionary with assigned memberships\n x_ranges(dict): the generated range of values for each membership\n var_names(list): list of variable names for lookup\n fuzzy_variables(dict): the original parsed fuzzy variable dictionary\n \n '''\n\n\n if from_file:\n fuzzy_variables = read_variables(file)\n else:\n fuzzy_variables = file\n fuzzy_dict = {}\n x_ranges = {}\n var_names = []\n for k, v in fuzzy_variables.items():\n var_name = k\n max_range = 0\n fuzzy_val_dict = {}\n for k_j, v_j in v.items():\n max_range_j = v_j[1] + v_j[3]\n if max_range_j > max_range:\n max_range = max_range_j\n\n x_range = np.arange(0, max_range + 0.1, 0.1)\n\n for k_j, v_j in v.items():\n cat_name = k_j\n a, b, c, d = np.r_[np.float32([v_j[0] - v_j[2], v_j[0], v_j[1], v_j[3] + v_j[1]])]\n y = np.ones(len(x_range))\n\n ### triangle membership 1\n idx = np.nonzero(x_range <= b)[0]\n\n a1, b1, c1 = np.r_[np.r_[a, b, b]]\n y1 = np.zeros(len(x_range[idx]))\n\n # Left side\n if a1 != b1:\n idx1 = np.nonzero(np.logical_and(a1 < x_range[idx], x_range[idx] < b1))[0]\n y1[idx1] = (x_range[idx][idx1] - a1) / float(b1 - a1)\n\n # Right side\n if b1 != c1:\n idx1 = np.nonzero(np.logical_and(b1 < x_range[idx], x_range[idx] < c1))[0]\n y1[idx1] = (c1 - x_range[idx][idx1]) / float(c1 - b1)\n\n idx1 = np.nonzero(x_range[idx] == b1)\n y1[idx1] = 1\n y[idx] = y1\n\n ### Triangle membership 2\n idx = np.nonzero(x_range >= c)[0]\n\n a2, b2, c2 = np.r_[np.r_[c, c, d]]\n y2 = np.zeros(len(x_range[idx]))\n\n # Left side\n if a2 != b2:\n idx2 = np.nonzero(np.logical_and(a2 < x_range[idx], x_range[idx] < b2))[0]\n y2[idx2] = (x_range[idx][idx2] - a2) / float(b2 - a2)\n\n # Right side\n if b2 != c2:\n idx2 = np.nonzero(np.logical_and(b2 < x_range[idx], x_range[idx] < c2))[0]\n y2[idx2] = (c2 - x_range[idx][idx2]) / float(c2 - b2)\n\n idx2 = np.nonzero(x_range[idx] == b2)\n y2[idx2] = 1\n y[idx] = y2\n\n idx = np.nonzero(x_range < a)[0]\n y[idx] = np.zeros(len(idx))\n\n idx = np.nonzero(x_range > d)[0]\n y[idx] = np.zeros(len(idx))\n\n fuzzy_val_dict[str(cat_name)] = y\n\n x_ranges[str(var_name)] = x_range\n fuzzy_dict[str(var_name)] = fuzzy_val_dict\n var_names.append(var_name)\n\n return fuzzy_dict, x_ranges, var_names, fuzzy_variables\n\n\ndef plot_fuzzy_sets(fuzzy_dict, x_ranges):\n '''\n Creates one plot for each fuzzy variable and displays the resulting sets.\n \n Args:\n fuzzy_dict(dict): the processed fuzzy variable dictionary with assigned memberships\n x_ranges(dict): the generated range of values for each membership\n \n '''\n\n\n for k, v in fuzzy_dict.items():\n var_name = k\n plt.figure(figsize=(8, 6))\n plt.title(str(var_name))\n for k_j, v_j in v.items():\n sns.lineplot(x_ranges[var_name], v_j, label=str(k_j), linewidth=3)\n plt.ylabel('Fuzzy membership value')\n plt.xlabel('Variables')\n plt.ylim(-0.01, 1.1)\n plt.legend()\n plt.show()\n","sub_path":"modules/fuzzy_membership.py","file_name":"fuzzy_membership.py","file_ext":"py","file_size_in_byte":4120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"354854980","text":"import tweepy\nfrom decouple import config\nfrom random import choice\nfrom pymongo import MongoClient\n# import traceback\nfrom datetime import datetime,timedelta\nfrom fastapi import BackgroundTasks\nfrom send_email import send_email_background, send_email_async\n###BOMBIFY BOT FOR GAINING TRACTION\n\nmongo = MongoClient(config(\"mongo_host\"))\nuser = mongo.tweetypy.tokenize\n\nasync def tweetify(authToken,scripts=[],tags='',tweetnums=''):\n try:\n mainToken = user.find_one({'auth_token':authToken})\n if authToken == '' or authToken is None or mainToken is None:\n # data = {\n # 'header':'Your Task was terminated!',\n # 'body':'Your task was terminated because of a wrong/invalid auth token! Please check your auth token and try again!'\n # }\n # send_email_background(BackgroundTasks,'TweetyPy Alert!',mainToken['email'],data,type=1)\n return 0\n auth = tweepy.OAuthHandler(mainToken['keyval']['cons_key'],mainToken['keyval']['cons_sec'])\n auth.set_access_token(mainToken['keyval']['access_key'],mainToken['keyval']['access_sec'])\n\n api = tweepy.API(auth)\n try:\n api.verify_credentials()\n except:\n datas = {\n 'header':'Your Task was Terminated due to Authentication Failer!',\n 'body':'We failed to authenticate with your credentials and hence the job was terminated!'\n }\n send_email_background(BackgroundTasks,'TweetyPy Alert!',mainToken['email'],datas,type=1)\n return -1\n\n\n limit = mainToken['quota']\n time = mainToken['reset']\n\n if limit <= tweetnums:\n datas = {\n 'header':'Your Task was Terminated due to Lack of Balance!',\n 'body':f'Sorry You do not have enough balance to execute this order. Current balance :{limit},job size:{tweetnums}'\n }\n send_email_background(BackgroundTasks,'TweetyPy Alert!',mainToken['email'],datas,type=1)\n return 2\n \n datas = {\n 'header':'Your Task was succesfully started!',\n 'body':'Your task has been started Successfully!'\n }\n await send_email_async('TweetyPy Alert!',mainToken['email'],datas,type=1)\n MAX_TWEETS = 100 #Maximum tweetnumbers\n for tweet in tweepy.Cursor(api.search_tweets, q=tags).items(min(tweetnums,MAX_TWEETS)):\n try:\n api.update_status(status = choice(scripts),in_reply_to_status_id = tweet.id,auto_populate_reply_metadata = True)\n except:\n pass\n flag = False\n if time > datetime.now():\n limit = 100\n flag = True\n user.update_one({'auth_token':authToken},{\"$set\":{'quota':limit,'reset':datetime.now()+timedelta(days=1)}})\n else:\n limit = limit - tweetnums\n user.update_one({'auth_token':authToken},{'$set':{'quota':limit}})\n if flag:\n data = 'Your quota has been refilled!'\n else:\n data =\"\"\n datas = {\n 'header':'Your task was successfully Completed!',\n 'body':f'Good news! Your task has been successfully completed.{data} Your Current quota balance is : {limit}.'\n }\n send_email_background(BackgroundTasks,'TweetyPy Alert!',mainToken['email'],datas,type=1)\n return 1\n except Exception as e:\n datas = {\n 'header':'Your Task was terminated due to internal Error',\n 'body':'Due to some error your task was terminated. We are looking into it! Be sure , your balance has not been deducted!'\n }\n send_email_background(BackgroundTasks,'TweetyPy Alert!',mainToken['email'],datas,type=1)\n return -2","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"53075134","text":"import sqlite3\n\n\nclass DBHelper:\n\n def __init__(self, dbname=\"telegram.sqlite\"):\n self.dbname = dbname\n self.conn = sqlite3.connect(dbname, check_same_thread=False)\n\n def setup(self):\n tblstmt = \"CREATE TABLE IF NOT EXISTS items (chat_id integer, ticker text, pool_id text, \" \\\n \"delegations integer default 0 ,blocks_minted integer default 0)\"\n itemidx = \"CREATE UNIQUE INDEX IF NOT EXISTS itemIndex ON items (chat_id,ticker)\"\n self.conn.execute(tblstmt)\n self.conn.execute(itemidx)\n \n self.conn.commit()\n\n def add_chat_id(self, chat_id):\n stmt = \"INSERT INTO items (chat_id) VALUES (?)\"\n args = (chat_id)\n self.conn.execute(stmt, args)\n self.conn.commit()\n\n def add_item(self, chat_id, ticker):\n try:\n stmt = \"INSERT INTO items (chat_id, ticker) VALUES (?, ?)\"\n args = (chat_id, ticker)\n self.conn.execute(stmt, args)\n self.conn.commit()\n except sqlite3.Error:\n print(\"Failed to add new record.\")\n\n def delete_item(self, chat_id, ticker):\n stmt = \"DELETE FROM items WHERE chat_id = (?) AND ticker = (?)\"\n args = (chat_id, ticker )\n self.conn.execute(stmt, args)\n self.conn.commit()\n\n def get_chat_ids(self):\n stmt = \"SELECT chat_id FROM items\"\n args = ()\n return [x[0] for x in self.conn.execute(stmt, args)]\n\n def get_chat_ids_from_poolid(self, pool_id):\n stmt = \"SELECT chat_id FROM items WHERE pool_id = (?)\"\n args = (pool_id,)\n return [x[0] for x in self.conn.execute(stmt, args)]\n\n def get_ticker_from_poolid(self, pool_id):\n stmt = \"SELECT ticker FROM items WHERE pool_id = (?)\"\n args = (pool_id,)\n return [x[0] for x in self.conn.execute(stmt, args)]\n\n def get_tickers(self, chat_id):\n stmt = \"SELECT ticker FROM items WHERE chat_id = (?)\"\n args = (chat_id,)\n return [x[0] for x in self.conn.execute(stmt, args)]\n\n def get_items(self, chat_id, ticker):\n stmt = \"SELECT pool_id, delegations, blocks_minted FROM items WHERE chat_id = (?) AND ticker = (?)\"\n args = (chat_id, ticker)\n for x in self.conn.execute(stmt, args):\n x = x\n return x\n\n def update_items(self, chat_id, ticker, pool_id, delegations, blocks_minted):\n stmt = \"UPDATE items SET pool_id = (?), delegations = (?), blocks_minted = (?)\" \\\n \"WHERE chat_id = (?) AND ticker = (?)\"\n args = (pool_id, delegations, blocks_minted, chat_id, ticker)\n self.conn.execute(stmt, args)\n self.conn.commit()\n\n def update_delegation(self, chat_id, ticker, delegations):\n stmt = \"UPDATE items SET delegations = (?) WHERE chat_id = (?) AND ticker = (?)\"\n args = (delegations, chat_id, ticker)\n self.conn.execute(stmt, args)\n self.conn.commit()\n\n def update_blocks_minted(self, chat_id, ticker, blocks_minted):\n stmt = \"UPDATE items SET blocks_minted = (?) WHERE chat_id = (?) AND ticker = (?)\"\n args = (blocks_minted, chat_id, ticker)\n self.conn.execute(stmt, args)\n self.conn.commit()\n\n def update_pool_id(self, chat_id, ticker, pool_id):\n stmt = \"UPDATE items SET pool_id = (?) WHERE chat_id = (?) AND ticker = (?)\"\n args = (pool_id, chat_id, ticker)\n self.conn.execute(stmt, args)\n self.conn.commit()","sub_path":"dbhelper.py","file_name":"dbhelper.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"210952875","text":"import torch.nn as nn\n\nfrom .pws_layer import PWSConv, pws_init, PWSLinear\nfrom mmcv.cnn import build_norm_layer\nfrom .layers import PLinear\n\ndef build_conv_layer(conv_cfg, in_channels, out_channels, kernel_size=1, stride=0, padding=0, norm_cfg=None):\n convtype = conv_cfg.pop('type')\n norm_layer = None\n if convtype == 'pws':\n conv_layer = PWSConv(in_channels, out_channels, \n kernel_size=kernel_size, stride=stride, padding=padding, bias=True, **conv_cfg)\n else:\n conv_layer = nn.Conv2d(in_channels, out_channels, \n kernel_size=kernel_size, stride=stride, padding=padding, bias=(norm_cfg is None))\n \n if norm_cfg is not None:\n norm_name, norm_layer = build_norm_layer(norm_cfg, out_channels)\n conv_cfg['type'] = convtype\n return conv_layer, norm_layer\n\ndef build_linear_layer(linear_cfg, in_features, out_features, norm=False):\n linear_type = linear_cfg.pop('type')\n norm_layer = None\n if linear_type == 'pws':\n layer = PWSLinear(in_features, out_features, **linear_cfg)\n if 'initalpha' in linear_cfg:\n linear_cfg.pop('initalpha')\n norm = False\n elif linear_type == 'plinear':\n layer = PLinear(in_features, out_features, bias=not norm)\n else:\n layer = nn.Linear(in_features, out_features, bias=not norm)\n\n if norm:\n norm_layer = nn.BatchNorm1d(out_features)\n linear_cfg['type'] = linear_type\n \n if norm_layer is not None:\n return [layer, norm_layer]\n else:\n return [layer]","sub_path":"modules/utils/build_layer.py","file_name":"build_layer.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"307525956","text":"\"\"\"Functions for converting coordinates.\"\"\"\n\nimport astropy.units as u\nimport numpy as np\nfrom astropy.coordinates import EarthLocation, SkyCoord\nfrom astropy.coordinates.builtin_frames import AltAz\nfrom astropy.time import Time\n\n\ndef enu_to_az_za(enu_e, enu_n, orientation=\"astropy\", periodic_azimuth=True):\n \"\"\"Convert angle cosines in ENU coordinates into azimuth and zenith angle.\n\n For a pointing vector in East-North-Up (ENU) coordinates vec{p}, the input\n arguments are ``enu_e = vec{p}.hat{e}`` and ``enu_n = vec{p}.hat{n}`, where\n ``hat{e}`` is a unit vector in ENU coordinates etc.\n\n For a drift-scan telescope pointing at the zenith, the ``hat{e}`` direction\n is aligned with the ``U`` direction (in the UVW plane), which means that we\n can identify the direction cosines ``l = enu_e`` and ``m = enu_n``.\n\n Azimuth is oriented East of North, i.e. Az(N) = 0 deg, Az(E) = +90 deg in\n the astropy convention, and North of East, i.e. Az(N) = +90 deg, and\n Az(E) = 0 deg in the UVBeam convention.\n\n Parameters\n ----------\n enu_e, enu_n : array_like\n Normalized angle cosine coordinates on the interval (-1, +1).\n\n orientation : str, optional\n Orientation convention used for the azimuth angle. The default is\n ``'astropy'``, which uses an East of North convention (Az(N) = 0 deg,\n Az(E) = +90 deg). Alternatively, the ``'uvbeam'`` convention uses\n North of East (Az(N) = +90 deg, Az(E) = 0 deg).\n\n periodic_azimuth : bool, optional\n if True, constrain az to be betwee 0 and 2 * pi\n This avoids the issue that arctan2 outputs angles between -pi and pi\n while most CST beam formats store azimuths between 0 and 2pi which leads\n interpolation domain mismatches.\n\n Returns\n -------\n az, za : array_like\n Corresponding azimuth and zenith angles (in radians).\n \"\"\"\n assert orientation in [\n \"astropy\",\n \"uvbeam\",\n ], \"orientation must be either 'astropy' or 'uvbeam'\"\n\n lsqr = enu_n ** 2.0 + enu_e ** 2.0\n zeta = np.where(lsqr < 1.0, np.sqrt(1.0 - lsqr), 0.0)\n\n az = np.arctan2(enu_e, enu_n)\n za = 0.5 * np.pi - np.arcsin(zeta)\n\n # Flip and rotate azimuth coordinate if uvbeam convention is used\n if orientation == \"uvbeam\":\n az = 0.5 * np.pi - az\n if periodic_azimuth:\n az = np.mod(az, 2 * np.pi)\n return az, za\n\n\ndef eci_to_enu_matrix(ha, lat):\n \"\"\"3x3 transformation matrix to rotate ECI to ENU coordinates.\n\n Transformation matrix to project Earth-Centered Inertial (ECI) coordinates\n to local observer-centric East-North-Up (ENU) coordinates at a given time\n and location.\n\n The ECI coordinates are aligned with the celestial pole, i.e. for (x,y,z)\n (RA=0 deg, Dec=0 deg) = (1, 0, 0)\n (RA=90 deg, Dec=0 deg) = (0, 1, 0)\n (RA=0 deg, Dec=90 deg) = (0, 0, 1)\n\n Note: This is a stripped-down version of the ``eq2top_m`` function.\n\n Parameters\n ----------\n ha : float\n Hour angle, in radians, where HA = LST - RA.\n\n lat : float\n Latitude of the observer, in radians.\n\n Returns\n -------\n m : array_like\n 3x3 array containing the rotation matrix for a given time.\n \"\"\"\n # Reference: https://gssc.esa.int/navipedia/index.php/Transformations_between_ECEF_and_ENU_coordinates\n return np.array(\n [\n [-np.sin(ha), np.cos(ha), 0.0 * ha],\n [-np.sin(lat) * np.cos(ha), -np.sin(lat) * np.sin(ha), np.cos(lat)],\n [np.cos(lat) * np.cos(ha), np.cos(lat) * np.sin(ha), np.sin(lat)],\n ]\n )\n\n\ndef enu_to_eci_matrix(ha, lat):\n \"\"\"3x3 transformation matrix to rotate ENU to ECI coordinates.\n\n 3x3 transformation matrix to project local observer-centric East-North-Up\n (ENU) coordinates at a given time and location to Earth-Centered Inertial\n (ECI) coordinates.\n\n The ECI coordinates are aligned with the celestial pole, i.e. for (x,y,z)\n (RA=0 deg, Dec=0 deg) = (1, 0, 0)\n (RA=90 deg, Dec=0 deg) = (0, 1, 0)\n (RA=0 deg, Dec=90 deg) = (0, 0, 1)\n\n Parameters\n ----------\n ha : float\n Hour angle, in radians, where HA = LST - RA.\n\n lat : float\n Latitude of the observer, in radians.\n\n Returns\n -------\n m : array_like\n 3x3 array containing the rotation matrix for a given time.\n \"\"\"\n # Reference: https://gssc.esa.int/navipedia/index.php/Transformations_between_ECEF_and_ENU_coordinates\n return np.array(\n [\n [-np.sin(ha), -np.cos(ha) * np.sin(lat), np.cos(ha) * np.cos(lat)],\n [np.cos(ha), -np.sin(ha) * np.sin(lat), np.sin(ha) * np.cos(lat)],\n [0.0 * ha, np.cos(lat), np.sin(lat)],\n ]\n )\n\n\ndef point_source_crd_eq(ra, dec):\n \"\"\"Coordinate transform of source locations from equatorial to Cartesian.\n\n This converts RA and Dec angles to a Cartesian x,y,z unit vector in an\n Earth-Centered Inertial (ECI) coordinate system aligned with the celestial\n pole, i.e. for (x,y,z)\n (RA=0 deg, Dec=0 deg) = (1, 0, 0)\n (RA=90 deg, Dec=0 deg) = (0, 1, 0)\n (RA=0 deg, Dec=90 deg) = (0, 0, 1)\n\n The RA and Dec are assumed to be in a particular reference frame that may\n not match-up with standard frames like ICRS/J2000. To convert coordinates\n from a standard system into the relevant frame, see\n :func:`~equatorial_to_eci_coords`.\n\n Parameters\n ----------\n ra, dec : array_like\n 1D arrays of source positions in equatorial coordinates (radians).\n\n Returns\n -------\n array_like\n Equatorial coordinates of sources, in Cartesian\n system. Shape=(3, NSRCS).\n \"\"\"\n return np.asarray([np.cos(ra) * np.cos(dec), np.cos(dec) * np.sin(ra), np.sin(dec)])\n\n\ndef equatorial_to_eci_coords(ra, dec, obstime, location, unit=\"rad\", frame=\"icrs\"):\n \"\"\"Convert RA and Dec coordinates into the ECI system used by vis_cpu.\n\n Convert RA and Dec coordinates into the ECI (Earth-Centered Inertial)\n system used by vis_cpu. This ECI system is aligned with the celestial pole,\n not the Earth's axis.\n\n To ensure that all corrections are properly taken into account, this\n function uses Astropy to find the Alt/Az positions of the coordinates at a\n specified reference time and location. These are then transformed back to\n ENU (East-North-Up) coordinates, and then to Cartesian ECI coordinates,\n using the inverses of the same transforms that are used to do the forward\n transforms when running ``vis_cpu``. The ECI coordinates are then finally\n converted back into adjusted RA and Dec coordinates in the ECI system.\n\n While the time-dependent corrections are determined for the reference time,\n the adjusted coordinates are expected to yield a good approximation to the\n true Azimuth and Zenith angle of the sources at other times (but the same\n location) when passed into the ``vis_cpu`` function via the ``crd_eq``\n array and then converted using the standard conversions within ``vis_cpu``.\n\n The following example code shows how to set up the Astropy ``Time`` and\n ``EarthLocation`` objects that are required by this function::\n\n # HERA location\n location = EarthLocation.from_geodetic(lat=-30.7215,\n lon=21.4283,\n height=1073.)\n # Observation time\n obstime = Time('2018-08-31T04:02:30.11', format='isot', scale='utc')\n\n\n Parameters\n ----------\n ra, dec : array_like\n Input RA and Dec positions. The units and reference frame of these\n positions can be set using the ``unit`` and ``frame`` kwargs.\n\n obstime : astropy.Time object\n ``Time`` object specifying the time of the reference observation.\n\n location : astropy.EarthLocation\n ``EarthLocation`` object specifying the location of the reference\n observation.\n\n unit : str, optional\n Which units the input RA and Dec values are in, using names intelligible\n to ``astropy.SkyCoord``. Default: 'rad'.\n\n frame : str, optional\n Which frame that input RA and Dec positions are specified in. Any\n system recognized by ``astropy.SkyCoord`` can be used. Default: 'icrs'.\n\n Returns\n -------\n eci_ra, eci_dec : array_like\n Arrays of RA and Dec coordinates with respect to the ECI system used\n by vis_cpu.\n \"\"\"\n if not isinstance(obstime, Time):\n raise TypeError(\"obstime must be an astropy.Time object\")\n if not isinstance(location, EarthLocation):\n raise TypeError(\"location must be an astropy.EarthLocation object\")\n\n # Local sidereal time at this obstime and location\n lst = obstime.sidereal_time(\"apparent\", longitude=location.lon).rad\n\n # Create Astropy SkyCoord object\n skycoords = SkyCoord(ra, dec, unit=unit, frame=frame)\n\n # Rotation matrix from Cartesian ENU to Cartesian ECI\n m = enu_to_eci_matrix(lst, location.lat.rad) # Evaluated at HA (= LST - RA) = LST\n\n # Get AltAz and ENU coords of sources at reference time and location. Ref:\n # https://gssc.esa.int/navipedia/index.php/Transformations_between_ECEF_and_ENU_coordinates\n alt_az = skycoords.transform_to(AltAz(obstime=obstime, location=location))\n el, az = alt_az.alt.rad, alt_az.az.rad\n astropy_enu = np.array(\n [np.cos(el) * np.sin(az), np.cos(el) * np.cos(az), np.sin(el)]\n )\n # astropy has Az oriented East of North, i.e. Az(N) = 0 deg, Az(E) = +90 deg\n\n # Convert to ECI coordinates using ENU->ECI transform\n astropy_eci = np.dot(m, astropy_enu)\n\n # Infer RA and Dec coords from astropy ECI\n px, py, pz = astropy_eci\n pdec = np.arcsin(pz)\n pra = np.arctan2(py, px)\n return pra, pdec\n\n\ndef uvbeam_to_lm(uvbeam, freqs, n_pix_lm=63, polarized=False, **kwargs):\n \"\"\"Evaluate a UVBeam object on a uniform direction cosine (l,m) grid.\n\n Here, (l, m) are the direction cosines, associated with the East and North\n ENU coordinates (and also the U and V directions for a zenith-pointing\n drift-scan telescope). For a vector in East-North-Up (ENU) coordinates\n vec{p}, we therefore have ``l = vec{p}.hat{e}`` etc.\n\n Parameters\n ----------\n uvbeam : UVBeam object\n Beam to convert to an (l, m) grid.\n freqs : array_like\n Frequencies to interpolate to in [Hz]. Shape=(NFREQS,).\n n_pix_lm : int, optional\n Number of pixels for each side of the beam grid.\n polarized : bool, optional\n Whether to return full polarized beam information or not.\n\n Returns\n -------\n ndarray\n The beam map cube. Shape: (NFREQS, BEAM_PIX, BEAM_PIX) if\n `polarized=False` or (NAXES, NFEEDS, NFREQS, BEAM_PIX, BEAM_PIX) if\n `polarized=True`.\n \"\"\"\n # Define angle cosines\n L = np.linspace(-1, 1, n_pix_lm, dtype=np.float32)\n L, m = np.meshgrid(L, L)\n L = L.flatten()\n m = m.flatten()\n\n # Get azimuth and zenith angles (note the different azimuth convention\n # used by UVBeam)\n az, za = enu_to_az_za(enu_e=L, enu_n=m, orientation=\"uvbeam\", periodic_azimuth=True)\n\n # Interpolate beam onto cube\n efield_beam = uvbeam.interp(az_array=az, za_array=za, freq_array=freqs, **kwargs)[0]\n if polarized:\n bm = efield_beam[:, 0, :, :, :] # spw=0\n else:\n bm = efield_beam[0, 0, 1, :, :] # (phi, e) == 'xx' component\n\n # Peak normalization and reshape output\n if polarized:\n Naxes = bm.shape[0] # polarization vector axes\n Nfeeds = bm.shape[1] # polarized feeds\n\n # Separately normalize each polarization channel\n for i in range(Naxes):\n for j in range(Nfeeds):\n if np.max(bm[i, j]) > 0.0:\n bm /= np.max(bm[i, j])\n return bm.reshape((Naxes, Nfeeds, len(freqs), n_pix_lm, n_pix_lm))\n else:\n # Normalize single polarization channel\n if np.max(bm) > 0.0:\n bm /= np.max(bm)\n return bm.reshape((len(freqs), n_pix_lm, n_pix_lm))\n","sub_path":"src/vis_cpu/conversions.py","file_name":"conversions.py","file_ext":"py","file_size_in_byte":12004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"162809065","text":"import unittest\nfrom inferelator_ng import utils\nfrom inferelator_ng.utils import Validator as check\nfrom io import StringIO\nimport pandas as pd\n\nmetadata_text_1 = u\"\"\"\n\"isTs\"\\t\"is1stLast\"\\t\"prevCol\"\\t\"del.t\"\\t\"condName\"\nFALSE\\t\"e\"\\tNA\\tNA\\t\"wt\"\nFALSE\\t\"e\"\\tNA\\tNA\\t\"c1\"\nFALSE\\t\"l\"\\t\"c4\"\\t5\\t\"c2\"\nFALSE\\t\"e\"\\tNA\\tNA\\t\"c3\"\nFALSE\\t\"f\"\\tNA\\tNA\\t\"c4\"\nFALSE\\t\"e\"\\tNA\\tNA\\t\"c5\"\n\"\"\".strip()\n\nexpression_data_1 = u\"\"\"\n\\t\"wt\"\\t\"c1\"\\t\"c2\"\\t\"c3\"\\t\"c4\"\\t\"c5\"\ngene1\\t1\\t1\\t1\\t1\\t1\\t1\ngene2\\t0\\t0\\t0\\t0\\t0\\t0\n\"\"\".strip()\n\nclass TestUtils(unittest.TestCase):\n\n def test_read_tf_names(self):\n text = u'\"G1\"\\n\"G2\"\\n\"G3\"\\n'\n f = StringIO(text)\n tf_names = utils.read_tf_names(f)\n self.assertEqual([\"G1\", \"G2\", \"G3\"], tf_names)\n\n def test_metadata_df(self):\n f = StringIO(metadata_text_1)\n df = utils.metadata_df(f)\n self.assertEqual({'del.t', 'is1stLast', 'isTs', 'prevCol'}, set(df.keys()))\n return df\n\nclass TestValidator(unittest.TestCase):\n\n def setUp(self):\n self.frame1 = pd.DataFrame(index=[\"A\", \"B\", \"C\", \"D\", \"E\"], columns = [\"RED\", \"BLUE\", \"GREEN\"])\n self.frame2 = pd.DataFrame(index=[\"A\", \"B\", \"C\", \"D\", \"E\"], columns = [\"CYAN\", \"BLUE\", \"MAUVE\"])\n self.frame3 = pd.DataFrame(index=[\"A\", \"B\", \"C\", \"E\", \"D\"], columns = [\"RED\", \"BLUE\", \"GREEN\"])\n\n def test_frame_alignment(self):\n\n self.assertTrue(check.dataframes_align([self.frame1, self.frame1, self.frame1]))\n self.assertTrue(check.dataframes_align([self.frame1, self.frame1, self.frame3], check_order=False))\n\n with self.assertRaises(ValueError):\n check.dataframes_align([self.frame1, self.frame2, self.frame1])\n\n with self.assertRaises(ValueError):\n check.dataframes_align([self.frame1, self.frame3, self.frame1])\n\n def test_numeric(self):\n\n self.assertTrue(check.argument_numeric(0))\n self.assertTrue(check.argument_numeric(0.0))\n\n with self.assertRaises(ValueError):\n check.argument_numeric(\"0\")\n\n self.assertTrue(check.argument_numeric(1, 0, 2))\n\n with self.assertRaises(ValueError):\n self.assertTrue(check.argument_numeric(2, 0, 1))\n\n self.assertTrue(check.argument_numeric(None, allow_none=True))\n\n def test_type(self):\n\n self.assertTrue(check.argument_type(self, unittest.TestCase))\n self.assertTrue(check.argument_type(None, unittest.TestCase, allow_none=True))\n\n with self.assertRaises(ValueError):\n self.assertTrue(check.argument_type(\"0\", unittest.TestCase))\n\n def test_enum(self):\n\n self.assertTrue(check.argument_enum(\"A\", (\"A\", \"B\")))\n self.assertTrue(check.argument_enum([\"A\", \"B\", \"A\"], (\"A\", \"B\")))\n\n with self.assertRaises(ValueError):\n check.argument_enum([\"A\", \"B\", \"C\"], (\"A\", \"B\"))\n\n def test_none(self):\n\n self.assertTrue(check.arguments_not_none((\"A\", \"B\")))\n self.assertTrue(check.arguments_not_none((\"A\", None), num_none=1))\n with self.assertRaises(ValueError):\n self.assertTrue(check.arguments_not_none((None, None, \"A\")))\n with self.assertRaises(ValueError):\n self.assertTrue(check.arguments_not_none((None, None, \"A\"), num_none=0))\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n","sub_path":"inferelator_ng/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"242781152","text":"#\n# Hyhyhy - https://github.com/MaciejCzyzewski/Hyhyhy\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2014 Maciej A. Czyzewski\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# Author: Maciej A. Czyzewski \n#\n\nimport sys\nimport os\n\nif sys.version_info < (3, 2):\n sys.exit(\"Hyhyhy requires python in version >= 3.2\")\n\nimport configparser\nimport glob\n\n__version__ = '1.0.0'\n\n__help__ = '''\n Hyhyhy - Presentation nano-framework. [v ''' + __version__ + ''']\n hyhyhy.py build - Build project to file\n hyhyhy.py status - Show project structure\n '''\n\n\ndef num(path):\n name = os.path.basename(path)\n name, ext = os.path.splitext(name)\n return int(name)\n\n\ndef prf(a):\n b = {\n 'OK': '\\033[92m[OK]\\033[0m',\n 'FAIL': '\\033[91m[FAIL]\\033[0m',\n 'INFO': '\\033[95m[INFO]\\033[0m',\n 'WARNING': '\\033[93m[WARNING]\\033[0m',\n }\n return b[str(a)]\n\nassets, sections, default = list(glob.glob(\"assets/*\")), list(glob.glob(\"sections/*\")), 'default.cfg'\nhtml = '(head)(body)'\n\nconfig = configparser.ConfigParser()\nconfig.read(default)\n\nsections.sort(key=num)\n\n\ndef get_head(a=\"\"):\n global html, assets, sections\n\n if config['head']['charset']:\n a += \"\"\n\n if config['head']['title']:\n a += \"\" + str(config['head']['title']) + \"\"\n\n for i in assets:\n print(prf('OK'), \"Parsing file\", i, \"...\")\n if i.split('.')[-1] == \"css\":\n a += \"\"\n elif i.split('.')[-1] == \"js\":\n a += \"\"\n\n return a\n\n\ndef get_body(a=\"\"):\n global html, assets, sections\n\n for i in sections:\n print(prf('OK'), \"Parsing file\", i, \"...\")\n a += \"
\" + str(open(i, 'r').read()) + \"
\"\n\n return a\n\n\ndef get_html():\n global html\n\n html = html.replace('(head)', get_head())\n html = html.replace('(body)', get_body())\n\n return html\n\n\ndef init_build():\n global config\n\n if not os.path.exists(config['core']['build']):\n os.makedirs(config['core']['build'].split('/')[-2])\n\n with open(config['core']['build'], 'w') as build:\n build.write(get_html())\n\n print(prf('OK'), \"Saved in\", config['core']['build'], \"->\", config['head']['title'])\n\n\ndef init_status():\n global assets, sections\n\n print(prf('OK'), \"Structure of project\", \"[\" + str(len(sections)) + \" slides]\")\n\n print(\" - assets/\")\n\n for i in assets:\n if i.split('.')[-1] == \"css\":\n print(\" -\", i.split('/')[-1], \"[style]\")\n elif i.split('.')[-1] == \"js\":\n print(\" -\", i.split('/')[-1], \"[script]\")\n else:\n print(\" -\", i.split('/')[-1])\n\n print(\" - sections/\")\n\n for i in sections:\n print(\" -\", i.split('/')[-1])\n\n\nif len(sys.argv) == 2 and sys.argv[1] == 'help':\n print(__help__)\nelse:\n print(prf('INFO'), \"Starting hyhyhyhyhyhyhyhyhy\", \"...\")\n print(prf('OK'), \"Reading config file\", default, \"...\")\n\n if len(sys.argv) == 2 and sys.argv[1] == 'status':\n init_status()\n else:\n init_build()\n","sub_path":"hyhyhy.py","file_name":"hyhyhy.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"22683551","text":"import argparse\nfrom collections import defaultdict\nimport gc\nimport itertools\nimport logging\nimport pandas as pd\nimport numpy as np\nimport psutil\nimport os\nimport re\n\n#pd.options.mode.chained_assignment = 'raise'\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s')\n\nCOLUMN_TYPES = {\n 'chrom': 'str',\n 'start_1based': 'int32',\n 'end_1based': 'int32',\n 'strand': 'int8',\n 'intron_motif': 'int8',\n 'known_splice_junction': 'int8',\n 'unique_reads': 'int32',\n 'multi_mapped_reads': 'int32',\n 'total_reads': 'int32',\n 'maximum_overhang': 'int16',\n 'num_samples_with_this_junction': 'int32',\n 'num_samples_total': 'int32',\n 'max_per_sample_unique_reads': 'int32',\n 'max_per_sample_total_reads': 'int32',\n 'strand_counter': 'int32',\n}\n\nCOLUMN_NAMES = [\n 'strand',\n 'intron_motif',\n 'known_splice_junction',\n 'unique_reads',\n 'multi_mapped_reads',\n 'maximum_overhang',\n 'total_reads',\n 'num_samples_with_this_junction',\n 'num_samples_total',\n 'max_per_sample_unique_reads',\n 'max_per_sample_total_reads',\n 'strand_counter',\n 'sample_id',\n]\n\nAGGREGATED_COLUMNS_TO_ADD_TO_INDIVIDUAL_TABLES = [\n 'num_samples_with_this_junction',\n 'num_samples_total',\n 'max_per_sample_unique_reads',\n 'max_per_sample_total_reads',\n 'sample_id',\n]\n\ndef parse_args():\n p = argparse.ArgumentParser(description=\"Combines multiple SJ.out.tab tables into one combined .bed file which can be loaded into TGG-viewer to visualize splice junctions\")\n p.add_argument(\"-n\", \"--batch-size\", type=int, default=50, help=\"How many tables to merge in memory before writing to disk. Bigger batch sizes use more memory.\")\n p.add_argument(\"-o\", \"--output-path\", help=\"Combined .bed output path\")\n p.add_argument(\"--normalize-read-counts\", action=\"store_true\", help=\"whether to normalize unique- and multi-mapped read counts rather than just summing them across input tables\")\n p.add_argument(\"--save-individual-tables\", action=\"store_true\", help=\"Also export individual .bed files with additional columns\")\n p.add_argument(\"--discard-sample-id-column\", action=\"store_true\", help=\"Don't add a sample_id column with a list of samples that have each splice junction. This increases compute time by 10x.\")\n p.add_argument(\"paths\", nargs=\"+\", help=\"Paths of 1 or more input SJ.out.tab tables\")\n args = p.parse_args()\n\n if args.normalize_read_counts:\n for column_name in 'unique_reads', 'multi_mapped_reads', 'total_reads', 'max_per_sample_unique_reads', 'max_per_sample_total_reads':\n COLUMN_TYPES[column_name] = 'float32'\n\n return args\n\n\ndef batched_iter(iterable, batch_size=1):\n it = iter(iterable)\n while True:\n batch = tuple(itertools.islice(it, batch_size))\n if not batch:\n break\n yield batch\n\n\nprev_memory_bytes = 0\ndef print_memory_stats(message=\"\", run_gc=False):\n global prev_memory_bytes\n if message:\n message = \" - \" + message\n if run_gc:\n gc.collect()\n\n memory_bytes = psutil.Process(os.getpid()).memory_info().rss\n\n logging.info(f'memory used {message}: {memory_bytes//10**6} Mb delta: {(memory_bytes - prev_memory_bytes)//10**6} Mb')\n prev_memory_bytes = memory_bytes\n\n\ndef read_SJ_out_tab(path, i=None):\n df = pd.read_csv(\n path,\n names=[\n 'chrom', 'start_1based', 'end_1based',\n f'strand',\n f'intron_motif',\n f'known_splice_junction',\n f'unique_reads',\n f'multi_mapped_reads',\n f'maximum_overhang'],\n index_col=['chrom', 'start_1based', 'end_1based'],\n dtype=COLUMN_TYPES,\n sep='\\t')\n\n df.loc[:, 'total_reads'] = df[\"unique_reads\"] + df[\"multi_mapped_reads\"]\n\n df.loc[:, 'num_samples_with_this_junction'] = np.int32(1)\n df.loc[:, 'num_samples_total'] = np.int32(1)\n df.loc[:, 'max_per_sample_unique_reads'] = df['unique_reads']\n df.loc[:, 'max_per_sample_total_reads'] = df['total_reads']\n\n df.loc[:, 'strand_counter'] = df['strand'].apply(lambda s: 1 if s == 1 else (-1 if s == 2 else 0)).astype('int32')\n df.loc[:, 'sample_id'] = os.path.basename(path).replace(\".SJ.out.tab\", \"\").replace(\".gz\", \"\")\n\n # print some stats\n print(f\" {df.unique_reads.sum()/1_000_000:0.1f} million uniquely-mapped reads\")\n print(f\" {100*df.multi_mapped_reads.sum()/float(df.unique_reads.sum() + df.multi_mapped_reads.sum()):0.0f}% multi-mapped\")\n\n if i is not None:\n name_mapping = dict(zip(df.columns, [f\"{c}_{i}\" for c in df.columns]))\n df.rename(columns=name_mapping, inplace=True)\n\n return df\n\n\n\"\"\"\nHow the normalization works:\n\n2 samples: \n800 reads, 1200 reads\ntotal_unique_reads_across_all_samples = 1000\nscalars:\n1.25 (5/4), 0.83 (5/6)\n\njunction1: 10, 15 => 10*1.25/2 + 15*0.83/2 => normalized count: 12.475 \njunction2: 10, 5 => 10*1.25/2 + 5*0.83/2 => normalized count: 8.325 \n\"\"\"\n\n\ndef process_all_batches(args):\n total_samples = len(args.paths)\n logging.info(f'Processing {total_samples} tables')\n\n if args.normalize_read_counts:\n # read all the tables to compute total_unique_reads_across_all_samples and average_unique_reads_per_sample\n total_unique_reads_across_all_samples = 0\n for path in args.paths:\n df = read_SJ_out_tab(path)\n if args.discard_sample_id_column:\n df.drop(columns=['sample_id'], inplace=True)\n total_unique_reads_across_all_samples += df.unique_reads.sum()\n\n average_unique_reads_per_sample = total_unique_reads_across_all_samples/float(total_samples)\n\n all_combined_SJ_out_tab_df = pd.DataFrame()\n sample_i = 0\n for batch_number, batch_sample_paths in enumerate(batched_iter(args.paths, args.batch_size)):\n tables_in_batch = []\n batch_start_i = sample_i\n for path in batch_sample_paths:\n logging.info(f\"Batch {batch_number}, Table {sample_i}: {path}\")\n current_SJ_out_tab_df = read_SJ_out_tab(path, sample_i)\n\n if args.normalize_read_counts:\n unique_reads_in_sample = current_SJ_out_tab_df[f\"unique_reads_{sample_i}\"].sum()\n scalar = average_unique_reads_per_sample / float(unique_reads_in_sample)\n\n current_SJ_out_tab_df.loc[:, f\"unique_reads_{sample_i}\"] *= scalar / float(total_samples)\n current_SJ_out_tab_df.loc[:, f\"multi_mapped_reads_{sample_i}\"] *= scalar / float(total_samples)\n current_SJ_out_tab_df.loc[:, f\"total_reads_{sample_i}\"] *= scalar / float(total_samples)\n current_SJ_out_tab_df.loc[:, f\"max_per_sample_unique_reads_{sample_i}\"] *= scalar / float(total_samples)\n current_SJ_out_tab_df.loc[:, f\"max_per_sample_total_reads_{sample_i}\"] *= scalar / float(total_samples)\n\n current_SJ_out_tab_df.loc[:, f\"unique_reads_{sample_i}\"] = current_SJ_out_tab_df[f\"unique_reads_{sample_i}\"].round(decimals=3)\n current_SJ_out_tab_df.loc[:, f\"multi_mapped_reads_{sample_i}\"] = current_SJ_out_tab_df[f\"multi_mapped_reads_{sample_i}\"].round(decimals=3)\n current_SJ_out_tab_df.loc[:, f\"total_reads_{sample_i}\"] = current_SJ_out_tab_df[f\"total_reads_{sample_i}\"].round(decimals=3)\n current_SJ_out_tab_df.loc[:, f\"max_per_sample_unique_reads_{sample_i}\"] = current_SJ_out_tab_df[f\"max_per_sample_unique_reads_{sample_i}\"].round(decimals=3)\n current_SJ_out_tab_df.loc[:, f\"max_per_sample_total_reads_{sample_i}\"] = current_SJ_out_tab_df[f\"max_per_sample_total_reads_{sample_i}\"].round(decimals=3)\n logging.info(f\"{path} has {int(unique_reads_in_sample)} total unique reads while the \"\n f\"per-sample average is {average_unique_reads_per_sample}. Scaling read counts \"\n f\"by {scalar} and dividing by {total_samples}\")\n\n tables_in_batch.append(current_SJ_out_tab_df)\n sample_i += 1\n batch_end_i = sample_i\n\n all_combined_SJ_out_tab_df = all_combined_SJ_out_tab_df.join(tables_in_batch, how=\"outer\")\n\n current_batch_columns = {}\n for column in COLUMN_NAMES:\n current_batch_columns[column] = [f'{column}_{k}' for k in range(batch_start_i, batch_end_i)]\n if batch_number > 0: current_batch_columns[column].append(column)\n\n # merge intron_motif columns across samples in the current batch\n intron_motif_columns_df = all_combined_SJ_out_tab_df[current_batch_columns['intron_motif']]\n intron_motif_columns_df.ffill(axis=1, inplace=True)\n intron_motif_columns_df = intron_motif_columns_df.iloc[:,-1].astype(COLUMN_TYPES['intron_motif'])\n all_combined_SJ_out_tab_df.loc[:, 'intron_motif'] = intron_motif_columns_df\n\n # merge known_splice_junction columns across samples in the current batch\n known_splice_junction_df = all_combined_SJ_out_tab_df[current_batch_columns['known_splice_junction']]\n known_splice_junction_df.replace(0, np.nan, inplace=True)\n known_splice_junction_df.ffill(axis=1, inplace=True)\n known_splice_junction_df = known_splice_junction_df.iloc[:,-1]\n known_splice_junction_df.fillna(0, inplace=True)\n known_splice_junction_df = known_splice_junction_df.astype(COLUMN_TYPES['known_splice_junction'])\n all_combined_SJ_out_tab_df.loc[:, 'known_splice_junction'] = known_splice_junction_df\n\n # merged other columns across samples in the current batch\n all_combined_SJ_out_tab_df.loc[:, 'unique_reads'] = all_combined_SJ_out_tab_df[current_batch_columns['unique_reads']].sum(axis=1).astype(COLUMN_TYPES['unique_reads'])\n all_combined_SJ_out_tab_df.loc[:, 'multi_mapped_reads'] = all_combined_SJ_out_tab_df[current_batch_columns['multi_mapped_reads']].sum(axis=1).astype(COLUMN_TYPES['multi_mapped_reads'])\n all_combined_SJ_out_tab_df.loc[:, 'total_reads'] = all_combined_SJ_out_tab_df[current_batch_columns['total_reads']].sum(axis=1).astype(COLUMN_TYPES['total_reads'])\n all_combined_SJ_out_tab_df.loc[:, 'maximum_overhang'] = all_combined_SJ_out_tab_df[current_batch_columns['maximum_overhang']].max(axis=1).astype(COLUMN_TYPES['maximum_overhang'])\n all_combined_SJ_out_tab_df.loc[:, 'strand_counter'] = all_combined_SJ_out_tab_df[current_batch_columns['strand_counter']].sum(axis=1).astype(COLUMN_TYPES['strand_counter'])\n\n # compute derived columns\n all_combined_SJ_out_tab_df.loc[:, 'num_samples_with_this_junction'] = all_combined_SJ_out_tab_df[current_batch_columns['num_samples_with_this_junction']].sum(axis=1).astype(COLUMN_TYPES['num_samples_with_this_junction'])\n all_combined_SJ_out_tab_df.loc[:, 'num_samples_total'] = total_samples\n all_combined_SJ_out_tab_df.loc[:, 'max_per_sample_unique_reads'] = all_combined_SJ_out_tab_df[current_batch_columns['max_per_sample_unique_reads']].max(axis=1).astype(COLUMN_TYPES['unique_reads'])\n all_combined_SJ_out_tab_df.loc[:, 'max_per_sample_total_reads'] = all_combined_SJ_out_tab_df[current_batch_columns['max_per_sample_total_reads']].max(axis=1).astype(COLUMN_TYPES['total_reads'])\n\n if not args.discard_sample_id_column:\n all_combined_SJ_out_tab_df.loc[:, 'sample_id'] = all_combined_SJ_out_tab_df[current_batch_columns['sample_id']].apply(lambda row: \",\".join(row[~row.isna()]), axis=1).astype('str')\n\n for column in COLUMN_NAMES:\n if batch_number > 0: current_batch_columns[column].remove(column)\n\n #logging.info(f\"Dropping columns: {current_batch_columns[column]} from {all_combined_SJ_out_tab_df.columns}\")\n all_combined_SJ_out_tab_df.drop(columns=current_batch_columns[column], inplace=True)\n\n print_memory_stats(f'after table {sample_i}')\n logging.info(f\"Done processing batch {batch_number}\")\n\n if args.normalize_read_counts:\n # undo the scaling that was applied to unique read counts with the expectation that they'd be summed (instead of taking the max value as is done for this column)\n all_combined_SJ_out_tab_df.loc[:, 'max_per_sample_unique_reads'] *= total_samples\n all_combined_SJ_out_tab_df.loc[:, 'max_per_sample_total_reads'] *= total_samples\n\n return all_combined_SJ_out_tab_df\n\n\ndef main():\n args = parse_args()\n\n all_combined_SJ_out_tab_df = process_all_batches(args)\n\n # set final strand value to 1 (eg. '+') or 2 (eg. '-') or 0 (eg. uknown) based on the setting in the majority of samples\n all_combined_SJ_out_tab_df.loc[:, 'strand'] = all_combined_SJ_out_tab_df['strand_counter'].apply(\n lambda s: 1 if s > 0 else (2 if s < 0 else 0)).astype('int8')\n\n logging.info(all_combined_SJ_out_tab_df.dtypes)\n logging.info(\"-----\")\n #pd.set_option('display.max_columns', 10000)\n #logging.info(all_combined_SJ_out_tab_df.describe())\n\n # save the combined table\n if args.output_path:\n output_path = args.output_path\n else:\n output_path = f\"combined.{len(args.paths)}_samples\"\n if args.normalize_read_counts:\n output_path += \".normalized\"\n output_path += \".SJ.out.tsv.gz\"\n\n out = all_combined_SJ_out_tab_df.reset_index().astype(COLUMN_TYPES)\n\n out[[\"chrom\", \"start_1based\", \"end_1based\"] + COLUMN_NAMES].to_csv(output_path, index=False, sep=\"\\t\")\n logging.info(f\"Wrote out {output_path}\")\n\n # save per-sample tables\n if args.save_individual_tables:\n if args.discard_sample_id_column:\n AGGREGATED_COLUMNS_TO_ADD_TO_INDIVIDUAL_TABLES.remove('sample_id')\n\n for path in args.paths:\n df = read_SJ_out_tab(path)\n df.drop(columns=AGGREGATED_COLUMNS_TO_ADD_TO_INDIVIDUAL_TABLES, inplace=True)\n df = df.join(all_combined_SJ_out_tab_df[AGGREGATED_COLUMNS_TO_ADD_TO_INDIVIDUAL_TABLES], how=\"left\")\n out = df.reset_index()\n output_path = re.sub(\"(.SJ.out)?(.tsv|.tab)(.gz)?$\", \"\", os.path.basename(path))\n if args.normalize_read_counts:\n output_path += \".normalized\"\n output_path += \".SJ.out.tsv.gz\"\n\n logging.info(f\"Wrote out {output_path}\")\n out[[\"chrom\", \"start_1based\", \"end_1based\"] + COLUMN_NAMES].to_csv(output_path, index=False, sep=\"\\t\")\n\n\nif __name__ == \"__main__\":\n main()\n\n\"\"\"\n#strand_conflicts_count = combined_ht.filter(hl.abs(combined_ht.strand_counter)/hl.float(combined_ht.num_samples_with_this_junction) < 0.1, keep=True).count()\n#joined_table.to_csv(f\"combined_using_pandas.{total_samples}_samples.SJ.out.tab\", sep=\"\\t\", header=True, index=False)\n#joined_table = pd.read_parquet(f\"combined_using_pandas.{total_samples}_samples.SJ.out.parquet\")\n\n#total_junctions_count = combined_ht.count()\n#strand_conflicts_count = combined_ht.filter(hl.abs(combined_ht.strand_counter)/hl.float(combined_ht.num_samples_with_this_junction) < 0.1, keep=True).count()\n\n#combined_ht = combined_ht.annotate_globals(\n# combined_tables=args.paths,\n# n_combined_tables=total_samples)\n\n#if strand_conflicts_count:\n# print(f\"WARNING: Found {strand_conflicts_count} strand_conflicts out of {total_junctions_count} total_junctions\")\n\"\"\"\n","sub_path":"pipelines/tgg_viewer/junctions_track_pipelines/docker/combine_splice_junctions_using_pandas.py","file_name":"combine_splice_junctions_using_pandas.py","file_ext":"py","file_size_in_byte":15201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"236406064","text":"\n\nfrom xai.brain.wordbase.nouns._consideration import _CONSIDERATION\n\n#calss header\nclass _CONSIDERATIONS(_CONSIDERATION, ):\n\tdef __init__(self,): \n\t\t_CONSIDERATION.__init__(self)\n\t\tself.name = \"CONSIDERATIONS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"consideration\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_considerations.py","file_name":"_considerations.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"548073823","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: GuiLearn3\n Description :\n Author : houyujiang\n date: 2018/1/23 11:38\n IDE: PyCharm\n-------------------------------------------------\n Change Activity:\n 2018/1/23:\n-------------------------------------------------\n\"\"\"\nimport sys\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QWidget,QApplication,QGridLayout,QLabel\n\nclass Example(QWidget):\n\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n def initUI(self):\n grid = QGridLayout()\n grid.setSpacing(10)\n\n x = 10\n y = 0\n self.text = \"x:{0},y:{1}\".format(x,y)\n self.label= QLabel(self.text,self)\n grid.addWidget(self.label,0,0,Qt.AlignTop)\n self.setMouseTracking(True)\n self.setLayout(grid)\n self.setGeometry(300,300,350,200)\n self.setWindowTitle('Event Object')\n self.show()\n #捕捉鼠标动作获取坐标\n def mouseMoveEvent(self, QMouseEvent):\n x = QMouseEvent.x()\n y = QMouseEvent.y()\n print(type(x))\n text =\"x:{0},y:{1}\".format(x,y)\n print (text)\n self.label.setText(text)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())","sub_path":"GuiLearn3.py","file_name":"GuiLearn3.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"514229347","text":"import copy\nimport os\nimport re\nimport time\nfrom pathlib import Path\n\nfrom fuzzywuzzy import fuzz\n\nfrom amplio.programspec import errors, programspec\nfrom amplio.programspec.programspec_constants import DIRECTORIES, XDIRECTORIES, XLSX, RECIPIENTS\nfrom recipient_file_utils import RecipientFileUtils\n\n# In this module is it very useful to refer to recipients by (community, group, agent). For that purpose,\n# we use the term \"community_group\".\n#\n# Please be consistent here.\n\n# To find non-word, non-hyphen characters (replace with _ in filenames). \n\n_file_substitutions = re.compile('[^\\w-]+')\n\n\ndef _recip_key(comm_or_recip, group_or_none: None, se_or_none: None):\n pass\n\n\n# Cannonicalize strings to upper case before fuzzy matching.\ndef ufuzz(left, right):\n return fuzz.ratio(left.upper(), right.upper())\n\ndef format_cga(cga):\n ''' community /group (if group) /agent (if agent) '''\n s = cga[0]\n s = s + ('/' + cga[1] if cga[1] else '')\n s = s + ('/' + cga[2] if cga[2] else '')\n return s\n\n\nclass FuzzyDirectoryMatcher:\n def __init__(self, reconciler):\n self._reconciler = reconciler\n # formats a recip (community, group, agent) as a string\n self._fmt = reconciler._fmt\n\n # Sets values used outside of the walk function.\n def _prepare(self):\n self.dirs = sorted([d for d in self._reconciler._unmatched_dirs], key=lambda d: d.upper())\n self.recips = sorted([r for r in self._reconciler._unmatched_recipients], key=lambda r: self._fmt(r).upper())\n self.dir_width = max([0] + [len(d) for d in self.dirs]) + 5\n self.recip_width = max([0] + [len(self._fmt(r)) for r in self.recips]) + 5\n\n def _walk(self, matched, advanced_dirs, advanced_recips):\n # convenience references\n dirs = self.dirs\n recips = self.recips\n # Does a fuzzy match on the d'th dir and r'th recip, -1 if no such element\n fz = lambda d, r: ufuzz(dirs[d].replace(' ', ''), self._fmt(recips[r]).replace(' ', '')) if d < len(\n dirs) and r < len(recips) else -1\n\n while len(dirs) and len(recips):\n # Compare current elements, plus 1 & 2 lookaheads. The comparisons of 2,1 and 1,2 don't seem to\n # affect the outcome, but they do affect how we get there.\n score = [fz(0, 0), fz(1, 0), fz(0, 1), fz(2, 0), fz(0, 2)] # , fz(2,1), fz(1,2)]\n max_score = max(score)\n # Is any of them good enough?\n if max_score > self._reconciler._threshold:\n score_ix = score.index(max_score) # returns first one found, which is what we want\n # prefer the tip, if it is equal or better. Otherwise take one from right or left, then do the\n # comparisons again.\n if score_ix == 0:\n matched(recips.pop(0), dirs.pop(0), max_score)\n elif score_ix % 2 == 1:\n # The next or second left matches the current right better. Skip one left.\n advanced_dirs(dirs.pop(0))\n else:\n # The next or second right matches the current left better. Skip one right.\n advanced_recips(recips.pop(0))\n else:\n # Just advance based on lexical comparison\n if dirs[0].upper() < self._fmt(recips[0]).upper():\n advanced_dirs(dirs.pop(0))\n else:\n advanced_recips(recips.pop(0))\n while len(dirs):\n advanced_dirs(dirs.pop(0))\n while len(recips):\n advanced_recips(recips.pop(0))\n\n def make_matches(self):\n self._prepare()\n matched = lambda r, d, s: matches.append((r, d, s))\n advanced = lambda x: None # doesn't do anything, so use same one for left and right\n\n num_matched = 0\n matches = []\n self._walk(matched, advanced, advanced)\n while len(matches) > 0:\n num_matched = num_matched + len(matches)\n for recip, directory, score in matches:\n self._reconciler.remove_matched(recip, directory, score)\n matches = []\n self._prepare()\n self._walk(matched, advanced, advanced)\n return num_matched\n\n def print_unmatched(self):\n self._prepare()\n # convenience shortcuts\n fmt = lambda r: '{}/{}'.format(r[0], r[1])\n matched = lambda d, r, s: print(\n ' {:{lw}} {:{rw}} ({}% match)'.format(format_cga(r), d, s, lw=lw, rw=rw))\n advanced_dirs = lambda d: print(' {:{lw}} {:{rw}}'.format('', d, lw=lw, rw=rw))\n advanced_recips = lambda r: print(' {:{lw}} {:{rw}}'.format(format_cga(r), '', lw=lw, rw=rw))\n\n cghead = '{} Community/Groups'.format(len(self.recips))\n dirhead = '{} Directories'.format(len(self.dirs))\n lw = max(self.recip_width, len(cghead))\n rw = max(self.dir_width, len(dirhead))\n\n if len(self.recips) > 0 or len(self.dirs) > 0:\n print('Unmatched directories and communities')\n print(' {:{lw}} {:{rw}}'.format(cghead, dirhead, lw=lw, rw=rw))\n print(' {:-^{lw}} {:-^{rw}}'.format('', '', rw=rw, lw=lw))\n\n self._walk(matched, advanced_dirs, advanced_recips)\n\n\nclass Reconciler:\n def __init__(self, acmdir, spec: programspec, strategy: int, update: set, outdir):\n def _strategy0(r):\n return _file_substitutions.sub('_', r[1])\n\n def _strategy3(r):\n # community {-group_or_community_worker}\n grp = '-' + r[1] if r[1] else ''\n return _file_substitutions.sub('_', r[0] + grp)\n\n def _strategy4(r):\n # community {-group_or_community_worker}\n name = r[0]\n name += ('-'+r[1]) if r[1] else ''\n name += ('-'+r[2]) if r[2] else ''\n return _file_substitutions.sub('_', name)\n\n self._acmdir = acmdir\n self._spec = spec\n self._update = update\n self._outdir = outdir\n\n self._recipient_utils = RecipientFileUtils(spec, acmdir)\n\n self._unmatched_dirs = set()\n # set of {(community, group, agent)}. Initialized from program spec, ideally there will be a directory matching each one.\n self._unmatched_recipients = set()\n\n # dictionary of {directory : recipientid}\n self._recipientid_by_directory = {}\n # dictionary of {recipientid : directory}\n self._directory_by_recipientid = {}\n\n # set of {DIRECTORY} found in communities dir, upper cased\n self._upper_case_directory_names = set()\n\n # list of [directory] without a recipientid file\n self._directories_without_recipientid = []\n\n # dictionary of {recipientid: {recipient.id file contents} }\n self._recipient_id_files_by_directory = {}\n\n # dictionary of {recipientid : Recipient}, from the Program Specification\n self._recipients_by_recipientid_from_spec = {}\n # dictionary of {directory : Recipient}, from the Program Specification\n self._recipients_by_directory_from_spec = {}\n # dictionary of {(community, group, agent) : Recipient }, from the Program Specification\n self._recipients_by_community_group_from_spec = {}\n # dictionary of {community : [Recipient,...]} from the Program Specification\n self._recipients_by_community_from_spec = {}\n\n # list of [(recipient, directory, score)], where recipient is (community, group, agent)\n self._matches = []\n # set of communities with at least one matched directory\n self._matched_communities = set()\n\n # how good does a fuzzy match need to be for use to consider it a match?\n self._threshold_value = None\n self._joiner = '-'\n # How the community and group names were *usually* joined into directory names.\n self._strategy = strategy\n if strategy == 4:\n self._fmt = _strategy4\n elif strategy == 3:\n self._fmt = _strategy3\n elif strategy == 2:\n self._fmt = lambda r: '{}{}{}'.format(r[1] if r[1] else '', '-' if r[1] else '', r[0])\n elif strategy == 1:\n self._fmt = lambda r: '{}{}{}'.format(r[0], ' ' if r[1] else '', r[1] if r[1] else '')\n else:\n self._fmt = _strategy0\n\n @property\n def _threshold(self):\n if self._threshold_value is None:\n self._threshold_value = 85\n print('Using {}% threshold for fuzzy matching.'.format(self._threshold_value))\n\n return self._threshold_value\n\n @property\n def communities_dir(self):\n return self._recipient_utils.communities_dir #self._acmdir + '/TB-Loaders/communities'\n\n @property\n def retired_communities_dir(self):\n return self._recipient_utils.retired_communities_dir #self._acmdir + '/TB-Loaders/archive/retired_communities'\n\n # Build a tuple for the recipient's name. Read as \"X in Community\", where X is group or support entity (CHW, etc)\n def _recip_tuple(self, recip: programspec.Recipient):\n return (recip.community, recip.group_name, recip.agent)\n # keys = [recip.community]\n # if recip.model.lower() == 'hhr':\n # keys.append(None)\n # elif recip.model.lower() == 'group':\n # keys.append(recip.group_name)\n # else:\n # # community worker model?\n # # If the _recipients_by_community_from_spec hasn't yet been initialized, this will give an empty list\n # # of recipients. We'll \"all(...)\" will be true because none are false.\n # community_recipients = self._recipients_by_community_from_spec.get(recip.community, [])\n # agent = None\n # # Is there a \"group_name\", and is it unique? If so, use that for agent.\n # # Otherwise try with support_entity.\n # # Otherwise concat group_name, support_entity, and model.\n # if recip.group_name and all([r == recip or recip.group_name != r.group_name for r in community_recipients]):\n # keys.append(recip.group_name)\n # elif recip.support_entity and all(\n # [r == recip or recip.support_entity != r.support_entity for r in community_recipients]):\n # keys.append(recip.support_entity)\n # else:\n # keys.append(recip.model)\n # if recip.group_name:\n # keys.append(recip.group_name)\n # if recip.support_entity:\n # keys.append(recip.support_entity)\n # return tuple(keys)\n\n def _recip_key(self, recip: programspec.Recipient):\n return self._recip_tuple(recip)\n # tup = self._recip_tuple(recip)\n # a = tup[0]\n # b = tup[1]\n # for k in tup[2:]:\n # b += '_' + k\n # return a, b\n\n # if recip.model.lower() == 'hhr':\n # return (recip.community, None)\n # elif recip.model.lower() == 'group':\n # return (recip.community, recip.group_name)\n # else:\n # # community worker model?\n # return (recip.community, recip.support_entity)\n\n def _recip_name(self, recip: programspec.Recipient):\n tup = self._recip_tuple(recip)\n name = tup[0]\n for k in tup[1:]:\n if k is not None:\n name += '/' + k\n return name\n #\n # if recip.model.lower() == 'hhr':\n # return recip.community\n # elif recip.model.lower() == 'group':\n # return '{}/{}'.format(recip.community, recip.group_name)\n # else:\n # # community worker model?\n # # If the _recipients_by_community_from_spec hasn't yet been initialized, this will give an empty list\n # # of recipients. We'll \"all(...)\" will be true because none are false.\n # community_recipients = self._recipients_by_community_from_spec.get(recip.community, [])\n # agent = None\n # # Is there a \"group_name\", and is it unique? If so, use that for agent.\n # # Otherwise try with support_entity.\n # # Otherwise concat group_name, support_entity, and model.\n # if recip.group_name and all([r==recip or recip.group_name!=r.group_name for r in community_recipients]):\n # agent = recip.group_name\n # elif recip.support_entity and all([r==recip or recip.support_entity!=r.support_entity for r in community_recipients]):\n # agent = recip.support_entity\n # else:\n # agent = recip.model\n # if recip.group_name:\n # agent += ' ' + recip.group_name\n # if recip.support_entity:\n # agent += ' ' + recip.support_entity\n #\n # return '{}/{}'.format(recip.community, agent)\n\n # Move the unused directories out of the communities directory.\n def _remove_unused_directories(self):\n path = Path(self.retired_communities_dir)\n path.mkdir(parents=True, exist_ok=True)\n for unmatched_dir in self._unmatched_dirs:\n unmatched_path = Path(self.communities_dir).joinpath(unmatched_dir)\n target_dir = unmatched_dir\n increment = 0\n target_path = path.joinpath(target_dir)\n while target_path.exists():\n increment += 1\n target_dir = '{}-{}'.format(unmatched_dir, increment)\n target_path = path.joinpath(target_dir)\n print('Moving {} to {}'.format(unmatched_dir, target_dir))\n unmatched_path.rename(target_path)\n\n def _normalize_pathname(self, pathname: str):\n # Replace whitespace with underscores, eliminate some problematic characters.\n pathname = re.sub(r'\\s', '_', pathname)\n pathname = re.sub(r'[\\\\\\'\"&*?]+', '', pathname)\n print(pathname)\n return pathname\n\n def _create_recipientid_for_recipient(self, recipient: programspec.Recipient):\n if recipient.recipient is not None:\n return\n directory = self._fmt(self._recip_key(recipient)) # (recipient.community, recipient.group_name))\n directory = self._normalize_pathname(directory)\n recipientid = self._recipient_utils.compute_recipientid(directory)\n if recipientid in self._recipients_by_recipientid_from_spec:\n errors.err(errors.recipientid_would_collide,\n {'recipientid': recipientid,\n 'community': '{}'.format(self._recip_name(recipient)),\n 'community2': '{}'.format(self._recip_name(self._recipients_by_recipientid_from_spec[recipientid]))})\n\n recipient.recipientid = recipientid\n\n def _create_missing_recipientids(self):\n # For every component, for every recipient...\n for component in self._spec.components.values():\n for recipient in component.recipients:\n if recipient.recipientid is None:\n self._create_recipientid_for_recipient(recipient)\n\n # Given a recipient, create the TB-Loaders/communities/* directory for that recipient. Include languages,\n # system (.grp), and recipient.id file.\n def _create_directory_for_recipient(self, recipient: programspec.Recipient):\n if recipient.directory_name is not None:\n return\n\n #RECIP_NAME\n # Compute the directory name and full path to the community/group directory\n directory = self._fmt(self._recip_key(recipient)) # (recipient.community, recipient.group_name))\n directory = self._normalize_pathname(directory)\n path = Path(self.communities_dir, directory)\n if path.exists() or directory.upper() in self._upper_case_directory_names:\n errors.err(errors.community_directory_exists,\n {'directory': directory, 'community': '{}'.format(self._recip_name(recipient))})\n return\n # Make the directory structure & create recipient.id for the community/group\n existing = 'existing ' if recipient.recipientid else ''\n recipientid = self._recipient_utils.create_directory_for_recipient_in_path(recipient, path)\n\n #RECIP_NAME\n print('Created directory \"{}\" for {} with {}recipientid {}'.format(directory, self._recip_name(recipient),\n existing, recipientid))\n # Update the directories of what's in the TB-Loaders/communities directory\n self._recipientid_by_directory[directory] = recipientid\n self._directory_by_recipientid[recipientid] = directory\n self._upper_case_directory_names.add(directory.upper())\n if directory in self._directories_without_recipientid:\n self._directories_without_recipientid.remove(directory)\n # Update the recipient itself.\n recipient.recipientid = recipientid\n recipient.directory_name = directory\n\n def _create_directories_for_recipients(self):\n for community, group, agent in self._unmatched_recipients:\n recipient = self._recipients_by_community_group_from_spec[(community, group, agent)]\n self._create_directory_for_recipient(recipient)\n\n # Checks whether any of the directories that we would create would cause collisions.\n def _directories_to_create_are_ok(self):\n ok = True\n mark = errors.get_mark()\n directories_to_create = {}\n directory_collisions = {}\n for community, group, agent in self._unmatched_recipients:\n recipient = self._recipients_by_community_group_from_spec[(community, group, agent)]\n if recipient.directory_name is not None: # already has a directory\n continue\n # Compute the directory name, and check for collisions with existing or to-be-created directories\n directory = self._fmt(\n self._recip_key(recipient)).upper() # (recipient.community, recipient.group_name)).upper()\n if directory in self._upper_case_directory_names:\n errors.err(errors.community_directory_exists, {'directory': directory,\n 'community': '{}'.format(\n self._recip_name(recipient))})\n ok = False\n elif directory in directories_to_create:\n if directory not in directory_collisions:\n directory_collisions[directory] = [directories_to_create[directory]]\n directory_collisions[directory].append(recipient)\n ok = False\n else:\n directories_to_create[directory] = recipient\n if len(directory_collisions) > 0:\n for directory, recipients in directory_collisions.items():\n communities = '\", \"'.join([self._recip_name(r) for r in recipients])\n errors.err(errors.community_directory_would_collide, {'directory': directory,\n 'communities': communities})\n if not ok:\n print()\n errors.print_errors(mark=mark)\n print('No directories created.')\n return ok\n\n # For recipients without a recipientid file, create the file.\n def _create_missing_recipient_id_files(self):\n for community_group, directory, _ in self._matches:\n if directory in self._directories_without_recipientid:\n recipient = self._recipients_by_community_group_from_spec[community_group]\n recipientid = recipient.recipientid\n existing = 'existing ' if recipient.recipientid else ''\n recipientid = self._recipient_utils.create_recipient_id_file(directory, recipientid)\n print('Created recipient.id in \"{}\" for {}/{} with {}recipientid {}'.format(directory,\n recipient.community,\n recipient.group_name,\n existing, recipientid))\n # Update the directories of what's in the TB-Loaders/communities directory\n self._recipientid_by_directory[directory] = recipientid\n self._directory_by_recipientid[recipientid] = directory\n self._directories_without_recipientid.remove(directory)\n # Update the recipient itself (writing a new xlsx, or not, is handled later)\n recipient.recipientid = recipientid\n recipient.directory_name = directory\n\n # For any newly matched recipents, record the newly found recipientid\n def _update_recipients_with_new_matches(self):\n for community_group, directory, _ in self._matches:\n recipient = self._recipients_by_community_group_from_spec[community_group]\n updates = {}\n if not recipient.recipientid and directory in self._recipientid_by_directory:\n recipientid = self._recipientid_by_directory[directory]\n recipient.recipientid = recipientid\n updates['recipientid'] = recipientid\n if not recipient.directory_name:\n recipient.directory_name = directory\n updates['directory'] = directory\n if len(updates) > 0:\n ups = ', '.join(['{}={}'.format(k, v) for k, v in updates.items()])\n print('Updated {}/{} with {}'.format(recipient.community, recipient.group_name, ups))\n\n # Enumerate \"community\" directories in the given TB-Loaders/communities directory.\n # Look for a recipient.id file in each one. Track what is and is not found.\n def read_existing_recipient_id_files(self):\n directories = os.listdir(self.communities_dir)\n recipient_id_files = {}\n for directory in directories:\n if not Path(self.communities_dir, directory).is_dir():\n continue\n recipient_id_file = self._recipient_utils.read_existing_recipient_id_file(directory)\n if recipient_id_file and 'recipientid' in recipient_id_file:\n recipientid = recipient_id_file['recipientid']\n if recipientid in self._directory_by_recipientid:\n # Fatal error\n other = self._directory_by_recipientid[recipientid]\n print('Duplicate recipientid \"{}\" found in directory \"{}\" and \"{}\".'\n .format(recipientid, directory, other))\n self._recipientid_by_directory[directory] = recipientid\n self._directory_by_recipientid[recipientid] = directory\n else:\n self._directories_without_recipientid.append(directory)\n self._upper_case_directory_names.add(directory.upper())\n recipient_id_files[directory] = recipient_id_file\n self._recipient_id_files_by_directory = recipient_id_files\n return recipient_id_files\n\n # Get the list of community directories. Each contains the language, greeting, and group for\n # some community, and may contain a recipient.id file.\n #\n # Builds a member dictionary of {directory name : recipient.id file}\n def get_community_dirs(self):\n recipient_id_files = self.read_existing_recipient_id_files()\n return recipient_id_files\n\n # Gets all of the recipients into a member dictionary of {(community, group_name, se) : Recipient}\n def get_recipients_from_spec(self):\n community_groups = {}\n communities = {}\n\n # For every community, a list of all the recipients\n for component in self._spec.components.values():\n for recipient in component.recipients:\n if recipient.community in communities:\n communities[recipient.community].append(recipient)\n else:\n communities[recipient.community] = [recipient]\n self._recipients_by_community_from_spec = communities\n\n for component in self._spec.components.values():\n for recipient in component.recipients:\n key = self._recip_key(recipient)\n if key in community_groups:\n print('Unexpected duplicate community/group: \"{}\" in \"{}\" and \"{}\"'\n .format(self._recip_name(recipient), recipient.component,\n community_groups[key].component))\n else:\n community_groups[key] = recipient\n # If there is a recipient id, make sure it isn't a duplicate.\n if recipient.recipientid:\n if recipient.recipientid in self._recipients_by_recipientid_from_spec:\n # fatal error\n other = self._recipients_by_recipientid_from_spec[recipient.recipientid]\n recip_name = self._recip_name(recipient)\n other_name = self._recip_name(other)\n print('Duplicate recipientid \"{}\" assigned to \"{}\" and \"{}\".'\n .format(recipient.recipientid, recip_name, other_name))\n self._recipients_by_recipientid_from_spec[recipient.recipientid] = recipient\n # If there is a directory, make sure it isn't a duplicate.\n if recipient.directory_name:\n if recipient.directory_name in self._recipients_by_directory_from_spec:\n # fatal error\n other = self._recipients_by_directory_from_spec[recipient.directory_name]\n recip_name = self._recip_name(recipient)\n other_name = self._recip_name(other)\n print('Duplicate directory name \"{}\" assigned to \"{}\" and \"{}\".'\n .format(recipient.directory_name, recip_name, other_name))\n self._recipients_by_directory_from_spec[recipient.directory_name] = recipient\n self._recipients_by_community_group_from_spec = community_groups\n return community_groups\n\n##\n## group -> (group, agent)\n##\n # For each community, a list of unmatched groups. Built from unmatched_recipients.\n # { community : [ (group, agent), ...]}\n def unmatched_ga_s_by_community(self):\n unmatched_ga_s = {}\n # List of unique community names, with a list of groups for each\n for community, group, agent in self._unmatched_recipients:\n if community is None:\n print(\"well, that's unexpected\")\n if community in unmatched_ga_s:\n unmatched_ga_s[community].append((group, agent))\n else:\n unmatched_ga_s[community] = [(group, agent)]\n return unmatched_ga_s\n\n # Given a recipient and a directory, and optional score, record the match.\n # Remove the recipient and directory from unmatched lists.\n def remove_matched(self, community_group, directory, score=100):\n # TODO: if there is already a recipient id, be sure it is in the Recipient\n # TODO: be sure the directory name is in the Recipient\n self._unmatched_dirs.remove(directory)\n self._unmatched_recipients.remove(community_group)\n self._matches.append((community_group, directory, score))\n self._matched_communities.add(community_group[0])\n\n # Print the matches that were found.\n def print_matched(self):\n print('Matched {} community/groups --> directories:'.format(len(self._matches)))\n if len(self._matches) == 0:\n print(' No matches.')\n return\n if len([r for r, d, s in self._matches if s != 'recipientid']) == 0:\n print(' All match by recipientid.')\n return\n print_data = [(format_cga(r), d, s) for r, d, s in self._matches]\n rw = max(len(r) for r, d, s in print_data)\n dw = max(len(d) for r, d, s in print_data)\n for r, d, s in sorted(print_data, key=lambda x: x[0]):\n match_label = '{}{}'.format(s, '%' if s != 'recipientid' else '')\n print(' {:{rw}} --> {:{dw}} ({} match)'.format(r, d, match_label, rw=rw, dw=dw))\n\n # Prints the unmatched community/groups, with the groups that DO match, plus the model, if a group is None.\n def print_unmatched(self):\n unmatched_groups = self.unmatched_ga_s_by_community()\n if len(unmatched_groups) == 0:\n print('No unmatched communities.')\n return\n\n print('Unmatched community details:')\n # For each distinct community...\n for community, groups in sorted(unmatched_groups.items(), key=lambda c: c[0].upper()):\n all_groups = [r[1] for r in self._recipients_by_community_group_from_spec.keys() if\n r[0] == community and r[1] is not None]\n unmatched = sorted(groups, key=lambda g: g if g is not None else ' ')\n if len(all_groups) == 0:\n group_list = 'no groups'\n else:\n group_list = '{} groups: {}'.format(len(all_groups), ', '.join(all_groups))\n print(' {}, {}'.format(community, group_list))\n for u in unmatched:\n if u is None:\n recipient = self._recipients_by_community_group_from_spec[(community, u)]\n model = ' {}?'.format(recipient.properties['model'])\n else:\n model = ''\n print(' {} {}'.format(u, model))\n\n # Given a community, a list of directories containing that community name, the (group,agent)s\n # of the community, and the fuzzy match ratios, perform fuzzy matching on the\n # directories and community/group names.\n #\n # Return a dictionary of { (group,agent): {dir: fuzzy_match_ratio, ...}, ...}\n def get_fuzzy_community_match_ratios(self, community, ga_s, dirs):\n ratios = {}\n # For each group in the community...\n for ga in ga_s:\n test = self._fmt((community, ga[0], ga[1])).strip().upper()\n # test = '{} {}'.format(community, group_name).strip().upper()\n ratios[ga] = {}\n # ...make a fuzzy match test with every directory that matched the community\n for d in dirs:\n ratios[ga][d] = fuzz.ratio(test, d.upper())\n return ratios\n\n # Given a community, a list of directories containing that community name, the groups\n # of the community, and the fuzzy match ratios, print them out in a nice table.\n @staticmethod\n def print_fuzzy_community_match_ratios(ratios, community, ga_s, dirs, matches):\n '''\n :param ratios: { (group, agent) : {candidate_directory : match_score} }\n :param community: str\n :param ga_s: [ (group, agent), ...]\n :param potential_dirs: [ potential_dir, ...]\n :return: (num_matches, [((group, agent), directory), ...])\n '''\n def _name(ga):\n name = ga[0] if ga[0] else ''\n name += (('-' if ga[0] else '') + ga[1]) if ga[1] else ''\n name = '-' if not name else name\n return name\n\n dir_name_width = 20\n for d in dirs:\n dir_name_width = max(dir_name_width, len(d))\n # Print the results, header line first\n print('Community \\'{}\\'\\ndir{:>{width}s}'.format(community, 'group ->', width=dir_name_width - 4), end=' | ')\n for ga in ga_s:\n group_label = _name(ga)\n width = max(len(group_label), 4)\n print('{:^{width}}'.format(group_label, width=width), end=' | ')\n print()\n for d in dirs:\n print('{:>{width}s}'.format(d, width=dir_name_width), end=' | ')\n for ga in ga_s:\n group_name = _name(ga)\n width = max(len(group_name), 4)\n score = '{}{}'.format(ratios[ga][d], '*' if (ga, d) in matches else ' ')\n print('{:^{width}}'.format(score, width=width), end=' | ')\n print()\n print()\n\n # Given a set of fuzzy matches for a community, its groups, and matching dirs,\n # remove any matches that are \"good enough\"\n def make_fuzzy_community_matches(self, ratios, community, ga_s, potential_dirs):\n '''\n :param ratios: { (group, agent) : {candidate_directory : match_score} }\n :param community: str\n :param ga_s: [ (group, agent), ...]\n :param potential_dirs: [ potential_dir, ...]\n :return: (num_matches, [((group, agent), directory), ...])\n '''\n matches = []\n n_removed = 0\n for ga in ga_s:\n scores = ratios[ga]\n # Find the best scoring directory for this group\n best_score, best_dir = -1, None\n for potential_dir in potential_dirs:\n if scores[potential_dir] > best_score:\n best_score, best_dir = scores[potential_dir], potential_dir\n # Good enough to consider a match?\n if best_score > self._threshold:\n # See if this is the best scoring group for the directory\n best = True\n for dirs_ga in ga_s:\n if dirs_ga != ga and ratios[dirs_ga][best_dir] >= best_score:\n best = False\n break\n if best:\n matches.append((ga, best_dir))\n recip = (community, ga[0], ga[1])\n self.remove_matched(recip, best_dir, best_score)\n n_removed = n_removed + 1\n\n if n_removed > 0:\n print()\n return n_removed, matches\n\n # Find the directory names containing community names as a substring. Do fuzzy matching\n # of community / group to the directory name, and match the ones that are \"good enough\".\n def make_community_matches(self):\n n_removed = 0\n # { community : [ (group, agent), ...]}\n unmatched_ga_s = self.unmatched_ga_s_by_community()\n\n # For each distinct community... (sorted so it is same run-to-run, for easier debugging)\n for community, ga_s in sorted(unmatched_ga_s.items(), key=lambda c: c):\n dirs = []\n # find the dirs containing that community name.\n for unmatched_dir in self._unmatched_dirs:\n if community.upper() in unmatched_dir.upper():\n dirs.append(unmatched_dir)\n\n if len(dirs) > 0:\n # { (group, agent) : {candidate_directory : match_score} }\n ratios = self.get_fuzzy_community_match_ratios(community, ga_s, dirs)\n removed, matches = self.make_fuzzy_community_matches(ratios, community, ga_s, dirs)\n n_removed = n_removed + removed\n self.print_fuzzy_community_match_ratios(ratios, community, ga_s, dirs, matches)\n\n return n_removed\n\n # Given a list of unmatched directory names and recipients, finds (and removes) the\n # easy matches, which are where the names match exactly.\n def make_exact_matches(self):\n # Compare what may be a directory name against the list of unmatched directories.\n def examine(potential_dir):\n if potential_dir in self._unmatched_dirs:\n self.remove_matched(recip, potential_dir)\n return True\n potential_dir = potential_dir.upper() # lots of combinations of casing, but only do the most trivial\n if potential_dir in self._unmatched_dirs:\n self.remove_matched(recip, potential_dir)\n return True\n\n n_removed = 0\n # uppercase_dirs = [x.upper() for x in self._unmatched_dirs]\n for recip in copy.copy(self._unmatched_recipients):\n # Does this recipient already know its directory?\n recipient = self._recipients_by_community_group_from_spec[recip]\n if recipient.directory_name and recipient.directory_name in self._unmatched_dirs:\n self.remove_matched(recip, recipient.directory_name)\n n_removed = n_removed + 1\n continue\n\n (community, group, agent) = recip\n if group:\n test = '{}{}{}'.format(community, self._joiner, group)\n if examine(test):\n n_removed = n_removed + 1\n continue\n test = '{}{}{}'.format(group, self._joiner, community)\n if examine(test):\n n_removed = n_removed + 1\n continue\n else:\n # Is the bare community name a match?\n if examine(community):\n n_removed = n_removed + 1\n continue\n return n_removed\n\n # If a recipient has a recipientid, match that up with any directory with the same recipientid\n def _match_existing_recipientids(self):\n for recipientid, recipient in self._recipients_by_recipientid_from_spec.items():\n directory = self._directory_by_recipientid.get(recipientid)\n if directory:\n self.remove_matched(self._recip_key(recipient), directory, 'recipientid')\n\n # Make sure that if a recipient thinks it knows its directory, the directory doesn't contradict.\n def _check_recipientid_mismatches(self):\n for recipientid, recipient in self._recipients_by_recipientid_from_spec.items():\n if recipient.directory_name and recipientid in self._directory_by_recipientid:\n if recipient.directory_name != self._directory_by_recipientid[recipientid]:\n # Fatal error\n recip_name = self._recip_name(recipient)\n print('Recipient \"{}\" claims directory \"{}\", but \"{}\" claims recipient.'\n .format(recip_name, recipient.directory_name,\n self._directory_by_recipientid[recipientid]))\n\n def reconcile(self):\n # We can't reconcile the recipients if the directory doesn't even exist.\n if not self.communities_dir.exists() or not self.communities_dir.is_dir():\n errors.err(errors.missing_directory, {'directory': self.communities_dir})\n return\n\n # list of directory names, they all start off as unmatched.\n self._unmatched_dirs = set(self.get_community_dirs().keys())\n # list of (community, group_name) tuples\n self._unmatched_recipients = set(self.get_recipients_from_spec().keys())\n\n self._check_recipientid_mismatches()\n self._match_existing_recipientids()\n\n n_matched = self.make_exact_matches()\n n_matched = n_matched + self.make_community_matches()\n\n fdm = FuzzyDirectoryMatcher(self)\n n_matched = n_matched + fdm.make_matches()\n\n self.print_matched()\n print()\n fdm.print_unmatched()\n print()\n self.print_unmatched()\n\n print()\n print('{:4} matches\\n{:4} unmatched community/groups\\n'\n '{:4} unmatched directories\\n{:4} directories without recipientid file'\n .format(len(self._matches), len(self._unmatched_recipients), len(self._unmatched_dirs),\n len(self._directories_without_recipientid)))\n\n if DIRECTORIES in self._update:\n if self._directories_to_create_are_ok():\n self._create_directories_for_recipients()\n self._create_missing_recipient_id_files()\n if XDIRECTORIES in self._update:\n self._remove_unused_directories()\n if XLSX in self._update:\n self._update_recipients_with_new_matches()\n if RECIPIENTS in self._update:\n self._create_missing_recipientids()\n\n return\n\n\ndef reconcile(acmdir, spec: programspec, strategy: int, update: set, outdir=None):\n start = time.time()\n reconciler = Reconciler(acmdir, spec, strategy, update, outdir)\n result = reconciler.reconcile()\n end = time.time()\n print('Reconciled in {:.2g} seconds'.format(end - start))\n return result\n","sub_path":"psutil/reconcilliation.py","file_name":"reconcilliation.py","file_ext":"py","file_size_in_byte":40210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"362142429","text":"from dagster_ge.factory import ge_data_context, ge_validation_solid_factory\nfrom pandas import read_csv\n\nfrom dagster import (\n DagsterInstance,\n InputDefinition,\n ModeDefinition,\n Output,\n execute_pipeline,\n pipeline,\n reconstructable,\n solid,\n)\nfrom dagster.utils import file_relative_path\n\n\n@solid\ndef yielder(_):\n return read_csv(\"./basic.csv\")\n\n\n@solid(input_defs=[InputDefinition(name='res')])\ndef reyielder(_context, res):\n yield Output((res['statistics'], res['results']))\n\n\n@pipeline(mode_defs=[ModeDefinition('basic', resource_defs={'ge_data_context': ge_data_context})],)\ndef hello_world_pipeline():\n return reyielder(ge_validation_solid_factory(\"getest\", \"basic.warning\")(yielder()))\n\n\ndef test_yielded_results_config():\n run_config = {\n 'resources': {\n 'ge_data_context': {\n 'config': {'ge_root_dir': file_relative_path(__file__, \"./great_expectations\")}\n }\n }\n }\n result = execute_pipeline(\n reconstructable(hello_world_pipeline),\n run_config=run_config,\n mode='basic',\n instance=DagsterInstance.local_temp(),\n )\n assert result.result_for_solid(\"reyielder\").output_value()[0][\"success_percent\"] == 100\n expectations = result.result_for_solid(\"ge_validation_solid\").expectation_results_during_compute\n assert len(expectations) == 1\n mainexpect = expectations[0]\n assert mainexpect.success\n metadata = mainexpect.metadata_entries[0].entry_data.data\n assert metadata['overall'] == {\n 'evaluated_expectations': 11,\n 'success_percent': 100.0,\n 'successful_expectations': 11,\n 'unsuccessful_expectations': 0,\n }\n","sub_path":"python_modules/libraries/dagster-ge/dagster_ge_tests/test_basic_integ.py","file_name":"test_basic_integ.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"345478177","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.9-x86_64/egg/easyexplore/data_import_export.py\n# Compiled at: 2020-05-10 09:08:45\n# Size of source mod 2**32: 25694 bytes\nimport csv, json, os, pandas as pd, pickle, sqlite3, zipfile\nfrom sqlalchemy import create_engine\nfrom typing import List\n\nclass FileUtilsException(Exception):\n __doc__ = '\\n\\n Class for handling exceptions for class FileUtils\\n\\n '\n\n\nclass FileUtils:\n __doc__ = '\\n\\n Class for handling files\\n\\n '\n\n def __init__(self, file_path: str, create_dir: bool=True):\n \"\"\"\n :param file_path: String containing the file path\n :param create_dir: Boolean indicating whether to create directories if they are not existed\n \"\"\"\n if len(file_path) == 0:\n raise FileUtilsException('No file path found')\n else:\n self.full_path = file_path.replace('\\\\', '/')\n self.file_name = self.full_path.split('/')[(-1)]\n self.file_path = self.full_path.replace(self.file_name, '')\n _file_type = self.file_name.split('.')\n if len(_file_type) > 0:\n self.file_type = _file_type[(len(_file_type) - 1)]\n else:\n self.file_type = None\n self.create_dir = create_dir\n if self.create_dir:\n if self.full_path.find('/') >= 0:\n self.make_dir()\n\n def make_dir(self, other_dir: str=None):\n \"\"\"\n\n Create directory if it not exists\n\n :param other_dir: String containing the name of the additional directory to create\n \"\"\"\n if not os.path.exists(self.file_path):\n os.mkdir(path=(self.file_path))\n if other_dir is not None:\n if len(other_dir) > 0:\n os.mkdir(path=other_dir)\n\n def kill(self):\n \"\"\"\n\n Kill a file if it exists\n\n \"\"\"\n if os.path.isfile(self.full_path):\n os.remove(self.full_path)\n else:\n raise FileUtilsException('File ({}) not exists in directory ({}) !'.format(self.file_name, self.full_path))\n\n\nclass DataImporter(FileUtils):\n __doc__ = '\\n\\n Class for import data from external file types\\n\\n '\n\n def __init__(self, file_path, as_data_frame=True, create_dir=True, sep=',', **kwargs):\n \"\"\"\n :param str file_path: String containing the file path\n :param as_data_frame: bool: Import data set as pandas data frame or not\n :param bool create_dir: Boolean indicating whether to create directories if they are not existed\n :param str sep: File separator\n :param dict kwargs: Dictionary containing additional key word arguments\n \"\"\"\n super().__init__(file_path=file_path, create_dir=create_dir)\n self.as_df = as_data_frame\n self.sep = sep\n self.user_kwargs = kwargs\n self.kwargs = None\n self._config_args()\n\n def _config_args(self):\n \"\"\"\n\n Set configuration setting for the data import as Pandas DataFrame\n\n \"\"\"\n self.kwargs = {'filepath':self.full_path, \n 'sep':self.sep, \n 'decimal':'.', \n 'header':0, \n 'encoding':'utf-8', \n 'skip_blank_lines':True, \n 'na_values':None, \n 'keep_default_na':True, \n 'parse_dates':True, \n 'quotechar':'|', \n 'quoting':csv.QUOTE_NONE, \n 'doublequote':False, \n 'sheet_name':0, \n 'names':None, \n 'index_col':None, \n 'usecols':None, \n 'squeeze':False, \n 'prefix':None, \n 'mangle_dup_cols':True, \n 'dtype':None, \n 'engine':None, \n 'converters':None, \n 'true_values':None, \n 'false_values':None, \n 'skipinitialspace':False, \n 'skiprows':None, \n 'skipfooter':0, \n 'nrows':None, \n 'na_filter':True, \n 'verbose':False, \n 'infer_datetime_format':True, \n 'keep_date_col':False, \n 'date_parser':None, \n 'dayfirst':False, \n 'iterator':False, \n 'chunksize':None, \n 'compression':'infer', \n 'thousands':None, \n 'float_precision':None, \n 'lineterminator':None, \n 'escapechar':None, \n 'comment':None, \n 'dialect':None, \n 'error_bad_lines':False, \n 'warn_bad_lines':True, \n 'low_memory':True, \n 'memory_map':False}\n if self.user_kwargs is not None:\n for kwarg, value in self.user_kwargs.items():\n if kwarg in self.kwargs.keys():\n self.kwargs[kwarg] = value\n else:\n print('Key word argument ({}) not supported !'.format(kwarg))\n\n def _excel_as_df(self) -> pd.DataFrame:\n \"\"\"\n\n Import excel file as Pandas DataFrame\n\n :return: Pandas DataFrame containing the content of the html file\n \"\"\"\n return pd.read_excel(io=(self.kwargs.get('filepath')), sheet_name=(self.kwargs.get('sheet_name')),\n header=(self.kwargs.get('header')),\n names=(self.kwargs.get('names')),\n index_col=(self.kwargs.get('index_col')),\n usecols=(self.kwargs.get('usecols')),\n squeeze=(self.kwargs.get('squeeze')),\n prefix=(self.kwargs.get('prefix')),\n dtype=(self.kwargs.get('dtype')),\n engine=(self.kwargs.get('engine')),\n converters=(self.kwargs.get('converters')),\n true_values=(self.kwargs.get('true_values')),\n false_values=(self.kwargs.get('false_values')),\n skipinitialspace=(self.kwargs.get('skipinitialspace')),\n skiprows=(self.kwargs.get('skiprows')),\n skipfooter=(self.kwargs.get('skipfooter')),\n nrows=(self.kwargs.get('nrows')),\n na_values=(self.kwargs.get('na_values')),\n keep_default_na=(self.kwargs.get('keep_default_na')),\n na_filter=(self.kwargs.get('na_filter')),\n verbose=(self.kwargs.get('verbose')),\n skip_blank_lines=(self.kwargs.get('skip_blank_lines')),\n parse_dates=(self.kwargs.get('parse_dates')),\n infer_datetime_format=(self.kwargs.get('infer_datetime_format')),\n keep_date_col=(self.kwargs.get('keep_date_col')),\n date_parser=(self.kwargs.get('date_parser')),\n dayfirst=(self.kwargs.get('dayfirst')),\n iterator=(self.kwargs.get('iterator')),\n thousands=(self.kwargs.get('thousands')),\n decimal=(self.kwargs.get('decimal')),\n float_precision=(self.kwargs.get('float_precision')),\n lineterminator=(self.kwargs.get('lineterminator')),\n quotechar=(self.kwargs.get('quotechar')),\n quoting=(self.kwargs.get('quoting')),\n doublequote=(self.kwargs.get('doublequote')),\n escapechar=(self.kwargs.get('escapechar')),\n comment=(self.kwargs.get('comment')),\n encoding=(self.kwargs.get('encoding')),\n error_bad_lines=(self.kwargs.get('error_bad_lines')),\n warn_bad_lines=(self.kwargs.get('warn_bad_lines')),\n low_memory=(self.kwargs.get('low_memory')))\n\n def _file(self):\n \"\"\"\n\n Import file\n\n :return: Object containing the file content\n \"\"\"\n with open(file=(self.file_path), mode=('r' if self.kwargs.get('mode') is None else self.kwargs.get('mode')),\n encoding=('utf-8' if self.kwargs.get('encoding') is None else self.kwargs.get('encoding'))) as (file):\n return file.read()\n\n def _html(self):\n \"\"\"\n\n Import parsed text content from html file\n\n :return:\n \"\"\"\n pass\n\n def _html_as_df(self) -> List[pd.DataFrame]:\n \"\"\"\n\n Import html file as Pandas DataFrame\n\n :return: List[pd.DataFrame]: Contents of the html file as pandas data frames\n \"\"\"\n return pd.read_html(io=None, match=None,\n flavor=(self.kwargs.get('flavor')),\n header=(self.kwargs.get('header')),\n index_col=(self.kwargs.get('index_col')),\n skiprows=(self.kwargs.get('skiprows')),\n attrs=(self.kwargs.get('attrs')),\n parse_dates=(self.kwargs.get('parse_dates')),\n thousands=(self.kwargs.get('thousands')),\n encoding=(self.kwargs.get('encoding')),\n decimal=(self.kwargs.get('decimal')),\n converters=(self.kwargs.get('converters')),\n na_values=(self.kwargs.get('na_values')),\n keep_default_na=(self.kwargs.get('keep_default_na')),\n displayed_only=(self.kwargs.get('displayed_only')))\n\n def _json(self) -> json.load:\n \"\"\"\n\n Import json file\n\n :return: json.load: Object containing the content of the json file\n \"\"\"\n with open(file=(self.file_path), mode=('r' if self.kwargs.get('mode') is None else self.kwargs.get('mode')),\n encoding=('utf-8' if self.kwargs.get('encoding') is None else self.kwargs.get('encoding'))) as (json_file):\n return json.load(fp=json_file, cls=(self.kwargs.get('cls')),\n object_hook=(self.kwargs.get('object_hook')),\n parse_float=(self.kwargs.get('parse_float')),\n parse_int=(self.kwargs.get('parse_int')),\n parse_constant=(self.kwargs.get('parse_constant')),\n object_pairs_hook=(self.kwargs.get('object_pairs_hook')))\n\n def _json_as_df(self) -> pd.DataFrame:\n \"\"\"\n\n Import json file as Pandas DataFrame\n\n :return: Pandas DataFrame containing the content of the json file\n \"\"\"\n return pd.read_json(path_or_buf=(self.kwargs.get('filepath')), orient=None,\n typ='frame',\n dtype=True,\n convert_axes=True,\n convert_dates=True,\n keep_default_dates=True,\n numpy=False,\n precise_float=False,\n date_unit=None,\n encoding=None,\n lines=False,\n chunksize=None,\n compression=(self.kwargs.get('compression')))\n\n def _pickle(self) -> pickle.load:\n \"\"\"\n\n Import pickle file\n\n :return: pickle.load: Object in pickle file\n \"\"\"\n with open(self.file_path, 'rb') as (file):\n return pickle.load(file=file)\n\n def _pickle_as_df(self) -> pd.DataFrame:\n \"\"\"\n\n Import pickle file as Pandas DataFrame\n\n :return: Pandas DataFrame containing the content of the pickle file\n \"\"\"\n return pd.read_pickle(path=(self.full_path), compression=(self.kwargs.get('compression')))\n\n def _text_as_df(self) -> pd.DataFrame:\n \"\"\"\n\n Import text file (csv, txt) as Pandas DataFrame\n\n :return: Pandas DataFrame containing the content of the text file\n \"\"\"\n return pd.read_csv(filepath_or_buffer=(self.kwargs.get('filepath')), sep=(self.kwargs.get('sep')),\n header=(self.kwargs.get('header')),\n names=(self.kwargs.get('names')),\n index_col=(self.kwargs.get('index_col')),\n usecols=(self.kwargs.get('usecols')),\n squeeze=(self.kwargs.get('squeeze')),\n prefix=(self.kwargs.get('prefix')),\n mangle_dupe_cols=(self.kwargs.get('mangle_dup_cols')),\n dtype=(self.kwargs.get('dtype')),\n engine=(self.kwargs.get('engine')),\n converters=(self.kwargs.get('converters')),\n true_values=(self.kwargs.get('true_values')),\n false_values=(self.kwargs.get('false_values')),\n skipinitialspace=(self.kwargs.get('skipinitialspace')),\n skiprows=(self.kwargs.get('skiprows')),\n skipfooter=(self.kwargs.get('skipfooter')),\n nrows=(self.kwargs.get('nrows')),\n na_values=(self.kwargs.get('na_values')),\n keep_default_na=(self.kwargs.get('keep_default_na')),\n na_filter=(self.kwargs.get('na_filter')),\n verbose=(self.kwargs.get('verbose')),\n skip_blank_lines=(self.kwargs.get('skip_blank_lines')),\n parse_dates=(self.kwargs.get('parse_dates')),\n infer_datetime_format=(self.kwargs.get('infer_datetime_format')),\n keep_date_col=(self.kwargs.get('keep_date_col')),\n date_parser=(self.kwargs.get('date_parser')),\n dayfirst=(self.kwargs.get('dayfirst')),\n iterator=(self.kwargs.get('iterator')),\n chunksize=(self.kwargs.get('chunksize')),\n compression=(self.kwargs.get('compression')),\n thousands=(self.kwargs.get('thousands')),\n decimal=(self.kwargs.get('decimal')),\n float_precision=(self.kwargs.get('float_precision')),\n lineterminator=(self.kwargs.get('lineterminator')),\n quotechar=(self.kwargs.get('quotechar')),\n quoting=(self.kwargs.get('quoting')),\n doublequote=(self.kwargs.get('doublequote')),\n escapechar=(self.kwargs.get('escapechar')),\n comment=(self.kwargs.get('comment')),\n encoding=(self.kwargs.get('encoding')),\n error_bad_lines=(self.kwargs.get('error_bad_lines')),\n warn_bad_lines=(self.kwargs.get('warn_bad_lines')),\n low_memory=(self.kwargs.get('low_memory')),\n memory_map=(self.kwargs.get('memory_map')))\n\n def file(self):\n \"\"\"\n\n Import data from file\n\n :return: File content\n \"\"\"\n if self.file_type in ('csv', 'txt'):\n if self.as_df:\n return self._text_as_df()\n else:\n return self._file()\n else:\n if self.file_type in ('p', 'pkl', 'pickle'):\n if self.as_df:\n return self._pickle_as_df()\n else:\n return self._pickle()\n else:\n if self.file_type == 'json':\n if self.as_df:\n return self._json_as_df()\n else:\n return self._json()\n if self.file_type == 'html':\n if self.as_df:\n return self._html_as_df()\n else:\n return self._file()\n if self.file_type in ('xls', 'xlsx'):\n if self.as_df:\n return self._excel_as_df()\n else:\n return self._file()\n raise FileUtilsException('File type ({}) not supported'.format(self.file_type))\n\n def zip(self, files: List[str], as_df: bool=False) -> dict:\n \"\"\"\n :param files: List[str]: File to look for in zip file\n :param as_df: bool: Store detected files in dictionary as pandas data frames or not\n :return: dict: Detected file names and file objects\n \"\"\"\n _zip_content = {self.file_name: {}}\n _zip = zipfile.ZipFile(file=(self.full_path), mode=('r' if self.kwargs.get('mode') is None else self.kwargs.get('mode')),\n compression=(zipfile.ZIP_STORED if self.kwargs.get('compression') is None else self.kwargs.get('compression')),\n allowZip64=(True if self.kwargs.get('allowZip64') is None else self.kwargs.get('allowZip64')))\n for file in files:\n try:\n with _zip.open(name=file, mode=('r' if self.kwargs.get('mode') is None else self.kwargs.get('mode')),\n pwd=(self.kwargs.get('pwd')),\n force_zip64=(False if self.kwargs.get('force_zip64') is None else self.kwargs.get('force_zip64'))) as (uncompressed_file):\n _zip_content[self.file_name].update({file: uncompressed_file.read()})\n except Exception as e:\n print('Could not open file ({}) because of the following error\\n{}'.format(file, e))\n\n return _zip_content\n\n\nclass DataExporter(FileUtils):\n __doc__ = '\\n\\n Class for export data to local files\\n\\n '\n\n def __init__(self, obj, file_path, create_dir=True, overwrite=False, **kwargs):\n \"\"\"\n :param obj: Object to export\n :param file_path: String containing the file path\n :param create_dir: Boolean indicating whether to create directories if they are not existed\n :param overwrite: Boolean indicating whether to overwrite an existing file or not\n :param kwargs: Dictionary containing additional key word arguments\n \"\"\"\n super().__init__(file_path=file_path, create_dir=create_dir)\n self.obj = obj\n if self.create_dir:\n self.make_dir()\n if not overwrite:\n self._avoid_overwriting()\n self.user_kwargs = kwargs\n\n def _avoid_overwriting(self):\n \"\"\"\n\n Generate file name extension to avoid overwriting of existing files\n\n \"\"\"\n _i = 1\n while os.path.isfile(self.full_path):\n _i += 1\n if _i <= 2:\n self.full_path = self.full_path.replace('.{}'.format(self.file_type), '({}).{}'.format(_i, self.file_type))\n else:\n self.full_path = self.full_path.replace('({}).{}'.format(_i - 1, self.file_type), '({}).{}'.format(_i, self.file_type))\n\n def _html(self):\n \"\"\"\n\n Export data as json file\n\n \"\"\"\n with open((self.full_path), 'w', encoding='utf-8') as (file):\n file.write(self.obj)\n\n def _gitignore(self):\n \"\"\"\n\n Export data as .gitignore file\n\n \"\"\"\n with open((self.file_path), 'w', encoding='utf-8') as (file):\n file.write(self.obj)\n\n def _json(self):\n \"\"\"\n\n Export data as json file\n\n \"\"\"\n with open((self.full_path), 'w', encoding='utf-8') as (file):\n json.dump((self.obj), file, ensure_ascii=False)\n\n def _pickle(self):\n \"\"\"\n\n Export data as pickle file\n\n \"\"\"\n with open(self.full_path, 'wb') as (_output):\n pickle.dump(self.obj, _output, pickle.HIGHEST_PROTOCOL)\n\n def _py(self):\n \"\"\"\n\n Export data as python file\n\n \"\"\"\n with open(self.full_path, 'w') as (file):\n file.write(self.obj)\n\n def _text(self):\n \"\"\"\n\n Export data as text (txt, csv) file\n\n \"\"\"\n _txt = open(self.full_path, 'wb')\n _txt.write(self.obj)\n _txt.close()\n\n def file(self):\n \"\"\"\n\n Export data as file object\n\n \"\"\"\n if self.file_type in ('csv', 'txt'):\n return self._text()\n else:\n if self.file_type in ('', 'p', 'pkl', 'pickle'):\n return self._pickle()\n else:\n if self.file_type == 'json':\n return self._json()\n if self.file_type == 'py':\n return self._py()\n if self.file_type == 'gitignore':\n return self._gitignore()\n return self._text()\n\n\nclass DBUtilsException(Exception):\n __doc__ = '\\n\\n Class for handling exceptions for class DBUtils\\n\\n '\n\n\nclass DBUtils:\n __doc__ = '\\n\\n Class for handling local SQLite3 database\\n\\n '\n\n def __init__(self, df: pd.DataFrame=None, table_name: str=None, database: str='sqlite', env_var: List[str]=None, con=None, file_path: str=None):\n \"\"\"\n :param df: Pandas DataFrame containing the data set\n :param table_name: String containing the table name\n :param con: SQLite3 connection\n :param database: String containing the name of the database\n -> sqlite: SQLite3 (local db)\n -> postgresql: Postgres db\n :param file_path: String containing the file path of the database\n \"\"\"\n self.df = df\n self.table_name = table_name\n self.con = con\n self.database = database\n self.env_var = env_var\n self.file_path = file_path\n\n def _get_creds(self) -> str:\n \"\"\"\n\n Get database credentials from environment variables\n\n :return: String containing the database credentials\n \"\"\"\n if self.env_var is None:\n return '{}://{}:{}@{}:{}/{}'.format(self.database, os.environ['DB_USER'], os.environ['DB_PWD'], os.environ['DB_HOST'], os.environ['DB_PORT'], os.environ['DB_NAME'])\n else:\n if len(self.env_var) == 1:\n return '{}'.format(os.environ[self.env_var[0]])\n if len(self.env_var) == 5:\n return '{}://{}:{}@{}:{}/{}'.format(self.database, os.environ[self.env_var[0]], os.environ[self.env_var[1]], os.environ[self.env_var[2]], os.environ[self.env_var[3]], os.environ[self.env_var[4]])\n raise DBUtilsException('Environment variables ({}) not supported'.format(self.env_var))\n\n def create_connection(self):\n \"\"\"\n\n Create connection to SQLite3 database\n\n :return: Object containing the database connection\n \"\"\"\n try:\n try:\n if self.database == 'sqlite':\n self.con = sqlite3.connect(self.file_path)\n else:\n self.con = create_engine(self._get_creds())\n except sqlite3.Error as e:\n self.con = None\n print(e)\n\n finally:\n return\n\n return self.con\n\n def get_table(self, query: str='SELECT * from ') -> pd.DataFrame:\n \"\"\"\n\n Fetch table from SQLite3 database\n\n :param query: String containing the SQL query for fetching data from table\n :return: Pandas DataFrame containing the table data\n \"\"\"\n return pd.read_sql_query(\"{}'{}'\".format(query, self.table_name), self.con)\n\n def update_table(self):\n \"\"\"\n\n Update table\n\n \"\"\"\n self.df.to_sql(name=(self.table_name), con=(self.con), if_exists='replace')\n\n def create_table(self):\n \"\"\"\n\n Create table\n\n \"\"\"\n self.df.to_sql(name=(self.table_name), con=(self.con), if_exists='fail')\n\n def drop_table(self):\n \"\"\"\n\n Drop existing table\n\n \"\"\"\n cursor = self.con.cursor()\n cursor.execute(\"DROP TABLE '{}'\".format(self.table_name))\n\n def close_connection(self):\n \"\"\"\n\n Close connection to SQLite3 database\n\n \"\"\"\n self.con.close()","sub_path":"pycfiles/easyexplore-0.1.1-py3.6/data_import_export.cpython-36.py","file_name":"data_import_export.cpython-36.py","file_ext":"py","file_size_in_byte":22186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"59596055","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nSvar på teorispørsmål fra oppgave 4.\n1. Dette er ikke lovlig kode. Man kan ikke utføre aritmetikk på to objekter av forskjellig type (int og string)\n\n2. Man vil støte på ett probleme ved kjøring av denne koden. Utførelsen av 'b + \"Hei!\"' vil resultere i en \nTypeError exception, og programmet vil avslutte. \n\"\"\"\n\na = input(\"Tast inn et heltall! \")\nb = int(a)\nif b < 10:\n print (b + \"Hei!\")","sub_path":"oblig2/kodeforstaaelse.py","file_name":"kodeforstaaelse.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"312024452","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('School', '0019_taskflow_idjoin'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='topiccontent',\n name='idReceiver',\n ),\n migrations.AddField(\n model_name='topic',\n name='response',\n field=models.BooleanField(default=True),\n ),\n migrations.AlterField(\n model_name='groupuser',\n name='idGroup',\n field=models.ForeignKey(related_name='fkGroupUseridGroup2Group', to='School.Group'),\n ),\n migrations.AlterField(\n model_name='topic',\n name='visible',\n field=models.BooleanField(default=True),\n ),\n ]\n","sub_path":"src/School/migrations/0020_auto_20160526_1805.py","file_name":"0020_auto_20160526_1805.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"622946478","text":"import unittest\nimport vega\nfrom vega.core.pipeline.pipe_step import PipeStep\nfrom vega.core.common.class_factory import ClassFactory, ClassType\nfrom vega.core.common.user_config import Config\n\n\n@ClassFactory.register(ClassType.PIPE_STEP)\nclass FakePipeStep(PipeStep, unittest.TestCase):\n\n def __init__(self):\n PipeStep.__init__(self)\n unittest.TestCase.__init__(self)\n\n def do(self):\n self.assertEqual(self.cfg.task.local_base_path, \"/efs/cache/local/\")\n dataset = ClassFactory.get_cls(\"dataset\")\n train_dataset = dataset(mode='train')\n self.assertEqual(len(train_dataset), 800)\n\n\nclass TestNetworkDesc(unittest.TestCase):\n\n def test_hb(self):\n cfg = Config(\"./hn1.yml\")\n # DefaultConfig().data = cfg\n vega.run(\"./esr_ea.yml\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/test/settings/test_hn.py","file_name":"test_hn.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"219637076","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/9/16 15:41\n# @Site : \n# @File : runner.py\n\nfrom IPPool.Middleware import Middleware\nimport sys\nimport io\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\n\n\ndef main():\n try:\n s = Middleware()\n s.run()\n except:\n main()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"285318758","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nfrom os import path\nfrom flask import Flask\nfrom flask import json\nfrom flask import request\nfrom pickle import load\nfrom pandas import DataFrame\nfrom werkzeug.exceptions import BadRequest\n\napp = Flask(__name__)\n\nscoring_obj = None\ndata_path = 'data'\nfile_name = 'model.pkl'\n\n\n@app.route('/api/credits/scoring/', methods=['POST'])\ndef scoring():\n try:\n return json.dumps({\"scoring_result\": get_score(request.json)})\n except Exception as e:\n raise BadRequest(\"Scoring counting failed. Details: {}\".format(e))\n\ncols = [\n u'RevolvingUtilizationOfUnsecuredLines',\n u'age',\n u'NumberOfTime30-59DaysPastDueNotWorse',\n u'DebtRatio',\n u'MonthlyIncome',\n u'NumberOfOpenCreditLinesAndLoans',\n u'NumberOfTimes90DaysLate',\n u'NumberRealEstateLoansOrLines',\n u'NumberOfTime60-89DaysPastDueNotWorse',\n u'NumberOfDependents'\n]\n\n\ndef get_score(data_dict):\n \"\"\"\n :param data_dict:\n age: int\n credit_monthly_payments: []\n credits_residue (except real estate and car loans): []\n credit_limits (except real estate and car loans): []\n MonthlyIncome: float\n NumberOfTimes90DaysLate: int\n NumberOfDependents: int\n NumberOfTime30-59DaysPastDueNotWorse: int\n NumberOfTime60-89DaysPastDueNotWorse: int\n NumberRealEstateLoansOrLines: int\n NumberOfOpenCreditLinesAndLoans: int\n :return:\n scoring value\n \"\"\"\n data_dict['DebtRatio'] = \\\n sum(data_dict['credit_monthly_payments']) / (data_dict['MonthlyIncome'] + 1)\n\n data_dict['RevolvingUtilizationOfUnsecuredLines'] = \\\n (sum(data_dict['credits_residue']) + 1) / (sum(data_dict['credit_limits']) + 1)\n\n data_dict['MonthlyIncome'] = \\\n data_dict['MonthlyIncome'] * 4.0 * 3263 / 959.0\n\n del data_dict['credit_monthly_payments']\n del data_dict['credits_residue']\n del data_dict['credit_limits']\n\n pd_data = DataFrame(data_dict, index=[1, ])\n score = scoring_obj.predict_proba(pd_data[cols])\n return score[0][0]\n\n\ndef main():\n with open(path.join(data_path, file_name)) as f:\n global scoring_obj\n scoring_obj = load(f)\n app.run('0.0.0.0', port=8001)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"services/scoring/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"481760887","text":"class Map:\n\n field = ['0 ', '0 ', '1 ', '0 ', '0 ', '0 ', '0 ', '0 ', '10', '10', '8 ', '9 ',\n '0 ', '0 ', '1 ', '0 ', '0 ', 'K ', '0 ', '0 ', '10', '10', '8 ', '9 ',\n '0 ', 'K ', '1 ', '0 ', '0 ', '0 ', '0 ', '0 ', '10', '10', '8 ', '9 ',\n '0 ', '0 ', '1 ', '1 ', 'K ', '0 ', '0 ', '0 ', '10', '10', '8 ', '9 ',\n '0 ', '0 ', 'K ', '1 ', '0 ', '0 ', '0 ', '0 ', '10', '10', '8 ', '9 ',\n '2 ', '2 ', '2 ', '1 ', '0 ', '0 ', '0 ', '0 ', '10', '10', '8 ', '9 ',\n '3 ', '3 ', '2 ', '1 ', '0 ', '0 ', '0 ', '0 ', 'K ', 'K ', '8 ', '8 ',\n '4 ', '3 ', '2 ', '1 ', '0 ', '0 ', '0 ', '0 ', '5 ', '5 ', '5 ', '5 ',\n '4 ', '3 ', '2 ', '1 ', '0 ', '0 ', '0 ', '11', '5 ', '6 ', '6 ', '6 ',\n '4 ', '3 ', '2 ', '1 ', '0 ', '0 ', '0 ', '11', '5 ', '6 ', '7 ', '7 ']\n\n topend = [i for i in range(0, 12)]\n bottomend = [i for i in range(108, 120)]\n rigthend = [(i*12)-1 for i in range(1, 11)]\n leftend = [(i*12) for i in range(0, 10)]\n\n def __init__(self):\n self.empty_field = []\n self.current = 0\n self.block = False\n self.game_over = False\n for i in self.field:\n if i == 'K ':\n self.empty_field.append(' -1')\n else:\n self.empty_field.append(' 0')\n\n def reset_map(self):\n self.current = 0\n self.block = False\n self.game_over = False\n index = 0\n for i in self.field:\n if i == 'K ':\n self.empty_field[index] = ' -1'\n else:\n self.empty_field[index] = ' 0'\n index += 1\n\n def print_map(self):\n for n in range(120):\n print(self.empty_field[n], end=\" \")\n if (n+1) % 12 == 0:\n print('')\n\n def get_start_index(self, start):\n if start > 43:\n start -= 44\n if start < 12:\n start_index = start\n elif 22 > start > 11:\n start_index = ((start - 11) * 12) - 1\n elif 34 > start > 21:\n start_index = 108 + 33 - start\n else:\n start_index = (43 - start) * 12\n return start_index\n\n def calculate(self, x):\n start = x\n index = self.get_start_index(start)\n return index\n\n def which_way(self, pos):\n if pos > 43:\n pos -= 44\n if 0 <= pos <= 11:\n return \"down\"\n elif 33 >= pos >= 22:\n return \"up\"\n elif 43 >= pos >= 34:\n return \"right\"\n elif 12 <= pos <= 21:\n return \"left\"\n\n def garden(self, gene, path_counter):\n index = 0\n start = self.calculate(gene)\n if self.empty_field[start] != \" 0\":\n self.empty_field[start] = \" X\"\n return -1\n self.current = start\n self.empty_field[self.current] = \" %2.d\" % path_counter\n return start\n\n def down(self, i):\n self.current += 12\n if self.empty_field[self.current] == ' 0':\n self.empty_field[self.current] = \" %2.d\" % i\n else:\n self.current -= 12\n self.block = True\n\n def up(self, i):\n self.current -= 12\n if self.empty_field[self.current] == ' 0':\n self.empty_field[self.current] = \" %2.d\" % i\n else:\n self.current += 12\n self.block = True\n\n def left(self, i):\n self.current -= 1\n if self.empty_field[self.current] == ' 0':\n self.empty_field[self.current] = \" %2.d\" % i\n else:\n self.current += 1\n self.block = True\n\n def right(self, i):\n self.current += 1\n if self.empty_field[self.current] == ' 0':\n self.empty_field[self.current] = \" %2.d\" % i\n else:\n self.current -= 1\n self.block = True\n\n def get_map_value(self):\n return self.empty_field[self.current]\n\n def change_l_r(self, x):\n if x > 43:\n return \"left\"\n else:\n return \"right\"\n\n def change_u_d(self, x):\n if x > 43:\n return \"down\"\n else:\n return \"up\"\n\n def is_monk_in_the_end_of_map(self):\n if self.current in self.topend:\n return True\n elif self.current in self.bottomend:\n return True\n elif self.current in self.rigthend:\n return True\n elif self.current in self.leftend:\n return True\n else:\n return False\n\n def end_of_map(self, direction):\n if self.current in self.topend and direction == \"up\":\n return True\n elif self.current in self.bottomend and direction == \"down\":\n return True\n elif self.current in self.rigthend and direction == \"right\":\n return True\n elif self.current in self.leftend and direction == \"left\":\n return True\n else:\n return False\n\n def two_possible_ways_l_r(self):\n if self.current in self.topend or self.current in self.bottomend:\n return False\n if self.empty_field[(self.current + 12)] == \" 0\" and self.empty_field[(self.current - 12)] == \" 0\":\n return True\n else:\n return False\n\n def two_possible_ways_u_d(self):\n if self.current in self.leftend or self.current in self.rigthend:\n return False\n if self.empty_field[(self.current + 1)] == \" 0\" and self.empty_field[(self.current - 1)] == \" 0\":\n return True\n else:\n return False\n\n def one_possible_way_l_r(self):\n if self.current in self.topend:\n if self.empty_field[self.current + 12] == \" 0\":\n return \"down\"\n else:\n return \"game over\"\n elif self.current in self.bottomend:\n if self.empty_field[self.current - 12] == \" 0\":\n return \"up\"\n else:\n return \"game over\"\n elif self.empty_field[self.current + 12] == \" 0\":\n return \"down\"\n elif self.empty_field[self.current - 12] == \" 0\":\n return \"up\"\n else:\n return \"game over\"\n\n def one_possible_way_u_d(self):\n if self.current in self.leftend:\n if self.empty_field[self.current + 1] == \" 0\":\n return \"right\"\n else:\n return \"game over\"\n elif self.current in self.rigthend:\n if self.empty_field[self.current - 1] == \" 0\":\n return \"left\"\n else:\n return \"game over\"\n elif self.empty_field[self.current + 1] == \" 0\":\n return \"right\"\n elif self.empty_field[self.current - 1] == \" 0\":\n return \"left\"\n else:\n return \"game over\"\n\n\n\n\nzen = Map()\n# print(zen.print_map())\n# print(zen.topend)\n# print(zen.bottomend)\n# print(zen.rigthend)\n# print(zen.leftend)\n# print(zen.get_start_index(21), zen.which_way(21))\n# print(zen.get_start_index(22), zen.which_way(22))\n\n","sub_path":"AI3/Fitness.py","file_name":"Fitness.py","file_ext":"py","file_size_in_byte":7060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"208306532","text":"from nltk.corpus import wordnet\nimport random\n\ndef make_keyword_recommendation(cluster_names):\n synonyms = []\n recommendations = []\n for cluster_name in cluster_names:\n for syn in wordnet.synsets(cluster_name):\n for l in syn.lemmas():\n synonyms.append(l.name())\n\n while cluster_name in synonyms:\n synonyms.remove(cluster_name)\n\n if synonyms:\n recommendations.append(synonyms[random.randint(0, len(synonyms)-1)])\n synonyms = []\n\n return recommendations\n\n\nif __name__== \"__main__\":\n \n cluster_names = [\"message\", \"voice\", \"chatbot\"]\n \n print(make_keyword_recommendation(cluster_names))","sub_path":"AI_modules/keyword_recommendation.py","file_name":"keyword_recommendation.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"172518902","text":" # Inventory what is here ^\n # Implement the CPU constructor ^\n # Add RAM functions ram_read() and ram_write()\n # Implement the core of run()\n # Implement the HLT instruction handler\n # Add the LDI instruction\n # Add the PRN instruction\n #\n\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.ram = [0]*256\n self.reg = [0]*8\n self.pc = 0 # program counter: address of the currently executing instruction\n self.ir = 0 # flags\n self.sp = 7 # represents the 8th register\n self.Flags = [0]*8\n\n def load(self):\n \"\"\"Load a program into memory.\"\"\"\n try:\n address = 0\n # sys.argv[0] is the name of the running program itself\n filename = sys.argv[1]\n with open(filename) as f:\n for line in f:\n # ignore comments\n comment_split = line.split('#')\n # strip out whitespace\n num = comment_split[0].strip()\n # ignore blank lines\n if num == \"\":\n continue\n # convert the binary string to integers.\n # built-in integer function dose it for us.\n value = int(num,2)\n\n self.ram[address] = value\n address+=1\n\n except FileNotFoundError:\n print(f\"{sys.argv[0]}: {sys.argv[1]} not found\")\n sys.exit(2)\n #\n #\n # for instruction in program:\n # self.ram[address] = instruction\n # address += 1\n\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n if op == \"ADD\":\n self.reg[reg_a] += self.reg[reg_b]\n #elif op == \"SUB\": etc\n if op == \"AND\":\n if reg_a == 1 and reg_b == 1:\n return True\n else:\n return False\n if op ==\"OR\":\n if reg_a == 1 and reg_b ==0:\n return True\n elif reg_a == 0 and reg_b == 1:\n return True\n elif reg_a == 1 and reg_b == 1:\n return True\n else:\n return False\n if op ==\"XOR\":\n if reg_a==1 and reg_b ==0:\n return True\n if reg_a==0 and reg_b ==1:\n return True\n else:\n return False\n\n if op ==\"NOR\":\n if reg_a==0 and reg_b==0:\n return True\n else:\n return False \n\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n #self.fl,\n #self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def ram_read(self, MAR):\n \"\"\"Accepts the address to read and return the value stored there\"\"\"\n return self.ram[MAR]\n # MAR contains the address that is being read or written to.\n # MDR contains the data that was read\n\n def ram_write(self, MAR, MDR):\n \"\"\"Should accept a value to write and the address to write it to\"\"\"\n self.ram[MAR]=MDR\n # so we will move the stuff from MAR TO MDR\n\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n\n Running=True\n\n LDI=0b10000010\n HLT=0b00000001\n PRN=0b01000111\n MUL=0b10100010\n PUSH=0b01000101\n POP=0b01000110\n CALL=0b01010000\n RET=0b00010001\n ADD=0b10100000\n CMP=0b10100111\n JMP=0b01010100\n JEQ=0b01010101\n JNE=0b01010110\n L= 0\n E= 0\n G= 0\n\n\n while Running:\n # read the memory address sotred in pc and store it in Instruction Register\n Command=self.ram_read(self.pc)\n # print(self.reg)\n #print(\"------\")\n # load immediate, store avalue in a register\n if Command == LDI:\n # self.trace()\n operand_a = self.ram_read(self.pc+1)\n operand_b = self.ram_read(self.pc+2)\n self.reg[operand_a]=operand_b # sets a specific register to a specified value\n self.pc+=3\n # print(operand_a)\n elif Command==HLT:\n Running=False\n self.pc+=1\n # halt the CPU and exit the emulator\n elif Command==PRN:\n # PRN: adding\n reg = self.ram[self.pc+1]\n #print(num)\n # print(self.reg[reg]) # prints 8 to the console.\n print(self.reg[reg])\n self.pc+=2\n # prints the numeric\n elif Command==MUL:\n register_a = self.ram_read(self.pc+1)\n register_b = self.ram_read(self.pc+2)\n # now save the multiplication of these two in register_a\n self.reg[register_a] = self.reg[register_a]*self.reg[register_b]\n #print(self.reg[register_a])\n self.pc+=3\n\n # elif Command == SAVE:\n # num = self.ram[self.pc+1]\n # reg = self.ram[self.pc+2]\n # self.reg[reg] = num\n # self.pc+=3\n\n # elif Command == ADD:\n # register_a = self.ram[self.pc+1]\n # register_b = self.ram[self.pc+2]\n # self.reg[register_a] += self.reg[register_b]\n # self.pc += 3\n\n elif Command == PUSH:\n # a number from 0 to 7\n #self.trace()\n reg = self.ram[self.pc+1]\n # look in the identified register and find the value\n val = self.reg[reg]\n # decriment the value i.e. memory address by 1\n self.reg[self.sp] -=1\n # copy the value from the register into the memory\n self.ram[self.reg[self.sp]] = val\n self.pc += 2 # because we had one argument\n\n elif Command == POP:\n reg = self.ram[self.pc+1] # memory of the register holding our SP\n val = self.ram[self.reg[self.sp]] # register number 7\n self.reg[reg] = val # copy that value into register that we are pointing at\n self.reg[self.sp] += 1 # incrememnt the stock pointer:\n # print(val)\n self.pc += 2\n\n elif Command == CALL:\n val = self.pc+2\n reg = self.ram[self.pc+1]\n sub_address = self.reg[reg]\n # decriment the stack pointer\n self.reg[self.sp]-=1\n self.ram[self.reg[self.sp]]=val\n # update the address\n self.pc=sub_address\n elif Command == ADD:\n self.alu(\"ADD\", self.ram_read(self.pc+1), self.ram_read(self.pc+2))\n self.pc+=3\n\n elif Command == RET:\n return_add = self.reg[self.sp]\n self.pc = self.ram[return_add]\n # increment the sp\n self.reg[self.sp] +=1\n\n # get the values froms the ram and read it into register\n # registerA = self.reg[self.ram_read(self.pc+1)]\n # registerB = self.reg[self.ram_read(self.pc+2)]\n # if A is less than B, set L flag to 1\n elif Command==CMP:\n self.Flags = CMP\n if self.reg[self.ram_read(self.pc+1)] < self.reg[self.ram_read(self.pc+2)]:\n L=1\n G=0\n E=0\n self.Flags=CMP-0b00000100\n elif self.reg[self.ram_read(self.pc+1)] > self.reg[self.ram_read(self.pc+2)]:\n G=1\n L=0\n E=0\n self.Flags=CMP-0b00000010\n elif self.reg[self.ram_read(self.pc+1)] ==self.reg[self.ram_read(self.pc+2)]:\n E=1\n L=0\n G=0\n self.Flags=CMP-0b00000001\n self.pc+=3\n# self.trace()\n # takes in the register\n # jumps to the address stored in the given register\n # set the PC to the address stored in the given register.\n elif Command==JMP:\n self.pc = self.reg[self.ram_read(self.pc+1)]\n\n elif Command==JEQ:\n if E==1:\n self.pc = self.reg[self.ram_read(self.pc+1)]\n else:\n self.pc+=2\n\n elif Command==JNE:\n if E==0:\n self.pc = self.reg[self.ram_read(self.pc+1)]\n else:\n self.pc+=2\n\n # else:\n # print(f\"Unknown Instruction: {Command}\")\n # sys.exit(1)\n","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":9281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"492563135","text":"import telebot\nfrom telebot import types\nimport pandas as pd\nfrom csv import writer\n\nbot = telebot.TeleBot(\"1317717235:AAGo2iVPuabY6FpayigYouJuA5ydgg_ypr4\", parse_mode=None)\nknownUsers = []\n\n#-------------------------------------------------------------------------------\ndef AddToCsvFile(FileName, ListRowContent):\n with open(FileName, 'a+', newline='') as i:\n csv_writer = writer(i)\n csv_writer.writerow(ListRowContent)\n #This function is used to add to a csv file\n#---------------------------------------------------------------------------------\n\n\nGender_markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)\nGender_markup.add('Male', 'Female')\nuserLocation_markup = types.ReplyKeyboardMarkup()\nyesBt = types.KeyboardButton(text = 'Share location', request_location = True)\nuserLocation_markup.row(yesBt)\nforce = types.ForceReply(selective=False)\nGroup_markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)\nGroup_markup.add('I need help!', 'I want to help!')\n#--------------------------------------------------------------------------------------\n\n\n@bot.message_handler(commands=['start']) #start\ndef ChooseGroup(message):\n cid = message.chat.id\n bot.send_message(message.chat.id, \"Are you looking to help or do you need help?\", reply_markup = Group_markup)\n\n\n@bot.message_handler(func=lambda message: message.text == \"I want to help!\")\ndef helping(message):\n cid = message.chat.id\n global Data_sheet\n Data_sheet = \"Volunteer.csv\"\n print(Data_sheet)\n volunteer_msg = bot.send_message(cid, \"Thank you for volunteering\")\n command_start(message)\n\n@bot.message_handler(func=lambda message: message.text == \"I need help!\")\ndef needinghelp(message):\n cid = message.chat.id\n global Data_sheet\n Data_sheet = \"Elderly.csv\"\n print(Data_sheet)\n elderly_msg = bot.send_message(cid, \"Thank you for using our service!\", )\n command_start(message)\n \n \ndef command_start(message):\n cid = message.chat.id\n global df\n df = pd.read_csv(Data_sheet)\n \n if cid not in df.values: \n knownUsers.append(str(cid)) \n print(cid)\n start_msg = bot.send_message(cid , \"Hello, it seems like this is the first time you are using our service. I will need your information. Firstly, what is your name?\", reply_markup = force)\n bot.register_next_step_handler(start_msg, ask_for_age)\n else:\n bot.send_message(cid, \"Hmm, it seems like we already know eachother!\")\n \n\n \ndef ask_for_age(message): \n cid = message.chat.id\n global userName\n userName = message.text\n print(userName)\n age_msg = bot.send_message(cid , \"What is your age?\", reply_markup = force)\n bot.register_next_step_handler(age_msg, ask_for_gender)\n\ndef ask_for_gender(message): #ask_for gender\n cid = message.chat.id\n global userAge\n userAge = message.text\n print(userAge)\n sex_msg = bot.send_message(cid , \"What gender do you indentify as?\", reply_markup = Gender_markup)\n bot.register_next_step_handler(sex_msg, ask_for_phone)\n\ndef ask_for_phone(message): #ask_for_phone\n cid = message.chat.id\n global userGender\n userGender = message.text\n print(userGender)\n phone_msg = bot.send_message(cid , \"What is your phone number?\", reply_markup = force)\n bot.register_next_step_handler(phone_msg, ask_for_mail)\n\ndef ask_for_mail(message): #ask_ for_mail\n cid = message.chat.id\n global userPhone\n userPhone = message.text\n print(userPhone)\n mail_msg = bot.send_message(cid , \"What is your email address?\", reply_markup = force)\n bot.register_next_step_handler(mail_msg, ask_for_location)\n\ndef ask_for_location(message): #ask_for_location\n cid = message.chat.id\n global userMail\n userMail = message.text\n print(userMail)\n bot.send_message(cid, \"Can you share your location with us?\", reply_markup = userLocation_markup)\n\n@bot.message_handler(content_types=['location']) #collect user location \ndef handle_location(message):\n global location_latitude\n location_latitude = message.location.latitude\n global location_longitude\n location_longitude = message.location.longitude\n print(location_latitude, location_longitude)\n \n \n RowContent = [knownUsers[0], userName, userAge, userGender, userPhone, userMail, location_latitude, location_longitude]\n AddToCsvFile(Data_sheet , RowContent)\n\nbot.polling()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"11119884","text":"# Quick and dirty program to pull down operational \n# Puerto Rico 48-hour ARW forecasts. \n\n# Logan Karsten\n# National Center for Atmospheric Research\n# Research Applications Laboratory\n\nimport datetime\nimport urllib\nfrom urllib import request\nimport http\nfrom http import cookiejar\nimport os\nimport sys\nimport shutil\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef errOut(msgContent,emailTitle,emailRec,lockFile):\n\tmsg = MIMEText(msgContent)\n\tmsg['Subject'] = emailTitle\n\tmsg['From'] = emailRec\n\tmsg['To'] = emailRec\n\ts = smtplib.SMTP('localhost')\n\ts.sendmail(emailRec,[emailRec],msg.as_string())\n\ts.quit()\n\t# Remove lock file\n\tos.remove(lockFile)\n\tsys.exit(1)\n\ndef warningOut(msgContent,emailTitle,emailRec,lockFile):\n\tmsg = MIMEText(msgContent)\n\tmsg['Subject'] = emailTitle\n\tmsg['From'] = emailRec\n\tmsg['To'] = emailRec\n\ts = smtplib.SMTP('localhost')\n\ts.sendmail(emailRec,[emailRec],msg.as_string())\n\ts.quit()\n\tsys.exit(1)\n\ndef msgUser(msgContent,msgFlag):\n\tif msgFlag == 1:\n\t\tprint(msgContent)\n\noutDir = \"/glade/p/cisl/nwc/nwm_forcings/Forcing_Inputs/WRF_ARW_Puerto_Rico\"\ntmpDir = \"/glade/scratch/karsten\"\nlookBackHours = 72 # How many hours to look for data.....\ncleanBackHours = 240 # Period between this time and the beginning of the lookback period to cleanout old data. \nlagBackHours = 6 # Wait at least this long back before searching for files. \ndNowUTC = datetime.datetime.utcnow()\ndNow = datetime.datetime(dNowUTC.year,dNowUTC.month,dNowUTC.day,dNowUTC.hour)\nncepHTTP = \"https://ftp.ncep.noaa.gov/data/nccf/com/hiresw/prod\"\n\n# Define communication of issues.\nemailAddy = 'jon.doe@youremail.com'\nerrTitle = 'Error_get_ARW_PR'\nwarningTitle = 'Warning_ARW_PR'\n\npid = os.getpid()\nlockFile = tmpDir + \"/GET_ARW_PR.lock\"\n\n# First check to see if lock file exists, if it does, throw error message as\n# another pull program is running. If lock file not found, create one with PID.\nif os.path.isfile(lockFile):\n\tfileLock = open(lockFile,'r')\n\tpid = fileLock.readline()\n\twarningMsg = \"WARNING: Another WRF ARW Puerto Rico Fetch Program Running. PID: \" + pid\n\twarningOut(warningMsg,warningTitle,emailAddy,lockFile)\nelse:\n\tfileLock = open(lockFile,'w')\n\tfileLock.write(str(os.getpid()))\n\tfileLock.close()\n\nfor hour in range(cleanBackHours,lookBackHours,-1):\n\t# Calculate current hour.\n\tdCurrent = dNow - datetime.timedelta(seconds=3600*hour)\n\n\t# Go back in time and clean out any old data to conserve disk space. \n\tif dCurrent.hour != 6 and dCurrent.hour != 18:\n\t\tcontinue # WRF-ARW Puerto Rico nest data is only available for 06/18 UTC.. \n\telse:\n\t\t# Compose path to directory containing data. \n\t\tcleanDir = outDir + \"/hiresw.\" + dCurrent.strftime('%Y%m%d')\n\n\t\t# Check to see if directory exists. If it does, remove it. \n\t\tif os.path.isdir(cleanDir):\n\t\t\tprint(\"Removing old data from: \" + cleanDir)\n\t\t\tshutil.rmtree(cleanDir)\n\n# Now that cleaning is done, download files within the download window. \nfor hour in range(lookBackHours,lagBackHours,-1):\n\t# Calculate current hour.\n\tdCurrent = dNow - datetime.timedelta(seconds=3600*hour)\n\n\tif dCurrent.hour != 6 and dCurrent.hour != 18:\n\t\tcontinue # WRF-ARW Hawaii nest data is only available for 06/18 UTC...\n\telse:\n\t\tarwOutDir = outDir + \"/hiresw.\" + dCurrent.strftime('%Y%m%d')\n\t\thttpDownloadDir = ncepHTTP + \"/hiresw.\" + dCurrent.strftime('%Y%m%d')\n\t\tif not os.path.isdir(arwOutDir):\n\t\t\tos.mkdir(arwOutDir)\n\n\t\tnFcstHrs = 48\n\t\tfor hrDownload in range(1,nFcstHrs + 1):\n\t\t\tfileDownload = \"hiresw.t\" + dCurrent.strftime('%H') + \\\n\t\t\t\t\t\t \"z.arw_2p5km.f\" + str(hrDownload).zfill(2) + \\\n\t\t\t\t\t\t \".pr.grib2\"\n\t\t\turl = httpDownloadDir + \"/\" + fileDownload\n\t\t\toutFile = arwOutDir + \"/\" + fileDownload\n\t\t\tif os.path.isfile(outFile):\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tprint(\"Pulling ARW file: \" + url)\n\t\t\t\trequest.urlretrieve(url,outFile)\n\t\t\texcept:\n\t\t\t\tprint(\"Unable to retrieve: \" + url)\n\t\t\t\tprint(\"Data may not available yet...\")\n\t\t\t\tcontinue\n\n# Remove the LOCK file.\nos.remove(lockFile)\n\n","sub_path":"Util/get_ARW_Puerto_Rico.py","file_name":"get_ARW_Puerto_Rico.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"125512884","text":"# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"FunMCMC backend.\n\nThis module is used to provide simultaneous compatibility between TensorFlow and\nJAX.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n# [internal] enable type annotations\nfrom __future__ import print_function\n\n__all__ = [\n 'get_backend',\n 'JAX',\n 'set_backend',\n 'TENSORFLOW',\n 'tf',\n 'util',\n]\n\nTENSORFLOW = 'tensorflow'\nJAX = 'jax'\n_BACKEND = TENSORFLOW\n\n\ndef get_backend():\n \"\"\"Returns the current backend used by FunMCMC.\"\"\"\n return _BACKEND\n\n\ndef set_backend(backend):\n \"\"\"Sets the backend used by FunMCMC.\"\"\"\n global _BACKEND\n _BACKEND = backend\n\n\nclass _TfDispatcher(object):\n \"\"\"Dispacher for the `tf` module.\"\"\"\n\n def __getattr__(self, attr):\n # pylint: disable=g-import-not-at-top\n if get_backend() == TENSORFLOW:\n import tensorflow.compat.v2 as tf_\n elif get_backend() == JAX:\n from discussion.fun_mcmc import tf_on_jax\n tf_ = tf_on_jax.tf\n else:\n raise ValueError('Unknown backend \"{}\"'.format(get_backend()))\n return getattr(tf_, attr)\n\n\nclass _UtilDispatcher(object):\n \"\"\"Dispacher for the `util` module.\"\"\"\n\n def __getattr__(self, attr):\n # pylint: disable=g-import-not-at-top\n if get_backend() == TENSORFLOW:\n from discussion.fun_mcmc import util_tf as util_\n elif get_backend() == JAX:\n from discussion.fun_mcmc import util_jax as util_\n else:\n raise ValueError('Unknown backend \"{}\"'.format(get_backend()))\n return getattr(util_, attr)\n\n\ntf = _TfDispatcher()\nutil = _UtilDispatcher()\n","sub_path":"discussion/fun_mcmc/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"408747404","text":"import csv\n\ndef save_records(left, right, records):\n '''Save a list of [year, temp] pairs as CSV.'''\n filename = left + '-' + right + '.csv'\n with open(filename, 'w') as raw:\n writer = csv.writer(raw)\n writer.writerows(records)\n\nsave_records('AUS', 'BRA', [[1, 2], [3, 4]])\n","sub_path":"src/syndicate/save_records_02.py","file_name":"save_records_02.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"382796615","text":"from datetime import datetime\nfrom django_notification_system.utils import (\n check_for_user_opt_out,\n user_notification_targets,\n)\n\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\n\nfrom ..models import Notification\nfrom ..exceptions import (\n NotificationsNotCreated,\n UserHasNoTargetRecords,\n UserIsOptedOut,\n)\n\n\ndef create_notification(\n user: User,\n title: str,\n body: str,\n scheduled_delivery: datetime = None,\n retry_time_interval: int = 1440,\n max_retries: int = 3,\n quiet=False,\n extra: dict = None,\n) -> None:\n \"\"\"\n This function will generate a Twilio SMS notification.\n\n Args:\n user (User): The user to whom the push notification will be sent.\n title (str): The title for the push notification.\n body (str, optional): The body of the sms notification.\n scheduled_delivery (datetime, optional): Defaults to immediately.\n retry_time_interval (int, optional): Delay between send attempts. Defaults to 60 seconds.\n max_retries (int, optional): Maximum number of retry attempts for delivery. Defaults to 3.\n quiet (bool, optional): Suppress exceptions from being raised. Defaults to False.\n extra (dict, optional): Defaults to None.\n\n Raises:\n UserIsOptedOut: When the user has an active opt-out.\n UserHasNoTargetRecords: When the user has no eligible targets for this notification type.\n NotificationsNotCreated: When the notifications could not be created.\n \"\"\"\n try:\n check_for_user_opt_out(user=user)\n except UserIsOptedOut:\n if quiet:\n return\n else:\n raise UserIsOptedOut()\n\n target_user_records = user_notification_targets(user=user, target_name=\"Twilio\")\n\n if not target_user_records:\n if quiet:\n return\n else:\n raise UserHasNoTargetRecords()\n\n if scheduled_delivery is None:\n scheduled_delivery = timezone.now()\n\n notifications_created = []\n for target_user_record in target_user_records:\n # JSONField casts None to {}, so we have to check if the server value = {}\n if extra is None:\n extra = {} # I hate casting so much\n notification, created = Notification.objects.get_or_create(\n target_user_record=target_user_record,\n title=title,\n scheduled_delivery=scheduled_delivery,\n extra=extra,\n defaults={\n \"body\": body,\n \"status\": 'SCHEDULED',\n \"retry_time_interval\": retry_time_interval,\n \"max_retries\": max_retries\n }\n )\n\n if created:\n notifications_created.append(notification)\n\n if not notifications_created:\n if quiet:\n return\n else:\n raise NotificationsNotCreated()\n","sub_path":"django_notification_system/notification_creators/twilio.py","file_name":"twilio.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"311295085","text":"## Author: Danny August Ramaputra\n## FIle name: lab02a.py\n## using turtle to draw reqular polygons\n## prompt user for the number of sides and the color component (r, g, b)\nimport turtle\nimport sys\n\nturtle.shape('turtle')\nturtle.title('Lab 02 -- 2017')\n\n# get the number of sides from user\nn = int(turtle.textinput(\"Lab 02\", \"The number of sides: \"))\n\n# draw the n-side polygon using a for loop\n# the length of a side is getting shorter as n is getting larger\n# when n = 4, the length of the side is 100\npoly_angle = 180 - 180*(n - 2)/n\npoly_length = (4/n)*100\n\nturtle.pendown()\nfor i in range(n):\n turtle.forward(poly_length)\n turtle.left(poly_angle)\nturtle.penup()\n\n# get the value of RED color from user\ncolor_r = float(turtle.textinput(\"Lab 02\", \"The RED color component [between 0 and 1]:\"))\n\n# get the value of GREEN color from user\ncolor_g = float(turtle.textinput(\"Lab 02\", \"The GREEN color component [between 0 and 1]:\"))\n\n# get the value of BLUE color from user\ncolor_b = float(turtle.textinput(\"Lab 02\", \"The BLUE color component [between 0 and 1]:\"))\n\n# move turtle to new position\nturtle.setpos(0, -150)\n6\n# create the color from rgb values given by user\nturtle.color(color_r, color_g, color_b)\n\n# draw regular polygon with color fill\n# draw a regular polygon without the color\nturtle.pendown()\nturtle.begin_fill()\nfor i in range(n):\n turtle.forward(poly_length)\n turtle.left(poly_angle)\nturtle.penup()\nturtle.end_fill()\n\n# make turtle invisible\nturtle.hideturtle()\n\n# message for user\nprint(\"Please click on the graphics window to exit...\")\n\nturtle.exitonclick()\n\n# the end","sub_path":"fprog_lab/lab02/DannyAugustRamaputra_1706019791_lab02a.py","file_name":"DannyAugustRamaputra_1706019791_lab02a.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"363625945","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom oslo_policy import policy\n\n# FIXME(hrybacki): Repetitive check strings: Port to simpler checks\n# - secret_acls:delete, secret_acls:put_patch\n# - container_acls:delete container_acls:put_patch\n\nrules = [\n policy.DocumentedRuleDefault(\n name='secret_acls:get',\n check_str='rule:all_but_audit and rule:secret_project_match',\n scope_types=[],\n description='Retrieve the ACL settings for a given secret.'\n 'If no ACL is defined for that secret, then Default ACL '\n 'is returned.',\n operations=[\n {\n 'path': '/v1/secrets/{secret-id}/acl',\n 'method': 'GET'\n },\n ]\n ),\n policy.DocumentedRuleDefault(\n name='secret_acls:delete',\n check_str='rule:secret_project_admin or rule:secret_project_creator',\n scope_types=[],\n description='Delete the ACL settings for a given secret.',\n operations=[\n {\n 'path': '/v1/secrets/{secret-id}/acl',\n 'method': 'DELETE'\n },\n ]\n ),\n policy.DocumentedRuleDefault(\n name='secret_acls:put_patch',\n check_str='rule:secret_project_admin or rule:secret_project_creator',\n scope_types=[],\n description='Create new, replaces, or updates existing ACL for a ' +\n 'given secret.',\n operations=[\n {\n 'path': '/v1/secrets/{secret-id}/acl',\n 'method': 'PUT'\n },\n {\n 'path': '/v1/secrets/{secret-id}/acl',\n 'method': 'PATCH'\n },\n ]\n ),\n policy.DocumentedRuleDefault(\n name='container_acls:get',\n check_str='rule:all_but_audit and rule:container_project_match',\n scope_types=[],\n description='Retrieve the ACL settings for a given container.',\n operations=[\n {\n 'path': '/v1/containers/{container-id}/acl',\n 'method': 'GET'\n }\n ]\n ),\n policy.DocumentedRuleDefault(\n name='container_acls:delete',\n check_str='rule:container_project_admin or ' +\n 'rule:container_project_creator',\n scope_types=[],\n description='Delete ACL for a given container. No content is returned '\n 'in the case of successful deletion.',\n operations=[\n {\n 'path': '/v1/containers/{container-id}/acl',\n 'method': 'DELETE'\n }\n ]\n ),\n policy.DocumentedRuleDefault(\n name='container_acls:put_patch',\n check_str='rule:container_project_admin or ' +\n 'rule:container_project_creator',\n scope_types=[],\n description='Create new or replaces existing ACL for a given '\n 'container.',\n operations=[\n {\n 'path': '/v1/containers/{container-id}/acl',\n 'method': 'PUT'\n },\n {\n 'path': '/v1/containers/{container-id}/acl',\n 'method': 'PATCH'\n }\n ]\n ),\n]\n\n\ndef list_rules():\n return rules\n","sub_path":"barbican/common/policies/acls.py","file_name":"acls.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"295277680","text":"from django.core.exceptions import ImproperlyConfigured\n\nfrom .base import *\n\n\ndef get_env_variable(var_name):\n try:\n return os.environ[var_name]\n except KeyError:\n err_msg = f'Set {var_name} env variable'\n raise ImproperlyConfigured(err_msg)\n\n\nSECRET_KEY = get_env_variable('GALLARY_SECRET_KEY')\n\nDEBUG = True\n\nINSTALLED_APPS += ['gallary.callforward', 'gallary.home.apps.HomeConfig']\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'gallary',\n 'USER': 'django',\n 'PASSWORD': get_env_variable('DATABASE_PASSWORD'),\n 'HOST': 'localhost',\n 'PORT': '5432',\n }\n}\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'gallary/', 'static/')\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'gallary/', 'media/')\n","sub_path":"config/settings/staging.py","file_name":"staging.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"75637305","text":"from __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass FacebookInfo(models.Model):\n email = models.EmailField()\n image = models.URLField()\n detail = models.TextField()\n\n\nclass JobDescription(models.Model):\n user = models.ForeignKey(User)\n jd = models.FileField(upload_to='JobDescription/')\n jd_data = models.TextField(null=True, blank=True)\n\n\nclass Resume(models.Model):\n jd = models.ForeignKey(JobDescription)\n resume = models.FileField(upload_to='resumes/')\n resume_data = models.TextField(null=True, blank=True)\n score = models.FloatField(null=True, blank=True)\n","sub_path":"web/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"215840652","text":"\"\"\"004_Add_instrumentid_to_SampleHeader\n\nRevision ID: 27510d530989\nRevises: 93ebd34a0943\nCreate Date: 2019-08-24 13:37:11.590805\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '27510d530989'\ndown_revision = '93ebd34a0943'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.add_column('sample_header', sa.Column('instrument_id', sa.INTEGER()))\n op.create_foreign_key('fk_instrument_id', 'sample_header', 'instrument'\n , ['instrument_id'], ['id'])\n\n\ndef downgrade():\n op.drop_constraint('fk_instrument_id', 'sample_header', type_='foreignkey')\n op.drop_column('sample_header', 'instrument_id')\n\n","sub_path":"alembic/versions/27510d530989_004_add_instrumentid_to_sampleheader.py","file_name":"27510d530989_004_add_instrumentid_to_sampleheader.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"122638419","text":"import re\nimport struct\nfrom typing import Iterable, List, Text, Tuple, Union\nimport unicodedata\nimport six\n\n\ndef wtq_normalize(x):\n \"\"\"Returns the normalized version of x.\n This normalization function is taken from WikiTableQuestions github, hence the\n wtq prefix. For more information, see\n https://github.com/ppasupat/WikiTableQuestions/blob/master/evaluator.py\n Args:\n x: the object (integer type or string) to normalize.\n Returns:\n A normalized string.\n \"\"\"\n x = x if isinstance(x, six.text_type) else six.text_type(x)\n # Remove diacritics.\n x = \"\".join(\n c for c in unicodedata.normalize(\"NFKD\", x)\n if unicodedata.category(c) != \"Mn\")\n # Normalize quotes and dashes.\n x = re.sub(u\"[‘’´`]\", \"'\", x)\n x = re.sub(u\"[“”]\", '\"', x)\n x = re.sub(u\"[‐‑‒–—−]\", \"-\", x)\n x = re.sub(u\"[‐]\", \"\", x)\n while True:\n old_x = x\n # Remove citations.\n x = re.sub(u\"((?\", \"\", x)\n x = x.replace(\"\\n\", \" \")\n return x\n\n\n_TOKENIZER = re.compile(r\"\\w+|[^\\w\\s]+\", re.UNICODE)\n\n\ndef tokenize_string(x):\n return list(_TOKENIZER.findall(x.lower()))\n\n\n# List of string normalization functions to be applied in order. We go from\n# simplest to more complex normalization procedures.\nSTRING_NORMALIZATIONS = (\n lambda x: x,\n lambda x: x.lower(),\n tokenize_string,\n wtq_normalize,\n)\n\n\ndef _split_thousands(delimiter, value):\n split = value.split(delimiter)\n return len(split) > 1 and any(map(lambda x: len(x) == 3, split))\n\n\ndef convert_to_float(value):\n \"\"\"Converts value to a float using a series of increasingly complex heuristics.\n Args:\n value: object that needs to be converted. Allowed types include\n float/int/strings.\n Returns:\n A float interpretation of value.\n Raises:\n ValueError if the float conversion of value fails.\n \"\"\"\n if isinstance(value, float):\n return value\n if isinstance(value, int):\n return float(value)\n if not isinstance(value, six.string_types):\n raise ValueError(\"Argument value is not a string. Can't parse it as float\")\n sanitized = value\n\n try:\n # Example: 1,000.7\n if \".\" in sanitized and \",\" in sanitized:\n return float(sanitized.replace(\",\", \"\"))\n # 1,000\n if \",\" in sanitized and _split_thousands(\",\", sanitized):\n return float(sanitized.replace(\",\", \"\"))\n # 5,5556\n if \",\" in sanitized and sanitized.count(\",\") == 1 and not _split_thousands(\n \",\", sanitized):\n return float(sanitized.replace(\",\", \".\"))\n # 0.0.0.1\n if sanitized.count(\".\") > 1:\n return float(sanitized.replace(\".\", \"\"))\n # 0,0,0,1\n if sanitized.count(\",\") > 1:\n return float(sanitized.replace(\",\", \"\"))\n return float(sanitized)\n except ValueError:\n # Avoid adding the sanitized value in the error message.\n raise ValueError(\"Unable to convert value to float\")\n\n\ndef to_float32(v):\n \"\"\"If v is a float reduce precision to that of a 32 bit float.\"\"\"\n if not isinstance(v, float):\n return v\n return struct.unpack(\"!f\", struct.pack(\"!f\", v))[0]\n\n\ndef get_sequence_id(example_id, annotator):\n if \"-\" in annotator:\n raise ValueError('\"-\" not allowed in annotator.')\n return f\"{example_id}-{annotator}\"\n\n\ndef get_question_id(sequence_id, position):\n return f\"{sequence_id}_{position}\"","sub_path":"src/transformers/tapas_text_utils.py","file_name":"tapas_text_utils.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"418488646","text":"from pmb import *\n\nfrom googleapiclient import discovery\nimport googleapiclient\nimport uuid\nimport logging\n\nlogging.getLogger(\"googleapiclient\").setLevel(logging.WARNING)\n\nconfig = get_config()\n\n# Perspective Processing\ndef get_scores(comment):\n\tid = comment.id\n\tbody = comment.body\n\n\tfirst_keys = {k for k in config['perspective']['report'].keys()}\n\tsecond_keys = {k for k in config['perspective']['remove'].keys()}\n\tkeys = first_keys.union(second_keys)\n\n\tperspective = discovery.build('commentanalyzer', 'v1alpha1', developerKey=config['perspective']['api_key'], cache_discovery=False)\n\tanalyze_request = { 'comment': { 'text': body }, 'clientToken' : id, 'requestedAttributes': {k: {} for k in keys}, 'languages' : ['en'], \"clientToken\" : id }\n\tresponse = perspective.comments().analyze(body=analyze_request).execute()\n\tscores = {}\n\tall_scores = {}\n\tattributeScores = response['attributeScores']\n\tfor attr, threshold in config['perspective']['report'].items():\n\t\tscore = float(attributeScores[attr]['summaryScore']['value'])\n\t\tif score >= threshold:\n\t\t\tscores[attr] = score\n\t\tall_scores[attr] = score\n\n\tfor attr, threshold in config['perspective']['remove'].items():\n\t\tscore = float(attributeScores[attr]['summaryScore']['value'])\n\t\tif score >= threshold:\n\t\t\tdt = pendulum.now('UTC').to_datetime_string()\n\t\t\ttarget_fullname = 't1_' + comment.id\n\t\t\treason = attr + \" \" + str(score)\n\n\t\t\tdb.BotLog.insert(id=target_fullname, module='perspective', created_utc=dt, action='removecomment', details=reason, author=comment.author, body=comment.body).execute()\n\n\t\t\tcomment.mod.remove()\n\n\treturn scores, all_scores\n\n# PRAW Processing\ndef process_comment(comment):\n\ttry:\n\t\tscores, all_scores = get_scores(comment)\n\texcept googleapiclient.errors.HttpError:\n\t\tout = '*[PERSPECTIVE]* Unable to get perspective on comment ' + comment.id\n\t\tlog('warn', out)\n\t\treturn\n\n\tif not scores:\n\t\treturn\n\n\tif not config['perspective']['report']:\n\t\treturn\n\n\tscore_text = []\n\n\tfor attr, score in scores.items():\n\t\tthreshold = config['perspective']['report'][attr]\n\t\ttext = \"*{}* ({:.2f}/{:.2f})\".format(attr, score, threshold)\n\t\tscore_text.append(text)\n\n\tlink_id = get_id(comment.link_id)\n\tout = \"*[PERSPECTIVE]* Comment ** by ** exceeds Perspective thresholds: {}\".format(config['subreddit'], link_id, comment.id, comment.id, comment.author, comment.author, ', '.join(score_text))\n\treply(config['perspective']['channel'], out)\n\t# log('info', out)\n\n\tdt = pendulum.from_timestamp(comment.created_utc, tz='UTC')\n\ttarget_fullname = 't1_' + comment.id\n\tdb.Perspective.insert(id=target_fullname, created_utc=dt, author=comment.author, scores=all_scores, body=comment.body).execute()\n\n\treturn\n","sub_path":"modules/perspective.py","file_name":"perspective.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"646690222","text":"import argparse\nimport os\n\nimport tensorflow as tf\n\nfrom six import text_type\nfrom six.moves import cPickle\n\nfrom model import Model\n\n\ndef main():\n tf.reset_default_graph() \n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n archivo = open(\"sentencia.txt\", \"r\") \n contenido = archivo.readlines()\n archivo.close()\n parser.add_argument('--save_dir', type=str, default='checkpoints',\n help='model directory to store checkpointed models')\n parser.add_argument('-n', type=int, default=380,\n help='number of characters to sample')\n #parser.add_argument('--prime', type=text_type, default=u'A row of motorcycles parked next to each other. ',\n parser.add_argument('--prime', type=text_type, default=contenido[0],\n help='prime text')\n parser.add_argument('--sample', type=int, default=1,\n help='0 to use max at each timestep, 1 to sample at '\n 'each timestep, 2 to sample on spaces')\n\n sample(parser.parse_args())\n\n\ndef sample(args):\n with open(os.path.join(args.save_dir, 'data\\conan\\config.pkl'), 'rb') as f:\n saved_args = cPickle.load(f)\n\n with open(os.path.join(args.save_dir, 'data\\conan\\chars_vocab.pkl'), 'rb') as f:\n chars, vocab = cPickle.load(f)\n\n model = Model(saved_args, training=False)\n #print(\"Hola\")\n with tf.Session() as sess:\n #print(\"Hola2\")\n tf.global_variables_initializer().run()\n saver = tf.train.Saver(tf.global_variables())\n #ckpt = tf.train.get_checkpoint_state(args.save_dir)\n ckpt = tf.train.get_checkpoint_state('checkpoints\\data\\conan\\data')\n #print(ckpt)\n #print(ckpt.model_checkpoint_path)\n if ckpt and ckpt.model_checkpoint_path:\n #print(\"Hola3\")\n saver.restore(sess, ckpt.model_checkpoint_path)\n samp = model.sample(sess, chars, vocab, args.n, args.prime, args.sample)\n #print(samp.encode('utf-8'))\n #print(\"Ejemplo: \"+str(samp.encode('utf-8')))\n print(\"Ejemplo: \"+str(samp)) \t\n archivo = open(\"broma.txt\",\"w\")\n archivo.write(samp)\n archivo.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"204082977","text":"# coding: utf-8\n'''\nCreated on 2014-10-08\n\n@author: Administrator\n''' \nfrom libs import web\nfrom core.modules.module_handle import api_handle\n\nfrom utils.func_api import FuncResult \nfrom core.log.logging_trace import log_trace \nfrom utils.tools import json_to_obj \nfrom libs.orm.ormutils import get_data_from_sql2\nfrom utils.crypt import des_encrypt,des_decrypt\nimport re\nfrom apps.crm.common.get_roomratetype import handler as rmrate_handler\n\nclass handler(object):\n '''查询会员\n ''' \n @api_handle(db=True) \n def GET(self): \n log_trace() \n input = web.input()\n query = json_to_obj(input.get('query')) or {}\n page_obj = json_to_obj(input.get('page')) or {}\n order = input.get('order')\n \n result = self.get_data(query, order, page_obj)\n\n return result\n \n \n def get_data(self, query, order, page_obj):\n \n grp_code = web.ctx.session.login_hotel_info['Group']['HotelGroupCode']\n \n params = ['a.HotelGroupCode =:HotelGroupCode']\n params_value = {'HotelGroupCode': grp_code}\n \n if query.has_key('smart_text') and query['smart_text']: \n if len(query['smart_text']) == 11 and query['smart_text'][0]=='1':\n params.append('a.ContractMobile = :Mobile')\n params_value['Mobile'] = des_encrypt(query['smart_text'])\n elif re.findall('[\\x80-\\xff].', str(query['smart_text'])):#中文,表示公司名称搜索\n params.append('a.AgreementName like :agr_name')\n params_value['agr_name'] = '%'+query['smart_text']+'%'\n elif len(query['smart_text']) < 11:\n params.append('a.ContractNo = :ContractNo')\n params_value['ContractNo'] = query['smart_text']\n \n else:\n begin_sign = query.get('begin_sign')\n end_sign = query.get('end_sign') \n begin_deadline = query.get('begin_deadline')\n end_deadline = query.get('end_deadline')\n seller_sign = query.get('seller_sign')\n seller_follow = query.get('seller_follow')\n industry = query.get('industry')\n roomratetype = query.get('roomratetype')\n mobile = query.get('mobile')\n tel = query.get('tel')\n state = query.get('state')\n \n if begin_sign and end_sign:\n params.append('a.CreateTime Between :begin_sign And :end_sign')\n params_value['begin_sign'] = begin_sign\n params_value['end_sign'] = end_sign\n \n if begin_deadline and end_deadline:\n params.append('a.DeadLine Between :begin_deadline And :end_deadline')\n params_value['begin_deadline'] = begin_deadline\n params_value['end_deadline'] = end_deadline\n \n if seller_sign:\n params.append('a.SignSellerID =:seller_sign')\n params_value['seller_sign'] = seller_sign\n \n if seller_follow:\n params.append('a.FollowSellerID =:seller_follow')\n params_value['seller_follow'] = seller_follow\n \n if industry:\n params.append('a.Industry =:industry')\n params_value['industry'] = industry\n \n if roomratetype:\n params.append('a.RoomRateTypeCode =:roomratetype')\n params_value['roomratetype'] = roomratetype\n \n if mobile:\n params.append('a.ContractMobile =:mobile')\n params_value['mobile'] = mobile\n \n if tel:\n params.append('a.Tel =:tel')\n params_value['tel'] = tel\n \n if state or state == 0:\n params.append('a.State =:state')\n params_value['state'] = state\n \n \n sql = ''' \n Select SQL_CALC_FOUND_ROWS\n a.AgreementID, a.AgreementName, a.CreateHotelCode, a.HotelGroupCode, a.ContractPersion, \n a.ContractMobile, a.ContractPosition, a.BusinessCode, a.AgreementType, a.LegalPerson, \n a.ContractNo, a.CreateTime, a.CreateUserCode, a.CreateUserName, a.RoomRateTypeCode,a.State\n From \n g_Agreement a\n '''\n\n ret = get_data_from_sql2(sql, params, params_value, order, '', page_obj).value\n \n if ret['data'] and len(ret['data'])>0:\n rmratetype = rmrate_handler().get_all_roomratetype(self)\n \n \n for d in ret['data']:\n rmrate = [r for r in rmratetype if r['RoomRateTypeCode'] == d['RoomRateTypeCode'] and r['HotelCode'] == d['CreateHotelCode']]\n if len(rmrate)>0:\n d['RoomRateName'] = rmrate[0]['RoomRateName']\n \n d['ContractMobile'] = des_decrypt(d['ContractMobile'])\n \n return FuncResult(success=True, value=ret)\n","sub_path":"crm/agreement/get_agreement_list.py","file_name":"get_agreement_list.py","file_ext":"py","file_size_in_byte":5112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"211461460","text":"import copy\nimport unittest\nfrom contextlib import contextmanager\nfrom io import StringIO\nfrom unittest import mock\n\nfrom django.db import DEFAULT_DB_ALIAS, connection, connections\nfrom django.db.backends.base.creation import (\n TEST_DATABASE_PREFIX, BaseDatabaseCreation,\n)\nfrom django.db.backends.mysql.creation import (\n DatabaseCreation as MySQLDatabaseCreation,\n)\nfrom django.db.backends.oracle.creation import (\n DatabaseCreation as OracleDatabaseCreation,\n)\nfrom django.db.utils import DatabaseError\nfrom django.test import SimpleTestCase, TestCase\n\ntry:\n import psycopg2 # NOQA\nexcept ImportError:\n pass\nelse:\n from psycopg2 import errorcodes\n from django.db.backends.postgresql.creation import \\\n DatabaseCreation as PostgreSQLDatabaseCreation\n\n\nclass TestDbSignatureTests(SimpleTestCase):\n\n def get_connection_copy(self):\n # Get a copy of the default connection. (Can't use django.db.connection\n # because it'll modify the default connection itself.)\n test_connection = copy.copy(connections[DEFAULT_DB_ALIAS])\n test_connection.settings_dict = copy.copy(connections[DEFAULT_DB_ALIAS].settings_dict)\n return test_connection\n\n def test_default_name(self):\n # A test db name isn't set.\n prod_name = 'hodor'\n test_connection = self.get_connection_copy()\n test_connection.settings_dict['NAME'] = prod_name\n test_connection.settings_dict['TEST'] = {'NAME': None}\n signature = BaseDatabaseCreation(test_connection).test_db_signature()\n self.assertEqual(signature[3], TEST_DATABASE_PREFIX + prod_name)\n\n def test_custom_test_name(self):\n # A regular test db name is set.\n test_name = 'hodor'\n test_connection = self.get_connection_copy()\n test_connection.settings_dict['TEST'] = {'NAME': test_name}\n signature = BaseDatabaseCreation(test_connection).test_db_signature()\n self.assertEqual(signature[3], test_name)\n\n def test_custom_test_name_with_test_prefix(self):\n # A test db name prefixed with TEST_DATABASE_PREFIX is set.\n test_name = TEST_DATABASE_PREFIX + 'hodor'\n test_connection = self.get_connection_copy()\n test_connection.settings_dict['TEST'] = {'NAME': test_name}\n signature = BaseDatabaseCreation(test_connection).test_db_signature()\n self.assertEqual(signature[3], test_name)\n\n\n@unittest.skipUnless(connection.vendor == 'postgresql', \"PostgreSQL-specific tests\")\nclass PostgreSQLDatabaseCreationTests(SimpleTestCase):\n\n @contextmanager\n def changed_test_settings(self, **kwargs):\n settings = connection.settings_dict['TEST']\n saved_values = {}\n for name in kwargs:\n if name in settings:\n saved_values[name] = settings[name]\n\n for name, value in kwargs.items():\n settings[name] = value\n try:\n yield\n finally:\n for name, value in kwargs.items():\n if name in saved_values:\n settings[name] = saved_values[name]\n else:\n del settings[name]\n\n def check_sql_table_creation_suffix(self, settings, expected):\n with self.changed_test_settings(**settings):\n creation = PostgreSQLDatabaseCreation(connection)\n suffix = creation.sql_table_creation_suffix()\n self.assertEqual(suffix, expected)\n\n def test_sql_table_creation_suffix_with_none_settings(self):\n settings = {'CHARSET': None, 'TEMPLATE': None}\n self.check_sql_table_creation_suffix(settings, \"\")\n\n def test_sql_table_creation_suffix_with_encoding(self):\n settings = {'CHARSET': 'UTF8'}\n self.check_sql_table_creation_suffix(settings, \"WITH ENCODING 'UTF8'\")\n\n def test_sql_table_creation_suffix_with_template(self):\n settings = {'TEMPLATE': 'template0'}\n self.check_sql_table_creation_suffix(settings, 'WITH TEMPLATE \"template0\"')\n\n def test_sql_table_creation_suffix_with_encoding_and_template(self):\n settings = {'CHARSET': 'UTF8', 'TEMPLATE': 'template0'}\n self.check_sql_table_creation_suffix(settings, '''WITH ENCODING 'UTF8' TEMPLATE \"template0\"''')\n\n def _execute_raise_database_already_exists(self, cursor, parameters, keepdb=False):\n error = DatabaseError('database %s already exists' % parameters['dbname'])\n error.pgcode = errorcodes.DUPLICATE_DATABASE\n raise DatabaseError() from error\n\n def _execute_raise_permission_denied(self, cursor, parameters, keepdb=False):\n error = DatabaseError('permission denied to create database')\n error.pgcode = errorcodes.INSUFFICIENT_PRIVILEGE\n raise DatabaseError() from error\n\n def patch_test_db_creation(self, execute_create_test_db):\n return mock.patch.object(BaseDatabaseCreation, '_execute_create_test_db', execute_create_test_db)\n\n @mock.patch('sys.stdout', new_callable=StringIO)\n @mock.patch('sys.stderr', new_callable=StringIO)\n def test_create_test_db(self, *mocked_objects):\n creation = PostgreSQLDatabaseCreation(connection)\n # Simulate test database creation raising \"database already exists\"\n with self.patch_test_db_creation(self._execute_raise_database_already_exists):\n with mock.patch('builtins.input', return_value='no'):\n with self.assertRaises(SystemExit):\n # SystemExit is raised if the user answers \"no\" to the\n # prompt asking if it's okay to delete the test database.\n creation._create_test_db(verbosity=0, autoclobber=False, keepdb=False)\n # \"Database already exists\" error is ignored when keepdb is on\n creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)\n # Simulate test database creation raising unexpected error\n with self.patch_test_db_creation(self._execute_raise_permission_denied):\n with self.assertRaises(SystemExit):\n creation._create_test_db(verbosity=0, autoclobber=False, keepdb=False)\n with self.assertRaises(SystemExit):\n creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)\n\n\n@unittest.skipUnless(connection.vendor == 'oracle', \"Oracle specific tests\")\n@mock.patch.object(OracleDatabaseCreation, '_maindb_connection', return_value=connection)\n@mock.patch('sys.stdout', new_callable=StringIO)\n@mock.patch('sys.stderr', new_callable=StringIO)\nclass OracleDatabaseCreationTests(TestCase):\n\n def _execute_raise_user_already_exists(self, cursor, statements, parameters, verbosity, allow_quiet_fail=False):\n # Raise \"user already exists\" only in test user creation\n if statements and statements[0].startswith('CREATE USER'):\n raise DatabaseError(\"ORA-01920: user name 'string' conflicts with another user or role name\")\n\n def _execute_raise_tablespace_already_exists(\n self, cursor, statements, parameters, verbosity, allow_quiet_fail=False\n ):\n raise DatabaseError(\"ORA-01543: tablespace 'string' already exists\")\n\n def _execute_raise_insufficient_privileges(\n self, cursor, statements, parameters, verbosity, allow_quiet_fail=False\n ):\n raise DatabaseError(\"ORA-01031: insufficient privileges\")\n\n def _test_database_passwd(self):\n # Mocked to avoid test user password changed\n return connection.settings_dict['SAVED_PASSWORD']\n\n def patch_execute_statements(self, execute_statements):\n return mock.patch.object(OracleDatabaseCreation, '_execute_statements', execute_statements)\n\n @mock.patch.object(OracleDatabaseCreation, '_test_user_create', return_value=False)\n def test_create_test_db(self, *mocked_objects):\n creation = OracleDatabaseCreation(connection)\n # Simulate test database creation raising \"tablespace already exists\"\n with self.patch_execute_statements(self._execute_raise_tablespace_already_exists):\n with mock.patch('builtins.input', return_value='no'):\n with self.assertRaises(SystemExit):\n # SystemExit is raised if the user answers \"no\" to the\n # prompt asking if it's okay to delete the test tablespace.\n creation._create_test_db(verbosity=0, keepdb=False)\n # \"Tablespace already exists\" error is ignored when keepdb is on\n creation._create_test_db(verbosity=0, keepdb=True)\n # Simulate test database creation raising unexpected error\n with self.patch_execute_statements(self._execute_raise_insufficient_privileges):\n with self.assertRaises(SystemExit):\n creation._create_test_db(verbosity=0, keepdb=False)\n with self.assertRaises(SystemExit):\n creation._create_test_db(verbosity=0, keepdb=True)\n\n @mock.patch.object(OracleDatabaseCreation, '_test_database_create', return_value=False)\n def test_create_test_user(self, *mocked_objects):\n creation = OracleDatabaseCreation(connection)\n with mock.patch.object(OracleDatabaseCreation, '_test_database_passwd', self._test_database_passwd):\n # Simulate test user creation raising \"user already exists\"\n with self.patch_execute_statements(self._execute_raise_user_already_exists):\n with mock.patch('builtins.input', return_value='no'):\n with self.assertRaises(SystemExit):\n # SystemExit is raised if the user answers \"no\" to the\n # prompt asking if it's okay to delete the test user.\n creation._create_test_db(verbosity=0, keepdb=False)\n # \"User already exists\" error is ignored when keepdb is on\n creation._create_test_db(verbosity=0, keepdb=True)\n # Simulate test user creation raising unexpected error\n with self.patch_execute_statements(self._execute_raise_insufficient_privileges):\n with self.assertRaises(SystemExit):\n creation._create_test_db(verbosity=0, keepdb=False)\n with self.assertRaises(SystemExit):\n creation._create_test_db(verbosity=0, keepdb=True)\n\n\n@unittest.skipUnless(connection.vendor == 'mysql', \"MySQL specific tests\")\nclass MySQLDatabaseCreationTests(SimpleTestCase):\n\n def _execute_raise_database_exists(self, cursor, parameters, keepdb=False):\n raise DatabaseError(1007, \"Can't create database '%s'; database exists\" % parameters['dbname'])\n\n def _execute_raise_access_denied(self, cursor, parameters, keepdb=False):\n raise DatabaseError(1044, \"Access denied for user\")\n\n def patch_test_db_creation(self, execute_create_test_db):\n return mock.patch.object(BaseDatabaseCreation, '_execute_create_test_db', execute_create_test_db)\n\n @mock.patch('sys.stdout', new_callable=StringIO)\n @mock.patch('sys.stderr', new_callable=StringIO)\n def test_create_test_db_database_exists(self, *mocked_objects):\n # Simulate test database creation raising \"database exists\"\n creation = MySQLDatabaseCreation(connection)\n with self.patch_test_db_creation(self._execute_raise_database_exists):\n with mock.patch('builtins.input', return_value='no'):\n with self.assertRaises(SystemExit):\n # SystemExit is raised if the user answers \"no\" to the\n # prompt asking if it's okay to delete the test database.\n creation._create_test_db(verbosity=0, autoclobber=False, keepdb=False)\n # \"Database exists\" shouldn't appear when keepdb is on\n creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)\n\n @mock.patch('sys.stdout', new_callable=StringIO)\n @mock.patch('sys.stderr', new_callable=StringIO)\n def test_create_test_db_unexpected_error(self, *mocked_objects):\n # Simulate test database creation raising unexpected error\n creation = MySQLDatabaseCreation(connection)\n with self.patch_test_db_creation(self._execute_raise_access_denied):\n with self.assertRaises(SystemExit):\n creation._create_test_db(verbosity=0, autoclobber=False, keepdb=False)\n","sub_path":"django/tests/backends/test_creation.py","file_name":"test_creation.py","file_ext":"py","file_size_in_byte":12240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"527650723","text":"# first in, last out \n# last in, first out\n\nclass Stack:\n\tdef __init__(self):\n\t\tself.items = []\n\n\tdef is_empty(self):\n\t\treturn len(self.items) == 0\n\n\tdef push(self, item):\n\t\tself.items.append(item)\n\n\tdef pop(self):\n\t\treturn self.items.pop()\n\n\tdef peek(self):\n\t\treturn self.items[len(self.items) - 1]\n\n\tdef size(self):\n\t\treturn len(self.items)\n\nOPEN_PARENS = \"{[(\"\nCLOSE_PARENS = \"}])\"\n\ndef check_paren(string):\n\tglobal OPEN_PARENS, CLOSE_PARENS\n\n\tstack = Stack()\n\n\tfor char in string:\n\t\tif char in OPEN_PARENS:\n\t\t\topen_paren = char\n\t\t\t# push the open_paren into the stack\n\t\t\tstack.push(open_paren)\n\t\telif char in CLOSE_PARENS:\n\t\t\tclose_paren = char\n\t\t\t# grab the last item in the stack \n\t\t\t# and check if the paren is an opening paren to the closing paren\n\t\t\topen_paren = stack.pop()\n\t\t\tif not parens_match(open_paren, close_paren):\n\t\t\t\treturn False\n\n\t# if all the parens matched, the stack is empty\n\treturn stack.is_empty()\n\n\ndef parens_match(open_paren, close_paren):\n\tglobal OPEN_PARENS, CLOSE_PARENS\t\n\treturn OPEN_PARENS.index(open_paren) == CLOSE_PARENS.index(close_paren)\n\n\nif __name__ == \"__main__\":\n\tbalanced_1 = \"{ { ( [ ] [ ] ) } ( ) }\"\n\tbalanced_2 = \"[ [ { { ( ( ) ) } } ] ]\"\n\tbalanced_3 = \"[ ] [ ] [ ] ( ) { }\"\n\n\tbalanced_4 = \"abc\"\n\tbalanced_5 = \"\"\n\tbalanced_6 = \"{ { (x, [1, 2], [3, 4], y) }, (a, b) }\"\n\n\tinbalanced_1 = \"( [ ) ]\"\n\tinbalanced_2 = \"( ( ( ) ] ) )\"\n\tinbalanced_3 = \"[ { ( ) ]\"\n\n\tprint(\"Is \\\"{}\\\" balanced? {}\".format(balanced_1, check_paren(balanced_1)))\n\tprint(\"Is \\\"{}\\\" balanced? {}\".format(balanced_2, check_paren(balanced_2)))\n\tprint(\"Is \\\"{}\\\" balanced? {}\".format(balanced_3, check_paren(balanced_3)))\n\tprint(\"Is \\\"{}\\\" balanced? {}\".format(balanced_4, check_paren(balanced_4)))\n\tprint(\"Is \\\"{}\\\" balanced? {}\".format(balanced_5, check_paren(balanced_5)))\n\tprint(\"Is \\\"{}\\\" balanced? {}\".format(balanced_6, check_paren(balanced_6)))\n\tprint(\"Is \\\"{}\\\" balanced? {}\".format(inbalanced_1, check_paren(inbalanced_1)))\n\tprint(\"Is \\\"{}\\\" balanced? {}\".format(inbalanced_2, check_paren(inbalanced_2)))\n\tprint(\"Is \\\"{}\\\" balanced? {}\".format(inbalanced_3, check_paren(inbalanced_3)))","sub_path":"data_structures/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"567416748","text":"# -*- coding: utf-8 -*-\nimport sys\nfrom os.path import abspath, dirname\nsys.path.insert(0, dirname(abspath(__file__)))\nimport bar\nimport time\nimport queue\nimport const as ct\nimport dataFramefeed\nfrom base.clog import getLogger\nfrom futu.common.constant import SubType\nfrom datetime import timedelta, datetime\nfrom pyalgotrade.dataseries import DEFAULT_MAX_LEN\nfrom algotrade.broker.futu.subscriber import Subscriber\nfrom base.base import PollingThread, localnow, get_today_time\nON_END = 1\nON_BARS = 2\nclass GetBarThread(PollingThread):\n def __init__(self, mqueue, identifiers, start_time, end_time, frequency, timezone):\n PollingThread.__init__(self)\n self.logger = getLogger(__name__)\n self.__queue = mqueue\n self.__start_time = get_today_time(start_time)\n self.__end_time = get_today_time(end_time)\n self.__timezone = timezone\n self.__frequency = frequency\n self.__identifiers = identifiers \n self.__subscriber = Subscriber()\n self.__next_call_time = localnow(self.__timezone)\n self.__last_response_time = localnow(self.__timezone)\n\n def getNextCallDateTime(self):\n self.__next_call_time = max(localnow(self.__timezone), self.__next_call_time + self.__frequency)\n return self.__next_call_time\n\n def build_bar(self, quote_dict, order_dict):\n time_str = \"{} {}\".format(quote_dict[\"date\"][0], quote_dict[\"time\"][0])\n sdatetime = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')\n if self.__last_response_time >= sdatetime: return None\n self.__last_response_time = sdatetime\n return bar.BasicTick(sdatetime, quote_dict['open'][0], quote_dict['high'][0], quote_dict['low'][0], quote_dict['close'][0], quote_dict['preclose'][0], quote_dict['volume'][0], quote_dict['amount'][0],\n order_dict['Bid'][0][0], order_dict['Bid'][0][1], order_dict['Bid'][1][0], order_dict['Bid'][1][1], order_dict['Bid'][2][0], order_dict['Bid'][2][1], order_dict['Bid'][3][0], order_dict['Bid'][3][1], order_dict['Bid'][4][0], order_dict['Bid'][4][1],\n order_dict['Ask'][0][0], order_dict['Ask'][0][1], order_dict['Ask'][1][0], order_dict['Ask'][1][1], order_dict['Ask'][2][0], order_dict['Ask'][2][1], order_dict['Ask'][3][0], order_dict['Ask'][3][1], order_dict['Ask'][4][0], order_dict['Ask'][4][1],\n bar.Frequency.TRADE)\n\n def doCall(self):\n bar_dict = {}\n for identifier in self.__identifiers:\n quote_ret, quote_data = self.__subscriber.get_quote_data(identifier)\n order_ret, order_data = self.__subscriber.get_order_book_data(identifier)\n if 0 == order_ret and 0 == quote_ret:\n quote_data = quote_data[['data_date', 'data_time', 'open_price', 'high_price', 'low_price', 'last_price', 'prev_close_price', 'volume', 'turnover']]\n quote_data = quote_data.rename(columns = {\"data_date\": \"date\", \"data_time\": \"time\", \"open_price\": \"open\", \"high_price\": \"high\", \"low_price\": \"low\", \"last_price\": \"close\", \"prev_close_price\": \"preclose\", \"turnover\": \"amount\"})\n res = self.build_bar(quote_data.to_dict(), order_data)\n if res is not None: bar_dict[identifier] = res\n if len(bar_dict) > 0:\n bars = bar.Ticks(bar_dict)\n self.__queue.put((ON_BARS, bars))\n if localnow(self.__timezone) >= self.__end_time:\n self.stop()\n\n def init_instruments(self):\n quote_ret = self.__subscriber.subscribe(self.__identifiers, SubType.QUOTE)\n order_ret = self.__subscriber.subscribe(self.__identifiers, SubType.ORDER_BOOK)\n if 0 != order_ret or 0 != quote_ret: return False\n return True\n\n def wait(self):\n next_call_time = self.getNextCallDateTime()\n begin_time = localnow(self.__timezone)\n while not self.stopped and localnow(self.__timezone) < next_call_time:\n time.sleep((next_call_time - begin_time).seconds)\n\n def start(self):\n if not self.__subscriber.status(): self.__subscriber.start(host = ct.FUTU_HOST_LOCAL)\n if not self.init_instruments(): raise Exception(\"instruments subscribe failed\")\n PollingThread.start(self)\n\n def run(self):\n while not self.stopped:\n self.wait()\n if not self.stopped:\n try:\n self.doCall()\n except Exception as e:\n self.logger.error(\"unhandled exception:{}\".format(e))\n\n def stop(self):\n PollingThread.stop(self)\n self.__subscriber.stop()\n self.__subscriber.close()\n\nclass FutuFeed(dataFramefeed.TickFeed):\n \"\"\"\n a real-time BarFeed that builds bars using futu api\n :param identifiers: codes\n :param frequency 每隔几秒钟请求一次,默认3秒钟\n :param maxLen:\n \"\"\"\n def __init__(self, identifiers, timezone, dealtime, frequency = 3, maxLen = DEFAULT_MAX_LEN):\n dataFramefeed.TickFeed.__init__(self, bar.Frequency.TRADE, None, maxLen)\n if not isinstance(identifiers, list): raise Exception(\"identifiers must be a list\")\n self.__timezone = timezone\n self.__queue = queue.Queue()\n self.__start_time = dealtime['start']\n self.__end_time = dealtime['end']\n self.logger = getLogger(__name__)\n self.__thread = GetBarThread(self.__queue, identifiers, self.__start_time, self.__end_time, timedelta(seconds = frequency), self.__timezone)\n for instrument in identifiers: self.registerInstrument(instrument)\n\n def start(self):\n if self.__thread.is_alive(): raise Exception(\"already strated\")\n self.__thread.start()\n\n def stop(self):\n self.__thread.stop()\n\n def join(self):\n if self.__thread.is_alive():\n self.__thread.join()\n\n def eof(self):\n return self.__thread.stopped\n\n def peekDateTime(self):\n return dataFramefeed.TickFeed.peekDateTime(self)\n\n def getCurrentDateTime(self):\n return localnow(self.__timezone)\n\n def barsHaveAdjClose(self):\n return False\n\n def getNextBars(self):\n ret = None\n try:\n eventType, eventData = self.__queue.get(True, ct.QUEUE_TIMEOUT)\n if eventType == ON_BARS:\n ret = eventData\n elif eventType == ON_END:\n ret = eventData\n self.stop()\n else:\n self.logger.error(\"invalid event received: {}-{}\".format(eventType, eventData))\n except queue.Empty:\n self.logger.debug(\"get empty queue\")\n return ret\n","sub_path":"algotrade/feed/futufeed.py","file_name":"futufeed.py","file_ext":"py","file_size_in_byte":6656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"220559923","text":"from configparser import ConfigParser\n\nenvironments_object = ConfigParser()\nenvironments_object.read(\"/opt/sixfab/.env\")\n\ndef config_object_to_string(config_object):\n cache_string = \"\"\n \n def _section_parser(section_name):\n nonlocal cache_string\n nonlocal config_object\n\n cache_string += f\"[{section_name}]\\n\"\n\n for key, value in config_object[section_name].items():\n cache_string += f\"{key.upper()}={value}\\n\"\n\n cache_string += \"\\n\"\n\n for section in config_object.sections():\n _section_parser(section)\n\n return cache_string\n","sub_path":"core/helpers/configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"430017841","text":"from flask import Flask,jsonify,request\r\nimport json\r\napp = Flask(__name__)\r\n\r\nusers=[\r\n {\r\n 'sNo': 1,\r\n 'firstName': 'Daniel',\r\n 'lastName': 'Green',\r\n 'email': 'Daniel.Green@test.com'\r\n },\r\n {\r\n 'sNo': 2,\r\n 'firstName': 'Rickey',\r\n 'lastName': 'Avant',\r\n 'email': 'Rickey.Avant@test.com'\r\n },\r\n {\r\n 'sNo': 3,\r\n 'firstName': 'Pamela',\r\n 'lastName': 'Nash',\r\n 'email': 'Pamela.Nash@test.com'\r\n },\r\n {\r\n 'sNo': 4,\r\n 'firstName': 'Juanita',\r\n 'lastName': 'Cole',\r\n 'email': 'Juanita.Cole@test.com'\r\n },\r\n {\r\n 'sNo': 5,\r\n 'firstName': 'John',\r\n 'lastName': 'Nolan',\r\n 'email': 'John.Nolan@test.com'\r\n },\r\n {\r\n 'sNo': 6,\r\n 'firstName': 'Francisco',\r\n 'lastName': 'Kazee',\r\n 'email': 'Francisco.Kazee@test.com'\r\n },\r\n {\r\n 'sNo': 7,\r\n 'firstName': 'Oscar',\r\n 'lastName': 'Huggins',\r\n 'email': 'Oscar.Huggins@test.com'\r\n },\r\n {\r\n 'sNo': 8,\r\n 'firstName': 'Micheal',\r\n 'lastName': 'Reynolds',\r\n 'email': 'Micheal.Reynolds@test.com'\r\n },\r\n {\r\n 'sNo': 9,\r\n 'firstName': 'Daniel',\r\n 'lastName': 'Gomes',\r\n 'email': 'Daniel.Gomes@test.com'\r\n },\r\n {\r\n 'sNo': 10,\r\n 'firstName': 'Julia',\r\n 'lastName': 'Baker',\r\n 'email': 'Julia.Baker@test.com'\r\n },\r\n {\r\n 'sNo': 11,\r\n 'firstName': 'Dorothy',\r\n 'lastName': 'Eanes',\r\n 'email': 'Dorothy.Eanes@test.com'\r\n },\r\n {\r\n 'sNo': 12,\r\n 'firstName': 'Jose',\r\n 'lastName': 'Stevenson',\r\n 'email': 'Jose.Stevenson@test.com'\r\n },\r\n {\r\n 'sNo': 13,\r\n 'firstName': 'Earnestine',\r\n 'lastName': 'Hunt',\r\n 'email': 'Earnestine.Hunt@test.com'\r\n },\r\n {\r\n 'sNo': 14,\r\n 'firstName': 'Norman',\r\n 'lastName': 'Mack',\r\n 'email': 'Norman.Mack@test.com'\r\n },\r\n {\r\n 'sNo': 15,\r\n 'firstName': 'Patricia',\r\n 'lastName': 'Poling',\r\n 'email': 'Patricia.Poling@test.com'\r\n },\r\n {\r\n 'sNo': 16,\r\n 'firstName': 'Stephen',\r\n 'lastName': 'Kym',\r\n 'email': 'Stephen.Kym@test.com'\r\n },\r\n {\r\n 'sNo': 17,\r\n 'firstName': 'Earl',\r\n 'lastName': 'Robinson',\r\n 'email': 'Earl.Robinson@test.com'\r\n },\r\n {\r\n 'sNo': 18,\r\n 'firstName': 'Jacob',\r\n 'lastName': 'Smith',\r\n 'email': 'Jacob.Smith@test.com'\r\n },\r\n {\r\n 'sNo': 19,\r\n 'firstName': 'Terri',\r\n 'lastName': 'Gartrell',\r\n 'email': 'Terri.Gartrell@test.com'\r\n },\r\n {\r\n 'sNo': 20,\r\n 'firstName': 'Mamie',\r\n 'lastName': 'Diaz',\r\n 'email': 'Mamie.Diaz@test.com'\r\n },\r\n {\r\n 'sNo': 21,\r\n 'firstName': 'Janette',\r\n 'lastName': 'Spring',\r\n 'email': 'Janette.Spring@test.com'\r\n },\r\n {\r\n 'sNo': 22,\r\n 'firstName': 'Lisa',\r\n 'lastName': 'Lawler',\r\n 'email': 'Lisa.Lawler@test.com'\r\n },\r\n {\r\n 'sNo': 23,\r\n 'firstName': 'James',\r\n 'lastName': 'Martinez',\r\n 'email': 'James.Martinez@test.com'\r\n },\r\n {\r\n 'sNo': 24,\r\n 'firstName': 'Thomas',\r\n 'lastName': 'Hockensmith',\r\n 'email': 'Thomas.Hockensmith@test.com'\r\n }\r\n ]\r\n \r\n@app.route(\"/users\",methods=['GET'])\r\ndef get_userByEmail():\r\n param = request.args.get('email')\r\n param2 = request.args.get('firstName')\r\n param3 = request.args.get('lastName')\r\n for i in users:\r\n if not param == None and i['email'] == param:\r\n return jsonify(i)\r\n elif not param2 == None and i['firstName'] == param2:\r\n return jsonify(i)\r\n elif not param3 == None and i['lastName'] == param3:\r\n return jsonify(i)\r\n return jsonify({'errCode':404,'errMsg':'Record not found'})\r\n\r\n\r\n@app.route(\"/users/pages\",methods=['GET'])\r\ndef get_userByPage():\r\n page_no = request.args.get('page')\r\n page_no = int(page_no)\r\n if len(users) > (page_no-1)*10 or len(users) < page_no*10:\r\n res_list = users[(page_no-1)*10:page_no*10]\r\n if len(res_list) > 0:\r\n return jsonify(res_list)\r\n else: \r\n return jsonify({'errCode':404,'errMsg':'Records Exhausted'})\r\n \r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n\r\n\r\n\r\n","sub_path":"Assignment/rest_api.py","file_name":"rest_api.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"224686467","text":"string1 = 'some text'\r\nstring2 = \"어떤 텍스트\"\r\nstring3 = '{}도 {}도 지금 이것도 문자열'.format(string1, string2)\r\nprint(string1, string2, string3)\r\n\r\nquote = '테스트 \" 테스트\" '\r\nemphasize = \"테스트중입 '니다' \"\r\nprint(quote)\r\nprint(emphasize)\r\n\r\nlong_string = '''테에에\r\n에엥?'''\r\n\r\nprint(long_string)\r\n\r\nquote1 = \"가끔은 '와\"+ '\"를 모두 쓰기도 해'\r\nprint(quote1)","sub_path":"Python/quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"240630374","text":"from math import sqrt\n\nn = int(input())\nl=[]\n\nfor i in range(2, int(sqrt(n))+2):\n\tif n%i==0 and i not in l:\n\t\tl.append(i)\nfor i in reversed(l):\n\tif n/i not in l:\n\t\tl.append(int(n/i))\nprint(l)\n","sub_path":"divisors.py","file_name":"divisors.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"459224183","text":"__version__ = 1.0\n__author__ = \"Tozammel Hossain, Shuyang Gao\"\n__email__ = \"tozammel@isi.edu, sgao@isi.edu\"\n\nimport pandas as pd\nfrom model.model_evaluation import ModelEvaluation\nfrom datetime import datetime, timedelta\n\n\nclass GroundTruth(object):\n def fit(self, df):\n self.train_start_date = min(df['date'])\n self.train_end_date = max(df['date'])\n self.rate = float(df['count'].sum()) / float(len(df['count']))\n\n def make_future_dataframe(self, periods=0):\n date = []\n cur_date = self.train_end_date\n for i in range(periods):\n cur_date = cur_date + timedelta(days=1)\n date.append(cur_date)\n return pd.DataFrame({'date': date})\n\n def predict(self, future):\n count = []\n for i in range(len(future['date'])):\n count.append(self.rate)\n future['count'] = count\n return future\n\n def do_evaluation(self, model_evaluation, round_value=False,\n make_nonnegative=False):\n ground_truth = model_evaluation.ts_test\n model_evaluation.evaluate(ground_truth, ground_truth)\n","sub_path":"model/groundtruth/groundtruth.py","file_name":"groundtruth.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"53169349","text":"import sys\n\n##Returns the array element that is repeated the most\n##Does this in O(n^2)\ndef Algo_X(A):\n x = 0\n y = 0\n for i in range(1,len(A)):\n k = 1\n for j in range(i+1,len(A)):\n if A[i] == A[j]:\n k += 1\n if x < k:\n x = k\n y = A[i]\n return y\n\ndef Better_Algo_X(A):\n A.sort() ##O(n) or O(nlog(n))\n k = 1\n B = []\n i = 0\n while i < len(A): ##O(n)\n j = i+1\n if A[i] == A[j]:\n k += 1\n j += 1\n else:\n i = j\n B.append(k)\n k = 1\n return max(B) ##O(n)\n\nA = [7, 20, 1, 3, 4, 3, 31, 50, 9, 11]\nprint(Algo_X(A))\nprint(Better_Algo_X(A))\n","sub_path":"Algorithms and Data Structures/Python Exercises/Exercise_207.py","file_name":"Exercise_207.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"594399030","text":"from sklearn.ensemble import GradientBoostingClassifier\nimport pandas as pd\nimport numpy as np\nimport sys\nimport os\nfrom sklearn.metrics import precision_score, recall_score, accuracy_score, f1_score, roc_auc_score\n\nimport json\nimport traceback\nimport joblib\n\n\nclass Result:\n precision_score=0\n recall_score=0\n accuracy_score=0\n f1_score=0\n roc_auc_score=0\n\npath='F:/Last_Test/test3'#特征提取后的数据集\ndir_test=os.listdir(path)\ndir_test.sort(key =lambda x:int(x[4:-4]))\ninput_file=[os.path.join(r'F:/Last_Test/test3',name) for name in dir_test]#特征提取后的数据集\noutput_file=[os.path.join(r'F:/Last_Test/test5',name) for name in dir_test]#故障诊断之后数据集的存放位置\nfor x in range(0,len(input_file)):\n params = {}\n params['model'] = 'F:/Last_Python/code1/GBDT_model9.model'\n params['test'] = input_file[x]\n params['opath'] = output_file[x]\n argvs = sys.argv\n try:\n for i in range(len(argvs)):\n if i < 1:\n continue\n if argvs[i].split('=')[1] == 'None':\n params[argvs[i].split('=')[0]] = None\n else:\n Type = type(params[argvs[i].split('=')[0]])\n params[argvs[i].split('=')[0]] = Type(argvs[i].split('=')[1])\n\n model = joblib.load(params['model'])\n \n test1 = pd.DataFrame(pd.read_csv(params['test']))\n \n test_x = test1.drop(['label'],axis=1)\n y_pred = model.predict_proba(test_x)\n \n y_pred = model.predict(test_x)\n\n predict=np.array(y_pred)\n test=['TEST'+str(x+1)]*len(predict)\n\n predict=list(predict)\n file_data=pd.DataFrame(predict,columns=['label'])\n file_test=pd.DataFrame(test,columns=['filename'])\n file_all=file_data.join(file_test,how='outer')\n file_all.to_csv(output_file[x],index=False)\n except Exception as e:\n traceback.print_exc()\n","sub_path":"GBDT.py","file_name":"GBDT.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"335227388","text":"from typing import Dict, List, NamedTuple, Optional, Callable, Tuple, Any\n\nimport os\nimport sys\nimport importlib\nimport math\nimport warnings\nimport functools\nimport logging\nimport operator\nfrom argparse import Namespace\n\nfrom mindspore.common.tensor import Tensor\nfrom mindspore.ops import Pow\nfrom mindspore.ops import operations as P\nfrom mindspore.ops import functional as F\nimport mindspore.nn as nn\n\nfrom mindspore.common.parameter import Parameter\nfrom mindspore.common.initializer import initializer, XavierUniform, Normal, Constant\nimport mindspore.common.dtype as mstype\n\nimport numpy as np\nimport random\nimport uuid\n\nfrom mindspore.ops import Fill, Zeros, NotEqual, CumSum, \\\n Concat, matmul, Pad, ExpandDims, Softmax, Dropout, \\\n ReduceSum, ReLU, repeat_elements, Softmax, LogSoftmax, ReduceMean, Equal, ReduceAny\n\nfrom mindspore.ops import operations as P\nops_cast = P.Cast()\n\nEncoderOut = NamedTuple(\n \"EncoderOut\",\n [\n (\"encoder_out\", Tensor), # T x B x C\n (\"encoder_padding_mask\", Optional[Tensor]), # B x T\n (\"encoder_embedding\", Optional[Tensor]), # B x T x C\n (\"encoder_states\", Optional[List[Tensor]]), # List[T x B x C]\n (\"src_tokens\", Optional[Tensor]), # B x T\n (\"src_lengths\", Optional[Tensor]), # B x 1\n ],\n)\n\nlogger = logging.getLogger(__name__)\n\ndef get_available_activation_fns() -> List:\n return [\n \"relu\",\n \"gelu\",\n # \"gelu_fast\", # deprecated\n # \"gelu_accurate\",\n \"tanh\",\n \"linear\",\n ]\n\ndef item(tensor):\n if hasattr(tensor, \"item\"):\n return tensor.item()\n if hasattr(tensor, \"__getitem__\"):\n return tensor[0]\n return tensor\n\nclass LayerNorm(nn.Cell):\n \"\"\"\n Layer Normalization\n\n Args:\n normalized_shape: the corresponding shape of the normalized axes\n eps: epsilon, a small number avoiding zero division\n\n Inputs:\n x: input tensor\n\n Returns:\n rescaled_output: Tensor, returned tensor after layernorm\n \"\"\"\n def __init__(self, normalized_shape, eps=1e-5):\n super(LayerNorm, self).__init__()\n self.gamma = Parameter(initializer('ones', normalized_shape))\n self.beta = Parameter(initializer('zeros', normalized_shape))\n self.mean = P.ReduceMean(keep_dims=True)\n self.eps = eps\n\n def construct(self, x):\n mean = self.mean(x, -1)\n variance = self.mean(F.square(x - mean), -1)\n output = (x - mean) / F.sqrt(variance + self.eps)\n rescaled_output = output * self.gamma + self.beta\n return rescaled_output\n\ndef gelu():\n return nn.GELU()\n\ndef relu():\n return ReLU()\n\ndef softmax(x, dim=-1):\n softmax_ops = Softmax(axis=dim)\n return softmax_ops(x)\n\ndef log_softmax(x, dim=-1):\n logsoftmax_ops = LogSoftmax(axis=dim)\n return logsoftmax_ops(x)\n\ndef Linear(in_features, out_features, bias=True):\n m = nn.Dense(in_features, out_features, bias)\n # nn.init.xavier_uniform_(m.weight)\n # print(m.weight.asnumpy())\n m.weight = Parameter(initializer(XavierUniform(gain=1), [out_features, in_features]))\n if bias:\n m.bias = Parameter(initializer(\"zeros\", out_features))\n # nn.init.constant_(m.bias, 0.0)\n return m\n\ndef masked_fill(weights, mask, unsqueeze_ops, value='-inf'):\n mask = mask * 1\n unsqueeze_key_padding_mask = unsqueeze_ops(unsqueeze_ops(mask, 1), 2)\n # print(weights.shape, unsqueeze_key_padding_mask.shape)\n Inversed_unsqueeze_key_padding_mask = 1 - unsqueeze_key_padding_mask\n\n # make inf matrix shape like attn_output_weights\n tmp_infMatrix = Tensor(np.ones(weights.shape), weights.dtype)\n # using -1e10 to replace -inf, because 0 * -inf = nan\n tmp_infMatrix_inf = fill_with_neg_inf(tmp_infMatrix, value)\n tmp_infMatrix_inf = tmp_infMatrix_inf * unsqueeze_key_padding_mask\n need2convertinf_attn_output_weights = weights * tmp_infMatrix_inf\n keep_attn_output_weights = weights * Inversed_unsqueeze_key_padding_mask\n attn_output_weights = need2convertinf_attn_output_weights + keep_attn_output_weights\n return attn_output_weights\n\ndef masked_fill_withzero(weights, mask, unsqueeze_ops, value='-inf'):\n mask = mask * 1\n unsqueeze_key_padding_mask = mask\n Inversed_unsqueeze_key_padding_mask = 1 - unsqueeze_key_padding_mask\n\n # make inf matrix shape like attn_output_weights\n tmp_infMatrix = Tensor(np.ones(weights.shape), weights.dtype)\n # using -1e10 to replace -inf, because 0 * -inf = nan\n tmp_infMatrix_inf = fill_with_neg_inf(tmp_infMatrix, value)\n tmp_infMatrix_inf = tmp_infMatrix_inf * unsqueeze_key_padding_mask\n need2convertinf_attn_output_weights = weights * tmp_infMatrix_inf\n keep_attn_output_weights = weights * Inversed_unsqueeze_key_padding_mask\n attn_output_weights = need2convertinf_attn_output_weights + keep_attn_output_weights\n return attn_output_weights\n\ndef mindspore_linear(input, weight, bias=None):\n tens_ops = (input, weight)\n if input.dim() == 2 and bias is not None:\n # fused op is marginally faster\n tmp = matmul(input, weight.T)\n ret = bias + tmp\n # ret = torch.addmm(bias, input, weight.T)\n else:\n # print(input.shape, weight.shape) # [61, 24, 1024], [1024, 1024]\n output = matmul(input, weight.T)\n if bias is not None:\n output += bias\n ret = output\n return ret\n\ndef deprecation_warning(message, stacklevel=3):\n # don't use DeprecationWarning, since it's ignored by default\n warnings.warn(message, stacklevel=stacklevel)\n\ndef get_activation_fn(activation: str) -> Callable:\n \"\"\" Returns the activation function corresponding to `activation` \"\"\"\n if activation == \"relu\":\n return relu()\n elif activation == \"gelu\":\n return gelu()\n elif activation == \"tanh\":\n return nn.Tanh\n elif activation == \"linear\":\n return lambda x: x\n else:\n raise RuntimeError(\"--activation-fn {} not supported\".format(activation))\n\ndef make_positions(tensor, padding_idx: int, onnx_trace: bool = False):\n \"\"\"Replace non-padding symbols with their position numbers.\n\n Position numbers begin at padding_idx+1. Padding symbols are ignored.\n \"\"\"\n # The series of casts and type-conversions here are carefully\n # balanced to both work with ONNX export and XLA. In particular XLA\n # prefers ints, cumsum defaults to output longs, and ONNX doesn't know\n # how to handle the dtype kwarg in cumsum.\n\n cumsum = CumSum()\n mask = (tensor == padding_idx)\n\n # mask = mask * 1\n # mask.set_dtype(mstype.int32)\n mask = ops_cast(mask, mstype.int32)\n\n mask = 1 - mask\n # tmp = CumSum(mask, axis=1).type_as(mask) * mask\n tmp = cumsum(mask, 1) * mask + padding_idx\n return tmp\n\ndef fill_with_neg_inf(t, value='-inf'):\n \"\"\"FP16-compatible function that fills a tensor with -inf.\"\"\"\n fill = Fill()\n # return fill(mstype.float32, t.shape, float(\"-inf\"))\n # 0 * -inf = Nan !!!!!!!!!!!!\n if value == '-inf':\n return fill(mstype.float32, t.shape, float(-1e10))\n elif value == 0:\n return fill(mstype.float32, t.shape, float(0))\n\ndef PositionalEmbedding(\n num_embeddings: int,\n embedding_dim: int,\n padding_idx: int,\n learned: bool = False,\n):\n if learned:\n # if padding_idx is specified then offset the embedding ids by\n # this index and adjust num_embeddings appropriately\n # TODO: The right place for this offset would be inside\n # LearnedPositionalEmbedding. Move this there for a cleaner implementation.\n if padding_idx is not None:\n num_embeddings = num_embeddings + padding_idx + 1\n m = LearnedPositionalEmbedding(num_embeddings, embedding_dim)\n m.embedding_table = Parameter(initializer(Normal(sigma=258 ** -0.5), [258, 1024]))\n if padding_idx is not None:\n m.embedding_table[padding_idx] = Parameter(initializer(Constant(value=0), [1, 1024]))\n # nn.init.constant_(m.weight[padding_idx], 0)\n else:\n assert 'ERROR'\n return m\n\ndef eval_str_list(x, type=float):\n if x is None:\n return None\n if isinstance(x, str):\n x = eval(x)\n try:\n return list(map(type, x))\n except TypeError:\n return [type(x)]\n\ndef import_user_module(args):\n module_path = getattr(args, \"user_dir\", None)\n if module_path is not None:\n module_path = os.path.abspath(args.user_dir)\n if not os.path.exists(module_path):\n fairseq_rel_path = os.path.join(os.path.dirname(__file__), args.user_dir)\n if os.path.exists(fairseq_rel_path):\n module_path = fairseq_rel_path\n else:\n fairseq_rel_path = os.path.join(\n os.path.dirname(__file__), \"..\", args.user_dir\n )\n if os.path.exists(fairseq_rel_path):\n module_path = fairseq_rel_path\n else:\n raise FileNotFoundError(module_path)\n\n # ensure that user modules are only imported once\n import_user_module.memo = getattr(import_user_module, \"memo\", set())\n if module_path not in import_user_module.memo:\n import_user_module.memo.add(module_path)\n\n module_parent, module_name = os.path.split(module_path)\n if module_name not in sys.modules:\n sys.path.insert(0, module_parent)\n importlib.import_module(module_name)\n else:\n raise ImportError(\n \"Failed to import --user-dir={} because the corresponding module name \"\n \"({}) is not globally unique. Please rename the directory to \"\n \"something unique and try again.\".format(module_path, module_name)\n )\n\n\nclass LearnedPositionalEmbedding(nn.Embedding):\n \"\"\"\n This module learns positional embeddings up to a fixed maximum size.\n Padding ids are ignored by either offsetting based on padding_idx\n or by setting padding_idx to None and ensuring that the appropriate\n position ids are passed to the forward function.\n \"\"\"\n\n def __init__(self, num_embeddings: int, embedding_dim: int):\n super().__init__(num_embeddings, embedding_dim) # , padding_idx)\n self.onnx_trace = False\n padding_idx = 1\n if padding_idx is not None:\n if padding_idx > 0:\n assert padding_idx < self.vocab_size, 'Padding_idx must be within num_embeddings'\n elif padding_idx < 0:\n assert padding_idx >= -self.vocab_size, 'Padding_idx must be within num_embeddings'\n padding_idx = self.vocab_size + padding_idx\n self.padding_idx = padding_idx\n if self.padding_idx is not None:\n self.max_positions = self.vocab_size - self.padding_idx - 1\n else:\n self.max_positions = self.vocab_size\n\n def construct(\n self,\n input: Tensor,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n positions: Optional[Tensor] = None,\n ):\n \"\"\"Input is expected to be of size [bsz x seqlen].\"\"\"\n assert (positions is None) or (\n self.padding_idx is None\n ), \"If positions is pre-computed then padding_idx should not be set.\"\n if positions is None:\n if incremental_state is not None:\n # positions is the same for every token when decoding a single step\n # Without the int() cast, it doesn't work in some cases when exporting to ONNX\n\n # positions = torch.zeros(\n # (1, 1), device=input.device, dtype=input.dtype\n # ).fill_(int(self.padding_idx + input.size(1)))\n positions = Tensor(np.zeros(1, 1), dtype=input.dtype)\n positions = Fill(input.dtype, positions.shape, int(self.padding_idx + input.size(1)))\n\n else:\n positions = make_positions(\n input, self.padding_idx, onnx_trace=self.onnx_trace\n )\n tmp_embed = nn.Embedding(258, 1024, padding_idx=self.padding_idx)\n return tmp_embed(positions)\n\n\nclass MindsporeFairseqDropout(nn.Cell):\n def __init__(self, p, module_name=None):\n super().__init__()\n self.p = p\n self.module_name = module_name\n self.apply_during_inference = False\n self.training = True\n def construct(self, x, inplace: bool = False):\n if self.training or self.apply_during_inference:\n msDropoutLayer = nn.Dropout(keep_prob=self.p)\n msDropoutLayer.set_train()\n output = msDropoutLayer(x)\n return output\n\n # print(self.p)\n # msDropoutOp = Dropout(keep_prob=self.p)\n # out, mask = msDropoutOp(x)\n # return out\n else:\n return x\n\n\nclass FairseqIncrementalState(object):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.init_incremental_state()\n\n def init_incremental_state(self):\n self._incremental_state_id = str(uuid.uuid4())\n\n def _get_full_incremental_state_key(self, key: str) -> str:\n return \"{}.{}\".format(self._incremental_state_id, key)\n\n def get_incremental_state(\n self,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]],\n key: str,\n ) -> Optional[Dict[str, Optional[Tensor]]]:\n \"\"\"Helper for getting incremental state for an nn.Module.\"\"\"\n full_key = self._get_full_incremental_state_key(key)\n if incremental_state is None or full_key not in incremental_state:\n return None\n return incremental_state[full_key]\n\n def set_incremental_state(\n self,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]],\n key: str,\n value: Dict[str, Optional[Tensor]],\n ) -> Optional[Dict[str, Dict[str, Optional[Tensor]]]]:\n \"\"\"Helper for setting incremental state for an nn.Module.\"\"\"\n if incremental_state is not None:\n full_key = self._get_full_incremental_state_key(key)\n incremental_state[full_key] = value\n return incremental_state\n\ndef with_incremental_state(cls):\n cls.__bases__ = (FairseqIncrementalState,) + tuple(\n b for b in cls.__bases__ if b != FairseqIncrementalState\n )\n return cls\n\n@with_incremental_state\nclass MultiheadAttention(nn.Cell):\n def __init__(\n self,\n embed_dim,\n num_heads,\n kdim=None,\n vdim=None,\n dropout=0.0,\n bias=True,\n add_bias_kv=False,\n add_zero_attn=False,\n self_attention=False,\n encoder_decoder_attention=False,\n q_noise=0.0,\n qn_block_size=8,\n ):\n super().__init__()\n self.embed_dim = embed_dim\n self.kdim = kdim if kdim is not None else embed_dim\n self.vdim = vdim if vdim is not None else embed_dim\n self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim\n\n self.num_heads = num_heads\n self.dropout_p = dropout\n self.training = True\n\n self.dropout_module = MindsporeFairseqDropout(\n dropout, module_name=self.__class__.__name__\n )\n self.head_dim = embed_dim // num_heads\n assert (\n self.head_dim * num_heads == self.embed_dim\n ), \"embed_dim must be divisible by num_heads\"\n self.scaling = self.head_dim ** -0.5\n\n self.self_attention = self_attention\n self.encoder_decoder_attention = encoder_decoder_attention\n\n assert not self.self_attention or self.qkv_same_dim, (\n \"Self-attention requires query, key and \" \"value to be of the same size\"\n )\n\n self.k_proj = nn.Dense(self.kdim, self.embed_dim, has_bias=bias)\n self.v_proj = nn.Dense(self.vdim, self.embed_dim, has_bias=bias)\n self.q_proj = nn.Dense(self.embed_dim, self.embed_dim, has_bias=bias)\n self.out_proj = nn.Dense(self.embed_dim, self.embed_dim, has_bias=bias)\n\n if add_bias_kv:\n pass\n # self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))\n # self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))\n else:\n self.bias_k = self.bias_v = None\n\n self.add_zero_attn = add_zero_attn\n\n self.reset_parameters()\n\n self.onnx_trace = False\n self.tpu = False\n\n def prepare_for_onnx_export_(self):\n self.onnx_trace = True\n\n def prepare_for_tpu_(self, **kwargs):\n self.tpu = True\n\n def reset_parameters(self):\n if self.qkv_same_dim:\n self.k_proj.weight = Parameter(initializer(XavierUniform(gain=1 / math.sqrt(2))\n , [self.kdim, self.embed_dim]))\n self.v_proj.weight = Parameter(initializer(XavierUniform(gain=1 / math.sqrt(2))\n , [self.vdim, self.embed_dim]))\n self.q_proj.weight = Parameter(initializer(XavierUniform(gain=1 / math.sqrt(2))\n , [self.embed_dim, self.embed_dim]))\n else:\n assert 'ERROR reset params'\n\n def _get_input_buffer(\n self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]]\n ) -> Dict[str, Optional[Tensor]]:\n result = self.get_incremental_state(incremental_state, \"attn_state\")\n if result is not None:\n return result\n else:\n empty_result: Dict[str, Optional[Tensor]] = {}\n return empty_result\n\n def apply_sparse_mask(self, attn_weights, tgt_len: int, src_len: int, bsz: int):\n return attn_weights\n\n def construct(\n self,\n query,\n key: Optional[Tensor],\n value: Optional[Tensor],\n key_padding_mask: Optional[Tensor] = None,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n need_weights: bool = True,\n static_kv: bool = False,\n attn_mask: Optional[Tensor] = None,\n before_softmax: bool = False,\n need_head_weights: bool = False,\n ) -> Tuple[Tensor, Optional[Tensor]]:\n\n # print(query.shape, key.shape, key_padding_mask.shape, incremental_state, static_kv)\n static_k = None\n static_v = None\n\n if need_head_weights:\n need_weights = True\n\n tgt_len, bsz, embed_dim = query.shape\n assert embed_dim == self.embed_dim\n assert list(query.shape) == [tgt_len, bsz, embed_dim]\n\n if (\n not self.onnx_trace\n and not self.tpu # don't use PyTorch version on TPUs\n and incremental_state is None\n and not static_kv\n # A workaround for quantization to work. Otherwise JIT compilation\n # treats bias in linear module as method.\n ):\n assert key is not None and value is not None\n\n in_proj_weight = Tensor(np.array([]), mstype.float32)\n op_concat_axis0 = Concat()\n op_concat_axis1 = Concat(axis = 1)\n in_proj_bias = op_concat_axis0((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias))\n tens_ops = (query, key, value, in_proj_weight, in_proj_bias,\n self.bias_k, self.bias_v,\n self.out_proj.weight, self.out_proj.bias)\n tgt_len, bsz, embed_dim = query.shape\n embed_dim_to_check = self.embed_dim\n assert embed_dim == embed_dim_to_check\n # allow MHA to have different sizes for the feature dimension\n assert key.shape[0] == value.shape[0] and key.shape[1] == value.shape[1]\n\n use_separate_proj_weight = True\n if not use_separate_proj_weight:\n pass\n else:\n q_proj_weight_non_opt = self.q_proj.weight\n len1, len2 = q_proj_weight_non_opt.shape\n assert len1 == embed_dim and len2 == query.shape[-1]\n\n k_proj_weight_non_opt = self.k_proj.weight\n len1, len2 = k_proj_weight_non_opt.shape\n assert len1 == embed_dim and len2 == key.shape[-1]\n\n v_proj_weight_non_opt = self.v_proj.weight\n len1, len2 = v_proj_weight_non_opt.shape\n assert len1 == embed_dim and len2 == value.shape[-1]\n\n if in_proj_bias is not None:\n q = mindspore_linear(query, q_proj_weight_non_opt, in_proj_bias[0:embed_dim])\n k = mindspore_linear(key, k_proj_weight_non_opt, in_proj_bias[embed_dim:(embed_dim * 2)])\n v = mindspore_linear(value, v_proj_weight_non_opt, in_proj_bias[(embed_dim * 2):])\n else:\n q = mindspore_linear(query, q_proj_weight_non_opt, in_proj_bias)\n k = mindspore_linear(key, k_proj_weight_non_opt, in_proj_bias)\n v = mindspore_linear(value, v_proj_weight_non_opt, in_proj_bias)\n\n q = q * self.scaling\n unsqueeze_ops = ExpandDims()\n\n if attn_mask is not None:\n assert attn_mask.dtype == mstype.float32 or attn_mask.dtype == mstype.float64 or \\\n attn_mask.dtype == mstype.float16 or attn_mask.dtype == mstype.uint8 or attn_mask.dtype == mstype.bool_, \\\n 'Only float, byte, and bool types are supported for attn_mask, not {}'.format(attn_mask.dtype)\n if attn_mask.dim() == 2:\n attn_mask = unsqueeze_ops(attn_mask, 0)\n if list(attn_mask.shape) != [1, query.shape[0], key.shape[0]]:\n raise RuntimeError('The size of the 2D attn_mask is not correct.')\n\n\n # convert ByteTensor key_padding_mask to bool\n if key_padding_mask is not None and key_padding_mask.dtype == mstype.uint8:\n pass\n if self.bias_k is not None and self.bias_v is not None:\n\n k = op_concat_axis0([k, self.bias_k.repeat(1, bsz, 1)])\n v = op_concat_axis0([v, self.bias_v.repeat(1, bsz, 1)])\n if attn_mask is not None:\n ops_pad = Pad(((0, 0), (0, 1)))\n attn_mask = ops_pad(attn_mask)\n if key_padding_mask is not None:\n ops_pad = Pad(((0, 0), (0, 1)))\n key_padding_mask = ops_pad(key_padding_mask)\n\n else:\n assert self.bias_k is None\n assert self.bias_v is None\n\n q = q.view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(1, 0, 2)\n if k is not None:\n k = k.view(-1, bsz * self.num_heads, self.head_dim).transpose(1, 0, 2)\n if v is not None:\n v = v.view(-1, bsz * self.num_heads, self.head_dim).transpose(1, 0, 2)\n\n src_len = k.shape[1]\n if key_padding_mask is not None:\n assert key_padding_mask.shape[0] == bsz\n assert key_padding_mask.shape[1] == src_len\n\n if self.add_zero_attn:\n pass\n # src_len += 1\n # k = op_concat_axis1()\n\n attn_output_weights = matmul(q, k.transpose(0, 2, 1))\n assert list(attn_output_weights.shape) == [bsz * self.num_heads, tgt_len, src_len]\n\n if attn_mask is not None:\n # [1, 54, 54], 右上角-inf,左下角0矩阵。 dtype=float16\n if attn_mask.dtype == mstype.bool_:\n assert 'attn_mask type error'\n # attn_output_weights.masked_fill_(attn_mask, float('-inf'))\n else:\n attn_output_weights += attn_mask\n\n if key_padding_mask is not None:\n attn_output_weights = attn_output_weights.view(bsz, self.num_heads, tgt_len, src_len)\n ############################\n # add masked_fill ops\n # (attn_output_weights) # [24, 16, 61, 61]\n # (key_padding_mask.shape) # [24, 61] --> unsqueeze [24, 1, 1, 61]\n\n ###########################################\n # print(key_padding_mask, key_padding_mask.dtype) # bool Tensor\n\n # key_padding_mask = key_padding_mask * 1\n #\n # # print(key_padding_mask, key_padding_mask.shape, key_padding_mask.asnumpy().sum())\n # # tmp = key_padding_mask.asnumpy()\n # # print(tmp.sum())\n # # ############################################\n #\n # unsqueeze_key_padding_mask = unsqueeze_ops(unsqueeze_ops(key_padding_mask, 1), 2)\n # # #\n # Inversed_unsqueeze_key_padding_mask = 1 - unsqueeze_key_padding_mask\n # # print(unsqueeze_key_padding_mask.asnumpy().sum(), Inversed_unsqueeze_key_padding_mask.asnumpy().sum())\n #\n #\n # # make inf matrix shape like attn_output_weights\n # tmp_infMatrix = Tensor(np.ones(attn_output_weights.shape), attn_output_weights.dtype)\n # # using -1e10 to replace -inf, because 0 * -inf = nan\n # tmp_infMatrix_inf = fill_with_neg_inf(tmp_infMatrix)\n # tmp_infMatrix_inf = tmp_infMatrix_inf * unsqueeze_key_padding_mask\n # need2convertinf_attn_output_weights = attn_output_weights * tmp_infMatrix_inf\n # keep_attn_output_weights = attn_output_weights * Inversed_unsqueeze_key_padding_mask\n # attn_output_weights = need2convertinf_attn_output_weights + keep_attn_output_weights\n\n attn_output_weights = masked_fill(attn_output_weights, key_padding_mask, unsqueeze_ops)\n\n ##############################\n attn_output_weights = attn_output_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n\n softmax_ops = Softmax(axis=-1)\n attn_output_weights = softmax_ops(attn_output_weights)\n\n msDropoutLayer = nn.Dropout(keep_prob=self.dropout_p)\n if self.training:\n msDropoutLayer.set_train()\n attn_output_weights = msDropoutLayer(attn_output_weights)\n\n attn_output = matmul(attn_output_weights, v)\n assert list(attn_output.shape) == [bsz * self.num_heads, tgt_len, self.head_dim]\n attn_output = attn_output.transpose(1, 0, 2).view(tgt_len, bsz, embed_dim)\n attn_output = mindspore_linear(attn_output, self.out_proj.weight, self.out_proj.bias)\n\n if need_weights:\n # average attention weights over heads\n attn_output_weights = attn_output_weights.view(bsz, self.num_heads, tgt_len, src_len)\n sum_ops = ReduceSum(keep_dims=False)\n return attn_output, sum_ops(attn_output_weights, axis=1) / self.num_heads\n else:\n return attn_output, None\n\n else:\n unsqueeze_ops = ExpandDims()\n\n saved_state = None\n if self.self_attention:\n q = self.q_proj(query)\n k = self.k_proj(query)\n v = self.v_proj(query)\n elif self.encoder_decoder_attention:\n # encoder-decoder attention\n q = self.q_proj(query)\n if key is None:\n assert value is None\n k = v = None\n else:\n k = self.k_proj(key)\n v = self.v_proj(key)\n else:\n assert key is not None and value is not None\n q = self.q_proj(query)\n k = self.k_proj(key)\n v = self.v_proj(value)\n q *= self.scaling\n # print(self.bias_k) None\n\n q = q.view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(1, 0, 2)\n if k is not None:\n k = k.view(-1, bsz * self.num_heads, self.head_dim).transpose(1, 0, 2)\n if v is not None:\n v = v.view(-1, bsz * self.num_heads, self.head_dim).transpose(1, 0, 2)\n\n assert k is not None\n src_len = k.shape[1]\n\n # This is part of a workaround to get around fork/join parallelism\n # not supporting Optional types.\n if key_padding_mask is not None and key_padding_mask.dim() == 0:\n key_padding_mask = None\n\n if key_padding_mask is not None:\n assert key_padding_mask.shape[0] == bsz\n assert key_padding_mask.shape[1] == src_len\n\n # print(self.add_zero_attn) # False\n\n attn_weights = matmul(q, k.transpose(0, 2, 1))\n attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)\n\n assert list(attn_weights.shape) == [bsz * self.num_heads, tgt_len, src_len]\n\n # print(attn_weights.shape) # From DecoderLayer [384, 131, 61]\n if attn_mask is not None:\n attn_mask = unsqueeze_ops(attn_mask, 0)\n if self.onnx_trace:\n attn_mask = attn_mask.repeat(attn_weights.size(0), 1, 1)\n attn_weights += attn_mask\n\n if key_padding_mask is not None:\n # don't attend to padding symbols\n attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)\n if not self.tpu:\n attn_weights = masked_fill(attn_weights,\n key_padding_mask,\n unsqueeze_ops\n )\n else:\n attn_weights = attn_weights.transpose(0, 2)\n attn_weights = attn_weights.masked_fill(key_padding_mask, float(\"-inf\"))\n attn_weights = attn_weights.transpose(0, 2)\n attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n if before_softmax:\n return attn_weights, v\n\n attn_weights_float = softmax(attn_weights, dim=-1)\n # attn_weights.set_dtype(attn_weights_float.dtype)\n if not self.dropout_module is None:\n attn_probs = self.dropout_module(attn_weights)\n else:\n attn_probs = attn_weights # [384, 131, 61]\n\n assert v is not None\n attn = matmul(attn_probs, v)\n # print(attn.shape) # [384, 131, 61]\n assert list(attn.shape) == [bsz * self.num_heads, tgt_len, self.head_dim]\n\n if self.onnx_trace and attn.shape[1] == 1:\n # when ONNX tracing a single decoder step (sequence length == 1)\n # the transpose is a no-op copy before view, thus unnecessary\n attn = attn.view(tgt_len, bsz, embed_dim)\n else:\n attn = attn.transpose(1, 0, 2).view(tgt_len, bsz, embed_dim)\n\n attn = self.out_proj(attn)\n attn_weights: Optional[Tensor] = None\n # print(need_weights, attn_weights)\n if need_weights:\n attn_weights = attn_weights_float.view(\n bsz, self.num_heads, tgt_len, src_len\n ).transpose(1, 0, 2, 3)\n if not need_head_weights:\n ops_mean = ReduceMean(keep_dims=False)\n # average attention weights over heads\n attn_weights = ops_mean(attn_weights, axis=0)\n # raise ImportError\n\n # print(attn.shape, attn_weights.shape) # [131, 24, 1024], [24, 131, 61]\n return attn, attn_weights\n\ndef get_args():\n args = Namespace(activation_dropout=0.0, activation_fn='gelu', adam_betas='(0.9, 0.98)', adam_eps=1e-08,\n adaptive_input=False, adaptive_softmax_cutoff=None, adaptive_softmax_dropout=0,\n all_gather_list_size=16384, arch='transformer_wmt_en_de_big', attention_dropout=0.1,\n batch_size=None, batch_size_valid=None, best_checkpoint_metric='loss', bf16=False, bpe=None,\n broadcast_buffers=False, bucket_cap_mb=25, checkpoint_shard_count=1, checkpoint_suffix='',\n clip_norm=0.0, cpu=False, criterion='label_smoothed_cross_entropy', cross_self_attention=False,\n curriculum=0, data='../pre-train', data_buffer_size=10,\n dataset_impl=None, ddp_backend='no_c10d', decoder_attention_heads=16, decoder_embed_dim=1024,\n decoder_embed_path=None, decoder_ffn_embed_dim=4096, decoder_input_dim=1024, decoder_layerdrop=0,\n decoder_layers=6, decoder_layers_to_keep=None, decoder_learned_pos=True,\n decoder_normalize_before=False, decoder_output_dim=1024, device_id=0, disable_validation=False,\n distributed_backend='nccl', distributed_init_method=None, distributed_no_spawn=True,\n distributed_port=-1, distributed_rank=0, distributed_world_size=1, distributed_wrapper='DDP',\n dropout=0.2, empty_cache_freq=0, encoder_attention_heads=16, encoder_embed_dim=1024,\n encoder_embed_path=None, encoder_ffn_embed_dim=4096, encoder_layerdrop=0, encoder_layers=6,\n encoder_layers_to_keep=None, encoder_learned_pos=True, encoder_normalize_before=False,\n eval_bleu=False, eval_bleu_args=None, eval_bleu_detok='space', eval_bleu_detok_args=None,\n eval_bleu_print_samples=False, eval_bleu_remove_bpe=None, eval_tokenized_bleu=False,\n fast_stat_sync=False, find_unused_parameters=False, finetune_from_model=None,\n fix_batches_to_gpus=False, fixed_validation_seed=None, fp16=True, fp16_init_scale=128,\n fp16_no_flatten_grads=False, fp16_scale_tolerance=0.0, fp16_scale_window=None, gen_subset='test',\n ignore_prefix_size=0, keep_best_checkpoints=-1, keep_interval_updates=-1, keep_last_epochs=-1,\n label_smoothing=0.1, layernorm_embedding=False, left_pad_source='True', left_pad_target='False',\n load_alignments=False, localsgd_frequency=3, log_format=None, log_interval=5, lr=[0.0005],\n lr_scheduler='inverse_sqrt', max_epoch=0, max_source_positions=256, max_target_positions=256,\n max_tokens=4096, max_tokens_valid=4096, max_update=100000, maximize_best_checkpoint_metric=False,\n memory_efficient_bf16=False, memory_efficient_fp16=False, min_loss_scale=0.0001, min_lr=1e-09,\n model_parallel_size=1, no_cross_attention=False, no_epoch_checkpoints=False,\n no_last_checkpoints=False, no_progress_bar=True, no_save=False, no_save_optimizer_state=False,\n no_scale_embedding=False, no_seed_provided=False, no_token_positional_embeddings=False,\n nprocs_per_node=1, num_batch_buckets=0, num_shards=1, num_workers=1, optimizer='adam',\n optimizer_overrides='{}', patience=-1, pipeline_balance=None, pipeline_checkpoint='never',\n pipeline_chunks=0, pipeline_decoder_balance=None, pipeline_decoder_devices=None,\n pipeline_devices=None, pipeline_encoder_balance=None, pipeline_encoder_devices=None,\n pipeline_model_parallel=False, profile=False, quant_noise_pq=0, quant_noise_pq_block_size=8,\n quant_noise_scalar=0, quantization_config_path=None, report_accuracy=False,\n required_batch_size_multiple=8, required_seq_len_multiple=1, reset_dataloader=True,\n reset_lr_scheduler=True, reset_meters=True, reset_optimizer=True,\n restore_file='checkpoint_last.pt',\n save_dir='/userhome/jobs/NMTrans/mRASP-master/pretrain/transformer_big', save_interval=1,\n save_interval_updates=50, scoring='bleu', seed=1, sentence_avg=False, shard_id=0,\n share_all_embeddings=True, share_decoder_input_output_embed=False,\n skip_invalid_size_inputs_valid_test=True, slowmo_algorithm='LocalSGD', slowmo_momentum=None,\n source_lang='src', stop_time_hours=0, target_lang='trg', task='translation',\n tensorboard_logdir=None, threshold_loss_scale=None, tie_adaptive_weights=False, tokenizer=None,\n tpu=False, train_subset='train', truncate_source=False, update_freq=[1], upsample_primary=1,\n use_bmuf=False, use_old_adam=False, user_dir=None, valid_subset='valid', validate_after_updates=0,\n validate_interval=1, validate_interval_updates=0, warmup_init_lr=1e-07, warmup_updates=4000,\n weight_decay=0.0, zero_sharding='none')\n return args\n\n\nif __name__ == '__main__':\n tmp = LayerNorm(1024)\n tmp = gelu()\n\n SEED = 0\n np.random.seed(SEED)\n random.seed(SEED)\n\n # ############## Linear Layer Test ##########################\n # np.random.seed(0)\n # random.seed(0)\n # in_data = Tensor(np.random.randn(2, 2), mstype.float32)\n # # # test my linear:\n # # my_linear = Linear(2, 8, bias=True)\n # # print(my_linear.weight.asnumpy())\n # # print(my_linear.bias.asnumpy())\n # # print(my_linear, my_linear.weight)\n # # out_data1 = my_linear(in_data)\n # # print(out_data1.shape, out_data1)\n #\n #\n # # # test nn.Dense\n # # linear = nn.Dense(2, 8, weight_init=XavierUniform(gain=1))\n # # print(linear.weight.asnumpy())\n # # print(linear.bias.asnumpy())\n # # print(linear, linear.weight)\n # # out_data2 = linear(in_data)\n # # print(out_data2.shape, out_data2)\n # ##############################################################\n\n # in_data = Tensor(np.array([[3, 4, 6, 10], [1, 6, 7, 9], [4, 3, 8, 7], [1, 3, 7, 9]]).astype(np.float32))\n # res = fill_with_neg_inf(in_data)\n # print(res)\n # res = (in_data == 0)\n\n # res = make_positions(in_data, -2)\n\n # ###########################################################\n # # Test LearnedEmbeddings\n # input_tokens = Tensor(np.array([[64822, 4887, 31201, 1714, 4817, 94, 136, 1351, 3418, 7857,\n # 473, 1624, 436, 46, 4, 603, 9265, 948, 481, 663,\n # 20736, 81, 1144, 157, 70, 46, 4, 332, 35, 2240,\n # 515, 46, 2071, 4, 5740, 158, 29, 2102, 1598, 76,\n # 6752, 154, 1071, 5294, 99, 738, 132, 19877, 283, 38,\n # 2196, 6484, 12600, 4970, 766, 2857, 94, 14555, 2772, 5,\n # 2]]).astype(np.int32))\n # # print(input_tokens)\n # m = LearnedPositionalEmbedding(258, 1024)\n # padding_idx = 1\n # m.embedding_table = Parameter(initializer(Normal(sigma=258 ** -0.5), [258, 1024]))\n # # print(m.embedding_table.asnumpy()[padding_idx])\n # m.embedding_table[padding_idx] = Parameter(initializer(Constant(value=0), [1, 1024]))\n # print(m.embedding_table.asnumpy()[padding_idx])\n # res = m(input_tokens, None, None)\n # print(res.shape)\n # #####################################################\n\n # #############################################\n # # test msFairseqDropout Cell\n # MyDropout = MindsporeFairseqDropout(0.5)\n # x = Tensor((20, 16, 50, 50), mstype.float32)\n # res = MyDropout(x)\n # print(res)\n # #############################################\n\n # #########################################\n # # test Mindspore_linear function\n # input_x = Tensor(np.random.randn(2, 24, 1024))\n # weight = Tensor(np.random.randn(1024, 1024))\n # bias = Tensor(np.random.randn(1024))\n # res01 = mindspore_linear(input_x, weight, bias)\n # print(res01.shape)\n # #########################################\n\n ############################################\n # test Yizx_Mindspore_MultiHeadAttention\n net = MultiheadAttention(1024, 16, None, None, 0.1, True, False, False, True, False, 0, 8)\n # print(net)\n # src_tokens = Tensor(np.random.randint(0, 1024, (24, 61)), mstype.int32)\n src_tokens = Tensor(np.random.randint(0, 2, (24, 61)), mstype.int32)\n # after Transformer.forward_embedding(src_tokensforward_embedding, token_embeddings), return x,\n # encoder_embedding\n x = Tensor(np.random.randn(24, 61, 1024), mstype.float32)\n x = x.transpose(1, 0, 2)\n encoder_padding_mask = (src_tokens == 1) # [24, 61]\n attn_mask = None\n\n res = net(x, x, x, encoder_padding_mask, attn_mask)\n print(res[0].shape)\n ##################################################\n\n\n\n\n","sub_path":"yizx_mindspore_mRASP2_model/PYNATIVE_MODE/yizx_mindspore_utils.py","file_name":"yizx_mindspore_utils.py","file_ext":"py","file_size_in_byte":40738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"190593479","text":"# Sym class derived from Col\nimport math\nfrom col import Col\n\nclass Sym(Col):\n # initialize\n def __init__(self, col, text):\n Col.__init__(self, 0, col, text)\n self.mode = 0\n self.most = 0\n self.map = {}\n\n # add function\n def add(self, val):\n self.n += 1\n self.count = 0\n if val in self.map.keys(): \n self.count = self.map[val] + 1\n self.map[val] = self.count\n else: \n self.count = 1\n self.map[val] = self.count\n if self.count > self.most:\n self.mode = val\n self.most = self.count\n\n def symEnt(self):\n res = 0\n for i in self.map.keys():\n p = self.map[i]/self.n\n res -= (p)*(math.log(p)/math.log(2))\n return res\n\n def symLike(self, x, prior, m):\n f = self.map[x] if x in self.map else 0\n return (f + m * prior) / (self.n + m)\n","sub_path":"hw/4/sym.py","file_name":"sym.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"452452134","text":"#!/usr/bin/env python\n#\n# HyperTask Enterprise developed by HyperTask Enterprise GmbH.\n#\n# All source code and content (c) Copyright 2014, HyperTask Enterprise GmbH unless specifically noted otherwise.\n#\n# This source code is released under the HyperTask Enterprise Server and Client License, unless otherwise agreed with HyperTask Enterprise GmbH.\n# The latest version of this license can be found here: http://htvcenter-enterprise.com/license\n#\n# By using this software, you acknowledge having read this license and agree to be bound thereby.\n#\n# http://htvcenter-enterprise.com\n#\n# Copyright 2014, HyperTask Enterprise GmbH \n#\n\nimport atexit\nimport requests\nfrom pyVim import connect\nfrom pyVmomi import vmodl\n\nimport libvmtask\n\nfrom inspect import getmembers\nfrom pprint import pprint\nimport argparse\nimport sys\n\nrequests.packages.urllib3.disable_warnings()\n\n\n\ndef destroy_vm_by_name(service_instance, virtual_machine, name, depth=1):\n\tif hasattr(virtual_machine, 'childEntity'):\n\t\tvmList = virtual_machine.childEntity\n\t\tfor c in vmList:\n\t\t\tdestroy_vm_by_name(service_instance, c, name, depth + 1)\n\t\treturn\n\tsummary = virtual_machine.summary\n\tif summary.config.name == name:\n\t\tsys.stdout.write(\"name=\" + str(summary.config.name))\n\t\tsys.stdout.write(\"|uuid=\" + str(summary.config.uuid))\n\t\tprint(\"Found: {0}\".format(virtual_machine.name))\n\t\tprint(\"The current powerState is: {0}\".format(virtual_machine.runtime.powerState))\n\t\tif format(virtual_machine.runtime.powerState) == \"poweredOn\":\n\t\t\tprint(\"Attempting to power off {0}\".format(virtual_machine.name))\n\t\t\ttask = virtual_machine.PowerOffVM_Task()\n\t\t\tlibvmtask.WaitForTasks([task], service_instance)\n\t\t\tprint(\"{0}\".format(task.info.state))\n\n\t\tprint(\"Destroying VM from vSphere: {0}\".format(virtual_machine.name))\n\t\ttask = virtual_machine.Destroy_Task()\n\t\tlibvmtask.WaitForTasks([task], service_instance)\n\t\tprint(\"Done by name.\")\n\n\n\ndef main():\n\tparser = argparse.ArgumentParser(description='vCenter login')\n\tparser.add_argument('-s', '--host', required=True, action='store', help='vSphere IP')\n\tparser.add_argument('-o', '--port', type=int, default=443, action='store', help='vSphere Port')\n\tparser.add_argument('-u', '--user', required=True, action='store', help='User name')\n\tparser.add_argument('-p', '--password', required=True, action='store', help='Password')\n\tparser.add_argument('-n', '--name', required=False, action='store', help='VM name')\n\tparser.add_argument('-i', '--uuid', required=False, action='store', help='VM uuid')\n\targs = parser.parse_args()\n\n\ttry:\n\t\tservice_instance = connect.SmartConnect(host=args.host,\n\t\t\t\t\t\t\t\t\t\t\t\tuser=args.user,\n\t\t\t\t\t\t\t\t\t\t\t\tpwd=args.password,\n\t\t\t\t\t\t\t\t\t\t\t\tport=int(args.port))\n\t\tatexit.register(connect.Disconnect, service_instance)\n\n\n\t\tif args.uuid:\n\t\t\tvirtual_machine = service_instance.content.searchIndex.FindByUuid(None, args.uuid, True, False)\n\t\t\tif virtual_machine is None:\n\t\t\t\traise SystemExit(\"Unable to find VM.\")\n\n\t\t\tprint(\"Found: {0}\".format(virtual_machine.name))\n\t\t\tprint(\"The current powerState is: {0}\".format(virtual_machine.runtime.powerState))\n\t\t\tif format(virtual_machine.runtime.powerState) == \"poweredOn\":\n\t\t\t\tprint(\"Attempting to power off {0}\".format(virtual_machine.name))\n\t\t\t\ttask = virtual_machine.PowerOffVM_Task()\n\t\t\t\tlibvmtask.WaitForTasks([task], service_instance)\n\t\t\t\tprint(\"{0}\".format(task.info.state))\n\n\t\t\tprint(\"Destroying VM from vSphere: {0}\".format(virtual_machine.name))\n\t\t\ttask = virtual_machine.Destroy_Task()\n\t\t\tlibvmtask.WaitForTasks([task], service_instance)\n\t\t\tprint(\"Done by uuid.\")\n\n\n\t\telif args.name:\n\n\t\t\tcontent = service_instance.RetrieveContent()\n\t\t\tchildren = content.rootFolder.childEntity\n\t\t\tfor child in children:\n\t\t\t\tif hasattr(child, 'vmFolder'):\n\t\t\t\t\tdatacenter = child\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\n\t\t\t\tvm_folder = datacenter.vmFolder\n\t\t\t\tvm_list = vm_folder.childEntity\n\t\t\t\tfor virtual_machine in vm_list:\n\t\t\t\t\tdestroy_vm_by_name(service_instance, virtual_machine, args.name, 10)\n\n\t\telse:\n\t\t\traise SystemExit(\"Please provide a VM name or uuid\")\n\n\n\t\treturn 0\n\n\texcept vmodl.MethodFault as error:\n\t\tprint(\"ERROR: \" + error.msg)\n\t\tsys.exit(1)\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"plugins/vmware-vsphere/bin/python/vmdestroy.py","file_name":"vmdestroy.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"304796454","text":"from Arm.Stm32 import *\n\n#env = Stm32f1md()\n#haldir='stm32f103xb'\n#env.setLinkfile( '/ld/stm32f103xc_min.ld' )\n#port = 'ARM_CM3'\n\nenv = Stm32f1hd()\nhaldir='stm32f103ze_redbull'\nenv.setLinkfile( '/ld/stm32f103xe_min.ld' )\nport = 'ARM_CM3'\n\n#env = Stm32f407xx()\n#haldir='stm32f407zg_eu'\n#env.setLinkfile( '/ld/stm32f407zg_min.ld' )\n#port = 'ARM_CM4F'\n\n#env = Stm32f767xx()\n#haldir='stm32f767zi_nucleo'\n#env.setLinkfile( '/ld/stm32f767zi_min.ld' )\n#port = 'ARM_CM7'\n\nenv.appendDefineFlags([\n 'MCUSH_STACK_SIZE=10240',\n #'LUA_32BITS',\n 'USE_SHELL_PRINTF2=0',\n ])\n\n\nenv.appendPath([\n '.',\n '/libFreeRTOS',\n '/libFreeRTOS/include',\n '/libFreeRTOS/portable/GCC/%s'% port,\n '/mcush',\n '/hal%s'% haldir,\n '/liblua',\n])\n\n\nenv.appendGlobSource([\n '*.c',\n '/mcush/*.c',\n '/hal%s/*.c'% haldir,\n '/libFreeRTOS/*.c',\n '/libFreeRTOS/portable/MemMang/heap_3.c',\n '/libFreeRTOS/portable/GCC/%s/port.c'% port,\n '/liblua/*.c',\n])\n\nenv.makeApp()\n\n","sub_path":"appTestLua/SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"159879612","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport cherrypy, sqlite3, os, webbrowser, sys, json, uuid\nimport logging\nfrom jinja2 import Environment, FileSystemLoader\nfrom cherrypy import _cperror\nfrom datetime import date\n\nclass NewJob:\n\tdef __init__(self, env):\n\t\tself.env = env\n\t\t\"\"\"\n\t\tconnection = sqlite3.connect(\"data/namsframbod.sqlite\")\n\t\tcursor = connection.cursor()\n\t\tdata = cursor.execute('select * from learning_opportunities')\n\t\tresults = []\n\t\tfor row in data:\n\t\t\tresults.append(row)\n\t\treturn results\n\t\t\"\"\"\n\t@cherrypy.expose\n\t@cherrypy.tools.allow(methods=['GET'])\n\tdef index(self):\n\t\ttmpl = self.env.get_template('newjob/index.jinja2')\n\t\tconnection = sqlite3.connect(\"data/starfalysing.sqlite3\")\n\t\tcursor = connection.cursor()\n\t\tdata = cursor.execute('select * from councils')\n\t\tconnection.commit()\n\t\tcResults = []\n\t\tfor row in data:\n\t\t\tcResults.append(row)\n\t\tdata = cursor.execute('select * from ISQF_levels')\n\t\tconnection.commit()\n\t\tiResults = []\n\t\tfor row in data:\n\t\t\tiResults.append(row)\n\t\tconnection.close()\n\t\treturn tmpl.render(councils = cResults, ISQF_levels = iResults)#,user= cherrypy.request.login)\n\n\t@cherrypy.expose\n\t@cherrypy.tools.allow(methods=['POST'])\n\t@cherrypy.tools.json_in()\n\t@cherrypy.tools.json_out()\n\tdef newjob(self): #,JobName,JobNameEng,Occupation,OccupationEng,Skills,SkillsEng,Councils):\n\t\ttry:\n\t\t\t#prepare insert\n\t\t\tinserts = {key: value for key, value in cherrypy.request.json.items()}\n\t\t\tconnection = sqlite3.connect(\"data/starfalysing.sqlite3\")\n\t\t\tcursor = connection.cursor()\n\t\t\t#print ('byrja')\n\t\t\tcols_o = ','.join(inserts)\n\t\t\t\n\t\t\ttmp_opp = [inserts[key] for key in inserts]\n\t\t\tcols = [key for key in inserts]\n\t\t\t\n\t\t\t# Change the format\n\t\t\tvalues = []\n\t\t\tfor v in tmp_opp:\n\t\t\t if v:\n\t\t\t values.append(v)\n\t\t\t else:\n\t\t\t values.append(\"\")\n\t\t\t#print ('donni')\n\t\t\t#print (values)\n\t\t\tval_o = \"\"\n\t\t\ti = 0\n\t\t\tfor v in values:\n\t\t\t\tprint ('komin')\n\t\t\t\tprint (cols[-1])\n\t\t\t\tprint (cols[i])\n\t\t\t\tif cols[-1] == cols[i]:\n\n\t\t\t\t\tval_o =val_o+'\"'+v+'\"'\n\t\t\t\t\ti=i+1\n\t\t\t\telse:\n\t\t\t\t\tval_o =val_o+'\"'+v+'\",'\t\n\t\t\t\t\ti=i+1\n\t\t\t\n\t\t\tdata = cursor.execute('select max(jobId)+1 from descirption')\n\t\t\tconnection.commit()\n\t\t\tresults = data.fetchone()\n\t\t\t\n\t\t\tcols_o =cols_o + ',jobId,created_date,updated_date'\n\t\t\t#print (cols_o)\n\t\t\tif results[0] == None:\n\t\t\t\tval_o = val_o +', ' + str(0)+ ', \"' + str(date.today().isoformat()) + '\", \"' + str(date.today().isoformat()) + '\"'\n\t\t\telse:\n\t\t\t\tval_o = val_o +','+ str(results[0])+ ', \"' + str(date.today().isoformat()) + '\", \"'+ str(date.today().isoformat()) + '\"'\n\t\t\t#print (val_o)\n\t\t\tsql = 'insert into descirption ({}) VALUES ({})'.format(cols_o,val_o)\n\t\t\t#print ('alli')\n\t\t\t#print (sql)\n\t\t\tdata = cursor.execute(sql)\n\t\t\tconnection.commit()\n\t\t\tconnection.close()\n\t\t\t#print ('búinn')\n\t\t\treturn {\"Message\": \"translation added\"}\n\t\texcept Exception as e:\n\t\t\treturn {\"Message\": \"Error, failed to insert\"}\n\t\t","sub_path":"starfalysing/newjob.py","file_name":"newjob.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"438014542","text":"import sys\r\n##### sys.path.append(\"D:Ramon_2015/RECERCA/RETOS-2015/Tareas/Proves-FreeCAD-2\") # change for your path\r\nimport otsun\r\nimport FreeCAD\r\nfrom FreeCAD import Base\r\nimport Part\r\nimport numpy as np\r\n# ---\r\n# Materials\r\n# ---\r\n\r\nMyProject = 'test_PTC.FCStd'\r\nFreeCAD.openDocument(MyProject)\r\n\r\n\r\nfile_BK7 = 'BK7_Schott.txt' # change for your path\r\notsun.create_wavelength_volume_material(\"Glass1\", file_BK7)\r\notsun.create_opaque_simple_layer(\"Opa1\")\r\nfile_Ag = 'Ag_Yang.txt'\r\notsun.create_metallic_specular_layer(\"Mir\", file_Ag, 4.4, 20, 0.9)\r\notsun.create_two_layers_material(\"Mir1\", \"Mir\", \"Mir\")\r\nfile_AR1 = 'AR-J.txt'\r\notsun.create_polarized_coating_transparent_layer(\"file_AR1\", file_AR1)\r\notsun.create_two_layers_material(\"AR1\", \"file_AR1\", \"file_AR1\")\r\nfile_Abs_Coating = 'Si3N4Reflectancia.txt'\r\notsun.create_polarized_coating_absorber_layer(\"Abs1\", file_Abs_Coating)\r\n\r\n# ---\r\n# Inputs for Total Analysis\r\n# ---\r\n\r\ndoc = FreeCAD.ActiveDocument\r\nphi_ini = 0.0 + 1.E-9\r\nphi_end = 0.0 + 1.E-4\r\nphi_step = 5.0\r\ntheta_ini = 0.0 + 1.E-9\r\ntheta_end = 1.0 + 1.E-4\r\ntheta_step = 1.0\r\nnumber_of_rays = 100\r\naperture_collector_Th = 1845.0 * 10347.0\r\naperture_collector_PV = 0.0\r\n# for direction of the source two options: Buie model or main_direction \r\n# direction_distribution = None # default option main_direction\r\nCSR = 0.05\r\nBuie_model = otsun.BuieDistribution(CSR)\r\ndirection_distribution = Buie_model\r\n# for integral results three options: ASTMG173-direct (default option), ASTMG173-total, upload data_file_spectrum\r\ndata_file_spectrum = 'ASTMG173-direct.txt'\r\n# --------- end\r\n\r\n# ---\r\n# Constant inputs for Total Analysis\r\n# ---\r\nshow_in_doc = None\r\npolarization_vector = None\r\nlight_spectrum = otsun.create_CDF_from_PDF(data_file_spectrum)\r\n# --------- end\r\n\r\npower_emitted_by_m2 = otsun.integral_from_data_file(data_file_spectrum)\r\n\r\n# objects for scene\r\nsel = doc.Objects\r\ncurrent_scene = otsun.Scene(sel)\r\nresults = []\r\nfor ph in np.arange(phi_ini, phi_end, phi_step):\r\n for th in np.arange(theta_ini, theta_end, theta_step):\r\n main_direction = otsun.polar_to_cartesian(ph, th) * -1.0 # Sun direction vector\r\n emitting_region = otsun.SunWindow(current_scene, main_direction)\r\n l_s = otsun.LightSource(current_scene, emitting_region, light_spectrum, 1.0, direction_distribution, polarization_vector)\r\n exp = otsun.Experiment(current_scene, l_s, number_of_rays, show_in_doc)\r\n exp.run(show_in_doc)\r\n if aperture_collector_Th != 0.0:\r\n efficiency_from_source_Th = (exp.captured_energy_Th /aperture_collector_Th) / (exp.number_of_rays/exp.light_source.emitting_region.aperture)\r\n else:\r\n efficiency_from_source_Th = 0.0\r\n if aperture_collector_PV != 0.0:\r\n efficiency_from_source_PV = (exp.captured_energy_PV /aperture_collector_PV) / (exp.number_of_rays/exp.light_source.emitting_region.aperture)\r\n else:\r\n efficiency_from_source_PV = 0.0\r\n results.append((ph, th, efficiency_from_source_Th, efficiency_from_source_PV))\r\n\r\nFreeCAD.closeDocument(FreeCAD.ActiveDocument.Name)\r\n\r\n\r\ndef test_2():\r\n assert 0.9 > results[0][2] > 0.7 and 0.8 > results[1][2] > 0.5 and results[0][3] == 0.0 and results[1][3] == 0.0\r\n","sub_path":"tests/test_2.py","file_name":"test_2.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"394061095","text":"# -*-coding:utf-8 -*-\nimport pymysql\nimport re\nimport sys\nimport random\nimport time\nfrom imp import reload\nfrom scrapy.http import Request\nfrom scrapy.spiders import Spider\nfrom scrapy.selector import Selector\nfrom scrapy_splash import SplashRequest\n\nfrom bilibili_user_scrapy.items import BilibiliUserScrapyItem\n\nreload(sys)\n\n# 获取随机user_agent\ndef LoadUserAgents(uafile):\n \"\"\"\n uafile : string\n path to text file of user agents, one per line\n \"\"\"\n uas = []\n with open(uafile, 'rb') as uaf:\n for ua in uaf.readlines():\n if ua:\n uas.append(ua.strip()[1:-1-1])\n # random的序列随机混合方法\n random.shuffle(uas)\n return uas\n\nua_list = LoadUserAgents(\"user_agents.txt\")\n# 默认header\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Referer': 'http://space.bilibili.com/45388',\n 'Origin': 'http://space.bilibili.com',\n 'Host': 'space.bilibili.com',\n 'AlexaToolbar-ALX_NS_PH': 'AlexaToolbar/alx-4.0',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4',\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n}\n\n\n# 主爬虫类\nclass BILIBILIUserSpider(Spider): \n\n name = \"bilibili_user_scrapy\"\n\n start_urls = []\n # 截止2018/5/2日,B站注册账号数量\n start = 1\n end = 323000449\n\n # 构造url,根据机能分批爬取,未进行分布式爬虫 \n for i in range(2000, 100000):\n url = \"https://space.bilibili.com/\"+str(i)+\"/#/\"\n start_urls.append(url)\n \n\n def start_requests(self):\n for url in self.start_urls:\n time.sleep(1)\n # 随机headers\n headers = {'User-Agent':random.choice(ua_list),\n 'Referer':'http://space.bilibili.com/'+str(random.randint(9000,10000))+'/'}\n yield SplashRequest(url=url, callback=self.parse, args={'wait':0.5},\n endpoint='render.html',splash_headers=headers,\n )\n\n def parse(self, response):\n # 爬虫item类\n item = BilibiliUserScrapyItem()\n\n #一些常规的元素抓取\n attention = response.xpath(\"//*[@id=\\\"n-gz\\\"]/text()\").extract_first()\n fans = response.xpath(\"//*[@id=\\\"n-fs\\\"]/text()\").extract_first()\n level = response.xpath(\"//*[@id=\\\"app\\\"]/div[1]/div[1]/div[2]/div[2]/div/div[2]/div[1]/a[1]/@lvl\").extract_first()\n # 由于未知的原因,部分页面无法正确加载某些元素\n # 当元素为None时,将其设置为‘null’\n # 但uid特殊,必须存在,所以从response.url中截取\n uid = response.url[27:-3]\n # uid = response.xpath(\"//*[@id=\\\"page-index\\\"]/div[2]/div[6]/div[2]/div/div/div[1]/div[1]/span[2]/text()\").extract_first()\n sex = response.xpath(\"//*[@id=\\\"h-gender\\\"]/@class\").extract_first()\n \n # 小数值直接int\n item['attention'] = int(attention)\n item['level'] = int(level)\n\n item['birthday'] = response.xpath(\"//*[@id=\\\"page-index\\\"]/div[2]/div[6]/div[2]/div/div/div[2]/div[1]/span[2]/text()\").extract_first()\n item['name'] = response.xpath(\"//*[@id=\\\"h-name\\\"]/text()\").extract_first().strip()\n item['place'] = response.xpath(\"//*[@id=\\\"page-index\\\"]/div[2]/div[6]/div[2]/div/div/div[2]/div[2]/a/text()\").extract_first()\n item['regtime'] = response.xpath(\"//*[@id=\\\"page-index\\\"]/div[2]/div[6]/div[2]/div/div/div[1]/div[2]/span[2]/text()\").extract_first()\n \n item['uid'] = int(uid)\n item['mid'] = uid\n # 对性别进行处理\n if len(sex.split(\" \")) == 3:\n item['sex'] = sex.split(\" \")[2]\n else:\n item['sex'] = 'null'\n \n # 对地址进行处理\n if item['place'] is None:\n item['place'] = \"null\" \n\n # 对fans进行处理\n if \"万\" in fans:\n item['fans'] = int(float(fans[:-3])*10000)\n else:\n item['fans'] = int(fans)\n\n # 对生日进行处理\n if item['birthday'] is None:\n item['birthday'] = \"null\"\n else:\n item['birthday'] = item['birthday'].strip()\n\n # 对注册时间进行处理\n if item['regtime'] is None:\n item['regtime'] = \"null\"\n else:\n item['regtime'] = item['regtime'].strip()\n\n # 这些项暂时无法直接从界面获取\n #item['coins'] = response.xpath(\"/html/body/div[1]/div/div[2]/div[3]/ul/li[1]/div/div[1]/div[2]/div[1]/a/span[2]/text()\").extract_first()\n #item['friend'] = item[\"fans\"]\n #item['exp'] = response.xpath(\"/html/body/div[1]/div/div[2]/div[3]/ul/li[1]/div/div[1]/div[3]/a/div/div[3]/div/text()\").extract_first()\n \n yield item","sub_path":"bilibili_user_scrapy/spiders/bilibili-user.py","file_name":"bilibili-user.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"525848421","text":"\n\"\"\"\n Guia de listas y matrices.\n Alumno: Facundo Emiliano Choque Silberman\n Profesor: Matías Bordone\n Año lectivo: ITSC 2020\n\"\"\"\nlista=[1,2,3,4,5,6,7,8,9,10]\nlista2=[1,1,2,2,3,3,4,4,5,5]\nvector1=[1,2,3]\nvector2=[-1,0,2]\n\ndef cuantosPares(lista):\n i=0\n for element in lista:\n if element%2==0:\n i=i+1\n return i\nprint(\"Numero de pares:\", cuantosPares(lista))\n\n\ndef sumaLista(lista):\n total=0\n for element in lista:\n total=total+element\n return total\nprint(\"La suma da:\",sumaLista(lista))\n\n\ndef multiplicaLista(lista):\n total=1\n for element in lista:\n total=total*element\n return total\nprint(\"La multiplicacion da:\",multiplicaLista(lista))\n\ndef maximoEnLista(lista):\n max=0\n for element in lista:\n if element>max:\n max=element\n return max\nprint(\"Maximo en la lista:\",maximoEnLista(lista))\n\ndef filtrarPalabrasn(lista,n):\n return lista[:n]\nprint(filtrarPalabrasn(lista,4))\n\ndef multiplicarVectores(vec1,vec2):\n suma=0\n if len(vec1)==len(vec2):\n for i in range(len(vec1)):\n suma=suma+vec1[i]*vec2[i]\n return suma\n\nprint(multiplicarVectores(vector1,vector2))\n\ndef eliminaDuplicados(lista):\n return set(lista)\nprint(eliminaDuplicados(lista2))\n\n","sub_path":"guia listas y matrices/cuantosPares.py","file_name":"cuantosPares.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"439027318","text":"# list\nlst = [1, \"2\", ['sd',1, {'key': ''}]]\nlst1 = [1, 2, 3]\n\n# dict\ndct = {\"key\": \"value\"}\ndct1 = {\"name\": 'Rostyslav'}\nname = dct1['name']\n\n# set\nst = {'1', '2', '3'}\n\n# bytearray\n# bytearray() method returns a bytearray\n# object which is an array of given bytes.\n# It gives a mutable sequence of\n# integers in the range 0 <= x < 256.\n#bytearray(source, encoding, errors)\n# simple list of integers\nlist = [1, 2, 3, 4]\n# iterable as source\narray = bytearray(list)\nprint(array)\n# bytearray(b'\\x01\\x02\\x03\\x04')\nprint(\"Count of bytes:\", len(array))\n# Count of bytes: 4\n\n# user-defined classes\n\n# int\ni = 1\n# float\nflt = 1.1\n# complex\ncmplx = complex(2, -3)\n# z = (2-3j)\n# bool\nbl = True\n# string\nstrng = 'str'\n# tuple\ntpl = (1, 2, 3)\n# range\nrng = range(3, 6)\n\n# frozenset\n# tuple of numbers\nnu = (1, 2, 3, 4, 5, 6, 7, 8, 9)\n# converting tuple to frozenset\nfnum = frozenset(nu)\n# frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})\n\n# bytes\nx = bytes(4)\n# x = b'\\x00\\x00\\x00\\x00'","sub_path":"lectures/advanced_data_types/mutable_immutable.py","file_name":"mutable_immutable.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"34588487","text":"import sys\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.svm import LinearSVC\nimport joblib\nimport os.path\n\ndef ModelTrain():\n df = pd.read_csv('moviereviews2.tsv',sep='\\t')\n\n blanks = []\n\n for ind,label,review in df.itertuples():\n if type(review) == str:\n if review.isspace():\n blanks.append(ind)\n\n\n df.dropna(inplace=True)\n\n df['label'].value_counts()\n\n X = df['review']\n y = df['label']\n\n\n X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33,random_state=42)\n\n text_clf = Pipeline([('tfidf',TfidfVectorizer()),('clf',LinearSVC())])\n text_clf.fit(X_train,y_train)\n joblib.dump(text_clf,'sentiment_model.sav')\n \ndef SentimentAnalysis(text):\n \n text_clf = joblib.load('sentiment_model.sav')\n prediction = text_clf.predict(text)\n \n return prediction\n \nif __name__ == \"__main__\":\n \n if os.path.exists('sentiment_model.sav'):\n print(SentimentAnalysis([sys.argv[1]]))\n else:\n ModelTrain()\n print(SentimentAnalysis([sys.argv[1]]))\n","sub_path":"RPA Challenge/Movie Search/Text Classification.py","file_name":"Text Classification.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"470067873","text":"# Level module used to execute program in memory\nimport math\n\nimport core.levString as strings\nimport core.levNumber as numbers\nimport core.levLogic as logic\nimport core.levConsole as console\nimport core.levVector as vectors\n\nfrom core.levConfig import config\nfrom core.classSession import Session\nfrom core.levSymbols import *\n\n# ----------------------------\n# Infix operator precedence\n# ----------------------------\nop_prec = {\n \"(\" : 81,\n \")\" : 80,\n \"[\" : 71,\n \"]\" : 70,\n \"!\" : 61,\n \"?\" : 60,\n 'bit_left' : 55,\n 'bit_right' : 54,\n \"bit_not\" : 53,\n \"bit_and\" : 52,\n \"bit_xor\" : 51,\n \"bit_or\" : 50,\n \"±\" : 45,\n \"^\" : 44,\n \"%\" : 43,\n \"*\" : 42,\n \"/\" : 42,\n \"-\" : 40,\n \"+\" : 40,\n \"#\" : 31,\n \"&\" : 30,\n \"<\" : 20,\n \">\" : 20,\n \">=\" : 20,\n \"<=\" : 20,\n \"==\" : 20,\n \"~=\" : 20,\n \"=\" : 20,\n \"~\" : 20,\n \"not\" : 13,\n \"and\" : 11,\n \"or\" : 10\n}\n# ----------------------------------------------------------\n# Note: other operators not included in op_prec:\n# ----------------------------------------------------------\n# Functional operators is, in, like\n# Set related operators (intersect, union)\n# ----------------------------------------------------------\n\nbuilt_in = {\n \"next\" :numbers.bi_next,\n \"prior\" :numbers.bi_prior,\n \"format\" :numbers.bi_format,\n \"first\" :vectors.bi_first,\n \"last\" :vectors.bi_last,\n \"length\" :vectors.bi_length,\n \"count\" :vectors.bi_count,\n \"parse\" :strings.bi_parse,\n \"replace\" :strings.bi_replace,\n \"find\" :strings.bi_find,\n \"input\" :console.bi_input,\n \"output\" :console.bi_output,\n \"print\" :console.bi_print\n}\n\n\n# ----------------------------------------------------------\n# Function \"postfix\" convert infix expression to postfix\n# expression can contain any operator from op_prec{}\n# infix parameter is a list of infix expression\n# ----------------------------------------------------------\ndef postfix(infix):\n postfix = [] # postfix expression stack (result)\n operator = [] # operator stack (intermediate)\n\n # -----------------------------------------------------------\n # determine if top symbol have precedence over current symbol\n # -----------------------------------------------------------\n def has_precedence(top,sym):\n assert top != \")\"\n if sym == \"(\":\n result = False\n elif top == \"(\":\n result = False\n elif sym == \")\":\n result = True\n else:\n result = op_prec[top] >= op_prec[sym]\n return result\n\n # -----------------------------------------------------------\n # scan all symbol in expression and append to postfix stack\n # -----------------------------------------------------------\n is_first = True\n for symbol in infix:\n #fix unary operator \"-\" if is first\n if is_first and symbol == \"-\":\n symbol = \"±\"\n is_first = (symbol == \"(\")\n #check operator precedence\n if symbol not in op_prec:\n postfix.append(symbol)\n else:\n while len(operator)>0:\n top_op = operator[-1]\n if has_precedence(top_op,symbol):\n operator.pop()\n if top_op !=\"(\":\n postfix.append(top_op)\n else:\n break\n if symbol!=\")\":\n operator.append(symbol)\n while len(operator)>0:\n top_op = operator.pop()\n if top_op not in (\"(\", \")\"):\n postfix.append(top_op)\n\n return postfix\n# end postfix function\n\n#-------------------------------------------------\n# recursive evaluate an POSTFIX expression\n# using reverse polish notation\n#-------------------------------------------------\n# stack = [term1, term2, op, op ...]\n#-------------------------------------------------\ndef evaluate(postfix):\n op = postfix.pop()\n if op == '±': # unary change sign\n return -evaluate(postfix)\n elif op in numbers.op_num:\n op2 = evaluate(postfix)\n op1 = evaluate(postfix)\n return numbers.op_num[op](op1, op2)\n elif op in logic.op_rel:\n op2 = evaluate(postfix)\n op1 = evaluate(postfix)\n return logic.op_rel[op](op1, op2)\n elif op in logic.op_log:\n if op ==\"not\":\n op1 = evaluate(postfix)\n return logic.op_log[op](op1)\n else:\n op2 = evaluate(postfix)\n op1 = evaluate(postfix)\n return logic.op_log[op](op1, op2)\n elif op in strings.op_str:\n op2 = evaluate(postfix)\n op1 = evaluate(postfix)\n return strings.op_str[op](op1,op2)\n elif op in numbers.fn_num:\n op1 = evaluate(postfix)\n return numbers.fn_num[op](op1)\n elif op == \"pi\":\n return math.pi # 3.1415926535\n elif op == \"e\":\n return math.e # 2.718281828\n elif op[0].isalpha():\n return op\n else:\n return float(op)\n\n# parse and evaluate an expression\n# used in console eval command\n# expression = 1+2+1/2\ndef evalPostfix(p_xp):\n str_build = []\n for s in setDigraph:\n if s in p_xp:\n raise Exception(\"digraph not supported\")\n # prepare expression for split\n for s in p_xp:\n if s in setSeparator and s != \".\":\n str_build.append(' ')\n str_build.append(s)\n str_build.append(' ')\n else:\n str_build.append(s)\n postfix_xp = \"\".join(str_build)\n # split expression into a list\n test = postfix_xp.split()\n result = postfix(test)\n final = evaluate(result)\n print(\" \".join(test), \"=\", final)\n\n\n#-----------------------------------------------------------\n# intermediate type checking\n#-----------------------------------------------------------\n# op1 is mandatory\n# op2 is optional\n#-----------------------------------------------------------\n# expression = tp1 op1 op2 tp2\n# expression = op1 tp2\n# expression = tp1 op1 tp2\n#-----------------------------------------------------------\ndef checkType(op1, op2, tp1, tp2):\n r_type = None\n message = None\n # two mandatory parameters\n if not tp2:\n message = \"Internal error: parameter tp2 is required\"\n if not op1:\n message = \"Internal error: parameter op1 is required\"\n # two operators are provided\n if op2:\n if op1 not in setLogicOperator:\n message = 'Expect logical operator found: \"%s\"' % (op1)\n elif op2 == 'not':\n if op1 not in (\"and\", \"or\"):\n message = 'Invalid combination of operators: \"%s %s\"' % (op1, op2)\n elif op1 == 'not':\n if op2 not in (\"in\", \"is\", \"like\"):\n message = 'Invalid combination of operators: \"%s %s\"' % (op1, op2)\n else:\n message = 'Invalid combination of operators: \"%s %s\"' % (op1, op2)\n # at least one operator is provided\n if op1 in numericOperator:\n r_type = NUMERIC\n if not tp1 and op1 == \"-\":\n message = \"Unexpected unary operator \"+ op1\n elif tp1 != NUMERIC or tp2 != NUMERIC:\n message = \"Incompatible operand types: %s and %s!\" % (tp1,tp2)\n elif op1 in relationOperator:\n r_type = LOGICAL\n if tp1 != tp2:\n message = \"Incompatible comparison between types %s and: %s!\" % (tp1, tp2)\n elif op1 in stringOperator:\n r_type = STRING\n if op1 == \"&\" and tp1 != STRING or tp2 != STRING:\n message = \"Incompatible operand types: %s and %s!\" % (tp1, tp2)\n elif op1 == \"#\" and tp1 != STRING:\n message = \"Incompatible type %s with operator: %s!\" % (tp1, op1)\n elif op1 in setLogicOperator:\n r_type = LOGICAL\n if (not tp1) and (op1 != 'not'):\n message= \"Unexpected unary operator %s\" % op1\n elif \"in\" in (op1,op2):\n if tp2!=STRING or tp2 not in setComposition:\n message = 'Incompatible type %s with operator: \"%s\"!' % (tp2, \"in\")\n elif tp1 != LOGICAL or tp2 != LOGICAL:\n message = \"Incompatible operand types: %s and %s!\" % (tp1, tp2)\n # invalidate result type in case of error\n if message:\n r_type = None\n return r_type, message\n\n\n# -----------------------------------\n# run program from syntax tree\n# -----------------------------------\ndef run(root):\n callStack = [] # a list of calls\n\n # start new session\n session = Session(None)\n\n # local recursion, build a statement\n def run_node(node):\n nonlocal callStack\n if node.cargo:\n type = node.getType()\n if node.lineIndex > 0:\n if node.indent == 0:\n print()\n elif node.indent > 0:\n print()\n print(\" \" * node.indent, end=\"\")\n # rebuild\n if type == STRING:\n print('\"' + node.cargo.replace('\"', \"''\") + '\"', end=\"\")\n elif type == KEYWORD:\n if node.indent == -1:\n print(' ', end=\"\")\n print(node.cargo, end=\"\")\n elif type == IDENTIFIER:\n prev = node.prevNode()\n if node.indent == -1 and prev and prev.getType() != SYMBOL:\n print(' ', end=\"\")\n print(node.cargo, end=\"\")\n elif type == LOGICAL:\n if node.indent == -1:\n print(' ', end=\"\")\n print(node.cargo, end=\"\")\n elif node.cargo in (',', '$'):\n print(node.cargo, end=\" \")\n else:\n print(node.cargo, end=\"\")\n # recursive for all children\n for child in node.children:\n run(child)\n\n # recursive function entry point\n run_node(root)\n return 0\n","sub_path":"core/levExecute.py","file_name":"levExecute.py","file_ext":"py","file_size_in_byte":9850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"648935401","text":"while True:\n try:\n while True:\n cantNotasIngresar=int(input(f\"Cantidad de notas a ingresar:\\n\"))\n if cantNotasIngresar>=0:\n break\n else:\n print(\"Ingrese un numero mayor a 0\")\n break\n\n except ValueError:\n print(f'Ingrese un numero')\n\nnotas=[]\n\nfor i in range(0,cantNotasIngresar,1):\n while True:\n try:\n while True:\n nota=float(input(f\"Ingrese la nota {i+1}:\\n\"))\n if nota>=0 and nota<=20:\n notas.append(nota)\n break\n else:\n print(\"Ingrese una nota entre 0 a 20\")\n break\n\n except ValueError:\n print(f'Ingrese un numero valido')\nsuma=0\nprom=0\nnumMax=-9999\nnumMin=9999\n\nfor nota in notas:\n if notanumMax:\n numMax=nota\n \n suma+=nota\n\nprom=suma/len(notas)\nprint(f'El promedio de las notas es: {prom}')\n\nprint(f'La nota mas alta es: {numMax}')\n\nprint(f'La nota mas baja es: {numMin}')\n\n ","sub_path":"Alonso/Breto3.py","file_name":"Breto3.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"514857506","text":"def dylan():\n x_1 = 5\n # x_2 = 2\n # CALCULATE BMI\n for i in range(10):\n\n x_1 = x_1 + x_1\n if (x_1) % 4 == 0:\n print('mod 4: ' + str(x_1))\n else:\n print('remainder ' + str(x_1 % 4))\n print(x_1)\n\n\ndef BMI(mass, height):\n bmi = mass * 3/height\n print(bmi)\n\ndylan()","sub_path":"cs5350/a06/svm/DYLAN.py","file_name":"DYLAN.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"463863411","text":"import simplejson as json\n\n# load disprot db\nwith open('./disprot.json', 'r') as f:\n disprot_data = json.load(f)\nf.close()\n# create disprot.fasta\nwith open('./disprot.fasta','w') as disprot_fasta:\n # parsing disprot json data\n for disprot in disprot_data:\n name = disprot[\"uniprot_accession\"]\n for pfam in disprot['pfam']:\n f_name = pfam['id']\n \n sequence = disprot['sequence']\n data = '>%s|%s\\n%s\\n'%(name,f_name,sequence)\n disprot_fasta.write(data) \n\ndisprot_fasta.close()\n","sub_path":"parser/json_parsing.py","file_name":"json_parsing.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"203744851","text":"# Imports\n# core parser class and functions\nfrom parser_core import *\n\n# main player parser class\nclass PlayerParser(WLParser):\n \"\"\"takes a player ID\"\"\"\n\n def __init__(self, playerID):\n baseURL = \"https://www.warlight.net/Profile?\"\n self.ID = playerID\n self.URL = self.makeURL(baseURL, p=playerID)\n\n ## exists\n @property\n @getPageData\n def exists(self):\n \"\"\"returns a boolean determining whether a player exists\"\"\"\n page = self.pageData\n marker = \"Sorry, the requested player was not found.\"\n return (marker not in page)\n\n ## inClan\n @property\n @getPageData\n @checkNonexistent\n def inClan(self):\n \"\"\"\n returns True if the player is in a clan,\n False otherwise\n remember that nonexistent players will return None\n \"\"\"\n return self.clanID is not None\n\n ## clanID\n @property\n @getPageData\n @checkNonexistent\n def clanID(self):\n \"\"\"returns ID number for player's clan\"\"\"\n page = self.pageData\n marker = '', ' -')\n\n ## isMember\n @property\n @getPageData\n @checkNonexistent\n def isMember(self):\n \"\"\"returns boolean (True if user is a Member)\"\"\"\n page = self.pageData\n memberString = 'id=\"MemberIcon\" title=\"WarLight Member\"'\n return (memberString in page)\n\n ## level\n @property\n @getPageData\n @checkNonexistent\n def level(self):\n \"\"\"returns player's level\"\"\"\n page = self.pageData\n return self.getIntegerValue(page, 'Level ')\n\n ## points\n @property\n @getPageData\n @checkNonexistent\n def points(self):\n \"\"\"returns points earned in last 30 days (int)\"\"\"\n page = self.pageData\n points = self.getTypedValue(page, 'days: ',\n (string.digits + \",\"))\n return int(points.replace(\",\",\"\"))\n\n ## email\n @property\n @getPageData\n @checkNonexistent\n def email(self):\n \"\"\"returns player (partial) e-mail as a string\"\"\"\n page = self.pageData\n marker = \"E-mail: \"\n end = \"
\"\n return self.getValueFromBetween(page, marker, end)\n\n ## link\n @property\n @getPageData\n @checkNonexistent\n def link(self):\n \"\"\"returns player-supplied link as a string\"\"\"\n page = self.pageData\n marker = \"Player-supplied link:\"\n end = \"
\"\n dataRange = self.getValueFromBetween(page, marker, end)\n return self.getValueFromBetween(dataRange, '\">', None)\n\n ## tagline\n @property\n @getPageData\n @checkNonexistent\n def tagline(self):\n \"\"\"returns player tagline as a string\"\"\"\n page = self.pageData\n marker = \"Tagline: \"\n end = \"
\"\n return self.getValueFromBetween(page, marker, end)\n\n ## bio\n @property\n @getPageData\n @checkNonexistent\n def bio(self):\n \"\"\"returns player bio as a string\"\"\"\n page = self.pageData\n marker = \"Bio: \"\n end = \"
\"\n return self.trimString(self.getValueFromBetween(page, marker, end))\n\n ## getJoinString\n @getPageData\n @checkNonexistent\n def getJoinString(self):\n \"\"\"\n returns player join date as a string\n formatted mm/dd/yyyy\n \"\"\"\n page = self.pageData\n marker = \"Joined WarLight: \"\n end = \"
\"\n return self.getValueFromBetween(page, marker, end)\n\n ## joinDate\n @property\n @getPageData\n @checkNonexistent\n def joinDate(self):\n \"\"\"returns player join date as a datetime object\"\"\"\n return self.getDate(self.getJoinString())\n\n ## getMemberString\n @getPageData\n @checkNonexistent\n def getMemberString(self):\n \"\"\"\n returns player membership date as a string\n formatted mm/dd/yyyy\n \"\"\"\n page = self.pageData\n marker = \"Member since \"\n end = \"\"\n if marker not in page: return \"\"\n return self.getValueFromBetween(page, marker, end)\n\n ## memberSince\n @property\n @getPageData\n @checkNonexistent\n def memberSince(self):\n \"\"\"\n returns player membership date as a datetime object\n if player is not a member, returns None\n \"\"\"\n memberString = self.getMemberString()\n if memberString == \"\": return None\n return self.getDate(memberString)\n\n ## currentGames\n @property\n @getPageData\n @checkNonexistent\n def currentGames(self):\n \"\"\"returns integer amount of ongoing multi-day\"\"\"\n page = self.pageData\n dataRange = self.getValueFromBetween(page,\n \"Currently in \", \"games\")\n if \"multi-day\" not in dataRange: return 0\n return self.getIntegerValue(dataRange, \"\")\n\n ## playedGames\n @property\n @getPageData\n @checkNonexistent\n def playedGames(self):\n \"\"\"returns integer amount of played games\"\"\"\n page = self.pageData\n return self.getIntegerValue(page, \"Played in \")\n\n ## percentRT\n @property\n @getPageData\n @checkNonexistent\n def percentRT(self):\n \"\"\"returns float percentage of real-time games (relative to played)\"\"\"\n page = self.pageData\n dataRange = self.getValueFromBetween(page, \"Played in\",\n \"
\")\n return self.getNumericValue(dataRange, \" (\")\n\n ## getLastSeenString\n @getPageData\n @checkNonexistent\n def getLastSeenString(self):\n \"\"\"\n returns string indicating time since user last performed\n an action; minimum value is \"less than 15 minutes ago\"\n \"\"\"\n page = self.pageData\n marker = \"Last seen \"\n end = \"\"\n dataRange = self.getValueFromBetween(page, marker, end)\n return self.getNumericValue(dataRange, \" (\")\n\n ## singlePlayerStats\n @property\n @getPageData\n @checkNonexistent\n def singlePlayerStats(self):\n \"\"\"\n returns a player's single-player stats as a dictionary\n formatted {'level name': {'turns': # of turns, 'gold star': (bool)}}\n \"\"\"\n page = self.pageData\n marker = \"

Single-player stats

\"\n gsMarker = 'img src=\"/Images/GoldStar.png\"'\n data = dict()\n if marker not in page: return data\n dataRange = self.getValueFromBetween(page, marker, \"',\n ':')\n levelTurns = self.getIntegerValue(dataPoint, \"Won in \")\n data[levelName] = {'turns': levelTurns,\n 'gold star': (gsMarker in dataPoint)}\n return data\n\n ## favoriteGames\n @property\n @getPageData\n @checkNonexistent\n def favoriteGames(self):\n \"\"\"\n returns a player's favorite games in a list of dictionaries:\n {'ID': ID (integer), 'name': name (string)}\n \"\"\"\n page = self.pageData\n data = list()\n marker = \"

Favorite Games

\"\n if marker not in page: return data\n end = \"

\"\n dataRange = self.getValueFromBetween(page, marker, end)\n dataSet = dataRange.split(\"GameID=\")[1:]\n for dataPoint in dataSet:\n gameID = self.getIntegerValue(dataPoint, \"\")\n gameName = self.getValueFromBetween(dataPoint,\n '\">', \"\")\n gameData = {'ID': gameID, 'name': gameName}\n data.append(gameData)\n return data\n\n ## favoriteTournaments\n @property\n @getPageData\n @checkNonexistent\n def favoriteTournaments(self):\n \"\"\"\n returns a player's favorite tournaments in a list of dictionaries\n {'ID': ID (integer), 'name': name (string), 'rank': rank of player (int)}\n if a player isn't ranked, rank is set to None\n \"\"\"\n page = self.pageData\n marker = \"

Tournaments

\"\n data = list()\n if marker not in page: return data\n dataRange = self.getValueFromBetween(page, marker, \"',\n \"\")\n data.append({'ID': tourneyID, 'name': tourneyName, 'rank': rank})\n return data\n\n ## ladderData\n @property\n @getPageData\n @checkNonexistent\n def ladderData(self):\n \"\"\"\n fetches a player's ladder data in a dictionary\n output[ladder name] is a dictionary\n {'team': teamID (integer), 'rank': rank (integer),\n 'rating': rating (integer), 'peak rank': (integer),\n 'peak rating': (integer)}\n rank, rating, peakRank, peakRating are None if inapplicable\n \"\"\"\n page = self.pageData\n marker = \"

Ladder Statistics

\"\n data = dict()\n if marker not in page: return data\n dataRange = self.getValueFromBetween(page, marker, \"',\n \"\")\n if (\"Not Ranked\" in dataPoint):\n rank = None\n else: rank = self.getIntegerValue(dataPoint, \"Ranked \")\n rating = self.getIntegerValue(dataPoint, \"rating of \")\n if (\"Best rating ever:\" not in dataPoint):\n peakRating = None\n else: peakRating = self.getIntegerValue(dataPoint,\n \"Best rating ever: \")\n if (\"best rank ever: \" not in dataPoint):\n peakRank = None\n else: peakRank = self.getIntegerValue(dataPoint,\n \"best rank ever: \")\n data[ladderName] = {'team': teamID, 'rank': rank, 'rating': rating,\n 'peak rank': peakRank, 'peak rating': peakRating}\n return data\n\n ## rankedGames\n @property\n @getPageData\n @checkNonexistent\n def rankedGames(self):\n \"\"\"\n returns a player's ranked data as a dictionary\n output['data'][gameType] is a dictionary\n {'wins' (int), 'games' (int), 'win percent' (float)}\n output['wins'] (integer): total ranked wins\n output['games'] (integer): total ranked games\n output['win percent'] (float): win percent for all ranked games\n \"\"\"\n page = self.pageData\n marker = \"

Ranked Games

\"\n data = dict()\n if marker not in page:\n return {'data': data, 'wins': None, 'games': None, 'win percent': None}\n dataRange = self.getValueFromBetween(page, marker, \" \")\n if \"ranked games (\" in dataRange:\n rankedWins = self.getIntegerValue(dataRange,\n \"ranked games (\")\n else:\n rankedWins = self.getIntegerValue(dataRange,\n \"ranked game (\")\n rankedPercent = Decimal(rankedWins) / Decimal(rankedCount)\n rankedPercent = float(rankedPercent * Decimal(100))\n dataSet = dataRange.split('color=\"#858585\"')[2:]\n for dataPoint in dataSet:\n gameType = self.getValueFromBetween(dataPoint,\n '>', ': \")\n gamesPlayed = self.getIntegerValue(dataPoint,\n \" / \")\n winPercent = Decimal(gamesWon) / Decimal(gamesPlayed)\n winPercent = float(winPercent * Decimal(100))\n data[gameType] = {'wins': gamesWon,\n 'games': gamesPlayed,\n 'win percent': winPercent}\n return {'data': data, 'wins': rankedWins,\n 'games': rankedCount, 'win percent': rankedPercent}\n\n ## previousNames\n @property\n @getPageData\n @checkNonexistent\n def previousNames(self):\n \"\"\"\n returns a list of previous names as dictionaries\n {'name': previous name (string), 'date': date of change (date object)}\n \"\"\"\n page = self.pageData\n marker = \"

Previously known as...\"\n data = list()\n if marker not in page: return data\n dataRange = self.getValueFromBetween(page, marker, \"(', \")\")\n until = self.getDate(untilString)\n data.append({'name': name, 'date': until})\n return data\n\n ## playSpeed\n @property\n @getPageData\n @checkNonexistent\n def playSpeed(self):\n \"\"\"\n returns play speed as a dictionary\n output[type]: average time (in hours)\n type is either \"Multi-Day Games\" or \"Real-Time Games\"\n \"\"\"\n page = self.pageData\n marker = \"

Play Speed

\"\n data = dict()\n if marker not in page: return data\n dataRange = self.getValueFromBetween(page, marker, \" \", \"
\")\n avgTime = self.timeConvert(avgString)\n data[typeMarker[:-1]] = avgTime\n return data\n\n ## favoriteMaps\n @property\n @getPageData\n @checkNonexistent\n def favoriteMaps(self):\n \"\"\"\n returns a player's favorite maps as a list of dictionaries\n {'name': (string), 'author': name (string), 'link': URL to map (str)}\n \"\"\"\n page = self.pageData\n baseURL = \"https://warlight.net\"\n marker = \"Favorite Maps

\"\n data = list()\n if marker not in page: return data\n dataRange = self.getValueFromBetween(page, marker, \"')\n name = self.getValueFromBetween(dataPoint,\n \"
\", \"
\")\n author = self.getValueFromBetween(dataPoint, \"by \",\n \"\")\n data.append({'name': name, 'author': author, 'link': baseURL+link})\n return data\n\n ## achievementRate\n @property\n @getPageData\n @checkNonexistent\n def achievementRate(self):\n \"\"\"returns integer % value representing achievements completed\"\"\"\n page = self.pageData\n marker = \"

Achievements\"\n if marker not in page: return 0\n dataRange = self.getValueFromBetween(page, marker,\n \"\")\n return self.getIntegerValue(dataRange, \"(\")\n","sub_path":"wl_parsers/player_parser.py","file_name":"player_parser.py","file_ext":"py","file_size_in_byte":19007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"405018134","text":"# name : slip \n# date : 2019/7/7 17:22 \n# e-mail : slip1233@126.com\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\n# 模拟浏览器发送请求\n# 内部创建socket\n\nr1 = requests.get('https://www.qu.la/book/199613/1102643.html/',\n headers={\n 'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'\n })\n\n# 查看下载下来的文本信息\nsoup = BeautifulSoup(r1.text, 'html.parser')\n\ncontent = soup.findAll('div', attrs={'id': 'content'})\n\nprint(content)","sub_path":"进程线程/day34/爬虫.py","file_name":"爬虫.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"38457365","text":"# 插入图表\n\"\"\"\nopenpyxl库支持创建各种图表,包括条形图,折线图,面积图,气泡图,散点图和饼图。\n\n根据文档,openpyxl仅支持在工作表中创建图表。 现有工作簿中的图表将丢失。\n\"\"\"\n\nfrom openpyxl import Workbook\nfrom openpyxl.chart import (\n Reference,\n Series,\n BarChart\n)\n# 创键工作表单\nbook = Workbook()\nsheet = book.active\n\nrows = [\n (\"USA\", 46),\n (\"China\", 38),\n (\"UK\", 29),\n (\"Russia\", 22),\n (\"South Korea\", 13),\n (\"Germany\", 11)\n]\n\nfor row in rows:\n sheet.append(row)\n pass\n\n# 创键数据轴\ndata = Reference(sheet, min_col=2, min_row=1, max_row=6, max_col=2)\n# 创键类别轴\ncategs = Reference(sheet, min_col=1, min_row=1, max_row=6, max_col=1)\n# 绘制条形图\nchart = BarChart()\nchart.add_data(data=data)\nchart.set_categories(categs)\n# 使用legend和majorGridlines属性,可以关闭图例和主要网格线。\nchart.legend = None\nchart.y_axis.majorGridlines = None\n# 设置每一个条形图都有不同的颜色\nchart.varyColors = True\n# 设置标题\nchart.title = \"Olympic Gold medals in London\"\n# 将条形图添加到工作簿\nsheet.add_chart(chart, \"A8\")\nbook.save(\"pro02_13.xlsx\")\n","sub_path":"python/excel/pro02_13.py","file_name":"pro02_13.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"559167684","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n url(r'', include('abstract.urls')),\n url(r'', include('accounts.urls')),\n url(r'^admin/', admin.site.urls),\n url(r'home/', include('main.urls')),\n url(r'devices/', include('devices.urls')),\n url(r'receipts/', include('receipts.urls')),\n url(r'expenses/', include('expenses.urls')),\n url(r'attendance/', include('attendance.urls')),\n]\n\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"electron_project/electron_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"421328351","text":"from io import BytesIO\nfrom time import sleep\nfrom PIL import Image\nfrom picamera import PiCamera\nfrom zbarlight import scan_codes\nimport paho.mqtt.client as mqttClient\nimport time\n\ndef on_connect(client, userdata, flags, rc):\n \n if rc == 0:\n \n print(\"Connected to broker\")\n \n global Connected #Use global variable\n Connected = True #Signal connection \n else:\n print(\"Connection failed\")\n \nConnected = False #global variable for the state of the connection\n \nbroker_address= \"localhost\"\nport = 1883\nuser = \"user\"\npassword = \"user\"\n\nclient = mqttClient.Client(\"Python\") #create new instance\nclient.username_pw_set(user, password=password) #set username and password\nclient.on_connect= on_connect #attach function to callback\nclient.connect(broker_address, port=port) #connect to broker\n \nclient.loop_start() #start the loop\n \nwhile Connected != True: #Wait for connection\n time.sleep(0.1)\n \ntry:\n while True:\n stream = BytesIO()\n codes = None\n\n\n with PiCamera() as camera:\n camera.start_preview()\n sleep(2)\n while codes is None:\n stream.seek(0)\n camera.capture(stream, 'jpeg')\n stream.seek(0)\n codes = scan_codes(['qrcode'], Image.open(stream))\n camera.stop_preview()\n print(codes)\n qr_code_re = [int(s) for s in codes[0].split() if s.isdigit()]\n\n \n values = ','.join(str(v) for v in qr_code_re)\n print(values)\n client.publish(\"QR_code_ref\", values)\n\nexcept KeyboardInterrupt:\n \n client.disconnect()\n client.loop_stop()\n\n\n\n\n\n\n","sub_path":"QRcode.py","file_name":"QRcode.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"650728528","text":"#!/usr/bin/env python3\n\"\"\"Tag draftified articles.\"\"\"\n# Author : JJMC89\n# License: MIT\nimport argparse\nimport re\nfrom functools import lru_cache\nfrom typing import Any, FrozenSet, Generator, Iterable, Optional, Union\n\nimport pywikibot\nfrom pywikibot.bot import (\n _GLOBAL_HELP,\n ExistingPageBot,\n NoRedirectPageBot,\n SingleSiteBot,\n)\nfrom pywikibot.pagegenerators import GeneratorFactory, parameterHelp\n\n\n@lru_cache()\ndef get_redirects(\n pages: FrozenSet[pywikibot.Page],\n) -> FrozenSet[pywikibot.Page]:\n \"\"\"Given pages, return all possible titles.\"\"\"\n link_pages = set()\n for page in pages:\n while page.isRedirectPage():\n try:\n page = page.getRedirectTarget()\n except pywikibot.exceptions.CircularRedirectError:\n break\n if not page.exists():\n continue\n link_pages.add(page)\n for redirect in page.backlinks(filter_redirects=True):\n link_pages.add(redirect)\n return frozenset(link_pages)\n\n\ndef has_template(\n page: pywikibot.Page,\n templates: Union[str, Iterable[Union[pywikibot.Page, str]]],\n) -> bool:\n \"\"\"\n Return True if the page has one of the templates. False otherwise.\n\n :param page: page to check\n :param templates: templates to check\n \"\"\"\n if isinstance(templates, str):\n templates = [templates]\n template_pages = get_redirects(\n frozenset(\n tpl\n if isinstance(tpl, pywikibot.Page)\n else pywikibot.Page(page.site, tpl, ns=10)\n for tpl in templates\n )\n )\n return bool(template_pages & set(page.templates()))\n\n\nclass DfyTaggerBot(SingleSiteBot, ExistingPageBot, NoRedirectPageBot):\n \"\"\"Bot to tag draftified articles.\"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Initialize.\"\"\"\n self.available_options.update( # pylint: disable=no-member\n {\n 'summary': 'Add {{{{{tpl}}}}}',\n 'template': 'drafts moved from mainspace',\n }\n )\n super().__init__(**kwargs)\n template = self.opt.template\n self.add_text = f'\\n\\n{{{{subst:{template}}}}}'\n self.summary = self.opt.summary.format(tpl=template)\n\n def skip_page(self, page: pywikibot.Page) -> bool:\n \"\"\"Skip non-drafts and drafts with the template.\"\"\"\n if page.namespace() != 118:\n pywikibot.warning(f'{page!r} is not a draft.')\n return True\n if has_template(page, self.opt.template):\n pywikibot.warning(f'{page!r} already has the template.')\n return True\n return super().skip_page(page)\n\n def check_disabled(self) -> None:\n \"\"\"Check if the task is disabled. If so, quit.\"\"\"\n class_name = self.__class__.__name__\n page = pywikibot.Page(\n self.site,\n f'User:{self.site.username()}/shutoff/{class_name}.json',\n )\n if page.exists():\n content = page.get(force=True).strip()\n if content:\n pywikibot.error(f'{class_name} disabled:\\n{content}')\n self.quit()\n\n def treat_page(self) -> None:\n \"\"\"Process one page.\"\"\"\n self.check_disabled()\n self.put_current(\n self.current_page.text.strip() + self.add_text,\n summary=self.summary,\n nocreate=True,\n )\n\n\ndef draftified_page_generator(\n site: pywikibot.site.BaseSite,\n start: Optional[pywikibot.Timestamp],\n) -> Generator[pywikibot.Page, None, None]:\n \"\"\"\n Yield draftified pages based on page moves.\n\n :param site: site to yield page moves from\n \"\"\"\n gen = site.logevents(\n logtype='move', namespace=0, start=start, reverse=True\n )\n for move in gen:\n if move.target_ns == 118:\n yield move.target_page\n\n\ndef main(*args: str) -> None:\n \"\"\"Process command line arguments and invoke bot.\"\"\"\n local_args = pywikibot.handle_args(args, do_help=False)\n site = pywikibot.Site()\n site.login()\n gen_factory = GeneratorFactory(site)\n script_args = gen_factory.handle_args(local_args)\n parser = argparse.ArgumentParser(\n description='Tag draftified articles',\n epilog=re.sub(\n r'\\n\\n?-help +.+?(\\n\\n-|\\s*$)',\n r'\\1',\n _GLOBAL_HELP + parameterHelp,\n flags=re.S,\n ),\n formatter_class=argparse.RawDescriptionHelpFormatter,\n allow_abbrev=False,\n )\n parser.add_argument(\n '--always',\n '-a',\n action='store_true',\n help='Do not prompt to save changes',\n )\n parser.add_argument(\n '--start',\n type=pywikibot.Timestamp.fromISOformat,\n help='Timestamp to start from',\n metavar='%Y-%m-%dT%H:%M:%SZ',\n )\n parser.add_argument(\n '--summary', help='Edit aummary for the bot', default=argparse.SUPPRESS\n )\n parser.add_argument(\n '--template', help='Template to add', default=argparse.SUPPRESS\n )\n parsed_args = vars(parser.parse_args(args=script_args))\n start = parsed_args.pop('start')\n gen = None if gen_factory.gens else draftified_page_generator(site, start)\n gen = gen_factory.getCombinedGenerator(gen=gen)\n DfyTaggerBot(generator=gen, site=site, **parsed_args).run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"enwiki/draftification_tagger.py","file_name":"draftification_tagger.py","file_ext":"py","file_size_in_byte":5326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"339523319","text":"from pysandesh.gen_py.sandesh.ttypes import SandeshLevel\nfrom cfgm_common.exceptions import SearchServiceError\n\nSEARCH_ERROR = 0\nDB_ERROR = 1\nOP_CREATE = 'create'\nOP_UPDATE = 'update'\nOP_DELETE = 'delete'\nOP_REINDEX = 'reindex'\n\nclass VncDBRollBackHandler(object):\n \"\"\"\n This class handles roll back logic for DB changes\n \"\"\"\n\n def __init__(self, application_mgr, msg_bus, db_mgr, search_mgr):\n self._application_mgr = application_mgr\n self._msg_bus = msg_bus\n self._search_mgr = search_mgr\n # end __init__\n\n def handle_error(self, error_type, error_exception, operation, obj_type, object_ids, object_dict=None):\n if error_type is SEARCH_ERROR:\n do_raise = self.__handler_search_error(operation, obj_type, object_ids, object_dict)\n raise SearchServiceError(str(error_exception)) if do_raise else None\n if error_type is DB_ERROR:\n do_raise = self.__handle_db_error(operation, obj_type, object_ids, object_dict)\n raise error_exception if do_raise else None\n else:\n raise NotImplementedError\n\n # end handle_error\n\n def config_log(self, msg, level = SandeshLevel.SYS_NOTICE):\n self._application_mgr.config_log(msg, level=level)\n\n # end config_log\n\n def __handle_db_error(self, operation, obj_type, object_ids, object_dict=None):\n return self.__rollback_action_on_db_failure(operation, obj_type, object_ids, object_dict)\n\n # end __handle_db_error\n\n def __handler_search_error(self, operation, obj_type, object_ids, object_dict=None):\n try:\n return self.__rollback_action_on_es_failure(operation, obj_type, object_ids, object_dict)\n except Exception as e:\n raise SearchServiceError(str(e))\n\n # end __handler_search_error\n\n def __rollback_action_on_db_failure(self, operation, obj_type, obj_ids, obj_dict):\n \"\"\"\n Rollback operation if DB reports failures\n :param operation:\n :param obj_type:\n :param obj_ids:\n :param obj_dict:\n :return:\n \"\"\"\n raise_exception = False\n if operation == OP_CREATE:\n try:\n self._search_mgr.search_delete(obj_type, obj_ids)\n except Exception as e:\n #Swallow any exception and re raise root exception\n self.config_log(\"Failed to delete object from es\")\n finally:\n self.__reconcile_delete(obj_type, obj_ids)\n raise_exception = True\n if operation == OP_UPDATE:\n # Reindex object\n self.__rollback_es_update(obj_type, obj_ids)\n raise_exception = True\n if operation == OP_DELETE:\n # raise exception up but do nothing since DB delete failed no rollback needed\n raise_exception = True\n\n return raise_exception\n\n # end rollback_on_db_failure\n\n def __rollback_action_on_es_failure(self, operation, obj_type, obj_ids, obj_dict):\n \"\"\"\n Rollback operation failures and decide if exception needs to be raised up\n :param operation:\n :param obj_type:\n :param obj_ids:\n :param obj_dict:\n :return: boolean\n \"\"\"\n if self._search_mgr.is_doc_type_mapped(obj_type):\n if operation == OP_CREATE:\n # No OP just raise exception and send error to user\n return True\n if operation == OP_UPDATE:\n # No OP on Update failure send user error\n return True\n if operation == OP_DELETE:\n # reconcile don't raise\n self.__reconcile_delete(obj_type, obj_ids)\n return False\n\n # end __rollback_es_failure\n\n def __rollback_es_delete(self, obj_type, obj_ids):\n #put to GC queue\n message = self.__reconciliation_message(OP_REINDEX, obj_type, obj_ids)\n self._msg_bus.search_rc_publish(message)\n # end __rollback_delete\n\n def __rollback_es_update(self, obj_type, obj_ids):\n #put to GC queue\n message = self.__reconciliation_message(OP_REINDEX, obj_type, obj_ids)\n self._msg_bus.search_rc_publish(message)\n\n # end __rollback_es_failure\n\n def __reconcile_delete(self, obj_type, obj_ids):\n # put to GC queue\n message = self.__reconciliation_message(OP_DELETE, obj_type, obj_ids)\n self._msg_bus.search_rc_publish(message)\n # end __reconcile_delete\n\n def __reconciliation_message(self, op, obj_type, obj_ids):\n if self._search_mgr.reconcile():\n message = {'reconcile': op, 'index': self._search_mgr.index}\n message.update(obj_ids)\n message.update({'type': obj_type})\n return message\n return None\n # end __reconciliation_message\n","sub_path":"api-server/app_cfg_server/server_core/vnc_db_rollback.py","file_name":"vnc_db_rollback.py","file_ext":"py","file_size_in_byte":4796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"368115294","text":"# coding: UTF-8\nimport random\nimport re\n\nfrom slackbot.bot import respond_to, listen_to, idle\n\n\n@respond_to('hello$', re.IGNORECASE)\ndef hello_reply(message):\n message.reply('hello sender!')\n\n\n@respond_to('^reply_webapi$')\ndef hello_webapi(message):\n message.reply_webapi('hello there!', attachments=[{\n 'fallback': 'test attachment',\n 'fields': [\n {\n 'title': 'test table field',\n 'value': 'test table value',\n 'short': True\n }\n ]\n }])\n\n\n@respond_to('^reply_webapi_not_as_user$')\ndef hello_webapi_not_as_user(message):\n message.reply_webapi('hi!', as_user=False)\n\n\n@respond_to('hello_formatting')\ndef hello_reply_formatting(message):\n # Format message with italic style\n message.reply('_hello_ sender!')\n\n\n@listen_to('hello$')\ndef hello_send(message):\n message.send('hello channel!')\n\n\n@listen_to('hello_decorators')\n@respond_to('hello_decorators')\ndef hello_decorators(message):\n message.send('hello!')\n\n@listen_to('hey!')\ndef hey(message):\n message.react('eggplant')\n\n\n@respond_to(u'你好')\ndef hello_unicode_message(message):\n message.reply(u'你好!')\n\n\n# idle tests\nIDLE_TEST = {'which': None, 'channel': None}\n\n\n@respond_to('start idle test ([0-9]+)')\n@listen_to('start idle test ([0-9]+)')\ndef start_idle_test(message, i):\n print(\"---------- start idle test! -----------\")\n IDLE_TEST['which'] = int(i)\n IDLE_TEST['channel'] = message._body['channel']\n print(\"Idle test is now {which} on channel {channel}\".format(**IDLE_TEST))\n # TESTING ONLY, don't rely on this behavior\n\n\n# idle function testing\n# tests 0 and 1: rtm and webapi work from idle function 1\n# tests 2 and 3: rtm and webapi work from idle function 2\n# test 4: both idle functions can operate simultaneously\n@idle\ndef idle_1(client):\n which = IDLE_TEST['which']\n msg = \"I am bored %s\" % which\n if which == 0:\n client.rtm_send_message(IDLE_TEST['channel'], msg)\n elif which == 1:\n client.send_message(IDLE_TEST['channel'], msg)\n elif which == 4:\n if random.random() <= 0.5:\n client.rtm_send_message(IDLE_TEST['channel'], \"idle_1 is bored\")\n\n\n@idle()\ndef idle_2(client):\n which = IDLE_TEST['which']\n msg = \"I am bored %s\" % which\n if which == 2:\n client.rtm_send_message(IDLE_TEST['channel'], msg)\n elif which == 3:\n client.send_message(IDLE_TEST['channel'], msg)\n elif which == 4:\n if random.random() <= 0.5:\n client.rtm_send_message(IDLE_TEST['channel'], \"idle_2 is bored\")\n","sub_path":"slackbot/plugins/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"567632530","text":"\"\"\"\nHelper functions for calculating statistical data\n\"\"\"\n\nfrom datetime import datetime\nimport lib.util as util\n\n__author__ = \"Joshua Gilman\"\n__version__ = \"0.1.0\"\n__license__ = \"MIT\"\n\ndef calc_popular_times(data):\n \"\"\" Returns the most popular month, day of week, and hour of day\n\n Performs the mode() operation on the given DataFrame for the `start_time`\n month, day, and hour. Converts the numerical month and day into their \n respective string representations for readability. Also converts the hour\n into the 12 hour AM/PM form to be sensitive to locality. Returns results in\n a dictionary. \n\n Args:\n data (DataFrame): The data to process\n\n Returns:\n A dictionary with the calculated results:\n { \"month\": ,\n \"day_of_week\": ,\n \"hour\": <-- Formatted in 12 hour AM/PM\n }\n \"\"\"\n result = {}\n\n # Calculate results\n result['month'] = int(data[util.COLS['start_time']].dt.month.mode()[0])\n result['day_of_week'] = int(\n data[util.COLS['start_time']].dt.dayofweek.mode()[0])\n result['hour'] = int(data[util.COLS['start_time']].dt.hour.mode()[0])\n \n # Format results\n month_dict = util.get_months_dict()\n day_dict = util.get_days_dict()\n\n result['month'] = month_dict[result['month']]\n result['day_of_week'] = day_dict[result['day_of_week']]\n\n dt = datetime.strptime(str(result['hour'])[1:], '%H')\n result['hour'] = dt.strftime('%I %p')\n\n return result\n\ndef calc_popular_stations(data):\n \"\"\" Returns the most popular start station, end station, and trip\n\n Performs the mode() operation on the given DataFrame for the `start_station`\n and `end_station`. Groups by both the start and end station and then\n identifies the max number of occurrences to determine the most popular\n route being used. Returns the results in a dictionary.\n\n Args:\n data (DataFrame): the data to be processed\n\n Returns:\n A dictionary with the calculated results:\n { \"start_station\": ,\n \"end_station\": ,\n \"trip\": <-- Start station, End station\n }\n \"\"\"\n result = {}\n\n # Calculate results\n result['start_station'] = data[util.COLS['start_station']].mode()[0]\n result['end_station'] = data[util.COLS['end_station']].mode()[0]\n result['trip'] = data.groupby(\n [util.COLS['start_station'], util.COLS['end_station']]).size().idxmax()\n\n return result\n\ndef calc_trip_durations(data):\n \"\"\" Returns total travel time and average travel time\n\n Performs the sum() and mean() operation on the total trip time (end_time - \n start_time) to determine total and average times. Returns the result in a \n dictionary.\n\n Args:\n data (DataFrame): the data to be processed\n\n Returns:\n A dictionary with the calculated results:\n { \"total_time\": ,\n \"avg_time\": ,\n }\n \"\"\"\n result = {}\n\n # Calculate results\n result['total_time'] = str(\n (data[util.COLS['end_time']] - data[util.COLS['start_time']]).sum())\n result['avg_time'] = str(\n (data[util.COLS['end_time']] - data[util.COLS['start_time']]).mean())\n\n return result\n\ndef calc_user_unfo(data):\n \"\"\" Returns counts of each user type and gender, aas well as earliest, \n most recent and most common year of birth where applicable\n\n Calculates the counts of each user type. If `gender` exists in the given\n DataFrame, calculates the count for each gender type. If `birth_year`\n exists in the given DataFrame, calculates the earliest year using min(),\n the most recent year using max(), and the most common year using mode().\n Returns the result in a dictionary.\n\n Args:\n data (DataFrame): the data to be processed\n\n Returns:\n A dictionary with the calculated results \n (None for non-applicable values):\n { \"type_count\": )>, <-- type name, count\n \"gender_count\": )>, <-- gender name, count\n \"earliest_year\": ,\n \"recent_year\": ,\n \"common_year\": \n }\n \"\"\"\n result = {}\n\n counts = data[util.COLS['user_type']].value_counts()\n result['type_count'] = tuple(zip(counts.index,counts))\n\n if util.COLS['gender'] in data.columns:\n counts = data[util.COLS['gender']].value_counts()\n result['gender_count'] = tuple(zip(counts.index,counts))\n else:\n result['gender_count'] = None\n\n if util.COLS['birth_year'] in data.columns:\n result['earliest_year'] = int(data[util.COLS['birth_year']].min())\n result['recent_year'] = int(data[util.COLS['birth_year']].max())\n result['common_year'] = int(data[util.COLS['birth_year']].mode())\n else:\n result['earliest_year'] = None\n result['recent_year'] = None\n result['common_year'] = None\n\n return result","sub_path":"lib/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"267094411","text":"import csv\nimport logging\nimport os\nimport typing\n\nfrom lms.lmsdb import models\nfrom lms.lmsweb import config\n\nimport requests\n\n\n_logger = logging.getLogger(__name__)\n\n\nclass UserToCreate(typing.NamedTuple):\n name: str\n email: str\n password: str\n\n def to_dict(self):\n return self._asdict()\n\n @classmethod\n def get_fields(cls):\n return cls._fields\n\n\nclass UserRegistrationCreator:\n _session = requests.Session()\n\n def __init__(self, users_to_create: typing.Sequence[UserToCreate]):\n self._users_to_create = users_to_create\n self._failed_users: typing.List[UserToCreate] = []\n\n @property\n def users_to_create(self):\n return self._users_to_create\n\n @property\n def failed_users(self):\n return self._failed_users\n\n @classmethod\n def from_csv_file(cls, file_path: str) -> 'UserRegistrationCreator':\n \"\"\"\n CSV file should be with three columns,\n and in the header: first_name,last_name,email and password[optional]\n \"\"\"\n\n if not os.path.exists(file_path):\n raise ValueError\n\n with open(file_path, 'r') as file_reader:\n csv_records = csv.DictReader(file_reader)\n\n users = []\n for record in csv_records:\n if 'password' not in record:\n record['password'] = models.User.random_password()\n users.append(UserToCreate(**record))\n\n return cls(users)\n\n def dump_failed_users_to_csv(self, file_path: str) -> None:\n with open(file_path, 'w') as file_writer:\n writer = csv.DictWriter(file_writer, UserToCreate.get_fields())\n for failed_user in self._failed_users:\n writer.writerow(failed_user.to_dict())\n\n def run_registration(self):\n for user in self._users_to_create:\n try:\n self._get_or_create_user_in_model(user)\n self._send_user_email_registration(user)\n except Exception:\n _logger.exception(\n 'Failed to create user %s, continue to next user',\n user.email)\n self._failed_users.append(user)\n\n @staticmethod\n def _get_or_create_user_in_model(user: UserToCreate) -> None:\n _logger.info('Create user with email: %s', user.email)\n models.User.get_or_create(**{\n models.User.mail_address.name: user.email,\n models.User.username.name: user.email,\n }, defaults={\n models.User.fullname.name: f'{user.name}',\n models.User.role.name: models.Role.get_student_role(),\n models.User.password.name: user.password,\n })\n\n def _send_user_email_registration(self, user: UserToCreate) -> None:\n response = None\n text = self._build_user_text(user)\n url = f'https://api.eu.mailgun.net/v3/{config.MAILGUN_DOMAIN}/messages'\n try:\n response = self._session.post(\n url=url,\n data={\n 'from': f'lms@{config.MAILGUN_DOMAIN}',\n 'to': user,\n 'subject': 'Learn Python - מערכת הגשת התרגילים',\n 'html': text,\n },\n auth=('api', config.MAILGUN_API_KEY))\n response.raise_for_status()\n except Exception:\n _logger.exception(\n 'Failed to create user %s. response: %s',\n user.email,\n response.content)\n raise\n\n @staticmethod\n def _build_user_text(user: UserToCreate) -> str:\n details = {\n 'username': user.email,\n 'password': user.password,\n 'url': config.SERVER_ADDRESS,\n }\n msg = config.MAIL_WELCOME_MESSAGE\n for k, v in details.items():\n msg = msg.replace(f'@@{k}@@', v)\n return msg\n\n\nif __name__ == '__main__':\n registration = UserRegistrationCreator.from_csv_file(config.USERS_CSV)\n print(registration.users_to_create) # noqa: T001\n registration.run_registration()\n registration.dump_failed_users_to_csv(config.ERRORS_CSV)\n","sub_path":"lms/lmsweb/tools/registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"29718336","text":"from django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.urls import reverse\nimport fitz\nfrom base.models import Ticket\nimport pandas as pd\nimport os\nfrom django.conf import settings\nimport base64\nimport urllib.request\n\n\nfrom django.core.files.storage import default_storage\n\ndef ilustrator(request):\n\t#return HttpResponse(\"

Página de formulario

\")\n\tdir_url = request.GET.get('name')\n\tfile = request.GET.get('file')\n\tarchivo = base64.b64decode(dir_url).decode(\"utf-8\") \n\t\n\tborrador = os.path.join(settings.MEDIA_ROOT)\n\timprenta = os.path.join(settings.MEDIA_ROOT,'imprenta')\n\n\tif archivo in os.listdir(imprenta):\n\t\tprint(\"imprenta\\n\"*2)\n\t\tdire = 'media/imprenta'\n\telif archivo in os.listdir(borrador):\n\t\tprint(\"borrador\\n\"*2)\n\t\tdire = 'media'\n\tdire = 'media'\n\n\tif request.user.is_authenticated:\n\t\tprint(\"\\n\"*2,file[-3:],\"\\n\"*2)\n\t\tif file[-3:] == '.ai':\n\t\t\turllib.request.urlretrieve(archivo, 'borrame.ia')\n\t\t\tarchivo = 'borrame.ia'\n\t\t\t#archivo = dire + '/'+ archivo\n\t\t\tdoc = fitz.open(archivo)\n\t\t\tdoc.save(\"media/tmp_.pdf\")\n\t\t\tarchivo = \"/media/tmp_.pdf\"\n\t\telse:\n\t\t\tarchivo = archivo\n\t\tcampos = {\n\t\t'archivo': archivo,\n\t\t }\n\t\treturn render(request, \"ilustrator.html\", campos )\n\telse:\n\t\treturn render(request, 'home.html')\n\ndef vista_imprenta(request):\n\tticket =Ticket()\n\tif request.method == 'POST':\n\t\tall_items = Ticket.objects.filter(status=13)\n\t\t\n\t\td = []\n\t\tfor e in all_items:\n\t\t\td.append({\"no\":e.no, \"subject\":e.subject, \"archivo\":e.archivo})\n\t\t\tprint(\"Registro %s, %s, %s\" % ( e.subject, e.description, e.archivo))\n\t\tcontex = {\n\t\t\"all_items\": d\n\t\t}\t\t\n\t\treturn render(request, \"vista_imprenta.html\", contex )\n\n\telif request.method == 'GET': \n\n\t\tall_items = Ticket.objects.filter(status=13)\n\t\tfiles = ticket.archivo.storage\n\t\td = []\n\t\tfor e in all_items:\n\t\t\td.append({\n\t\t\t\t\"no\":e.no, \n\t\t\t\t\"subject\":e.subject, \n\t\t\t\t\"archivo\":e.archivo, \n\t\t\t\t\"baja\":files.url(str(e.archivo)),\n\t\t\t\t\"status\":e.status\n\t\t\t\t})\n\t\tprint(d)\t\n\t\treturn render(request, \"vista_imprenta.html\", {'all_items':d} )\n\n\t#return HttpResponse(\"

Página de dash

\")\n\n\n","sub_path":"web_uoct/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"532879193","text":"'''\nUSAGE: python run.py \"AAPL\" \"2015-01-01\" \"2016-01-01\" \"2016-01-01\" \"2016-04-01\"\n'''\n\nimport argparse\nimport pandas as pd\nimport datetime as dt\n\nimport util as ut\nimport policy_learner as pl\n\n\ndef main(verbose = True):\n\n parser = argparse.ArgumentParser()\n parser.add_argument('symbol', type=str, help=\"Company\")\n parser.add_argument('train_start', type=str, help=\"Start date of Training\")\n parser.add_argument('train_end', type=str, help=\"End date of Training\")\n parser.add_argument('test_start', type=str, help=\"Start date of Testing\")\n parser.add_argument('test_end', type=str, help=\"End date of Testing\")\n args = parser.parse_args()\n\n # instantiate the strategy learner\n learner = pl.PolicyLearner(verbose = verbose)\n # set parameter for company\n sym = args.symbol\n\n #########\n # TRAIN #\n #########\n # set parameters for training the learner\n train_s_date = list(map(lambda x:int(x),args.train_start.split('-')))\n train_stdate =dt.datetime(train_s_date[0],train_s_date[1],train_s_date[2])\n train_e_date = list(map(lambda x:int(x),args.train_end.split('-')))\n train_enddate =dt.datetime(train_e_date[0],train_e_date[1],train_e_date[2])\n\n # train the learner\n learner.add_evidence(symbol = sym, sd = train_stdate, ed = train_enddate)\n\n ########\n # TEST #\n ########\n # set parameters for testing\n test_s_date = list(map(lambda x:int(x),args.test_start.split('-')))\n test_stdate = dt.datetime(test_s_date[0], test_s_date[1], test_s_date[2])\n test_e_date = list(map(lambda x:int(x),args.test_end.split('-')))\n test_enddate = dt.datetime(test_e_date[0], test_e_date[1], test_e_date[2])\n\n # test the learner\n learner.test_policy(symbol = sym, sd = test_stdate, ed = test_enddate)\n\n\nif __name__==\"__main__\":\n main(verbose = False)","sub_path":"code/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"230047441","text":"# LERvalKate0consisSEMnegKcadaKparSOMATimp1eK\n# provavelmente com ERRO. \nk=-1\nwhile(k!=0):\n while(k<0):\n k=int(input('Digite o Valor de K '))\n if(k%2==0):\n som=0\n for i in range(2,k):\n if(i%2!=0):\n som+=i\n print(f'O Somatório é {som}')\n k=-1","sub_path":"Todas/# LERvalKate0consisSEMnegKcadaKparSOMATimp1eK.py","file_name":"# LERvalKate0consisSEMnegKcadaKparSOMATimp1eK.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"205618253","text":"files = os.popen('file *').readlines()\n\nzips = []\nproblems = []\nfor f in files:\n if f.endswith('(MS-DOS, OS/2, NT)\\n') == True:\n zips.append(f)\n elif f.endswith('data\\n') == True:\n problems.append(f)\n\nzipFiles = list(map(lambda x: x.replace(': gzip compressed data, from FAT filesystem (MS-DOS, OS/2, NT)', ''), zips))\nproblemFiles = list(map(lambda x: x.replace(': data', ''), problems))\n\nz = open('zips', 'a+')\nfor name in zipFiles:\n z.write(name)\n\np = open('problems', 'a+')\nfor name in problemFiles:\n p.write(name)\n","sub_path":"python/separate_zipped_warc_file.py","file_name":"separate_zipped_warc_file.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"354293010","text":"\n\nfrom xai.brain.wordbase.nouns._powerboat import _POWERBOAT\n\n#calss header\nclass _POWERBOATS(_POWERBOAT, ):\n\tdef __init__(self,): \n\t\t_POWERBOAT.__init__(self)\n\t\tself.name = \"POWERBOATS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"powerboat\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_powerboats.py","file_name":"_powerboats.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"217303980","text":"def display_hash(hashTable):\n for i in range(len(hashTable)):\n print(i, end=\" \")\n\n for j in hashTable[i]:\n print(\"-->\", end=\" \")\n print(j, end=\" \")\n\n print()\n\n\n# Creating Hashtable as\n# a nested list.\n\n\n# Hashing Function to return\n# key for every value.\ndef hashing(keyvalue):\n return keyvalue % len(hash_table)\n\ndef search(hashtable, keyvalue):\n hash_key = hashing(keyvalue)\n index = hashtable[hash_key]\n for index_list, record in enumerate(index):\n record_key = record\n if record_key == keyvalue:\n return True\n #return index\n break\n# Insert Function to add\n# values to the hash table\ndef delete(hashtable, keyvalue):\n if search(hashtable, keyvalue):\n hash_key = hashing(keyvalue)\n index = hashtable[hash_key]\n for index_list, record in enumerate(index):\n record_key = record\n if record_key == keyvalue:\n index.pop(index_list)\n #search(hashtable, keyvalue).pop(keyvalue)\n\n\n\n\n\ndef insert(hashtable, value):\n hash_key = hashing(value)\n hashtable[hash_key].append(value)\n\n\n# Driver Cod\nhash_size = int(input())\nhash_table = [[] for _ in range(hash_size)]\ntheinput = input()\nn = theinput.split()\nmap_n = map(int, n)\n\nlist_n = list(map_n)\nlist_n.pop()\n\nfor num in list_n:\n insert(hash_table, num)\n\nnum_search = int(input())\ndelete(hash_table, num_search)\n#if search(hash_table, num_search):\n# print(\"Encontrado\\n\")\n# delete(hash_table, num_search)\n#else:\n# print(\"Não encontrado\\n\")\ndisplay_hash(hash_table)\n","sub_path":"teste_hash_table.py","file_name":"teste_hash_table.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"598892718","text":"'''\nCreated by Samvel Khalatyan, Nov 19, 2012\nCopyright 2012, All rights reserved\n'''\n\nimport os.path\n\nimport yaml\n\nimport lib.config\n\ndef load():\n ''' load favorites '''\n\n cfg = {}\n if os.path.exists(lib.config.favorite()):\n with open(lib.config.favorite(), 'r') as input_:\n cfg = yaml.load('\\n'.join(input_))\n\n return cfg\n\ndef save(cfg):\n ''' save favorites '''\n\n with open(lib.config.favorite(), 'w') as output_:\n yaml.dump(cfg, output_)\n","sub_path":"lib/favorite/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"452247579","text":"import os\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect, JsonResponse, HttpResponse\nfrom .forms import UploadFileForm\nfrom .forms import TypeInTextForm\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.core.files import File\nfrom django.core.files.storage import default_storage\nfrom django.core.files.base import ContentFile\nfrom io import BytesIO\n# from .forms import FileFieldForm\n# from django.views.generic.edit import FormView\nfrom templatesite import settings\nimport requests\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\n\nHSE_API_ROOT = os.environ.get(\"HSELING_API_ROOT\", \"http://hse-api-web/\")\n\n\ndef web_index(request):\n return render(request, 'index.html',\n context={})\n\n\ndef web_about(request):\n return render(request, 'about.html',\n context={})\n\ndef web_research(request):\n return render(request, 'research.html',\n context={})\n\ndef web_documentation(request):\n return render(request, 'documentation.html',\n context={})\n\ndef web_contact(request):\n return render(request, 'contact.html',\n context={})\n\n\ndef web_main(request):\n return render(request, 'main.html',\n context={})\n\n# context={\"status\": request.GET.get('status')}\n\ndef web_status(request):\n task_id = request.GET.get('task_id')\n if task_id:\n url = HSE_API_ROOT + \"status/\" + task_id\n content = requests.get(url)\n result = content.json()\n if result.get('status') == 'SUCCESS':\n content = requests.get(HSE_API_ROOT + 'files/' + result.get('result', [\"\"])[0])\n result['raw'] = content.content.decode('utf-8')\n return JsonResponse(result)\n return JsonResponse({\"error\": \"No task id\"})\n\n\ndef handle_uploaded_file(f, modules):\n\n # files = {'file[]': list(f)}\n # files = {'file[]': f}\n url = HSE_API_ROOT + \"upload\"\n content = requests.post(url, files=f)\n find_file_id = content.json()\n file_ids = list()\n for num in range(len(find_file_id)):\n file_id = find_file_id[str(num)]['file_id']\n file_ids.append(file_id)\n\n if file_ids:\n file_ids = [file_id[7:] for file_id in file_ids]\n file_ids = \",\".join(file_ids)\n # file_id = file_id[7:]\n url = HSE_API_ROOT + \"process/\" + file_ids\n content = requests.post(url, data=modules)\n\n\n else:\n raise Exception(content.json())\n response = list(content.json().values())\n\n return response\n\n\ndef delete_temp_files(path_lst):\n '''fuction to clean data storage after sending files to api'''\n\n for path in path_lst:\n if default_storage.exists(path):\n default_storage.delete(path)\n\n\ndef handle_text(modules):\n files = {'file[]': open(settings.MEDIA_ROOT + 'temporary.txt', 'rb')}\n url = HSE_API_ROOT + \"upload\"\n content = requests.post(url, files=files)\n find_file_id = content.json()\n file_id = find_file_id['0']['file_id']\n\n if file_id:\n file_id = file_id[7:]\n url = HSE_API_ROOT + \"process/\" + file_id\n content = requests.post(url, data=modules)\n\n\n else:\n raise Exception(content.json())\n response = list(content.json().values())\n\n return response\n\n@csrf_protect\ndef web_upload_file(request):\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n modules = list(filter(lambda t: t[0] in form.cleaned_data['modules'], form.fields['modules'].choices))\n modules = [f[0] for f in modules]\n modules = ','.join(modules)\n files = request.FILES.getlist('file')\n filenames = [file.name for file in files]\n [default_storage.save(file.name, ContentFile(file.read())) for file in files]\n multiple_files = [('file[]', open(settings.MEDIA_ROOT +\n filename, 'rb')) for filename in filenames]\n task_ids = handle_uploaded_file(multiple_files, modules)\n path_lst_temp_files = [str(settings.MEDIA_ROOT + filename) for filename in filenames]\n delete_temp_files(path_lst_temp_files)\n task_ids = ','.join(task_ids)\n return HttpResponseRedirect('main?task_id=' + str(task_ids))\n else:\n form = UploadFileForm()\n return render(request, 'main.html', {'form_upload': form})\n\n@csrf_protect\ndef web_type_in(request):\n if request.method == 'POST':\n form = TypeInTextForm(request.POST, request.FILES)\n if form.is_valid():\n modules = list(filter(lambda t: t[0] in form.cleaned_data['modules'], form.fields['modules'].choices))\n modules = [f[0] for f in modules]\n modules = ','.join(modules)\n file = open(settings.MEDIA_ROOT + 'temporary.txt', 'wb')\n myfile = File(file)\n subject = form.cleaned_data['text']\n subject = bytes(subject, encoding='utf-8')\n myfile.write(subject)\n myfile.close()\n file.close()\n task_ids = handle_text(modules)\n task_ids = ','.join(task_ids)\n return HttpResponseRedirect('main?task_id=' + str(task_ids))\n else:\n form = TypeInTextForm()\n return render(request, 'type_in.html', {'form_text': form})","sub_path":"src/web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"143085088","text":"import sys\nfrom Constantes import Constante\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_Minima_Accueil(object):\n \n\n \n def setupUi(self, Minima_Accueil):\n \n \n\n x,y = Constante.xmax, Constante.ymax\n self.nombre = 0\n \n Minima_Accueil.setObjectName(\"Minima_Accueil\")\n Minima_Accueil.resize(1240, 813)\n self.centralwidget = QtWidgets.QWidget(Minima_Accueil)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.groupBox_Accueil = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox_Accueil.setEnabled(True)\n self.groupBox_Accueil.setGeometry(QtCore.QRect(210, 50, 10000, 1000))\n self.groupBox_Accueil.setTitle(\"\")\n self.groupBox_Accueil.setObjectName(\"groupBox_Accueil\")\n self.textBrowser = QtWidgets.QTextBrowser(self.groupBox_Accueil)\n self.textBrowser.setGeometry(QtCore.QRect(20, 30, 590, 170))\n self.textBrowser.setObjectName(\"textBrowser\")\n self.Button_Ac_Jouer = QtWidgets.QPushButton(self.groupBox_Accueil)\n self.Button_Ac_Jouer.setGeometry(QtCore.QRect(120, 210, 350, 100))\n self.Button_Ac_Jouer.setObjectName(\"Button_Ac_Jouer\")\n self.Button_Ac_Quitter = QtWidgets.QPushButton(self.groupBox_Accueil)\n self.Button_Ac_Quitter.setGeometry(QtCore.QRect(120, 430, 350, 90))\n self.Button_Ac_Quitter.setObjectName(\"Button_Ac_Quitter\")\n self.Button_Ac_Charger = QtWidgets.QPushButton(self.groupBox_Accueil)\n self.Button_Ac_Charger.setGeometry(QtCore.QRect(120, 320, 350, 100))\n self.Button_Ac_Charger.setObjectName(\"Button_Ac_Charger\")\n \n \n self.groupBox_Jeu = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox_Jeu.hide()\n self.groupBox_Jeu.setGeometry(QtCore.QRect(0, 0, 2000, 1000))\n self.groupBox_Jeu.setAutoFillBackground(False)\n self.groupBox_Jeu.setTitle(\"\")\n self.groupBox_Jeu.setObjectName(\"groupBox_Jeu\")\n \n self.conteneur = QtWidgets.QWidget( self.groupBox_Jeu)\n self.conteneur.setGeometry(QtCore.QRect(0,0, x*36,y*36))\n self.conteneur.setStyleSheet(\"\")\n self.conteneur.setObjectName(\"conteneur\")\n \n self.Button_Ready = QtWidgets.QPushButton(self.groupBox_Jeu)\n self.Button_Ready.setGeometry(QtCore.QRect(50,100, 500, 300))\n self.Button_Ready.setObjectName(\"Button_Ready\")\n self.Button_Ready.clicked.connect(self.Button_Ready.hide)\n\n\n \n self.textBrowser_Tours_restants = QtWidgets.QTextBrowser(self.groupBox_Jeu)\n self.textBrowser_Tours_restants.setGeometry(QtCore.QRect(1000, 30, 270, 30))\n self.textBrowser_Tours_restants.setObjectName(\"textBrowser_Tours_restants\")\n self.lcdNumber_Tours_restant = QtWidgets.QLCDNumber(self.groupBox_Jeu)\n self.lcdNumber_Tours_restant.setGeometry(QtCore.QRect(1055, 30, 70, 30))\n self.lcdNumber_Tours_restant.setObjectName(\"lcdNumber_Tours_restant\")\n self.textBrowser_Metal = QtWidgets.QTextBrowser(self.groupBox_Jeu)\n self.textBrowser_Metal.hide()\n self.textBrowser_Metal.setGeometry(QtCore.QRect(1000, 70, 250, 30))\n self.textBrowser_Metal.setObjectName(\"textBrowser_Metal\")\n self.lcdNumber_Metal = QtWidgets.QLCDNumber(self.groupBox_Jeu)\n self.lcdNumber_Metal.hide()\n self.lcdNumber_Metal.setGeometry(QtCore.QRect(1150, 70, 70, 30))\n self.lcdNumber_Metal.setSegmentStyle(QtWidgets.QLCDNumber.Filled)\n self.lcdNumber_Metal.setObjectName(\"lcdNumber_Metal\")\n self.textBrowser_Energie = QtWidgets.QTextBrowser(self.groupBox_Jeu)\n self.textBrowser_Energie.hide()\n self.textBrowser_Energie.setGeometry(QtCore.QRect(1000, 110, 250, 30))\n self.textBrowser_Energie.setObjectName(\"textBrowser_Energie\")\n self.lcdNumber_Energie = QtWidgets.QLCDNumber(self.groupBox_Jeu)\n self.lcdNumber_Energie.hide()\n self.lcdNumber_Energie.setGeometry(QtCore.QRect(1150, 110, 70, 30))\n self.lcdNumber_Energie.setObjectName(\"lcdNumber_Energie\")\n self.Defenseur = QtWidgets.QGroupBox(self.groupBox_Jeu)\n self.Defenseur.hide()\n self.Defenseur.setGeometry(QtCore.QRect(990, 560, 450, 170))\n self.Defenseur.setObjectName(\"Defenseur\")\n self.pushButton = QtWidgets.QPushButton(self.Defenseur)\n self.pushButton.setGeometry(QtCore.QRect(0, 30, 90, 30))\n self.pushButton.setObjectName(\"pushButton\")\n self.scrollArea = QtWidgets.QScrollArea(self.Defenseur)\n self.scrollArea.hide()\n self.scrollArea.setGeometry(QtCore.QRect(0, 70, 180, 80))\n self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 150, 80))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.Button_Foreuse = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.Button_Foreuse.setGeometry(QtCore.QRect(0, 0, 120, 30))\n self.Button_Foreuse.setObjectName(\"Button_Foreuse\")\n self.Button_Panneau_Solaire = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.Button_Panneau_Solaire.setGeometry(QtCore.QRect(0, 30, 120, 30))\n self.Button_Panneau_Solaire.setObjectName(\"Button_Panneau_Solaire\")\n self.Button_J_D_B_Fermer = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.Button_J_D_B_Fermer.setGeometry(QtCore.QRect(120, 0, 30, 30))\n self.Button_J_D_B_Fermer.setText(\"\")\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\"croix_rouge.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.Button_J_D_B_Fermer.setIcon(icon)\n self.Button_J_D_B_Fermer.setObjectName(\"Button_J_D_B_Fermer\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.pushButton_2 = QtWidgets.QPushButton(self.Defenseur)\n self.pushButton_2.setGeometry(QtCore.QRect(100, 30, 90, 30))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.scrollArea_2 = QtWidgets.QScrollArea(self.Defenseur)\n self.scrollArea_2.hide()\n self.scrollArea_2.setGeometry(QtCore.QRect(200,70, 170, 80))\n self.scrollArea_2.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.scrollArea_2.setAutoFillBackground(False)\n self.scrollArea_2.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.scrollArea_2.setWidgetResizable(True)\n self.scrollArea_2.setProperty(\"toolTipDuration\", -1)\n self.scrollArea_2.setObjectName(\"scrollArea_2\")\n self.scrollAreaWidgetContents_2 = QtWidgets.QWidget()\n self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 150, 80))\n self.scrollAreaWidgetContents_2.setObjectName(\"scrollAreaWidgetContents_2\")\n self.Button_Robot_Ouvrier = QtWidgets.QPushButton(self.scrollAreaWidgetContents_2)\n self.Button_Robot_Ouvrier.setGeometry(QtCore.QRect(0, 30, 120, 30))\n self.Button_Robot_Ouvrier.setObjectName(\"Button_Robot_Ouvrier\")\n self.Button_J_D_U_Fermer = QtWidgets.QPushButton(self.scrollAreaWidgetContents_2)\n self.Button_J_D_U_Fermer.setGeometry(QtCore.QRect(120, 0, 30, 30))\n self.Button_J_D_U_Fermer.setText(\"\")\n self.Button_J_D_U_Fermer.setIcon(icon)\n self.Button_J_D_U_Fermer.setObjectName(\"Button_J_D_U_Fermer\")\n self.Button_Robot_Combat = QtWidgets.QPushButton(self.scrollAreaWidgetContents_2)\n self.Button_Robot_Combat.setGeometry(QtCore.QRect(0, 0, 120, 30))\n self.Button_Robot_Combat.setObjectName(\"Button_Robot_Combat\")\n self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)\n self.Attaquant = QtWidgets.QGroupBox(self.groupBox_Jeu)\n self.Attaquant.hide()\n self.Attaquant.setGeometry(QtCore.QRect(990, 560, 360, 130))\n self.Attaquant.setObjectName(\"Attaquant\")\n self.Jeu_A_Unitees = QtWidgets.QPushButton(self.Attaquant)\n self.Jeu_A_Unitees.setGeometry(QtCore.QRect(0, 30, 90, 30))\n self.Jeu_A_Unitees.setObjectName(\"Jeu_A_Unitees\")\n self.scrollArea_3 = QtWidgets.QScrollArea(self.Attaquant)\n self.scrollArea_3.hide()\n self.scrollArea_3.setGeometry(QtCore.QRect(0, 70, 180, 50))\n self.scrollArea_3.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.scrollArea_3.setWidgetResizable(True)\n self.scrollArea_3.setObjectName(\"scrollArea_3\")\n self.scrollAreaWidgetContents_3 = QtWidgets.QWidget()\n self.scrollAreaWidgetContents_3.setGeometry(QtCore.QRect(0, 0, 130, 50))\n self.scrollAreaWidgetContents_3.setObjectName(\"scrollAreaWidgetContents_3\")\n self.Button_Scorpion = QtWidgets.QPushButton(self.scrollAreaWidgetContents_3)\n self.Button_Scorpion.setGeometry(QtCore.QRect(0, 0, 120, 30))\n self.Button_Scorpion.setObjectName(\"Button_Scorpion\")\n self.Button_J_A_Fermer = QtWidgets.QPushButton(self.scrollAreaWidgetContents_3)\n self.Button_J_A_Fermer.setGeometry(QtCore.QRect(120, 0, 30, 30))\n self.Button_J_A_Fermer.setText(\"\")\n self.Button_J_A_Fermer.setIcon(icon)\n self.Button_J_A_Fermer.setObjectName(\"Button_J_A_Fermer\")\n self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3)\n self.textBrowser_U_dispo = QtWidgets.QTextBrowser(self.Attaquant)\n self.textBrowser_U_dispo.setGeometry(QtCore.QRect(90, 30, 100, 30))\n self.textBrowser_U_dispo.setObjectName(\"textBrowser_U_dispo\")\n self.lcdNumber_Unitdispo = QtWidgets.QLCDNumber(self.Attaquant)\n self.lcdNumber_Unitdispo.setGeometry(QtCore.QRect(190, 30, 70, 30))\n self.lcdNumber_Unitdispo.setObjectName(\"lcdNumber_Unitdispo\")\n self.Bouton_Jeu_Quitter = QtWidgets.QPushButton(self.groupBox_Jeu)\n self.Bouton_Jeu_Quitter.setGeometry(QtCore.QRect(1300, 740, 90, 30))\n self.Bouton_Jeu_Quitter.setObjectName(\"Bouton_Jeu_Quitter\")\n self.Bouton_Sauvegarde = QtWidgets.QPushButton(self.groupBox_Jeu)\n self.Bouton_Sauvegarde.setGeometry(QtCore.QRect(1000, 740, 90, 30))\n self.Bouton_Sauvegarde.setObjectName(\"Bouton_Sauvegarde\")\n self.Bouton_Findetour = QtWidgets.QPushButton(self.groupBox_Jeu)\n self.Bouton_Findetour.setGeometry(QtCore.QRect(1130, 740, 90, 30))\n self.Bouton_Findetour.setObjectName(\"Bouton_Findetour\")\n \n self.Defaite = QtWidgets.QMessageBox(self.groupBox_Jeu)\n self.Defaite.setIcon(QtWidgets.QMessageBox.Information)\n self.Defaite.setText(\"Les attaquants gagnent\")\n self.Defaite.setWindowTitle(\"Fin de partie\")\n self.Defaite.setStandardButtons(QtWidgets.QMessageBox.Ok)\n self.Defaite.buttonClicked.connect(self.Defaite.close)\n self.Defaite.buttonClicked.connect(Minima_Accueil.close)\n self.Defaite.hide()\n \n self.Victoire = QtWidgets.QMessageBox(self.groupBox_Jeu)\n self.Victoire.setIcon(QtWidgets.QMessageBox.Information) \n self.Victoire.setText(\"Le défenseur gagne\")\n self.Victoire.setWindowTitle(\"Fin de partie\")\n self.Victoire.setStandardButtons(QtWidgets.QMessageBox.Ok)\n self.Victoire.buttonClicked.connect(self.Victoire.close)\n self.Victoire.buttonClicked.connect(Minima_Accueil.close)\n self.Victoire.hide()\n \n \n\n self.tr_defenseur_text = QtWidgets.QTextBrowser(self.groupBox_Jeu)\n self.tr_defenseur_text.setText(\"Tour du Défenseur\")\n self.tr_defenseur_text.setGeometry(QtCore.QRect(1000, 200, 200, 30))\n self.tr_defenseur_text.hide()\n \n self.tr_attaquant_1_text = QtWidgets.QTextBrowser(self.groupBox_Jeu)\n self.tr_attaquant_1_text.setText(\"Tour de l'attaquant n°0\")\n self.tr_attaquant_1_text.setGeometry(QtCore.QRect(1000, 200, 200, 30))\n self.tr_attaquant_1_text.hide()\n \n self.tr_attaquant_2_text = QtWidgets.QTextBrowser(self.groupBox_Jeu)\n self.tr_attaquant_2_text.setText(\"Tour de l'attaquant n°1\")\n self.tr_attaquant_2_text.setGeometry(QtCore.QRect(1000, 200, 200, 30))\n self.tr_attaquant_2_text.hide()\n \n self.tr_attaquant_3_text = QtWidgets.QTextBrowser(self.groupBox_Jeu)\n self.tr_attaquant_3_text.setText(\"Tour de l'attaquant n°2\")\n self.tr_attaquant_3_text.setGeometry(QtCore.QRect(1000, 200, 200, 30))\n self.tr_attaquant_3_text.hide()\n \n self.tr_attaquant_4_text = QtWidgets.QTextBrowser(self.groupBox_Jeu)\n self.tr_attaquant_4_text.setText(\"Tour de l'attaquant n°3\")\n self.tr_attaquant_4_text.setGeometry(QtCore.QRect(1000, 200, 200, 30))\n self.tr_attaquant_4_text.hide()\n \n self.Sauvegarde = QtWidgets.QMessageBox(self.centralwidget)\n self.Sauvegarde.setIcon(QtWidgets.QMessageBox.Information) \n self.Sauvegarde.setText(\"Sauvegarde réussie\")\n self.Sauvegarde.setWindowTitle(\"Sauvegarde\")\n self.Sauvegarde.setStandardButtons(QtWidgets.QMessageBox.Ok)\n self.Sauvegarde.buttonClicked.connect(self.Sauvegarde.close)\n self.Sauvegarde.hide()\n \n self.Chargement = QtWidgets.QMessageBox(self.centralwidget)\n self.Chargement.setIcon(QtWidgets.QMessageBox.Information) \n self.Chargement.setText(\"Chargement réussie\")\n self.Chargement.setWindowTitle(\"Chargement\")\n self.Chargement.setStandardButtons(QtWidgets.QMessageBox.Ok)\n self.Chargement.buttonClicked.connect(self.Chargement.close)\n self.Chargement.hide()\n \n self.info = QtWidgets.QGroupBox(self.groupBox_Jeu)\n self.info.setEnabled(True)\n self.info.setGeometry(QtCore.QRect(990, 270, 240, 200))\n self.info.setObjectName(\"groupBox_info\")\n self.info.hide()\n self.textBrowser_nomU = QtWidgets.QTextBrowser(self.info)\n self.textBrowser_nomU.setGeometry(QtCore.QRect(10, 10, 100, 30))\n self.textBrowser_nomU.setObjectName(\"textBrowser_nomU\")\n self.textBrowser_nomU.setText(\"nom :\")\n self.textBrowser_nomUn = QtWidgets.QTextBrowser(self.info)\n self.textBrowser_nomUn.setGeometry(QtCore.QRect(110, 10, 100, 30))\n self.textBrowser_nomUn.setObjectName(\"textBrowser_nomUn\")\n self.textBrowser_appartenance = QtWidgets.QTextBrowser(self.info)\n self.textBrowser_appartenance.setGeometry(QtCore.QRect(10, 50, 100, 30))\n self.textBrowser_appartenance.setObjectName(\"textBrowser_nomU\")\n self.textBrowser_appartenance.setText(\"appartenance :\")\n self.textBrowser_appartenanceUn = QtWidgets.QTextBrowser(self.info)\n self.textBrowser_appartenanceUn.setGeometry(QtCore.QRect(110, 50, 100, 30))\n self.textBrowser_appartenanceUn.setObjectName(\"textBrowser_appartenanceUn\")\n self.textBrowser_statut = QtWidgets.QTextBrowser(self.info)\n self.textBrowser_statut.setGeometry(QtCore.QRect(10, 90, 100, 30))\n self.textBrowser_statut.setObjectName(\"textBrowser_statut\")\n self.textBrowser_statut.setText(\"statut :\")\n self.textBrowser_statutUn = QtWidgets.QTextBrowser(self.info)\n self.textBrowser_statutUn.setGeometry(QtCore.QRect(110, 90, 100, 30))\n self.textBrowser_statutUn.setObjectName(\"textBrowser_statutUn\")\n self.textBrowser_position = QtWidgets.QTextBrowser(self.info)\n self.textBrowser_position.setGeometry(QtCore.QRect(10, 130, 100, 30))\n self.textBrowser_position.setObjectName(\"textBrowser_position\")\n self.textBrowser_position.setText(\"position :\")\n self.textBrowser_positionUn = QtWidgets.QTextBrowser(self.info)\n self.textBrowser_positionUn.setGeometry(QtCore.QRect(110, 130, 100, 30))\n self.textBrowser_positionUn.setObjectName(\"textBrowser_positionUn\")\n self.textBrowser_sante = QtWidgets.QTextBrowser(self.info)\n self.textBrowser_sante.setGeometry(QtCore.QRect(10, 170, 100, 30))\n self.textBrowser_sante.setObjectName(\"textBrowser_sante\")\n self.textBrowser_sante.setText(\"sante/valeur :\")\n self.textBrowser_santeUn = QtWidgets.QTextBrowser(self.info)\n self.textBrowser_santeUn.setGeometry(QtCore.QRect(110, 170, 100, 30))\n self.textBrowser_santeUn.setObjectName(\"textBrowser_santeUn\")\n \n self.groupBox_Charger = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox_Charger.hide()\n self.groupBox_Charger.setEnabled(True)\n self.groupBox_Charger.setGeometry(QtCore.QRect(200, 300, 350, 130))\n self.groupBox_Charger.setTitle(\"Chargement\")\n self.groupBox_Charger.setObjectName(\"groupBox_Charger\")\n self.textBrowser_nom = QtWidgets.QTextBrowser(self.groupBox_Charger)\n self.textBrowser_nom.setGeometry(QtCore.QRect(0, 20, 200, 30))\n self.textBrowser_nom.setObjectName(\"textBrowser_nom\")\n self.textBrowser_nom.setText(\"Nom de la sauvegarde\")\n self.nom_charger = QtWidgets.QLineEdit(self.groupBox_Charger)\n self.nom_charger.setGeometry(QtCore.QRect(210, 20, 110, 30))\n self.nom_charger.setObjectName(\"Nom de la partie à charger\")\n self.Ch_annuler = QtWidgets.QPushButton(self.groupBox_Charger)\n self.Ch_annuler.setGeometry(QtCore.QRect(0, 60, 320, 30))\n self.Ch_annuler.setObjectName(\"Ch_annuler\")\n \n self.Ch_annuler.clicked.connect(self.groupBox_Charger.hide)\n self.Ch_annuler.clicked.connect(self.groupBox_Accueil.show)\n self.Button_Ac_Charger.clicked.connect(self.groupBox_Charger.show)\n self.Button_Ac_Charger.clicked.connect(self.groupBox_Accueil.hide)\n \n self.groupBox_Sauvegarde = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox_Sauvegarde.hide()\n self.groupBox_Sauvegarde.setEnabled(True)\n self.groupBox_Sauvegarde.setGeometry(QtCore.QRect(1000, 400, 350, 130))\n self.groupBox_Sauvegarde.setTitle(\"Sauvegarde\")\n self.groupBox_Sauvegarde.setObjectName(\"groupBox_Charger\")\n self.textBrowser_nomS = QtWidgets.QTextBrowser(self.groupBox_Sauvegarde)\n self.textBrowser_nomS.setGeometry(QtCore.QRect(0, 20, 200, 30))\n self.textBrowser_nomS.setObjectName(\"textBrowser_nomS\")\n self.textBrowser_nomS.setText(\"Nom de la sauvegarde\")\n self.nom_sauvegarde = QtWidgets.QLineEdit(self.groupBox_Sauvegarde)\n self.nom_sauvegarde.setGeometry(QtCore.QRect(210, 20, 110, 30))\n self.nom_sauvegarde.setObjectName(\"Nom de la Sauvegarde\") \n self.S_annuler = QtWidgets.QPushButton(self.groupBox_Sauvegarde)\n self.S_annuler.setGeometry(QtCore.QRect(0, 60, 320, 30))\n self.S_annuler.setObjectName(\"S_annuler\")\n self.S_annuler.setText(\"Annuler\")\n\n self.Bouton_Sauvegarde.clicked.connect(self.groupBox_Sauvegarde.show) \n self.Bouton_Sauvegarde.clicked.connect(self.groupBox_Jeu.hide)\n self.S_annuler.clicked.connect(self.groupBox_Sauvegarde.hide)\n self.S_annuler.clicked.connect(self.groupBox_Jeu.show)\n \n self.groupBox_Option = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox_Option.hide()\n self.groupBox_Option.setEnabled(True)\n self.groupBox_Option.setGeometry(QtCore.QRect(80, 0, 850, 650))\n self.groupBox_Option.setTitle(\"\")\n self.groupBox_Option.setObjectName(\"groupBox_Option\")\n self.textBrowser_2 = QtWidgets.QTextBrowser(self.groupBox_Option)\n self.textBrowser_2.setGeometry(QtCore.QRect(140, 10, 200, 80))\n self.textBrowser_2.setObjectName(\"textBrowser_2\")\n self.textBrowser_IA_2 = QtWidgets.QTextBrowser(self.groupBox_Option)\n self.textBrowser_IA_2.setGeometry(QtCore.QRect(0, 120, 250, 40))\n self.textBrowser_IA_2.setObjectName(\"textBrowser_IA_2\")\n self.checkBox_Option_IA_OUI = QtWidgets.QCheckBox(self.groupBox_Option)\n self.checkBox_Option_IA_OUI.setGeometry(QtCore.QRect(260, 130, 90, 25))\n self.checkBox_Option_IA_OUI.setObjectName(\"checkBox_Option_IA_OUI\")\n \n self.groupBox_Accueil_nb_IA = QtWidgets.QGroupBox(self.groupBox_Option)\n self.groupBox_Accueil_nb_IA.setEnabled(True)\n self.groupBox_Accueil_nb_IA.setGeometry(QtCore.QRect(0, 160, 300, 170))\n self.groupBox_Accueil_nb_IA.setAcceptDrops(False)\n self.groupBox_Accueil_nb_IA.setInputMethodHints(QtCore.Qt.ImhHiddenText)\n self.groupBox_Accueil_nb_IA.setTitle(\"\")\n self.groupBox_Accueil_nb_IA.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.groupBox_Accueil_nb_IA.setObjectName(\"groupBox_Accueil_nb_IA\")\n self.groupBox_Accueil_nb_IA.hide()\n \n self.textBrowser_IA = QtWidgets.QTextBrowser(self.groupBox_Accueil_nb_IA)\n self.textBrowser_IA.setEnabled(True)\n self.textBrowser_IA.setGeometry(QtCore.QRect(0, 30, 200, 30))\n self.textBrowser_IA.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.textBrowser_IA.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.textBrowser_IA.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)\n self.textBrowser_IA.setObjectName(\"textBrowser_IA\")\n \n self.checkBox_IA_1 = QtWidgets.QCheckBox(self.groupBox_Accueil_nb_IA)\n self.checkBox_IA_1.setGeometry(QtCore.QRect(240, 60, 280, 25))\n self.checkBox_IA_1.setObjectName(\"checkBox_IA_1\")\n self.checkBox_IA_2 = QtWidgets.QCheckBox(self.groupBox_Accueil_nb_IA)\n self.checkBox_IA_2.setGeometry(QtCore.QRect(240, 80, 280, 25))\n self.checkBox_IA_2.setObjectName(\"checkBox_IA_2\")\n self.checkBox_IA_3 = QtWidgets.QCheckBox(self.groupBox_Accueil_nb_IA)\n self.checkBox_IA_3.setGeometry(QtCore.QRect(240, 100, 280, 25))\n self.checkBox_IA_3.setObjectName(\"checkBox_IA_3\")\n self.checkBox_IA_4 = QtWidgets.QCheckBox(self.groupBox_Accueil_nb_IA)\n self.checkBox_IA_4.setGeometry(QtCore.QRect(240, 120, 280, 25))\n self.checkBox_IA_4.setObjectName(\"checkBox_IA_4\")\n self.checkBox_IA_0 = QtWidgets.QCheckBox(self.groupBox_Accueil_nb_IA)\n self.checkBox_IA_0.setGeometry(QtCore.QRect(240, 40, 280, 25))\n self.checkBox_IA_0.setObjectName(\"checkBox_IA_0\")\n \n self.Button_Retour = QtWidgets.QPushButton(self.groupBox_Option)\n self.Button_Retour.setGeometry(QtCore.QRect(10, 540, 210, 90))\n self.Button_Retour.setObjectName(\"Button_Retour\")\n self.Button_Jouer = QtWidgets.QPushButton(self.groupBox_Option)\n self.Button_Jouer.setGeometry(QtCore.QRect(620, 540, 190, 90))\n self.Button_Jouer.setObjectName(\"Button_Jouer\")\n self.Button_Jouer.hide()\n \n self.checkBox_Option_IA_NON = QtWidgets.QCheckBox(self.groupBox_Option)\n self.checkBox_Option_IA_NON.setGeometry(QtCore.QRect(310, 130, 90, 25))\n self.checkBox_Option_IA_NON.setObjectName(\"checkBox_Option_IA_NON\")\n \n self.textBrowser_Humain = QtWidgets.QTextBrowser(self.groupBox_Option)\n self.textBrowser_Humain.setGeometry(QtCore.QRect(410, 120, 250, 40))\n self.textBrowser_Humain.setObjectName(\"textBrowser_Humain\")\n \n self.checkBox_Option_Humain_OUI = QtWidgets.QCheckBox(self.groupBox_Option)\n self.checkBox_Option_Humain_OUI.setGeometry(QtCore.QRect(670, 130, 90, 25))\n self.checkBox_Option_Humain_OUI.setObjectName(\"checkBox_Option_Humain_OUI\")\n self.checkBox_Option_Hum_NON = QtWidgets.QCheckBox(self.groupBox_Option)\n self.checkBox_Option_Hum_NON.setGeometry(QtCore.QRect(720, 130, 90, 25))\n self.checkBox_Option_Hum_NON.setObjectName(\"checkBox_Option_Hum_NON\")\n \n self.groupBox_Accueil_nb_humain = QtWidgets.QGroupBox(self.groupBox_Option)\n self.groupBox_Accueil_nb_humain.setEnabled(True)\n self.groupBox_Accueil_nb_humain.setGeometry(QtCore.QRect(410, 160, 350, 170))\n self.groupBox_Accueil_nb_humain.setAcceptDrops(False)\n self.groupBox_Accueil_nb_humain.setInputMethodHints(QtCore.Qt.ImhHiddenText)\n self.groupBox_Accueil_nb_humain.setTitle(\"\")\n self.groupBox_Accueil_nb_humain.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.groupBox_Accueil_nb_humain.setObjectName(\"groupBox_Accueil_nb_humain\")\n self.groupBox_Accueil_nb_humain.hide()\n \n self.textBrowser_IA_3 = QtWidgets.QTextBrowser(self.groupBox_Accueil_nb_humain)\n self.textBrowser_IA_3.setEnabled(True)\n self.textBrowser_IA_3.setGeometry(QtCore.QRect(0, 30, 200, 30))\n self.textBrowser_IA_3.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.textBrowser_IA_3.setObjectName(\"textBrowser_IA_3\")\n \n self.checkBox_IA_5 = QtWidgets.QCheckBox(self.groupBox_Accueil_nb_humain)\n self.checkBox_IA_5.setGeometry(QtCore.QRect(240, 60, 280, 25))\n self.checkBox_IA_5.setObjectName(\"checkBox_IA_5\")\n self.checkBox_IA_6 = QtWidgets.QCheckBox(self.groupBox_Accueil_nb_humain)\n self.checkBox_IA_6.setGeometry(QtCore.QRect(240, 80, 280, 25))\n self.checkBox_IA_6.setObjectName(\"checkBox_IA_6\")\n self.checkBox_IA_7 = QtWidgets.QCheckBox(self.groupBox_Accueil_nb_humain)\n self.checkBox_IA_7.setGeometry(QtCore.QRect(240, 100, 280, 25))\n self.checkBox_IA_7.setObjectName(\"checkBox_IA_7\")\n self.checkBox_IA_8 = QtWidgets.QCheckBox(self.groupBox_Accueil_nb_humain)\n self.checkBox_IA_8.setGeometry(QtCore.QRect(240, 120, 280, 25))\n self.checkBox_IA_8.setObjectName(\"checkBox_IA_8\")\n self.checkBox_IA_9 = QtWidgets.QCheckBox(self.groupBox_Accueil_nb_humain)\n self.checkBox_IA_9.setGeometry(QtCore.QRect(240, 40, 280, 25))\n self.checkBox_IA_9.setObjectName(\"checkBox_IA_9\")\n \n self.groupBox_Niveau = QtWidgets.QGroupBox(self.groupBox_Option)\n self.groupBox_Niveau.setEnabled(True)\n self.groupBox_Niveau.setGeometry(QtCore.QRect(0, 350, 350, 170))\n self.groupBox_Niveau.setAcceptDrops(False)\n self.groupBox_Niveau.setInputMethodHints(QtCore.Qt.ImhHiddenText)\n self.groupBox_Niveau.setTitle(\"\")\n self.groupBox_Niveau.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.groupBox_Niveau.setObjectName(\"groupBox_Niveau\")\n self.groupBox_Niveau.hide()\n \n self.textBrowser_Niveau = QtWidgets.QTextBrowser(self.groupBox_Niveau)\n self.textBrowser_Niveau.setText(\"Choix du nombre d'IA moyenne\")\n self.textBrowser_Niveau.setEnabled(True)\n self.textBrowser_Niveau.setGeometry(QtCore.QRect(0, 30, 200, 30))\n self.textBrowser_Niveau.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.textBrowser_Niveau.setObjectName(\"textBrowser_Niveau\")\n \n self.checkBox_IA_moyenne_1 = QtWidgets.QCheckBox(self.groupBox_Niveau)\n self.checkBox_IA_moyenne_1.setGeometry(QtCore.QRect(240, 60, 280, 25))\n self.checkBox_IA_moyenne_1.setObjectName(\"checkBox_IA_moyenne_1\")\n self.checkBox_IA_moyenne_1.setText(\"1\")\n self.checkBox_IA_moyenne_2 = QtWidgets.QCheckBox(self.groupBox_Niveau)\n self.checkBox_IA_moyenne_2.setGeometry(QtCore.QRect(240, 80, 280, 25))\n self.checkBox_IA_moyenne_2.setObjectName(\"checkBox_IA_moyenne_2\")\n self.checkBox_IA_moyenne_2.setText(\"2\")\n self.checkBox_IA_moyenne_3 = QtWidgets.QCheckBox(self.groupBox_Niveau)\n self.checkBox_IA_moyenne_3.setGeometry(QtCore.QRect(240, 100, 280, 25))\n self.checkBox_IA_moyenne_3.setObjectName(\"checkBox_IA_moyenne_3\")\n self.checkBox_IA_moyenne_3.setText(\"3\")\n self.checkBox_IA_moyenne_4 = QtWidgets.QCheckBox(self.groupBox_Niveau)\n self.checkBox_IA_moyenne_4.setGeometry(QtCore.QRect(240, 120, 280, 25))\n self.checkBox_IA_moyenne_4.setObjectName(\"checkBox_IA_moyenne_4\")\n self.checkBox_IA_moyenne_4.setText(\"4\")\n self.checkBox_IA_moyenne_0 = QtWidgets.QCheckBox(self.groupBox_Niveau)\n self.checkBox_IA_moyenne_0.setGeometry(QtCore.QRect(240, 40, 280, 25))\n self.checkBox_IA_moyenne_0.setObjectName(\"checkBox_IA_moyenne_0\")\n self.checkBox_IA_moyenne_0.setText(\"0\")\n \n \n \n \n \n \n self.textBrowser_2.raise_()\n self.textBrowser_IA_2.raise_()\n self.checkBox_Option_IA_OUI.raise_()\n self.groupBox_Accueil_nb_IA.raise_()\n self.Button_Retour.raise_()\n self.Button_Jouer.raise_()\n self.checkBox_Option_IA_NON.raise_()\n self.textBrowser_Humain.raise_()\n self.checkBox_Option_Humain_OUI.raise_()\n self.checkBox_Option_Hum_NON.raise_()\n self.groupBox_Accueil_nb_humain.raise_()\n self.textBrowser.raise_()\n self.tr_defenseur_text.raise_()\n self.groupBox_Accueil.raise_()\n self.groupBox_Jeu.raise_()\n self.groupBox_Option.raise_()\n self.textBrowser.raise_()\n Minima_Accueil.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(Minima_Accueil)\n \n\n\n\n self.checkBox_IA_moyenne_0.toggled.connect(lambda:self.checked(self.checkBox_IA_moyenne_0,0))\n self.checkBox_IA_moyenne_1.toggled.connect(lambda:self.checked(self.checkBox_IA_moyenne_1,1))\n self.checkBox_IA_moyenne_2.toggled.connect(lambda:self.checked(self.checkBox_IA_moyenne_2,2))\n self.checkBox_IA_moyenne_3.toggled.connect(lambda:self.checked(self.checkBox_IA_moyenne_3,3))\n self.checkBox_IA_moyenne_4.toggled.connect(lambda:self.checked(self.checkBox_IA_moyenne_4,4))\n \n self.checkBox_Option_IA_OUI.toggled['bool'].connect(self.groupBox_Niveau.setVisible)\n \n \n self.Button_Ac_Quitter.clicked.connect(Minima_Accueil.close)\n self.Button_Ac_Jouer.clicked.connect(self.groupBox_Accueil.hide)\n self.Button_Ac_Jouer.clicked.connect(self.groupBox_Option.show)\n self.Button_Retour.clicked.connect(self.groupBox_Option.hide)\n self.Button_Retour.clicked.connect(self.groupBox_Accueil.show)\n \n self.Button_Jouer.clicked.connect(self.groupBox_Jeu.show)\n self.Button_Jouer.clicked.connect(self.groupBox_Option.hide)\n self.Bouton_Jeu_Quitter.clicked.connect(Minima_Accueil.close)\n \n self.checkBox_IA_0.toggled.connect(lambda:self.checked(self.checkBox_IA_0,0))\n self.checkBox_IA_1.toggled.connect(lambda:self.checked(self.checkBox_IA_1,1))\n self.checkBox_IA_2.toggled.connect(lambda:self.checked(self.checkBox_IA_2,2))\n self.checkBox_IA_3.toggled.connect(lambda:self.checked(self.checkBox_IA_3,3))\n self.checkBox_IA_4.toggled.connect(lambda:self.checked(self.checkBox_IA_4,4))\n \n self.Button_J_A_Fermer.clicked.connect(self.scrollArea_3.hide)\n self.Jeu_A_Unitees.clicked.connect(self.scrollArea_3.show)\n self.Button_J_D_U_Fermer.clicked.connect(self.scrollArea_2.hide)\n self.pushButton_2.clicked.connect(self.scrollArea_2.show)\n self.Button_J_D_B_Fermer.clicked.connect(self.scrollArea.hide)\n self.pushButton.clicked.connect(self.scrollArea.show)\n self.checkBox_Option_IA_OUI.toggled['bool'].connect(self.groupBox_Accueil_nb_IA.setVisible)\n self.checkBox_Option_Humain_OUI.toggled['bool'].connect(self.groupBox_Accueil_nb_humain.setVisible)\n \n \n self.checkBox_IA_9.toggled.connect(lambda:self.checked(self.checkBox_IA_9,0))\n self.checkBox_IA_5.toggled.connect(lambda:self.checked(self.checkBox_IA_5,1))\n self.checkBox_IA_6.toggled.connect(lambda:self.checked(self.checkBox_IA_6,2)) \n self.checkBox_IA_7.toggled.connect(lambda:self.checked(self.checkBox_IA_7,3))\n self.checkBox_IA_8.toggled.connect(lambda:self.checked(self.checkBox_IA_8,4))\n \n \n self.checkBox_Option_IA_NON.stateChanged.connect(self.affichage_NON_OUI)\n self.checkBox_Option_Hum_NON.stateChanged.connect(self.affichage_NON_OUI)\n self.checkBox_Option_IA_OUI.stateChanged.connect(self.affichage_NON_OUI)\n self.checkBox_Option_Humain_OUI.stateChanged.connect(self.affichage_NON_OUI)\n\n QtCore.QMetaObject.connectSlotsByName(Minima_Accueil)\n \n \n def coche_0 (self):\n \n if self.checkBox_Option_IA_NON.isChecked() == True :\n self.checkBox_IA_0.setChecked(True)\n self.checkBox_IA_moyenne_0.setChecked(True)\n elif self.checkBox_Option_Hum_NON.isChecked() == True :\n self.checkBox_IA_9.setChecked(True)\n\n \n if self.checkBox_IA_4.isChecked() == True :\n self.checkBox_IA_9.setChecked(True)\n self.checkBox_IA_moyenne_0.setChecked(True)\n elif self.checkBox_IA_8.isChecked() == True :\n self.checkBox_IA_0.setChecked(True)\n self.checkBox_IA_moyenne_0.setChecked(True)\n elif self.checkBox_IA_moyenne_4.isChecked() == True :\n self.checkBox_IA_0.setChecked(True)\n self.checkBox_IA_9.setChecked(True)\n\n \n def cache_0 (self):\n if (self.checkBox_IA_0.isChecked() == True and self.checkBox_IA_9.isChecked() ):\n self.checkBox_IA_moyenne_0.hide()\n elif (self.checkBox_IA_moyenne_0.isChecked() == True and self.checkBox_IA_9.isChecked() ):\n self.checkBox_IA_0.hide()\n elif (self.checkBox_IA_moyenne_0.isChecked() == True and self.checkBox_IA_0.isChecked() ):\n self.checkBox_IA_9.hide()\n\n \n \n \n def cache (self):\n if self.checkBox_IA_5.isChecked() == True :\n self.checkBox_IA_6.hide()\n self.checkBox_IA_7.hide()\n self.checkBox_IA_8.hide()\n self.checkBox_IA_9.hide()\n elif self.checkBox_IA_6.isChecked() == True :\n self.checkBox_IA_5.hide()\n self.checkBox_IA_7.hide()\n self.checkBox_IA_8.hide()\n self.checkBox_IA_9.hide() \n elif self.checkBox_IA_7.isChecked() == True :\n self.checkBox_IA_5.hide()\n self.checkBox_IA_6.hide()\n self.checkBox_IA_8.hide()\n self.checkBox_IA_9.hide() \n elif self.checkBox_IA_8.isChecked() == True :\n self.checkBox_IA_5.hide()\n self.checkBox_IA_6.hide()\n self.checkBox_IA_7.hide()\n self.checkBox_IA_9.hide() \n elif self.checkBox_IA_9.isChecked() == True :\n self.checkBox_IA_5.hide()\n self.checkBox_IA_6.hide()\n self.checkBox_IA_7.hide()\n self.checkBox_IA_8.hide() \n \n if self.checkBox_IA_0.isChecked() == True :\n self.checkBox_IA_1.hide()\n self.checkBox_IA_2.hide()\n self.checkBox_IA_3.hide()\n self.checkBox_IA_4.hide()\n elif self.checkBox_IA_1.isChecked() == True :\n self.checkBox_IA_0.hide()\n self.checkBox_IA_2.hide()\n self.checkBox_IA_3.hide()\n self.checkBox_IA_4.hide() \n elif self.checkBox_IA_2.isChecked() == True :\n self.checkBox_IA_0.hide()\n self.checkBox_IA_1.hide()\n self.checkBox_IA_3.hide()\n self.checkBox_IA_4.hide() \n elif self.checkBox_IA_3.isChecked() == True :\n self.checkBox_IA_0.hide()\n self.checkBox_IA_1.hide()\n self.checkBox_IA_2.hide()\n self.checkBox_IA_4.hide() \n elif self.checkBox_IA_4.isChecked() == True :\n self.checkBox_IA_3.hide()\n self.checkBox_IA_1.hide()\n self.checkBox_IA_2.hide()\n self.checkBox_IA_0.hide() \n \n if self.checkBox_IA_moyenne_0.isChecked() == True :\n self.checkBox_IA_moyenne_1.hide()\n self.checkBox_IA_moyenne_2.hide()\n self.checkBox_IA_moyenne_3.hide()\n self.checkBox_IA_moyenne_4.hide()\n elif self.checkBox_IA_moyenne_1.isChecked() == True :\n self.checkBox_IA_moyenne_0.hide()\n self.checkBox_IA_moyenne_2.hide()\n self.checkBox_IA_moyenne_3.hide()\n self.checkBox_IA_moyenne_4.hide() \n elif self.checkBox_IA_moyenne_2.isChecked() == True :\n self.checkBox_IA_moyenne_0.hide()\n self.checkBox_IA_moyenne_1.hide()\n self.checkBox_IA_moyenne_3.hide()\n self.checkBox_IA_moyenne_4.hide() \n elif self.checkBox_IA_moyenne_3.isChecked() == True :\n self.checkBox_IA_moyenne_0.hide()\n self.checkBox_IA_moyenne_1.hide()\n self.checkBox_IA_moyenne_2.hide()\n self.checkBox_IA_moyenne_4.hide() \n elif self.checkBox_IA_moyenne_4.isChecked() == True :\n self.checkBox_IA_moyenne_3.hide()\n self.checkBox_IA_moyenne_1.hide()\n self.checkBox_IA_moyenne_2.hide()\n self.checkBox_IA_moyenne_0.hide() \n \n def affiche_Jouer(self):\n if ((self.checkBox_IA_0.isChecked() == True or self.checkBox_IA_1.isChecked() == True or self.checkBox_IA_2.isChecked() == True\n or self.checkBox_IA_3.isChecked() == True or self.checkBox_IA_4.isChecked() == True) and \n (self.checkBox_IA_5.isChecked() == True or self.checkBox_IA_6.isChecked() == True or self.checkBox_IA_7.isChecked() == True\n or self.checkBox_IA_8.isChecked() == True or self.checkBox_IA_9.isChecked() == True) and\n (self.checkBox_IA_moyenne_0.isChecked() == True or self.checkBox_IA_moyenne_1.isChecked() == True or self.checkBox_IA_moyenne_2.isChecked() == True\n or self.checkBox_IA_moyenne_3.isChecked() == True or self.checkBox_IA_moyenne_4.isChecked() == True)):\n \n self.Button_Jouer.show()\n else:\n self.Button_Jouer.hide()\n \n def affichage_NON_OUI (self):\n if self.checkBox_Option_IA_NON.isChecked() == True :\n self.checkBox_Option_IA_OUI.hide()\n self.checkBox_Option_Hum_NON.hide()\n self.checkBox_Option_IA_NON.show()\n self.checkBox_Option_Humain_OUI.show() \n if self.checkBox_Option_Hum_NON.isChecked() == True :\n self.checkBox_Option_IA_NON.hide()\n self.checkBox_Option_Humain_OUI.hide()\n self.checkBox_Option_IA_OUI.show()\n self.checkBox_Option_Hum_NON.show()\n if self.checkBox_Option_IA_OUI.isChecked() == True :\n self.checkBox_Option_IA_NON.hide()\n self.checkBox_Option_IA_OUI.show()\n self.checkBox_Option_Humain_OUI.show()\n self.checkBox_Option_Hum_NON.show()\n if self.checkBox_Option_Humain_OUI.isChecked() == True :\n self.checkBox_Option_Hum_NON.hide()\n self.checkBox_Option_IA_OUI.show()\n self.checkBox_Option_Humain_OUI.show()\n self.checkBox_Option_IA_NON.show() \n if (self.checkBox_Option_IA_NON.isChecked() == True and self.checkBox_Option_Humain_OUI.isChecked() == True ):\n self.checkBox_Option_Hum_NON.hide()\n self.checkBox_Option_IA_OUI.hide()\n self.checkBox_Option_Humain_OUI.show()\n self.checkBox_Option_IA_NON.show()\n if (self.checkBox_Option_IA_OUI.isChecked() == True and self.checkBox_Option_Hum_NON.isChecked() == True ):\n self.checkBox_Option_IA_NON.hide()\n self.checkBox_Option_Humain_OUI.hide()\n self.checkBox_Option_Hum_NON.show()\n self.checkBox_Option_IA_OUI.show()\n if (self.checkBox_Option_IA_OUI.isChecked() == True and self.checkBox_Option_Humain_OUI.isChecked() == True ):\n self.checkBox_Option_IA_NON.hide()\n self.checkBox_Option_Humain_OUI.show()\n self.checkBox_Option_Hum_NON.hide()\n self.checkBox_Option_IA_OUI.show()\n if (self.checkBox_Option_IA_OUI.isChecked() == False and self.checkBox_Option_Humain_OUI.isChecked() == False and self.checkBox_Option_Hum_NON.isChecked() == False and self.checkBox_Option_IA_NON.isChecked() == False ):\n self.checkBox_Option_IA_NON.show()\n self.checkBox_Option_Humain_OUI.show()\n self.checkBox_Option_Hum_NON.show()\n self.checkBox_Option_IA_OUI.show()\n\n \n \n def affichage (self):\n \n self.coche_0()\n \n if self.nombre ==0:\n \n self.checkBox_IA_8.show()\n self.checkBox_IA_4.show()\n self.checkBox_IA_moyenne_4.show() \n self.checkBox_IA_7.show()\n self.checkBox_IA_6.show()\n self.checkBox_IA_5.show() \n self.checkBox_IA_3.show()\n self.checkBox_IA_2.show() \n self.checkBox_IA_1.show() \n self.checkBox_IA_0.show()\n self.checkBox_IA_9.show()\n self.checkBox_IA_moyenne_0.show()\n self.checkBox_IA_moyenne_3.show()\n self.checkBox_IA_moyenne_2.show()\n self.checkBox_IA_moyenne_1.show()\n \n self.montre()\n self.cache()\n self.cache_0()\n self.affiche_Jouer()\n \n elif self.nombre ==1:\n \n self.checkBox_IA_8.hide()\n self.checkBox_IA_4.hide()\n self.checkBox_IA_moyenne_4.hide()\n \n self.checkBox_IA_0.show()\n self.checkBox_IA_9.show()\n self.checkBox_IA_moyenne_0.show()\n self.checkBox_IA_7.show()\n self.checkBox_IA_6.show()\n self.checkBox_IA_5.show() \n self.checkBox_IA_3.show()\n self.checkBox_IA_2.show() \n self.checkBox_IA_1.show() \n self.checkBox_IA_moyenne_3.show()\n self.checkBox_IA_moyenne_2.show()\n self.checkBox_IA_moyenne_1.show()\n \n self.montre()\n self.cache()\n self.cache_0()\n self.affiche_Jouer()\n elif self.nombre ==2:\n\n self.checkBox_IA_8.hide()\n self.checkBox_IA_7.hide()\n self.checkBox_IA_4.hide()\n self.checkBox_IA_3.hide()\n self.checkBox_IA_moyenne_4.hide()\n self.checkBox_IA_moyenne_3.hide()\n \n self.checkBox_IA_0.show()\n self.checkBox_IA_9.show()\n self.checkBox_IA_moyenne_0.show()\n self.checkBox_IA_6.show()\n self.checkBox_IA_5.show() \n self.checkBox_IA_2.show() \n self.checkBox_IA_1.show() \n self.checkBox_IA_moyenne_2.show()\n self.checkBox_IA_moyenne_1.show()\n \n self.montre()\n self.cache()\n self.cache_0()\n self.affiche_Jouer()\n elif self.nombre ==3:\n\n self.checkBox_IA_8.hide()\n self.checkBox_IA_7.hide()\n self.checkBox_IA_6.hide()\n self.checkBox_IA_4.hide()\n self.checkBox_IA_3.hide()\n self.checkBox_IA_2.hide() \n self.checkBox_IA_moyenne_4.hide()\n self.checkBox_IA_moyenne_3.hide()\n self.checkBox_IA_moyenne_2.hide()\n \n self.checkBox_IA_0.show()\n self.checkBox_IA_9.show()\n self.checkBox_IA_moyenne_0.show()\n self.checkBox_IA_5.show() \n self.checkBox_IA_1.show() \n self.checkBox_IA_moyenne_1.show()\n \n self.montre()\n self.cache()\n self.cache_0()\n self.affiche_Jouer()\n elif self.nombre ==4:\n\n \n self.checkBox_IA_8.hide()\n self.checkBox_IA_7.hide()\n self.checkBox_IA_6.hide()\n self.checkBox_IA_5.hide() \n self.checkBox_IA_4.hide()\n self.checkBox_IA_3.hide()\n self.checkBox_IA_2.hide() \n self.checkBox_IA_1.hide() \n self.checkBox_IA_moyenne_4.hide()\n self.checkBox_IA_moyenne_3.hide()\n self.checkBox_IA_moyenne_2.hide()\n self.checkBox_IA_moyenne_1.hide()\n \n self.checkBox_IA_0.show()\n self.checkBox_IA_9.show()\n self.checkBox_IA_moyenne_0.show()\n \n self.montre()\n self.cache()\n self.cache_0()\n self.affiche_Jouer()\n \n def montre (self):\n if self.checkBox_IA_0.isChecked() == True :\n self.checkBox_IA_0.show()\n if self.checkBox_IA_1.isChecked() == True :\n self.checkBox_IA_1.show()\n if self.checkBox_IA_2.isChecked() == True :\n self.checkBox_IA_2.show()\n if self.checkBox_IA_3.isChecked() == True :\n self.checkBox_IA_3.show()\n if self.checkBox_IA_4.isChecked() == True :\n self.checkBox_IA_4.show()\n \n if self.checkBox_IA_5.isChecked() == True :\n self.checkBox_IA_5.show()\n if self.checkBox_IA_6.isChecked() == True :\n self.checkBox_IA_6.show()\n if self.checkBox_IA_7.isChecked() == True :\n self.checkBox_IA_7.show()\n if self.checkBox_IA_8.isChecked() == True :\n self.checkBox_IA_8.show()\n if self.checkBox_IA_9.isChecked() == True :\n self.checkBox_IA_9.show()\n \n if self.checkBox_IA_moyenne_0.isChecked() == True :\n self.checkBox_IA_moyenne_0.show()\n if self.checkBox_IA_moyenne_1.isChecked() == True :\n self.checkBox_IA_moyenne_1.show()\n if self.checkBox_IA_moyenne_2.isChecked() == True :\n self.checkBox_IA_moyenne_2.show()\n if self.checkBox_IA_moyenne_3.isChecked() == True :\n self.checkBox_IA_moyenne_3.show()\n if self.checkBox_IA_moyenne_4.isChecked() == True :\n self.checkBox_IA_moyenne_4.show()\n \n\n def checked (self,b,n):\n if b.isChecked() == True :\n return self.addition(n)\n else :\n return self.addition(-n)\n \n \n \n \n \n \n def choix_sauvegarde (self):\n result = QtWidgets.QMessageBox.question(self.groupBox_Jeu,'Erreur Sauvegarde', \"Sauvegarde déjà existante. L'effacer?\", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)\n \n if result == QtWidgets.QMessageBox.Yes:\n return (\"Yes\")\n else:\n return (\"No\")\n \n def choix_chargement(self):\n result = QtWidgets.QMessageBox.question(self.groupBox_Accueil,'Erreur Chargement', \"Sauvegarde introuvable. Voulez-vous entrez un autre nom? \", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)\n \n if result == QtWidgets.QMessageBox.Yes:\n return (\"Yes\")\n else:\n return (\"No\") \n \n def nb_IA_moyenne_choisi(self):\n if self.checkBox_IA_moyenne_0.isChecked():\n return 0\n if self.checkBox_IA_moyenne_1.isChecked():\n return 1\n if self.checkBox_IA_moyenne_2.isChecked():\n return 2\n if self.checkBox_IA_moyenne_3.isChecked():\n return 3\n if self.checkBox_IA_moyenne_4.isChecked():\n return 4\n \n \n def nb_IA_facile_choisi(self):\n if self.checkBox_IA_0.isChecked():\n return 0\n if self.checkBox_IA_1.isChecked():\n return 1\n if self.checkBox_IA_2.isChecked():\n return 2\n if self.checkBox_IA_3.isChecked():\n return 3\n if self.checkBox_IA_4.isChecked():\n return 4\n \n def nb_Hn_choisi(self):\n if self.checkBox_IA_9.isChecked():\n return 0\n if self.checkBox_IA_5.isChecked():\n return 1\n if self.checkBox_IA_6.isChecked():\n return 2\n if self.checkBox_IA_7.isChecked():\n return 3\n if self.checkBox_IA_8.isChecked():\n return 4\n \n def addition(self, n):\n self.nombre += n\n self.affichage()\n print(self.nombre)\n\n \n \n \n \n \n \n \n \n \n \n \n def retranslateUi(self, Minima_Accueil):\n _translate = QtCore.QCoreApplication.translate\n Minima_Accueil.setWindowTitle(_translate(\"Minima_Accueil\", \"Minima Accueil\"))\n self.textBrowser.setHtml(_translate(\"Minima_Accueil\", \"\\n\"\n\"\\n\"\n\"\\n\"\n\"\\n\"\n\"
\\n\"\n\"

Minima

\"))\n \n self.Ch_annuler.setText(_translate(\"Minima_Accueil\", \"Annuler\"))\n self.Button_Ac_Jouer.setText(_translate(\"Minima_Accueil\", \"Jouer\"))\n self.Button_Ac_Quitter.setText(_translate(\"Minima_Accueil\", \"Quitter\"))\n self.Button_Ac_Charger.setText(_translate(\"Minima_Accueil\", \"Charger\"))\n self.textBrowser_Tours_restants.setHtml(_translate(\"Minima_Accueil\", \"\\n\"\n\"\\n\"\n\"\\n\"\n\"\\n\"\n\"
\\n\"\n\"

Il reste tour(s) à survivre

\"))\n self.textBrowser_Metal.setHtml(_translate(\"Minima_Accueil\", \"\\n\"\n\"\\n\"\n\"\\n\"\n\"\\n\"\n\"
\\n\"\n\"

Métal disponible

\"))\n self.textBrowser_Energie.setHtml(_translate(\"Minima_Accueil\", \"\\n\"\n\"\\n\"\n\"\\n\"\n\"\\n\"\n\"
\\n\"\n\"

Energie disponible

\"))\n self.Defenseur.setTitle(_translate(\"Minima_Accueil\", \"Défenseur\"))\n self.pushButton.setText(_translate(\"Minima_Accueil\", \"Batiments\"))\n self.Button_Foreuse.setText(_translate(\"Minima_Accueil\", \"Foreuse\"))\n self.Button_Panneau_Solaire.setText(_translate(\"Minima_Accueil\", \"Panneau Solaire\"))\n self.pushButton_2.setText(_translate(\"Minima_Accueil\", \"Unitées\"))\n self.Button_Robot_Ouvrier.setText(_translate(\"Minima_Accueil\", \"Robot Ouvrier\"))\n self.Button_Robot_Combat.setText(_translate(\"Minima_Accueil\", \"Robot Combat\"))\n self.Attaquant.setTitle(_translate(\"Minima_Accueil\", \"Attaquant\"))\n self.Jeu_A_Unitees.setText(_translate(\"Minima_Accueil\", \"Unité\"))\n self.Button_Scorpion.setText(_translate(\"Minima_Accueil\", \"Scorpion\"))\n self.textBrowser_U_dispo.setHtml(_translate(\"Minima_Accueil\", \"\\n\"\n\"\\n\"\n\"\\n\"\n\"\\n\"\n\"
\\n\"\n\"

disponibles

\"))\n self.Bouton_Jeu_Quitter.setText(_translate(\"Minima_Accueil\", \"Quitter\"))\n self.Bouton_Sauvegarde.setText(_translate(\"Minima_Accueil\", \"Sauvegarder\"))\n self.Button_Ready.setText(_translate(\"Minima_Accueil\", \"Ready\" ))\n self.Button_Ready.setStyleSheet(\"QPushButton {font: 100pt Times New Roman}\")\n self.Bouton_Findetour.setText(_translate(\"Minima_Accueil\", \"Fin de tour\"))\n self.textBrowser_2.setHtml(_translate(\"Minima_Accueil\", \"\\n\"\n\"\\n\"\n\"\\n\"\n\"\\n\"\n\"
\\n\"\n\"

Options

\"))\n self.textBrowser_IA_2.setHtml(_translate(\"Minima_Accueil\", \"\\n\"\n\"\\n\"\n\"\\n\"\n\"\\n\"\n\"
\\n\"\n\"

Jouer contre un IA ?

\"))\n self.checkBox_Option_IA_OUI.setText(_translate(\"Minima_Accueil\", \"OUI\"))\n self.textBrowser_IA.setHtml(_translate(\"Minima_Accueil\", \"\\n\"\n\"\\n\"\n\"\\n\"\n\"\\n\"\n\"
\\n\"\n\"

Choix du nombre d\\'IA facile

\"))\n self.checkBox_IA_1.setText(_translate(\"Minima_Accueil\", \"1\"))\n self.checkBox_IA_2.setText(_translate(\"Minima_Accueil\", \"2\"))\n self.checkBox_IA_3.setText(_translate(\"Minima_Accueil\", \"3\"))\n self.checkBox_IA_4.setText(_translate(\"Minima_Accueil\", \"4\"))\n self.checkBox_IA_0.setText(_translate(\"Minima_Accueil\", \"0\"))\n self.Button_Retour.setText(_translate(\"Minima_Accueil\", \"Retour\"))\n self.Button_Jouer.setText(_translate(\"Minima_Accueil\", \"Jouer\"))\n self.checkBox_Option_IA_NON.setText(_translate(\"Minima_Accueil\", \"NON\"))\n self.textBrowser_Humain.setHtml(_translate(\"Minima_Accueil\", \"\\n\"\n\"\\n\"\n\"\\n\"\n\"\\n\"\n\"
\\n\"\n\"

Jouer contre un humain ?

\"))\n self.checkBox_Option_Humain_OUI.setText(_translate(\"Minima_Accueil\", \"OUI\"))\n self.checkBox_Option_Hum_NON.setText(_translate(\"Minima_Accueil\", \"NON\"))\n self.textBrowser_IA_3.setHtml(_translate(\"Minima_Accueil\", \"\\n\"\n\"\\n\"\n\"\\n\"\n\"\\n\"\n\"
\\n\"\n\"

Choix du nombre d\\'Humain

\"))\n self.checkBox_IA_5.setText(_translate(\"Minima_Accueil\", \"1\"))\n self.checkBox_IA_6.setText(_translate(\"Minima_Accueil\", \"2\"))\n self.checkBox_IA_7.setText(_translate(\"Minima_Accueil\", \"3\"))\n self.checkBox_IA_8.setText(_translate(\"Minima_Accueil\", \"4\"))\n self.checkBox_IA_9.setText(_translate(\"Minima_Accueil\", \"0\"))\n\n \n\n\n\nif __name__ == \"__main__\":\n\n app = QtWidgets.QApplication(sys.argv)\n Minima_Accueil = QtWidgets.QMainWindow()\n ui = Ui_Minima_Accueil()\n ui.setupUi(Minima_Accueil,carte)\n Minima_Accueil.show()\n sys.exit(app.exec_())\n\n","sub_path":"Minima_propVF.py","file_name":"Minima_propVF.py","file_ext":"py","file_size_in_byte":59507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"419243137","text":"# 1. Прочитать содержимое файла text.txt\n# 2. Дать пользователю ввести с клавиатуры параметр \"максимальное количество символов в строке\", который должен быть больше 15\n# 3. Отформатировать текст с учётом максимального количества символов, при этом если слово целиком не умещается в строке, оно должно быть перенесено на следующую, а отступы между словами равномерно увеличены (по аналогии с функцией \"Выровнять по ширине\" текстовых редакторов)\n# 4. Записать получившийся текст в новый файл и оповестить об этом пользователя.\n# (модуль textwrap использовать нельзя)\n\n\nq = int(input(\"количество символов:\\n\"))\nprint(q)\n# with open('text.txt', 'r') as text:\n# x = text.read()\n# print(x,\"\\n\")\n# x = x.split(\"\\n\")\n# print(x,\"\\n\")\n# for i in range(len(x)):\n# print(i,\":\"+ x[i])\n# string = x[i]\n# string = string.split(\" \")\n# print(string)\n\nstring = ['Произнеся', 'всю', 'эту', 'ахинею,', 'Бенгальский', 'сцепил', 'обе', 'руки', 'ладонь', 'к', 'ладони', 'и', 'приветственно', 'замахал', 'ими', 'в', 'прорез', 'занавеса,', 'от', 'чего', 'тот,', 'тихо', 'шумя,', 'и', 'разошелся', 'в', 'стороны.']\n\n\n\nfor y in range(len(string)):\n string_new = \"\"\n if len(string_new) < q:\n string_new = string_new + string[y] + \" \"\n else:\n print(string_new)\n string_new = string_new.replace((\" \" + string[y - 1] + \" \", \"\",1))\n\n\n dob = q-len(string_new)\n while dob > 0:\n z=0\n for i in range(len(string_new)):\n if dob == 0: break\n if string_new[i+z] == \" \" and string_new[i] == \" \":\n string_new[i+z] = \" \"\n i = i + 1\n dob = dob - 1\n continue\n\n\n\n\n\n\n\n\n\n\n\n\n print(string_new)\n\n\n# for y in string:\n# if len(string_new) 1000:\n## break\n####\n##count = 0\n##while count >= 0:\n## count += 1\n## if count > 100:\n## break\n## if count == 5 or count == 25 or count == 50 or count == 75:\n## continue\n## print(count)\n\n\n\nhealth = 10\ntrolls = 0\ndamage = 5\n\n\nwhile health > 0:\n trolls +=1\n health-= damage\n print(\"Your hero has killed a troll adding up to\",trolls,\"Your hero took\",damage,\"damage\")\n","sub_path":"while loops.py","file_name":"while loops.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"577193404","text":"\"\"\"\nTools for managing DC/OS cluster nodes.\n\"\"\"\n\nfrom ipaddress import IPv4Address\nfrom pathlib import Path\nfrom subprocess import PIPE, CompletedProcess, Popen\nfrom typing import Dict, List, Optional\n\nimport paramiko\nfrom scp import SCPClient\n\nfrom ._common import run_subprocess\n\n\nclass Node:\n \"\"\"\n A record of a DC/OS cluster node.\n \"\"\"\n\n def __init__(\n self,\n public_ip_address: IPv4Address,\n private_ip_address: IPv4Address,\n ssh_key_path: Path,\n ) -> None:\n \"\"\"\n Args:\n public_ip_address: The public IP address of the node.\n private_ip_address: The IP address used by the DC/OS component\n running on this node.\n ssh_key_path: The path to an SSH key which can be used to SSH to\n the node as the `root` user.\n\n Attributes:\n ip_address: The IP address used by the DC/OS component\n running on this node.\n \"\"\"\n self.public_ip_address = public_ip_address\n self.private_ip_address = private_ip_address\n self._ssh_key_path = ssh_key_path\n\n def _compose_ssh_command(\n self,\n args: List[str],\n user: str,\n env: Optional[Dict] = None,\n ) -> List[str]:\n \"\"\"\n Return a command to run `args` on this node over SSH.\n\n Args:\n args: The command to run on this node.\n user: The user that the command will be run for over SSH.\n env: Environment variables to be set on the node before running\n the command. A mapping of environment variable names to\n values.\n\n Returns:\n The full SSH command to be run.\n \"\"\"\n env = dict(env or {})\n\n command = []\n\n for key, value in env.items():\n export = \"export {key}='{value}'\".format(key=key, value=value)\n command.append(export)\n command.append('&&')\n\n command += args\n\n ssh_args = [\n 'ssh',\n # Suppress warnings.\n # In particular, we don't care about remote host identification\n # changes.\n '-q',\n # This makes sure that only keys passed with the -i option are\n # used. Needed when there are already keys present in the SSH\n # key chain, which cause `Error: Too many Authentication\n # Failures`.\n '-o',\n 'IdentitiesOnly=yes',\n # The node may be an unknown host.\n '-o',\n 'StrictHostKeyChecking=no',\n # Use an SSH key which is authorized.\n '-i',\n str(self._ssh_key_path),\n # Run commands as the specified user.\n '-l',\n user,\n # Bypass password checking.\n '-o',\n 'PreferredAuthentications=publickey',\n str(self.public_ip_address),\n ] + command\n\n return ssh_args\n\n def run(\n self,\n args: List[str],\n user: str,\n log_output_live: bool = False,\n env: Optional[Dict] = None,\n ) -> CompletedProcess:\n \"\"\"\n Run a command on this node the given user.\n\n Args:\n args: The command to run on the node.\n user: The username to SSH as.\n log_output_live: If `True`, log output live. If `True`, stderr is\n merged into stdout in the return value.\n env: Environment variables to be set on the node before running\n the command. A mapping of environment variable names to\n values.\n\n Returns:\n The representation of the finished process.\n\n Raises:\n CalledProcessError: The process exited with a non-zero code.\n \"\"\"\n ssh_args = self._compose_ssh_command(args=args, user=user, env=env)\n return run_subprocess(args=ssh_args, log_output_live=log_output_live)\n\n def popen(\n self,\n args: List[str],\n user: str,\n env: Optional[Dict] = None,\n ) -> Popen:\n \"\"\"\n Open a pipe to a command run on a node as the given user.\n\n Args:\n args: The command to run on the node.\n user: The user to open a pipe for a command for over SSH.\n env: Environment variables to be set on the node before running\n the command. A mapping of environment variable names to\n values.\n\n Returns:\n The pipe object attached to the specified process.\n \"\"\"\n ssh_args = self._compose_ssh_command(args=args, user=user, env=env)\n return Popen(args=ssh_args, stdout=PIPE, stderr=PIPE)\n\n def send_file(\n self,\n local_path: Path,\n remote_path: Path,\n user: str,\n ) -> None:\n \"\"\"\n Copy a file to this node.\n\n Args:\n local_path: The path on the host of the file to send.\n remote_path: The path on the node to place the file.\n user: The name of the remote user to send the file via\n secure copy.\n \"\"\"\n ssh_client = paramiko.SSHClient()\n ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh_client.connect(\n str(self.public_ip_address),\n username=user,\n key_filename=str(self._ssh_key_path),\n )\n\n with SCPClient(ssh_client.get_transport()) as scp:\n self.run(\n args=['mkdir', '--parents',\n str(remote_path.parent)],\n user=user,\n )\n scp.put(files=str(local_path), remote_path=str(remote_path))\n","sub_path":"src/dcos_e2e/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":5656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"436709488","text":"import requests\nimport concurrent.futures\n\nBASE_URL = 'http://52.8.70.153'\nsession = requests.Session()\n\ndef sign_in():\n sign_url = BASE_URL + '/api/v1/user/signin/'\n sign_in_params = {\n 'email': 'www@www.www',\n 'password': '123123123'\n }\n response = session.get(sign_url, params=sign_in_params)\n return response\n\ndef create_report():\n create_report_url = BASE_URL + '/api/v1/report/create/'\n create_report_body = {\n \"data\": [{\n \"what\": \"I was sexually assaulted.\",\n \"location\": \"in school\",\n \"time\": \"02/01/2019\",\n \"who\": \"Bob\",\n \"details\": \"blah\",\n \"facebook_url\": \"bob\"\n }]\n }\n response = session.post(create_report_url, json=create_report_body)\n return response\n\ndef delete_report(reportId):\n delete_report_url = BASE_URL + '/api/v1/report/delete/'\n delete_params = {\n 'reportId': reportId\n }\n response = session.delete(delete_report_url, params=delete_params)\n return response\n\nresponse = sign_in()\nprint('sign in response', response)\nresponse = create_report()\nprint('create report response', response)\n\nwith concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n response = {executor.submit(create_report) for _ in range(200)}\n","sub_path":"TestCode/create_report_test.py","file_name":"create_report_test.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"39191290","text":"#\n# Authors: Dave Krestynick\n# Purpose: Django URLS for VMA Web App API\n#\n\n\"\"\"VMAWebAPI URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom VMAWebAPI.resources import *\n\nappointment_resource = AppointmentResource()\nmed_proc_resource = MedProcResource()\npatient_resource = PatientResource()\nsurvey_type_resource = SurveyTypeResource()\ninstruction_resource = InstructionResource()\nmed_instruction_resource = MedInstructionResource()\naudit_resource = AuditResource()\nsurvey_question_resource = SurveyQuestionResource()\nsurvey_response_resource = SurveyResponseResource()\nlocation_resource = LocationResource()\ndoctor_resource = DoctorResource()\nins_attribute_resource = InsAttributeResource()\ninstructions_per_patient_resource = InstructionsPerPatientResource()\npatient_attribute_resource = PatientAttributeResource()\n\nurlpatterns = [\n url(r'^', include(appointment_resource.urls)),\n url(r'^', include(med_proc_resource.urls)),\n url(r'^', include(patient_resource.urls)),\n url(r'^', include(survey_type_resource.urls)),\n url(r'^', include(audit_resource.urls)),\n url(r'^', include(survey_question_resource.urls)),\n url(r'^', include(survey_response_resource.urls)),\n url(r'^', include(location_resource.urls)),\n url(r'^', include(instruction_resource.urls)),\n url(r'^', include(med_instruction_resource.urls)),\n url(r'^', include(ins_attribute_resource.urls)),\n url(r'^', include(doctor_resource.urls)),\n url(r'^', include(instructions_per_patient_resource.urls)),\n url(r'^', include(patient_attribute_resource.urls)),\n]\n","sub_path":"VMAWebAPI/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"335037302","text":"from yodatools.dataloader.view.WizardDatabasePageView import WizardDatabasePageView\n\n\nclass WizardDatabasePageController(WizardDatabasePageView):\n def __init__(self, parent, title=''):\n super(WizardDatabasePageController, self).__init__(parent)\n\n del self.panel.choices['SQLite']\n self.panel.cbDatabaseType.SetItems(self.panel.choices.keys())\n\n\n self.title = title\n","sub_path":"yodatools/dataloader/controller/WizardDatabasePageController.py","file_name":"WizardDatabasePageController.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"544592163","text":"from tkinter import *\nfrom areamap import *\nfrom hero import *\nfrom skeletons import *\nfrom boss import *\n\nclass GameScreen(object):\n def __init__(self, canvas):\n self.canvas = canvas\n self.map = Map(canvas)\n self.hero = Hero(0, 0, canvas)\n self.skeleton1 = Skeleton(0, 3, canvas)\n self.skeleton2 = Skeleton(4, 8, canvas)\n self.skeleton3 = Skeleton(6, 2, canvas)\n self.boss = Boss(9, 6, canvas)\n self.size = 72\n\n def draw_screen(self):\n self.canvas.delete('all')\n for i in self.map.area_map:\n i.draw(self.canvas)\n self.draw_skeleton1()\n self.draw_skeleton2()\n self.draw_skeleton3()\n self.draw_boss()\n self.draw_hero()\n\n def draw_hero(self):\n self.canvas.create_image(self.hero.x * self.size, self.hero.y * self.size, anchor = NW, image = self.hero.image)\n\n def draw_skeleton1(self):\n self.canvas.create_image(self.skeleton1.x * self.size, self.skeleton1.y * self.size, anchor = NW, image = self.skeleton1.image)\n\n def draw_skeleton2(self):\n self.canvas.create_image(self.skeleton2.x * self.size, self.skeleton2.y * self.size, anchor = NW, image = self.skeleton2.image)\n\n def draw_skeleton3(self):\n self.canvas.create_image(self.skeleton3.x * self.size, self.skeleton3.y * self.size, anchor = NW, image = self.skeleton3.image)\n\n def draw_boss(self):\n self.canvas.create_image(self.boss.x * self.size, self.boss.y * self.size, anchor = NW, image = self.boss.image)\n\n def move_route(self, key):\n keypress = key.keysym\n if keypress == 'Up':\n if self.hero.y - 1 >= 0 and self.map.matrix[self.hero.y - 1][self.hero.x] == 0:\n self.hero.move_up()\n if keypress == 'Down':\n if self.hero.y + 1 <=9 and self.map.matrix[self.hero.y + 1][self.hero.x] == 0:\n self.hero.move_down()\n if keypress == 'Left':\n if self.hero.x - 1 >= 0 and self.map.matrix[self.hero.y][self.hero.x - 1] == 0:\n self.hero.move_left()\n if keypress == 'Right':\n if self.hero.x + 1 <=9 and self.map.matrix[self.hero.y][self.hero.x + 1] == 0:\n self.hero.move_right()\n","sub_path":"week-06/TkWanderer/gamescreen.py","file_name":"gamescreen.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"519755556","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom setuptools import setup\nimport os.path\n\ntry:\n from pypandoc import convert\n read_md = lambda f: convert(f, 'rst')\nexcept ImportError:\n print(\"warning: pypandoc module not found, could not convert Markdown to RST\")\n read_md = lambda f: open(f, 'r').read()\n\nreadme = read_md('README.md')\n\nwith open('HISTORY.rst') as history_file:\n history = history_file.read()\n\nrequirements = [\n 'click==6.7',\n 'click-log==0.1.8',\n]\n\ntest_requirements = [\n 'pytest==3.2.0',\n 'prospector==0.12.7',\n 'pylint==1.9.2',\n 'isort==4.2.15' # dependency of pylint'pytest==3.2.0'\n]\n\nextras = {\n 'test': test_requirements + requirements\n}\n\n# get version\nmetadata = {}\nversion_filename = os.path.join(os.path.dirname(__file__), 'cireqs','__version__.py')\nexec(open(version_filename).read(), None, metadata)\n\nsetup(\n name='cireqs',\n version=metadata['__version__'],\n description=\"cli tool to verify and update requirements files\",\n long_description=readme + '\\n\\n' + history,\n author=\"jgv\",\n author_email='jgv@trustpilot.com',\n url='https://github.com/trustpilot/python-cireqs',\n packages=[\n 'cireqs',\n ],\n package_dir={'cireqs':\n 'cireqs'},\n entry_points={\n 'console_scripts': [\n 'cireqs=cireqs.cli:cli'\n ]\n },\n include_package_data=True,\n install_requires=requirements,\n zip_safe=False,\n keywords='cireqs requirements ci',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n test_suite='tests',\n tests_require=test_requirements,\n extras_require=extras,\n\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"327484148","text":"import math\n\nprint('A simple quadratic equation solver')\n...\nprint('--- ax^2 + bx + c = 0 ---')\n...\nprint('**********************************')\n...\ninput('Press Enter or enter Ctrl+C to exit the program')\n...\n\nwhile True:\n\tprint('Enter the coefficients: (If a = 0, the equation is not quadratic)')\n\t...\n\ta = int(input('Enter a: '))\n\t...\n\tb = int(input('Enter b: '))\n\t...\n\tc = int(input('Enter c: '))\n\t...\n\tx1 = int(( -1 * b + math.sqrt(b**2 - 4*a*c) ) / 2*a)\n\tx2 = int(( -1 * b - math.sqrt(b**2 - 4*a*c) ) / 2*a)\n\t...\n\tprint('Result: ')\n\t...\n\tprint('x1 is: ' + str(x1))\n\t...\n\tprint('x2 is: ' + str(x2))\n\t...\n\task = input('Type \"exit\" to exit the program or press Enter to solve another equation: ')\n\n\tif ask == 'exit':\n\t\tbreak\n\telse:\n\t\tcontinue\n","sub_path":"quadratic.py","file_name":"quadratic.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"470680394","text":"import logging\nfrom chess.pgn import Game, GameNode\nfrom model import Puzzle\nimport requests\n\nclass Server:\n\n def __init__(self, logger: logging.Logger, url: str, token: str, version: int) -> None:\n self.logger = logger\n self.url = url\n self.token = token\n self.version = version\n\n def is_seen(self, id: str) -> bool:\n if not self.url:\n return False\n try:\n status = requests.get(self._seen_url(id)).status_code\n return status == 200\n except Exception as e:\n self.logger.error(e)\n return False\n\n def set_seen(self, game: Game) -> None:\n try:\n if self.url:\n requests.post(self._seen_url(game.headers.get(\"Site\", \"?\")[20:]))\n except Exception as e:\n self.logger.error(e)\n\n def _seen_url(self, id: str) -> str:\n return \"{}/seen?token={}&id={}\".format(self.url, self.token, id)\n\n def post(self, game_id: str, puzzle: Puzzle) -> None:\n parent : GameNode = puzzle.node.parent\n json = {\n 'game_id': game_id,\n 'fen': parent.board().fen(),\n 'ply': parent.ply(),\n 'moves': [puzzle.node.uci()] + list(map(lambda m : m.uci(), puzzle.moves)),\n 'kind': puzzle.kind,\n 'generator_version': self.version,\n }\n try:\n r = requests.post(\"{}/puzzle?token={}\".format(self.url, self.token), json=json)\n self.logger.info(r.text if r.ok else \"FAILURE {}\".format(r.text))\n except Exception as e:\n self.logger.error(\"Couldn't post puzzle: {}\".format(e))\n","sub_path":"generator/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"352119187","text":"import mpld3\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as mpatches\r\nimport csv\r\nimport seaborn as sns\r\nfrom sklearn.ensemble import RandomForestRegressor as RFR\r\nfrom sklearn.metrics import confusion_matrix as cm\r\nfrom sklearn.metrics import classification_report as cr\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import explained_variance_score\r\nfrom sklearn.utils import resample\r\nfrom sklearn.preprocessing import StandardScaler\r\n\r\ndef load_data(filename):\r\n with open(filename,'r') as file:\r\n reader = csv.reader(file)\r\n columnNames = next(reader)\r\n rows = np.array(list(reader), dtype=float)\r\n return columnNames, rows\r\n\r\ndef separate_labels(columnNames, rows):\r\n labelColumnIndex = columnNames.index('Outcome')\r\n ys = rows[:, labelColumnIndex]\r\n xs = np.delete(rows,labelColumnIndex,axis=1)\r\n del columnNames[labelColumnIndex]\r\n return columnNames, xs, ys\r\n\r\ndef train_test_split_two(xs,ys):\r\n train_x3, test_x3, train_y3, test_y3 = train_test_split(xs[ys==3],ys[ys==3],test_size=0.5,random_state=42)\r\n train_x4, test_x4, train_y4, test_y4 = train_test_split(xs[ys==4],ys[ys==4],test_size=0.5,random_state=42)\r\n condition567 = np.logical_or(np.logical_or(ys==5,ys==6),ys==7)\r\n train_x567, test_x567, train_y567, test_y567 = train_test_split(xs[condition567],ys[condition567],test_size=0.66,random_state=42)\r\n train_x8, test_x8, train_y8, test_y8 = train_test_split(xs[ys==8],ys[ys==8],test_size=0.5,random_state=42)\r\n train_x9, test_x9, train_y9, test_y9 = train_test_split(xs[ys==9],ys[ys==9],test_size=0.5,random_state=42)\r\n train_x = np.concatenate([train_x3,train_x4,train_x567,train_x8,train_x9])\r\n test_x = np.concatenate([test_x3,test_x4,test_x567,test_x8,test_x9])\r\n train_y = np.concatenate([train_y3,train_y4,train_y567,train_y8,train_y9])\r\n test_y = np.concatenate([test_y3,test_y4,test_y567,test_y8,test_y9])\r\n return train_x, test_x, train_y, test_y\r\n\r\ndef run_algo2(file_path):\r\n\r\n df = pd.read_csv('Final_App/white_wine.csv')\r\n #df = pd.read_csv('../media/upload/white_wine.csv')\r\n ys = df['quality']\r\n xs = df.drop('quality',1)\r\n\r\n train_x, test_x, train_y, test_y = train_test_split_two(xs,ys)\r\n #print(train_x.shape,test_x.shape,train_y.shape,test_y.shape)\r\n\r\n clf=RFR(n_estimators=100,max_depth=20,random_state=0).fit(train_x,train_y)\r\n\r\n pred_y=np.round(clf.predict(test_x))\r\n #print(accuracy_score(test_y,pred_y))\r\n #print(explained_variance_score(test_y,pred_y))\r\n #plt.scatter(test_y,pred_y)\r\n #plt.show()\r\n\r\n #from sklearn.model_selection import cross_validate as cv\r\n #cv_result = cv(clf,train_x,train_y,return_train_score=True)\r\n #print('cross validation test score:', cv_result['test_score'])\r\n #print('cross validation train score:', cv_result['train_score'])\r\n #print('score:', clf.score(test_x,test_y))\r\n\r\n #print('ValidationResults')\r\n #print(cm(test_y,pred_y))\r\n #print(cr(test_y,pred_y))\r\n\r\n fig = plt.figure()\r\n feature9 = 9 #sulphates\r\n feature10 = 10 #alcohol\r\n scatter = plt.scatter(test_x[:,feature9],test_x[:,feature10],10,pred_y, cmap='jet')\r\n plt.title(label=\"Scatter of White Wine Data using the Random Forest Regressor\")\r\n plt.xlabel('sulphates')\r\n plt.ylabel('alcohol')\r\n #handles, labels = scatter.legend_elements()\r\n #plt.legend(handles=handles,labels=['Score = 4','Score = 5','Score = 6','Score = 7','Score = 8'], loc=\"upper right\", title=\"Legend\")\r\n\r\n fig.colorbar(scatter)\r\n #plt.show()\r\n\r\n return mpld3.fig_to_html(fig)\r\n\r\n#run_algo2('unknowns_white_wine.csv')\r\n#plt.show() ","sub_path":"ECE157A_Final_project/Final_App/hw2_regression.py","file_name":"hw2_regression.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"212211483","text":"from itertools import groupby\nfrom heapq import *\nfrom Node import *\nfrom math import log2\n\nclass HuffmanTree():\n \n codes = {}\n relAmount = {}\n codewortLen = []\n \n def __init__(self):\n pass\n \n def huffman(self, input):\n itemqueue = [Node(a,len(list(b)), None) for a,b in groupby(sorted(input))]\n heapify(itemqueue)\n while len(itemqueue) > 1:\n l = heappop(itemqueue)\n r = heappop(itemqueue)\n #Rel. Häufigkeit\n if l.item != None:\n self.relAmount[l.item] = l.weight / len(input)\n l.mLength = l.weight / len(input)\n if r.item != None:\n self.relAmount[r.item] = r.weight / len(input)\n r.mLength = r.weight / len(input)\n n = Node(None, r.weight+l.weight, r.mLength+l.mLength)\n self.codewortLen.append(n.mLength)\n n.setChildren(l,r)\n heappush(itemqueue, n)\n \n #print(self.relAmount)\n \n \n self.codeIt(self, \"\",itemqueue[0])\n \n #Entropie\n i = 0\n for a in self.relAmount:\n i += self.relAmount[a] * log2(self.relAmount[a])\n print(-i, \"Bits je Symbol (Entropie)\")\n #Mittlere Codewortlänge\n i = 0\n for a in self.codewortLen:\n i += a\n print(i, \"Bits je Symbol (mittlere Codewortlänge)\")\n\n return \"\".join([self.codes[a] for a in input]), itemqueue\n \n def codeIt(self, s, node):\n if node.item:\n if not s:\n self.codes[node.item] = \"0\"\n else:\n self.codes[node.item] = s\n else:\n self.codeIt(self, s+\"0\", node.left)\n self.codeIt(self, s+\"1\", node.right)","sub_path":"ALP3Python/weekFourteen/HuffmanTree.py","file_name":"HuffmanTree.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"419857635","text":"# coding=utf8\n\"\"\"\nTekton as a CODE: Main script\n\"\"\"\nimport json\nimport os\nimport random\nimport re\nimport string\nimport sys\nimport tempfile\nimport time\n\nfrom tektonasacode import github\nfrom tektonasacode import utils\nfrom tektonasacode import process_templates\nfrom tektonasacode import config\n\nCHECK_RUN_ID = None\nREPO_FULL_NAME = None\n\n\nclass TektonAsaCode:\n \"\"\"Tekton as a Code main class\"\"\"\n def __init__(self, github_token):\n self.utils = utils.Utils()\n self.github = github.Github(github_token)\n self.pcs = process_templates.Process(self.github)\n\n def github_checkout_pull_request(self, checked_repo, repo_owner_login,\n repo_html_url, pull_request_number,\n pull_request_sha):\n \"\"\"Checkout a pull request from github\"\"\"\n if not os.path.exists(checked_repo):\n os.makedirs(checked_repo)\n os.chdir(checked_repo)\n\n exec_init = self.utils.execute(\"git init\")\n if exec_init.returncode != 0:\n print(\"Error creating a GitHUB repo in {checked_repo}\")\n print(exec_init.stdout.decode())\n print(exec_init.stderr.decode())\n\n os.chdir(checked_repo)\n\n cmds = [\n f\"git remote add origin https://{repo_owner_login}:{self.github.token}@{repo_html_url.replace('https://', '')}\",\n f\"git fetch origin refs/pull/{pull_request_number}/head\",\n f\"git reset --hard {pull_request_sha}\",\n ]\n for cmd in cmds:\n self.utils.execute(\n cmd,\n \"Error checking out the GitHUB repo %s to the branch %s\" %\n (repo_html_url, pull_request_sha),\n )\n\n def create_temporary_namespace(self, namespace, repo_full_name,\n pull_request_number):\n \"\"\"Create a temporary namespace and labels\"\"\"\n self.utils.execute(f\"kubectl create ns {namespace}\",\n \"Cannot create a temporary namespace\")\n print(f\"Namespace {namespace} has been created\")\n\n # Apply label!\n self.utils.execute(\n f'kubectl label namespace {namespace} tekton.dev/generated-by=\"tekton-asa-code\"'\n )\n self.utils.execute(\n f'kubectl label namespace {namespace} tekton.dev/pr=\"{repo_full_name.replace(\"/\", \"-\")}-{pull_request_number}\"'\n )\n\n def grab_output(self, namespace):\n \"\"\"Grab output of the last pipelinerun in a namespace\"\"\"\n output_file = tempfile.NamedTemporaryFile(delete=False).name\n self.utils.stream(\n f\"tkn pr logs -n {namespace} --follow --last\",\n output_file,\n f\"Cannot show Pipelinerun log in {namespace}\",\n )\n output = open(output_file).read()\n\n # TODO: Need a better way!\n describe_output = self.utils.execute(\n f\"tkn pr describe -n {namespace} --last\").stdout.decode()\n regexp = re.compile(r\"^STARTED\\s*DURATION\\s*STATUS\\n(.*)$\",\n re.MULTILINE)\n status = regexp.findall(describe_output)[0].split(\" \")[-1]\n\n pipelinerun_output = \"\"\n if output:\n pipelinerun_output = f\"\"\"
\nPipelineRun Output\n\n
\n {output}\n
\n
\n\n \"\"\"\n report = f\"\"\"{self.utils.get_errors(output)}\n{pipelinerun_output}\n\n
\n PipelineRun status\n
\n{describe_output}\n 
\n
\n\n \"\"\"\n\n status_emoji = \"☠️\" if \"failed\" in status.lower() else \"👍🏼\"\n report_output = {\n \"title\": \"CI Run: Report\",\n \"summary\": f\"CI has **{status}** {status_emoji}\",\n \"text\": report\n }\n\n return status, describe_output, report_output\n\n def main(self, github_json):\n \"\"\"main function\"\"\"\n checked_repo = \"/tmp/repository\"\n jeez = json.loads(github_json.replace(\"\\n\", \" \"))\n random_str = \"\".join(\n random.choices(string.ascii_letters + string.digits, k=2)).lower()\n pull_request_sha = self.utils.get_key(\"pull_request.head.sha\", jeez)\n pull_request_number = self.utils.get_key(\"pull_request.number\", jeez)\n repo_full_name = self.utils.get_key(\"repository.full_name\", jeez)\n repo_owner_login = self.utils.get_key(\"repository.owner.login\", jeez)\n repo_html_url = self.utils.get_key(\"repository.html_url\", jeez)\n namespace = f\"pull-{pull_request_number}-{pull_request_sha[:5]}-{random_str}\"\n\n # Extras template parameters to add aside of the stuff from json\n parameters_extras = {\n \"revision\": pull_request_sha,\n \"repo_url\": repo_html_url,\n \"repo_owner\": repo_owner_login,\n \"namespace\": namespace,\n }\n\n target_url = self.utils.get_openshift_console_url(namespace)\n\n check_run = self.github.create_check_run(repo_full_name, target_url,\n pull_request_sha)\n # TODO\n # pull_request_user_login = self.utils.get_key(\"pull_request.user.login\",jeez)\n # tkaac_config = self.utils.get_config()\n # check_restrict_organization(\n # tkaac_config.get(\"restrict_organization\"),\n # pull_request_user_login,\n # jeez,\n # )\n\n self.github_checkout_pull_request(checked_repo, repo_owner_login,\n repo_html_url, pull_request_number,\n pull_request_sha)\n\n # Exit if there is not tekton directory\n if not os.path.exists(config.TEKTON_ASA_CODE_DIR):\n # Set status as pending\n self.github.set_status(\n repo_full_name,\n check_run['id'],\n \"https://tenor.com/search/sad-cat-gifs\",\n conclusion='neutral',\n status=\"completed\",\n output={\n \"title\":\n \"CI Run: Skipped\",\n \"summary\":\n \"Skipping this check 🤷🏻‍♀️\",\n \"text\":\n f\"No tekton-asa-code directory '{config.TEKTON_ASA_CODE_DIR}' has been found in this repository 😿\",\n })\n print(\"No tekton directory has been found 😿\")\n sys.exit(0)\n\n processed_templates = self.pcs.process_tekton_dir(\n checked_repo, repo_full_name, check_run['id'], jeez,\n parameters_extras)\n self.create_temporary_namespace(namespace, repo_full_name,\n pull_request_number)\n self.pcs.apply(processed_templates, namespace)\n\n time.sleep(2)\n\n status, describe_output, report_output = self.grab_output(namespace)\n print(describe_output)\n # Set status as pending\n self.github.set_status(\n repo_full_name,\n check_run[\"id\"],\n # Only set target_url which goest to the namespace in case of failure,\n # since we delete the namespace in case of success.\n (\"failed\" in status.lower() and target_url or \"\"),\n (\"failed\" in status.lower() and \"failure\" or \"success\"),\n report_output,\n status=\"completed\")\n if \"failed\" in status.lower():\n sys.exit(1)\n\n # Only delete if it succeed, keeping it for investigation\n self.utils.execute(\n f\"kubectl delete ns {namespace}\",\n \"Cannot delete temporary namespace {namespace}\",\n )\n","sub_path":"tektonasacode/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"285494673","text":"\nfrom rdflib import Namespace, Literal, URIRef\nfrom simpot import RdfsClass, BNamespace\nfrom rdflib.namespace import DC, FOAF\n\n\nVCARD = Namespace('https://www.w3.org/2006/vcard/ns#')\nDBO = Namespace('http://dbpedia.org/ontology/')\nDC = Namespace('http://purl.org/dc/terms/#')\nVIVO = Namespace(\"http://vivoweb.org/ontology/core#\")\nBIBO = Namespace(\"http://purl.org/ontology/bibo/\")\nOWL = Namespace(\"http://www.w3.org/TR/owl-ref/\")\nOPENCIN = Namespace(\"http://purl.org/ontology/opencin/\")\nDBACAD = Namespace(\"http://purl.org/ontology/dbacademic/\")\nAIISO = Namespace(\"http://purl.org/vocab/aiiso/schema#\")\n\n\nORG = Namespace (\"https://www.w3.org/TR/vocab-org/\")\n\n\nOPENUAI = Namespace(\"http://purl.org/ontology/openuai#\")\n\nclass Curso ():\n\n nome = FOAF.name\n\n area = OPENUAI.hasKnowledgeArea\n\n coordenador = AIISO.responsibilityOf\n\n unidade = AIISO.responsibilityOf\n\n university = AIISO.part_of\n\n code= AIISO.code\n\n @RdfsClass(AIISO.Programme, \"https://www.dbacademic.tech/resource/\")\n @BNamespace('cin', OPENCIN)\n @BNamespace('uai', OPENUAI)\n @BNamespace('aiiso', AIISO)\n @BNamespace('foaf', FOAF)\n def __init__(self, dict):\n self.nome = Literal(dict[\"nome\"])\n self.id = str(dict[\"id\"])\n self.code = str (dict[\"id\"])\n\n if \"area\" in dict:\n self.area = Literal(dict[\"area\"])\n \n if \"coordenador\" in dict:\n self.coordenador = URIRef(dict[\"coordenador\"])\n\n if \"unidade\" in dict:\n self.unidade = URIRef(dict[\"unidade\"])\n \n self.university = URIRef(dict[\"university\"])\n\n\n\nclass Docente ():\n\n nome = FOAF.name\n siape = OPENCIN.siape\n\n formacao = OPENCIN.academicDegree\n \n sameas = OWL.sameas\n\n unidade = ORG.memberOf\n\n university = ORG.memberOf\n\n sexo = VCARD.hasGender\n\n telefone = VCARD.hasTelephone\n imagem = VCARD.hasPhoto\n email = VCARD.hasEmail\n lattes = OPENCIN.lattes\n descricao = DBO.abstract\n \n @RdfsClass(DBO.Professor, \"https://www.dbacademic.tech/resource/\")\n @BNamespace('foaf', FOAF)\n @BNamespace('cin', OPENCIN)\n @BNamespace('owl', OWL)\n @BNamespace('vcard', VCARD)\n @BNamespace('dbo', DBO)\n @BNamespace('org', ORG)\n def __init__(self, dict):\n self.nome = Literal(dict[\"nome\"])\n\n if \"university\" in dict:\n self.university = URIRef(dict[\"university\"])\n\n if \"siape\" in dict:\n self.siape = Literal(dict[\"siape\"])\n self.id = str(dict[\"id\"])\n if \"formacao\" in dict:\n self.formacao = Literal(dict[\"formacao\"])\n if \"sameas\" in dict:\n self.sameas = URIRef(dict[\"sameas\"])\n if \"sexo\" in dict:\n self.sexo = Literal (dict[\"sexo\"])\n\n if \"unidade\" in dict:\n self.unidade = URIRef(dict[\"unidade\"])\n\n if \"telefone\" in dict:\n if dict[\"telefone\"]:\n self.telefone = Literal('tel:+55.98'+dict[\"telefone\"])\n\n if \"imagem\" in dict:\n if dict[\"imagem\"]:\n self.imagem = URIRef(dict[\"imagem\"])\n\n if \"email\" in dict:\n if dict[\"email\"]:\n self.email = Literal('mailto:' + dict[\"email\"]) # mudar para uriref\n\n if \"lattes\" in dict: # nao considerou valido\n if dict[\"lattes\"]:\n self.lattes = Literal(dict[\"lattes\"])\n #self.lattes = URIRef(dict[\"lattes\"])\n\n if \"descricao\" in dict:\n if dict[\"descricao\"]:\n self.descricao = Literal(dict[\"descricao\"])\n\n\n\n\n\nclass Unidade ():\n\n nome = FOAF.name\n sameas = OWL.sameas\n diretor = AIISO.responsibilityOf\n code= AIISO.code\n\n university = AIISO.part_of\n\n # unidade ? ou subunidade\n @RdfsClass(AIISO.Center, \"https://www.dbacademic.tech/resource/\") \n @BNamespace('foaf', FOAF)\n @BNamespace('cin', OPENCIN)\n @BNamespace('owl', OWL)\n @BNamespace('aiiso', AIISO)\n def __init__(self, dict):\n self.nome = Literal(dict[\"nome\"])\n self.code = dict[\"code\"]\n self.id = str(dict[\"id\"])\n if \"sameas\" in dict:\n self.sameas = URIRef(dict[\"sameas\"])\n if \"diretor\" in dict:\n self.diretor = URIRef(dict[\"diretor\"])\n if \"university\" in dict:\n self.university = URIRef(dict[\"university\"])\n\nclass Subunidade ():\n\n\n university = AIISO.part_of\n nome = FOAF.name\n sameas = OWL.sameas\n chefe = AIISO.responsibilityOf\n unidade = AIISO.part_of\n code= AIISO.code\n\n # unidade ? ou subunidade\n @RdfsClass(AIISO.Department, \"https://www.dbacademic.tech/resource/\") \n @BNamespace('foaf', FOAF)\n @BNamespace('cin', OPENCIN)\n @BNamespace('owl', OWL)\n @BNamespace('aiiso', AIISO)\n def __init__(self, dict):\n self.nome = Literal(dict[\"nome\"])\n self.id = str(dict[\"id\"])\n self.code = dict[\"code\"]\n if \"sameas\" in dict:\n self.sameas = URIRef(dict[\"sameas\"])\n if \"unidade\" in dict:\n self.unidade = URIRef(dict[\"unidade\"])\n\n if \"university\" in dict:\n self.university = URIRef(dict[\"university\"])\n\nclass Discente ():\n\n nome = FOAF.name\n curso = OPENCIN.isMemberOf\n code= DC.identifier\n\n university = ORG.memberOf\n\n @RdfsClass(OPENCIN.Student, \"https://www.dbacademic.tech/resource/\")\n @BNamespace('foaf', FOAF)\n @BNamespace('cin', OPENCIN)\n @BNamespace('aiiso', AIISO)\n @BNamespace('dc', DC)\n @BNamespace('dbacad', DBACAD)\n def __init__(self, dict ):\n self.nome = Literal(dict[\"nome\"])\n self.id = dict[\"id\"]\n self.code = dict[\"code\"]\n if \"curso\" in dict:\n self.curso = URIRef(dict[\"curso\"])\n if \"university\" in dict:\n self.university = URIRef(dict[\"university\"])\n\nclass GrupoPesquisa ():\n\n\n nome = FOAF.name\n area = OPENUAI.hasKnowledgeArea\n university = AIISO.responsibilityOf\n coordenador = AIISO.responsibilityOf\n\n @RdfsClass(AIISO.ResearchGroup, \"https://www.dbacademic.tech/resource/\")\n @BNamespace('foaf', FOAF)\n @BNamespace('cin', OPENCIN)\n @BNamespace('aiiso', AIISO)\n def __init__(self, dict):\n self.id = dict[\"id\"]\n self.nome = Literal (dict[\"nome\"])\n if \"area\" in dict:\n self.area = Literal (dict[\"area\"])\n if \"coordenador\" in dict:\n self.coordenador = URIRef(dict[\"coordenador\"])\n self.university = URIRef(dict[\"university\"])\n\n \nclass Monografia ():\n\n title = DC.title\n autor = DC.creator\n curso = BIBO.issuer\n university = BIBO.issuer\n orientador = DC.contributor\n\n @RdfsClass(BIBO.Report, \"https://www.dbacademic.tech/resource/\")\n @BNamespace('dc', DC)\n @BNamespace('bibo', BIBO)\n def __init__(self, dict ):\n self.title = Literal(dict[\"titulo\"])\n self.id = dict[\"id\"]\n if \"curso\" in dict:\n self.curso = URIRef(dict[\"curso\"])\n if \"university\" in dict:\n self.curso = URIRef(dict[\"university\"])\n if \"autor\" in dict:\n self.autor = Literal(dict[\"autor\"])\n if \"orientador\" in dict:\n self.orientador = URIRef(dict[\"orientador\"]) \n","sub_path":"model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"642684435","text":"# -*- coding: utf-8 -*-\n\nimport os\n\nfrom visigoth import Diagram\nfrom visigoth.utils.mapping import Geocoder, Mapping\nfrom visigoth.map_layers import WMS, Geoplot\nfrom visigoth.map_layers.geoplot import Multipoint\nfrom visigoth.containers import Map, Box\nfrom visigoth.common import Text\n\nfolder=os.path.split(__file__)[0]\n\nd = Diagram()\n\n# lets see where \"HelloWorld\" geocodes to!\ngc = Geocoder()\ncenter = gc.fetchCenter(\"Hello World\")\nbounds = Mapping.computeBoundaries(center,4000)\n\n# create a map with the default projection system (web mercator)\nm = Map(768,boundaries=bounds)\n\n# create a base layer with openstreetmap\nwms = WMS(\"osm\")\nwms.setInfo(\"Map\")\n\n# create a layer with a marker for \"HelloWorld\"\ngps = Geoplot(multipoints=[Multipoint([center],label=\"Hello World\",tooltip=\"Hello World\")])\n\nm.add(wms)\nm.add(gps)\n\n# compose the diagram\nd.add(Text(\"Where does \\\"Hello World\\\" Geolocate to?\",font_height=18))\nd.add(Box(m))\n\nhtml = d.draw(format=\"html\")\n\nf = open(\"example.html\", \"w\")\nf.write(html)\nf.close()\n\n","sub_path":"docs/src/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"530312532","text":"from collections.abc import Mapping\nfrom abc import ABCMeta\nfrom functools import partial\nimport importlib\nfrom urllib.parse import urlparse\nimport requests\nimport rethinkdb as r\nimport logging\nimport logging.config\nimport os\n\nfrom jsonschema import Draft4Validator\n\nfrom sondra import help\nfrom sondra.api.ref import Reference\nfrom sondra.schema import merge\nfrom . import signals\n\nCSS_PATH = os.path.join(os.getcwd(), 'static', 'css', 'help.css')\nDOCSTRING_PROCESSORS = {}\ntry:\n from docutils.core import publish_string\n from sphinxcontrib import napoleon\n\n\n def google_processor(s):\n return publish_string(\n str(napoleon.GoogleDocstring(s)),\n writer_name='html',\n settings_overrides={\n \"stylesheet_path\": CSS_PATH,\n \"embed_stylesheet\": True,\n 'report_level': 5\n }\n )\n\n def numpy_processor(s):\n return publish_string(\n str(napoleon.NumpyDocstring(s)),\n writer_name='html',\n settings_overrides={\n \"stylesheet_path\": CSS_PATH,\n \"embed_stylesheet\": True,\n 'report_level': 5\n }\n )\n\n DOCSTRING_PROCESSORS['google'] = google_processor\n DOCSTRING_PROCESSORS['numpy'] = numpy_processor\nexcept:\n DOCSTRING_PROCESSORS['google'] = lambda x: x\n DOCSTRING_PROCESSORS['numpy'] = lambda x: x \n\ntry:\n from docutils.core import publish_string\n\n DOCSTRING_PROCESSORS['rst'] = partial(publish_string, writer_name='html', settings_overrides={\"stylesheet_path\": CSS_PATH, \"embed_stylesheet\": True})\nexcept ImportError:\n pass\n\ntry:\n from markdown import markdown\n\n DOCSTRING_PROCESSORS['markdown'] = markdown\nexcept ImportError:\n pass\n\nDOCSTRING_PROCESSORS['preformatted'] = lambda x: \"
\" + str(x) + \"
\"\n\n\nBASIC_TYPES = {\n \"timedelta\": {\n \"type\": \"object\",\n \"required\": [\"start\", \"end\"],\n \"properties\": {\n \"days\": {\"type\": \"integer\"},\n \"hours\": {\"type\": \"integer\"},\n \"minutes\": {\"type\": \"integer\"},\n \"seconds\": {\"type\": \"number\"}\n }\n },\n \"filterOps\": {\n \"enum\": [\n 'with_fields',\n 'count',\n 'max',\n 'min',\n 'avg',\n 'sample',\n 'sum',\n 'distinct',\n 'contains',\n 'pluck',\n 'without',\n 'has_fields',\n 'order_by',\n 'between'\n ]\n },\n \"spatialOps\": {\n \"enum\": [\n 'distance',\n 'get_intersecting',\n 'get_nearest',\n ]\n }\n}\n\n\nclass SuiteException(Exception):\n \"\"\"Represents a misconfiguration in a :class:`Suite` class\"\"\"\n\n\nclass SuiteMetaclass(ABCMeta):\n def __new__(mcs, name, bases, attrs):\n definitions = {}\n for base in bases:\n if hasattr(base, \"definitions\") and base.definitions:\n definitions.update(base.definitions)\n\n if \"definitions\" in attrs:\n attrs['definitions'].update(definitions)\n else:\n attrs['definitions'] = definitions\n\n return super().__new__(mcs, name, bases, attrs)\n\n def __init__(self, name, bases, attrs):\n super(SuiteMetaclass, self).__init__(name, bases, attrs)\n url = \"http://localhost:5000/api\"\n for base in bases:\n if hasattr(base, 'url'):\n url = base.url\n\n attrs['url'] = attrs.get('url', url)\n p_base_url = urlparse(attrs['url'])\n self.base_url_scheme = p_base_url.scheme\n self.base_url_netloc = p_base_url.netloc\n self.base_url_path = p_base_url.path\n self.slug = self.base_url_path[1:] if self.base_url_path else \"\"\n\n\nclass Suite(Mapping, metaclass=SuiteMetaclass):\n \"\"\"This is the \"environment\" for Sondra. Similar to a `settings.py` file in Django, it defines the\n environment in which all :class:`Application`s exist.\n\n The Suite is also a mapping type, and it should be used to access or enumerate all the :class:`Application` objects\n that are registered.\n\n Attributes:\n always_allowed_formats (set): A set of formats where a\n applications (dict): A mapping from application name to Application objects. Suite itself implements a mapping\n protocol and this is its backend.\n base_url (str): The base URL for the API. The Suite will be mounted off of here.\n base_url_scheme (str): http or https, automatically set.\n base_url_netloc (str): automatically set hostname of the suite.\n connection_config (dict): For each key in connections setup keyword args to be passed to `rethinkdb.connect()`\n connections (dict): RethinkDB connections for each key in ``connection_config``\n docstring_processor_name (str): Any member of DOCSTRING_PROCESSORS: ``preformatted``, ``rst``, ``markdown``,\n ``google``, or ``numpy``.\n docstring_processor (callable): A ``lambda (str)`` that returns HTML for a docstring.\n logging (dict): A dict-config for logging.\n log (logging.Logger): A logger object configured with the above dictconfig.\n cross_origin (bool=False): Allow cross origin API requests from the browser.\n db_prefix: (str=\"\"): A default string to prepend to all the database names in this suite.\n schema (dict): The schema of a suite is a dict where the keys are the names of :class:`Application` objects\n registered to the suite. The values are the schemas of the named app. See :class:`Application` for more\n details on application schemas.\n \"\"\"\n title = \"Sondra-Based API\"\n name = None\n debug = False\n applications = None\n definitions = BASIC_TYPES\n url = \"http://localhost:5000/api\"\n logging = None\n log_level = None\n docstring_processor_name = 'preformatted'\n cross_origin = False\n allow_anonymous_formats = {'help', 'schema'}\n api_request_processors = ()\n file_storage = None\n connection_config = {\n 'default': {}\n }\n working_directory = os.getcwd()\n language = 'en'\n translations = None\n db_prefix = \"\"\n\n @property\n def schema_url(self):\n return self.url + \";schema\"\n\n @property\n def schema(self):\n return {\n \"id\": self.url + \";schema\",\n \"title\": self.title,\n \"type\": \"object\",\n \"description\": self.__doc__ or \"*No description provided.*\",\n \"applications\": {k: v.url for k, v in self.applications.items()},\n \"definitions\": self.definitions\n }\n\n @property\n def full_schema(self):\n return {\n \"id\": self.url + \";schema\",\n \"title\": self.title,\n \"type\": None,\n \"description\": self.__doc__ or \"*No description provided.*\",\n \"applications\": {k: v.full_schema for k, v in self.applications.items()},\n \"definitions\": self.definitions\n }\n\n def __init__(self, db_prefix=\"\"):\n self.applications = {}\n self.connections = None\n self.db_prefix = db_prefix\n\n if self.logging:\n logging.config.dictConfig(self.logging)\n elif self.log_level:\n logging.basicConfig(level=self.log_level)\n else:\n logging.basicConfig(level=logging.DEBUG if self.debug else logging.INFO)\n\n self.log = logging.getLogger(self.__class__.__name__) # use root logger for the environment\n\n signals.pre_init.send(self.__class__, isntance=self)\n\n self.connect()\n for name in self.connections:\n self.log.info(\"Connection established to '{0}'\".format(name))\n\n self.log.info(\"Suite base url is: '{0}\".format(self.url))\n\n self.docstring_processor = DOCSTRING_PROCESSORS[self.docstring_processor_name]\n self.log.info('Docstring processor is {0}')\n\n self.log.info('Default language is {0}'.format(self.language))\n self.log.info('Translations for default language are {0}'.format('present' if self.translations else 'not present'))\n\n self.name = self.name or self.__class__.__name__\n self.description = self.__doc__ or \"No description provided.\"\n signals.post_init.send(self.__class__, instance=self)\n\n def check_connections(self):\n for name, conn in self.connections.items():\n try:\n r.db_list().run(conn)\n except r.ReqlDriverError as e:\n self.connections[name] = r.connect(**self.connection_config[name])\n\n def connect(self):\n self.connections = {name: r.connect(**kwargs) for name, kwargs in self.connection_config.items()}\n\n def register_application(self, app):\n \"\"\"This is called automatically whenever an Application object is constructed.\"\"\"\n if app.slug in self.applications:\n self.log.error(\"Tried to register application '{0}' more than once.\".format(app.slug))\n raise SuiteException(\"Tried to register multiple applications with the same name.\")\n\n self.applications[app.slug] = app\n self.log.info('Registered application {0} to {1}'.format(app.__class__.__name__, app.url))\n\n def set_language_for_schema(self, app, collection, schema, definitions):\n \"\"\"Takes translations and applies them to the schema, overriding enumNames, title, and description where appropriate.\"\"\"\n self.log.info('Applying localization \"{0}\" for {1}/{2}'.format(self.language, app, collection))\n\n # update schema\n if (\n self.language and\n self.translations and\n self.language in self.translations and\n app in self.translations[self.language] and\n collection in self.translations[self.language][app]\n ):\n translated_schema = self.translations[self.language][app][collection]\n for key in translated_schema:\n schema_to_update = schema\n full_key = key.split('.')\n while full_key:\n schema_to_update = schema_to_update['properties'][full_key.pop(0)]\n schema_to_update.update(translated_schema[key])\n\n # update definitions\n if (\n self.language and\n self.translations and\n self.language in self.translations and\n 'definitions' in self.translations[self.language]\n ):\n translated_definitions = self.translations[self.language]['definitions']\n for key in translated_definitions:\n entry, *full_key = key.split('.')\n if entry in definitions:\n schema_to_update = definitions[entry]\n while full_key:\n schema_to_update = schema_to_update['properties'][full_key.pop(0)]\n schema_to_update.update(translated_definitions[key])\n\n if entry in schema.get('definitions', {}):\n schema_to_update = schema['definitions'][entry]\n while full_key:\n schema_to_update = schema_to_update['properties'][full_key.pop(0)]\n schema_to_update.update(translated_definitions[key])\n\n def set_language(self):\n for app_key, collections in self.items():\n for coll_key, coll in collections.items():\n self.set_language_for_schema(app_key, coll_key, coll.schema, coll.definitions)\n\n def drop_database_objects(self):\n for app in self.values():\n app.drop_database()\n\n def ensure_database_objects(self):\n for app in self.values():\n app.create_database()\n app.create_tables()\n\n def clear_databases(self):\n self.drop_database_objects()\n self.ensure_database_objects()\n\n def clear_tables(self):\n for app in self.values():\n app.clear_tables()\n\n def __getitem__(self, item):\n \"\"\"Application objects are indexed by \"slug.\" Every Application object registered has its name slugified.\n\n This means that if your app was called `MyCoolApp`, its registered name would be `my-cool-app`. This key is\n used whether you are accessing the application via URL or locally via Python. For example, the following\n both produce the same result::\n\n URL (yields schema as application/json):\n\n http://localhost:5000/api/my-cool-app;schema\n\n Python (yields schema as a dict):\n\n suite = Suite()\n suite['my-cool-app'].schema\n \"\"\"\n return self.applications[item]\n\n def __len__(self):\n return len(self.applications)\n\n def __iter__(self):\n return iter(self.applications)\n\n def __contains__(self, item):\n return item in self.applications\n\n def help(self, out=None, initial_heading_level=0):\n \"\"\"Return full reStructuredText help for this class\"\"\"\n builder = help.SchemaHelpBuilder(self.schema, self.url, out=out, initial_heading_level=initial_heading_level)\n builder.begin_subheading(self.name)\n builder.define(\"Suite\", self.url)\n builder.line()\n builder.define(\"Schema URL\", self.schema_url)\n builder.line()\n builder.build()\n builder.line()\n builder.begin_subheading(\"Applications\")\n builder.begin_list()\n for name, coll in self.applications.items():\n builder.define(name, coll.url + ';help')\n builder.end_list()\n builder.end_subheading()\n builder.end_subheading()\n return builder.rst\n\n def lookup(self, url):\n if not url.startswith(self.url):\n return requests.get(url).json() # TODO replace with client.\n else:\n return Reference(self, url).value\n\n def lookup_document(self, url):\n if not url.startswith(self.url):\n return requests.get(url).json() # TODO replace with client.\n else:\n return Reference(self, url).get_document()\n\n def validate(self):\n self.log.info(\"Checking schemas for validity\")\n for application in self.applications.values():\n self.log.info(\"+ \" + application.slug)\n for collection in application.collections:\n self.log.info('--- ' + collection.slug)\n Draft4Validator.check_schema(collection.schema)\n\n","sub_path":"sondra/suite/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"154297197","text":"from django import template\nfrom datetime import date, timedelta\nregister = template.Library()\n\n@register.filter(name='sale')\ndef sale(value, arg):\n return int(float(value)-float(value)*arg/100)\n\n@register.filter(name='new')\ndef new(value, arg):\n date_N_days_ago = date.today() - timedelta(days=arg)\n if value <= date_N_days_ago:\n return False\n else:\n return True\n\n@register.filter(name='times')\ndef times(value):\n if value is not None:\n value = 'x'*int(value)\n return value\n else:\n return 'x'\n@register.filter(name='is_auth')\ndef is_auth(value):\n if value.is_authenticated:\n return True\n else:\n return False\n\n@register.filter(name='summ')\ndef summ(value):\n sum = 0\n for product in value:\n sum += sale(product.price,product.discount)\n return sum","sub_path":"categories/templatetags/categories_extras.py","file_name":"categories_extras.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"508331598","text":"import csv\nimport random\nimport pandas\nimport numpy as np\nimport matplotlib.pyplot as plt # To visualize\nfrom sklearn.linear_model import LinearRegression\n\ndef main():\n dtypes = {\n 'rating': float,\n 'bayes_rating': float\n }\n headers = []\n with open('mechanics_data.csv') as data:\n csvreader = csv.reader(data)\n for row in csvreader:\n header = row\n for entry in header:\n if entry not in dtypes:\n dtypes[entry] = bool\n headers.append(entry)\n break\n data = pandas.read_csv('mechanics_data.csv', dtype=dtypes)\n columns = []\n for i in range(182):\n columns.append('bayes_rating')\n Y = data[columns].values.reshape(-1, 182)\n # X = data[['Singing', 'Legacy Game']].values.reshape(-1, 2)\n data = data.drop(columns=['bayes_rating', 'rating'])\n X = data.values.reshape(-1,182)\n linear_regressor = LinearRegression() # create object for the class\n linear_regressor.fit(X, Y) # perform linear regression\n # Y_pred = linear_regressor.predict(X) # make predictions\n # plt.scatter(X, Y)\n # plt.plot(X, Y_pred, color='red')\n # plt.show()\n\n # highest_rating = 0\n # while True:\n # new_data = []\n # for i in range(182):\n # new_data.append(0)\n # for i in range(5):\n # roll = random.randint(0,181)\n # new_data[roll] = 1\n # rating = linear_regressor.predict([new_data])[0][0]\n # if rating > highest_rating:\n # highest_rating = rating\n # print('-------------------------------')\n # print(f'New winner! - {highest_rating}')\n # print('Mechanics:')\n # for i in range(182):\n # if new_data[i]==1:\n # print(headers[i])\n\n coefs = linear_regressor.coef_[0]\n highest_coefs = [-1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000]\n best_coefs = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]\n for repeat in range(20):\n for i in range(182):\n for j in range(10):\n if coefs[i] > highest_coefs[j] and i not in best_coefs:\n highest_coefs[j] = coefs[i]\n best_coefs[j] = i\n output = {}\n for j in range(10):\n output[headers[best_coefs[j]]] = highest_coefs[j]\n for key in output:\n print(f'{key}: {output[key]}')\n\n # values = []\n # for i in range(182):\n # if headers[i] in ['Order Counters', 'Turn Order: Pass Order', 'Auction: Dutch', 'Delayed Purchase', 'Advantage Token']:\n # values.append(1)\n # else:\n # values.append(0)\n # rating = linear_regressor.predict([values])[0][0]\n # print(rating)\n\n # values = []\n # for i in range(182):\n # if headers[i] in ['Legacy Game', 'Resource to Move', 'Turn Order: Pass Order', 'Critical Hits and Failures', 'Advantage Token']:\n # values.append(1)\n # else:\n # values.append(0)\n # rating = linear_regressor.predict([values])[0][0]\n # print(rating)\n\n\nif __name__=='__main__':\n main()\n","sub_path":"linear_regression_mechanics.py","file_name":"linear_regression_mechanics.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"24588370","text":"#\r\n# L18_Rekurzija\r\n#\r\n\r\n# Ukljuci biblioteku pygame\r\nimport pygame\r\n\r\n# Definiraj boje\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\n\r\ndef recursive_draw(x, y, width, height):\r\n # Rekurzivno crtanje pravokutnika\r\n pygame.draw.rect(screen, BLACK,[x, y, width, height], 1)\r\n # Ako je širina pravokutnika veća od 14 smanji ju\r\n if(width > 14):\r\n # Smanji dimenzije\r\n x += width * .1\r\n y += height * .1\r\n width *= .8\r\n height *= .8\r\n # Ponovo pozovi funkciju rekurzivno\r\n recursive_draw(x, y, width, height)\r\n\r\n# Inicijaliziraj pygame\r\npygame.init()\r\n\r\n# Postavi dimenzije ekrana\r\nsize = [700, 500]\r\nscreen = pygame.display.set_mode(size)\r\n\r\n# Postavi naslov prozora \r\npygame.display.set_caption(\"Rekurzija\")\r\n \r\n# Postavi varijablu za kraj programa\r\ndone = False\r\n \r\n# Postavi varijablu za brzinu osvjezavanja ekrana\r\nclock = pygame.time.Clock()\r\n\r\n# Gavna petlja \r\nwhile not done:\r\n # Procitaj akciju igraca\r\n for event in pygame.event.get():\r\n # Ako je igrac kliknuo na kruzic zavrsi program\r\n if event.type == pygame.QUIT:\r\n done = True\r\n # Postavi pozadinu prozora\r\n screen.fill(WHITE)\r\n # Pozovi funkciju za crtanje pravokutnika\r\n recursive_draw(0, 0, 700, 500)\r\n # Obnovi prikaz na ekranu\r\n pygame.display.flip()\r\n # Postavi osvjezivanje ekrana na 60 fps\r\n clock.tick(60)\r\n\r\n# zatvori pygame\r\npygame.quit()\r\n\r\n\r\n","sub_path":"Code/L18_Rekurzija.py","file_name":"L18_Rekurzija.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"334084971","text":"# -*- coding: utf-8 -*-\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport logging\r\nimport requests\r\n\r\nfrom airflow import configuration\r\nfrom airflow.notifiers import AirflowNotifier\r\nfrom airflow.exceptions import AirflowException\r\n\r\n\r\nclass HipChatAPI(object):\r\n \r\n @staticmethod\r\n def send_message(url, token, body):\r\n response = requests.request('POST',\r\n url,\r\n headers={\r\n 'Content-Type': 'application/json',\r\n 'Authorization': 'Bearer %s' % token},\r\n data=body)\r\n \r\n if response.status_code >= 400:\r\n logging.error('HipChat API call failed: %s %s',\r\n response.status_code, response.reason)\r\n raise AirflowException('HipChat API call failed: %s %s' %\r\n (response.status_code, response.reason))\r\n\r\n\r\nclass HipChatNotifier(AirflowNotifier):\r\n \r\n def __init__(self, room_id, notify_on = []):\r\n self.room_id = room_id\r\n self.notify_on = notify_on\r\n \r\n def send_notification(self, task_instance, state, message, **kwargs):\r\n if state in self.notify_on:\r\n text_tpl = self.notify_on[state]\r\n text = self.render_template(text_tpl, task_instance, message=message, **kwargs)\r\n \r\n \r\n if configuration.has_option('hipchat', 'base_url'):\r\n base_url = configuration.get('hipchat', 'base_url')\r\n else:\r\n base_url = 'https://api.hipchat.com/v2'\r\n \r\n url = '%s/room/%s/notification' % (base_url, self.room_id)\r\n token = configuration.get('hipchat', 'token')\r\n body = {'message': text,\r\n 'message_format': 'text',\r\n 'frm': 'Airflow'}\r\n \r\n HipChatAPI.send_message(url, token, body)\r\n","sub_path":"airflow/notifiers/hipchat.py","file_name":"hipchat.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"39606654","text":"# %%\n\n# coding: utf-8\n\n# %%\n\nimport pandas as pd\nimport numpy as np\nimport scipy.stats as sc\nfrom scipy import sparse\nfrom collections import OrderedDict\nfrom scipy.optimize import minimize\nimport pylogit as pl\n\nimport time\n\n\ndef add_intercept_to_df(df_long, specification_dict):\n \n if (\"intercept\" in specification_dict \n and \"intercept\" not in df_long.columns):\n df_long[\"intercept\"] = 1\n \n return None\n\n\n# %%\n\ndef create_design_matrix(df_long, specification_dict,\n names_dict, alternative_id_col):\n \n add_intercept_to_df(df_long,specification_dict)\n \n columns = []\n for col in specification_dict:\n for group in specification_dict[col]:\n if type(group) == list:\n columns.append(df_long[alternative_id_col].isin(group)\n *df_long[col])\n else:\n columns.append((df_long[alternative_id_col]==group)\n *df_long[col])\n \n design_matrix = np.stack(columns,axis = 1)\n \n var_names = []\n for variable in names_dict:\n for name in names_dict[variable]:\n var_names.append(name)\n \n return design_matrix, var_names\n\n\n# %%\n\ndef calculate_utilities(betas, design_matrix):\n \n limit_max = 700\n limit_min = -700 \n \n utility = design_matrix.dot(betas)\n utility[utility>limit_max] = limit_max\n utility[utility anterior:\n listaMayores.append(i)\n anterior=i\n return(listaMayores)\n\n#Esta función intercambia la posición de cada par de datos de una lista provista. Si la lista tiene un\n#numero impar de datos, el último no se mueve.\ndef intercambiarPares(listaOriginal): \n listaNueva=[]\n contador=0\n if len(listaOriginal)>1:\n for j in listaOriginal:\n posicion=listaOriginal.index(j)\n if posicion==len(listaOriginal):\n listaNueva.append(j)\n elif posicion%2==1:\n listaNueva.insert(contador-1,j)\n else:\n listaNueva.insert(contador,j)\n contador+=1\n return(listaNueva)\n\n#Esta función calcula el promedio de un lista y regresa una lista nueva con los valores que superen el promedio.\ndef definirNumerosMayoresAlPromedio(listaOriginal):\n lenOriginal=len(listaOriginal)\n if lenOriginal>0:\n promedio= sum(listaOriginal) / lenOriginal\n listaFinal=[]\n contador=0\n for j in listaOriginal:\n if j >= promedio:\n contador+=1\n listaFinal.append(j)\n return(contador, promedio,listaFinal)\n else:\n return(0,0,listaOriginal)\n\n#Esta función intercambia la posición del valor mínimo y máximo de una lista provista\ndef cambiarPosicionMinMax(listaOriginal):\n listaIntercambiada = listaOriginal[:]\n if len(listaOriginal)>1:\n valormin=min(listaOriginal)\n valormax=max(listaOriginal)\n posicionmin=listaOriginal.index(valormin)\n posicionmax=listaOriginal.index(valormax)\n listaIntercambiada.remove(valormax)\n listaIntercambiada.insert(posicionmin,valormax)\n listaIntercambiada.remove(valormin)\n listaIntercambiada.insert(posicionmax,valormin)\n return(listaIntercambiada)\n \n#Esta función calcula el promedio y la desviación estandar de una lista.\ndef calcularMediaYDesviacionEstandar(listaOriginal):\n lenOriginal=len(listaOriginal)\n media=0\n if lenOriginal>1:\n media = sum(listaOriginal) / lenOriginal\n sumatoria=0\n for i in listaOriginal:\n sumatoria+=(i-media)**2\n adentro=sumatoria/ (lenOriginal-1)\n desviacion=adentro**.5\n else:\n desviacion=0\n return(media,desviacion)\n\n\ndef main():\n print(\"Ejercicio 1. Crear lista con solo números pares\")\n for k in listaDeListas:\n print(\"Si recibe\",k,\",regresa\",crearListaConPares(k))\n print(\"\")\n print(\"Ejercicio 2. Crear lista con los valores mayores al anterior\")\n for k in listaDeListas:\n print(\"Si recibe\", k, \",regresa\", crearListaMayores(k))\n print(\"\")\n print(\"Ejercicio 3. Intercambiar pareja de datos\")\n for k in listaDeListas:\n print(\"Si recibe\", k, \",regresa\", intercambiarPares(k))\n print(\"\")\n print(\"Ejercicio 4. Intercambiar mayor con menor\")\n for k in listaDeListas:\n print(\"Si recibe\", k, \",regresa\", cambiarPosicionMinMax(k))\n print(\"\")\n print(\"Ejercicio 5. Encontrar valores mayores al promedio\")\n for k in listaDeListas:\n cont, prome, listFinal= definirNumerosMayoresAlPromedio(k)\n print(\"Si recibe\", k, \",regresa %d. El promedio es %.2f y hay %d valores iguales o mayores que %.2f\" %(cont,prome,cont,prome), listFinal )\n print(\"\")\n print(\"Ejercicio 6. Encontrar la desviación estandar\")\n for j in listaDeListas:\n final=calcularMediaYDesviacionEstandar(j)\n print(\"Si recibe\",j,\"regresa\",final)\n\nmain()","sub_path":"listas2.py","file_name":"listas2.py","file_ext":"py","file_size_in_byte":4194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"58817082","text":"from functools import wraps\n\nfrom flask import request\nfrom sqlalchemy.orm import load_only\nfrom sqlalchemy import desc\nfrom werkzeug.exceptions import UnprocessableEntity\n\nfrom lib.utils import *\nfrom .settings import *\n\n__all__ = (\n 'get_offset',\n 'get_limit',\n 'get_sort',\n 'list_endpoint',\n 'get_list',\n 'load_schema',\n 'ValidationException'\n)\n\n\nclass ValidationException(UnprocessableEntity):\n def __init__(self, errors):\n self.description = 'Schema of body is wrong. Section `schema_errors` contains more info'\n self.errors = errors\n self.data = {'schema_errors': errors}\n\n\ndef load_schema(schema, in_json=True):\n \"\"\"\n Trying to load data using given form. If data\n as wrong format (validation failed) then exception will be raised.\n\n :param schema: Marshmallow schema\n :param in_json: If True uses ``Request.get_json()`` method, otherwise – use ``Request.form``.\n :exception: UnprocessableEntity (422 HTTP code) – if failed to validate data\n :exception: BadRequest (400 HTTP code) – if failed to parse json body\n :return: :type:`dict`\n \"\"\"\n data = request.get_json() if in_json else request.form\n result = schema.load(data)\n if len(result) != 0:\n raise ValidationException(result.errors)\n return data\n\n\ndef with_schema(schema, in_json=True):\n def decorator(f):\n @wraps(f)\n def wrapper(*a, **kw):\n kw['schema'] = load_schema(schema, in_json)\n return f(*a, **kw)\n return wrapper\n return decorator\n\n\ndef get_list(query, load_only_fields, limit, offset, sort_key=None, descending=False, **filter_args) -> list:\n objects = query.options(load_only(*load_only_fields))\n if sort_key and len(sort_key) != 0:\n for col in model.__mapper__.columns:\n if col.name == sort_key:\n objects = objects.order_by(desc(col) if descending else col)\n break\n if len(filter_args) != 0:\n objects = objects.filter_by(**filter_args)\n objects = objects.offset(offset).limit(limit)\n print(objects)\n return objects.all()\n\n\ndef get_offset(d) -> int:\n return parse_long(d.get('offset'), 0, min_value=0)\n\n\ndef get_limit(d) -> int:\n return parse_int(d.get('limit'), RECORDS_PER_REQUEST_DF, min_value=1, max_value=RECORDS_PER_REQUEST)\n\n\ndef get_sort(d):\n sort = d.get('sort')\n if sort:\n sort = sort.lower()\n is_desc = False\n if sort.startswith('-'):\n is_desc = True\n if sort[0] in ('+', '-'):\n sort = sort[1:]\n return is_desc, sort\n\n\ndef list_endpoint(f):\n @wraps(f)\n def wrapper(*a, **kw):\n is_desc, sort = get_sort(request.args) or (False, None)\n kw.update(limit=get_limit(request.args), offset=get_offset(request.args), sort=sort, descending=is_desc)\n return f(*a, **kw)\n return wrapper\n","sub_path":"api/v1/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"433808997","text":"'''\nAuthor: shawn233\nDate: 2021-03-06 19:20:17\nLastEditors: shawn233\nLastEditTime: 2021-03-14 15:38:56\nDescription: Processing Iris dataset\n'''\n\nimport os\nfrom numpy.random import shuffle\nimport numpy as np\n\n\ndef main():\n label_dict = {\n \"Iris-setosa\": \"0\",\n \"Iris-versicolor\": \"1\",\n \"Iris-virginica\": \"2\",\n }\n\n data = []\n with open(\"./iris.data\", \"r\") as iris:\n for line in iris:\n line = line.strip().split(',')\n if len(line) == 1:\n continue\n line[-1] = label_dict[line[-1]] # converts label to integer\n data.append(line)\n \n shuffle(data)\n\n features_arr = []\n for d in data:\n features_arr.append([float(entry) for entry in d[:-1]])\n features_arr = np.asarray(features_arr)\n # print(features_arr)\n # feature normalization\n min_val = np.min(features_arr, axis=0)\n max_val = np.max(features_arr, axis=0)\n features_arr = ( features_arr - min_val ) / ( max_val - min_val )\n \n features = [\"\\t\".join(list(features_arr[i].astype(str))) + \"\\n\" for i in range(features_arr.shape[0])]\n # print(features[100])\n # print(len(features))\n\n labels = [d[-1]+'\\n' for d in data]\n # print(labels)\n # print(len(labels))\n\n with open(\"iris-features.txt\", \"w\") as f:\n f.writelines(features)\n\n with open(\"iris-labels.txt\", \"w\") as f:\n f.writelines(labels)\n\n print(\"Done!\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"dev/data/iris/iris.py","file_name":"iris.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"363874647","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('CharClass', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ClassAbility',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('level', models.IntegerField(default=1)),\n ('desc', models.CharField(max_length=2500, default='description')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='charclass',\n name='bab',\n field=models.IntegerField(default=0),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='charclass',\n name='fort',\n field=models.IntegerField(default=0),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='charclass',\n name='ref',\n field=models.IntegerField(default=0),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='charclass',\n name='will',\n field=models.IntegerField(default=0),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='charclass',\n name='name',\n field=models.CharField(max_length=20, default='class'),\n preserve_default=True,\n ),\n ]\n","sub_path":"CharClass/migrations/0002_auto_20150203_1146.py","file_name":"0002_auto_20150203_1146.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"584118323","text":"\"\"\"\nCopyright (c) 2019 JD Finance America Corporation\n\"\"\"\n\nimport sys, os, time\nif sys.version_info[0] == 2:\n import xml.etree.cElementTree as ET\nelse:\n import xml.etree.ElementTree as ET\n\nimport cv2\nimport numpy as np\nimport collections\nimport torchvision\nimport torchvision.transforms as T\nfrom collections import Counter\n\n# detector utils\nimport sys\nsys.path.append('../other_utils/lighttrack')\n\n# pose estimation utils\nfrom HPE.dataset import Preprocessing\nfrom HPE.config import cfg\nsys.path.append(os.path.abspath(\"../other_utils/lighttrack/utils\"))\nsys.path.append(os.path.abspath(\"../other_utils/lighttrack/visualizer\"))\nsys.path.append(os.path.abspath(\"../other_utils/lighttrack/graph\"))\n\nfrom utils_json import *\nfrom visualizer import *\nfrom utils_io_file import *\nfrom utils_io_folder import *\nfrom natsort import natsorted, ns\nimport scipy.optimize as scipy_opt\nimport motmetrics as mm\n\nimport torch\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nfrom PIL import Image\n\nimport csv\n\nflag_nms = False #Default is False, unless you know what you are doing\n\ndef show_skeleton(img,pose_keypoints_2d):\n joints = reshape_keypoints_into_joints(pose_keypoints_2d)\n img = show_poses_from_python_data(img, joints, joint_pairs, joint_names)\n\ndef initialize_parameters():\n global video_name, img_id\n\n global nms_method, nms_thresh, min_scores, min_box_size\n nms_method = 'nms'\n nms_thresh = 1.\n min_scores = 1e-10\n min_box_size = 0.\n\n global keyframe_interval, enlarge_scale, pose_matching_threshold\n keyframe_interval = 1 # choice examples: [2, 3, 5, 8, 10, 20, 40, 100, ....]\n enlarge_scale = 0.2 # how much to enlarge the bbox before pose estimation\n pose_matching_threshold = 0.5\n\n global flag_flip\n flag_flip = True\n\n global total_time_POSE, total_time_DET, total_time_ALL, total_num_FRAMES, total_num_PERSONS\n total_time_POSE = 0\n total_time_DET = 0\n total_time_ALL = 0\n total_num_FRAMES = 0\n total_num_PERSONS = 0\n\n global spacial_thresh\n spacial_thresh = 0.3 # The max distance between 2 frames: Default : 0.3\n\n global check_pose_threshold, check_pose_method\n check_pose_threshold = 0.6 # The threshold on the confidence of pose estimation.\n check_pose_method = 'max_average' # How to average the confidences of the key points for a global confidence\n return\n\ndef enlarge_bbox(bbox, scale, image_shape):\n min_x, min_y, max_x, max_y = bbox\n margin_x = int(0.5 * scale[0] * (max_x - min_x))\n margin_y = int(0.5 * scale[1] * (max_y - min_y))\n\n min_x -= margin_x\n max_x += margin_x\n min_y -= margin_y\n max_y += margin_y\n\n min_x = max(0,min_x)\n min_y = max(0,min_y)\n max_x = min(image_shape[1],max_x)\n max_y = min(image_shape[0],max_y)\n\n bbox_enlarged = [min_x, min_y, max_x, max_y]\n return bbox_enlarged\n\n\ndef parse_voc_xml(node):\n voc_dict = {}\n children = list(node)\n if children:\n def_dic = collections.defaultdict(list)\n for dc in map(parse_voc_xml, children):\n for ind, v in dc.items():\n def_dic[ind].append(v)\n voc_dict = {\n node.tag:\n {ind: v[0] if len(v) == 1 else v\n for ind, v in def_dic.items()}\n }\n if node.text:\n text = node.text.strip()\n if not children:\n voc_dict[node.tag] = text\n return voc_dict\n\ndef rescale_img(img,rescale_img_factor):\n shape = img.size\n w = shape[0]\n h = shape[1]\n desired_h = h*rescale_img_factor\n desired_w = w*rescale_img_factor\n img = torchvision.transforms.Resize([int(desired_h), int(desired_w)])(img)\n w_pad = (w - desired_w)/2.\n h_pad = (h - desired_h)/2.\n img = torchvision.transforms.Pad((int(w_pad),int(h_pad)))(img)\n return(img)\n\ndef rescale_img_bbox(bbox,rescale_img_factor,image_shape):\n w = image_shape[1]\n h = image_shape[0]\n bbox = np.array(bbox)*rescale_img_factor\n target_w = w*rescale_img_factor\n target_h = h*rescale_img_factor\n w_pad = (w - target_w)/2.\n h_pad = (h - target_h)/2.\n new_w = target_w + 2*w_pad\n new_h = target_h + 2*h_pad\n bbox_center = bbox + np.array([w_pad,h_pad,w_pad,h_pad])\n return(bbox_center)\n\ndef extract_annotations(annotation_path, rescale_bbox, rescale_img_factor, image_shape):\n GT_bbox_list = []\n GT_idx_list = []\n target = parse_voc_xml(ET.parse(annotation_path).getroot())\n anno = target['annotation']\n image_path = anno['path']\n objects = anno['object']\n for obj in objects:\n idx = obj['name']\n bbox = obj['bndbox']\n bbox = [int(bbox[n]) for n in ['xmin', 'ymin', 'xmax', 'ymax']]\n bbox = enlarge_bbox(bbox,rescale_bbox,image_shape)\n bbox = rescale_img_bbox(bbox,rescale_img_factor,image_shape)\n GT_bbox_list.append(bbox)\n GT_idx_list.append(idx)\n return(GT_bbox_list, GT_idx_list,image_path)\n\ndef player_detection(image_path, rescale_img_factor, model_detection, thres_detection):\n bbox_list = []\n score_list = []\n max_w = 150\n max_h = 150\n with torch.no_grad():\n im = Image.open(image_path).convert('RGB')\n im = rescale_img(im,rescale_img_factor)\n x = [T.ToTensor()(im).to(torch.device('cuda'))]\n output, features = model_detection(x)\n output = output[0]\n scores = output['scores']\n labels = output['labels']\n boxes = output['boxes']\n for i in range(len(scores)):\n if scores[i]>thres_detection :\n xmin,ymin,xmax,ymax = int(boxes[i][0]),int(boxes[i][1]),int(boxes[i][2]),int(boxes[i][3])\n if 0 < xmax-xmin < max_w and 0 < ymax-ymin < max_h :\n bbox_list.append([xmin,ymin,xmax,ymax])\n score_list.append(scores[i])\n return(bbox_list,score_list,features)\n\n\ndef light_track(pose_estimator, model_detection, visual_feat_model, layer,\n image_folder, annotation_folder, rescale_bbox, rescale_img_factor,\n visualize_folder, output_video_path, output_csv_path, use_features,\n w_spacial, w_visual, w_pose, use_IOU, spacial_iou_thresh, thres_detection,\n use_pose, use_visual_feat, imagenet_model,\n display_pose, use_GT_position, flag_method, n_img_max, init_frame,\n frame_interval, write_csv, write_video, keyframe_interval, visualize,\n use_filter_tracks, thres_count_ids,weight_by_score_det,visual_metric,\n N_frame_lost_keep, N_past_to_keep, use_ReID_module,\n N_past_to_keep_reID, max_vis_feat, max_dist_factor_feat, max_vis_reID, max_dist_factor_reID,\n use_track_branch):\n\n total_time_DET = 0\n total_num_PERSONS = 0\n total_time_ALL = 0\n total_time_POSE = 0\n total_time_FEAT = 0\n st_time_total = time.time()\n\n bbox_dets_list = []\n frame_prev = -1\n frame_cur = 0\n img_id = -1\n next_id = 0\n bbox_dets_list_list = []\n track_ids_dict_list = []\n GT_bbox_list_list = []\n GT_idx_list_list = []\n bbox_lost_player_list = []\n track_feat_dict_list = []\n\n flag_mandatory_keyframe = False\n\n if annotation_folder is not None :\n annotation_paths = natsorted(os.listdir(annotation_folder), alg=ns.PATH | ns.IGNORECASE)\n num_imgs = min(n_img_max, len(annotation_paths)//frame_interval - init_frame)\n total_num_FRAMES = num_imgs\n else :\n image_paths = natsorted(os.listdir(image_folder), alg=ns.PATH | ns.IGNORECASE)\n num_imgs = min(n_img_max, len(image_paths)//frame_interval - init_frame)\n total_num_FRAMES = num_imgs\n\n acc = mm.MOTAccumulator(auto_id=True)\n image_shape = cv2.imread(os.path.join(image_folder,os.listdir(image_folder)[0])).shape\n\n N_IOU = 0\n N_feat = 0\n N_reID = 0\n\n while img_id < num_imgs-1:\n\n img_id += 1\n\n #print(\"Current tracking: [image_id:{}]\".format(img_id))\n\n if annotation_folder is not None :\n annotation_path = annotation_paths[img_id*frame_interval + init_frame]\n annotation_path = os.path.join(annotation_folder,annotation_path)\n GT_bbox_list, GT_idx_list, img_path = extract_annotations(annotation_path, rescale_bbox, rescale_img_factor, image_shape)\n GT_bbox_list_list.append(GT_bbox_list)\n GT_idx_list_list.append(GT_idx_list)\n else :\n img_path = image_paths[img_id*frame_interval + init_frame]\n img_path = os.path.join(image_folder,img_path)\n if 'u176443' in img_path :\n img_path = img_path.replace('u176443','pvitoria')\n\n frame_cur = img_id\n if (frame_cur == frame_prev):\n frame_prev -= 1\n\n if is_keyframe(img_id, keyframe_interval) or flag_mandatory_keyframe :\n\n flag_mandatory_keyframe = False\n bbox_dets_list = []\n\n # perform detection at keyframes\n st_time_detection = time.time()\n if use_GT_position :\n player_candidates = GT_bbox_list\n player_scores = torch.tensor([1.]*len(GT_bbox_list))\n else :\n #try :\n player_candidates, player_scores, img_feat = player_detection(img_path, rescale_img_factor, model_detection, thres_detection)\n # except Exception as e :\n # print(e)\n # player_candidates = []\n # player_scores = []\n # img_feat = []\n end_time_detection = time.time()\n total_time_DET += (end_time_detection - st_time_detection)\n\n num_dets = len(player_candidates)\n #print(\"Keyframe: {} detections\".format(num_dets))\n\n # if nothing detected at keyframe, regard next frame as keyframe because there is nothing to track\n if num_dets <= 0 :\n\n flag_mandatory_keyframe = True\n\n # add empty result\n bbox_det_dict = {\"img_id\": img_id,\n \"imgpath\": img_path,\n \"det_id\": 0,\n \"track_id\": None,\n \"bbox\": [0, 0, 2, 2],\n \"visual_feat\": [],\n \"keypoints\": []}\n bbox_dets_list.append(bbox_det_dict)\n\n bbox_dets_list_list.append(bbox_dets_list)\n track_ids_dict_list.append({})\n\n flag_mandatory_keyframe = True\n continue\n\n total_num_PERSONS += num_dets\n\n if img_id > 0 : # First frame does not have previous frame\n bbox_list_prev_frame = bbox_dets_list_list[img_id - 1].copy()\n track_ids_dict_prev = track_ids_dict_list[img_id - 1].copy()\n\n # Perform data association\n\n for det_id in range(num_dets):\n\n # obtain bbox position\n bbox_det = player_candidates[det_id]\n score_det = float(player_scores[det_id].cpu())\n\n # enlarge bbox by 20% with same center position\n bbox_det = enlarge_bbox(bbox_det, [0.,0.], image_shape)\n\n # update current frame bbox\n bbox_det_dict = {\"img_id\": img_id,\n \"det_id\": det_id,\n \"imgpath\": img_path,\n \"bbox\": bbox_det,\n \"score_det\": score_det}\n\n if img_id == 0 or len(bbox_list_prev_frame) == 0 : # First frame, all ids are assigned automatically\n track_id = next_id\n next_id += 1\n method = None\n\n else : # Perform data association\n\n if use_IOU : # use IOU as first criteria\n spacial_intersect = get_spacial_intersect(bbox_det, bbox_list_prev_frame)\n track_id, match_index = get_track_id_SpatialConsistency(spacial_intersect, bbox_list_prev_frame, spacial_iou_thresh)\n else :\n track_id = -1\n\n if track_id != -1:\n method = 'spacial'\n else :\n method = None\n\n # update current frame bbox\n bbox_det_dict = {\"img_id\": img_id,\n \"imgpath\": img_path,\n \"det_id\": det_id,\n \"track_id\": track_id,\n \"bbox\": bbox_det,\n \"score_det\": score_det,\n \"method\": method,\n \"visual_feat\": [],\n \"keypoints\": []}\n\n bbox_dets_list.append(bbox_det_dict)\n\n # Check for repetitions in track ids and remove them.\n track_ids = [bbox_det_dict[\"track_id\"] for bbox_det_dict in bbox_dets_list]\n track_ids_dict = collections.defaultdict(list)\n for idx, track in enumerate(track_ids) :\n track_ids_dict[track].append(idx)\n keys = list(track_ids_dict.keys())\n for track in keys :\n if len(track_ids_dict[track]) > 1 :\n for el in track_ids_dict[track] :\n bbox_dets_list[el][\"track_id\"] = -1\n bbox_dets_list[el][\"method\"] = None\n del track_ids_dict[track]\n\n if img_id > 0 and len(bbox_list_prev_frame) > 0 :\n\n # Remove already assigned elements in the previous frame.\n remaining_det_id_list = []\n prev_to_remove = []\n for det_id in range(num_dets):\n track_id = bbox_dets_list[det_id][\"track_id\"]\n if track_id == -1 :\n remaining_det_id_list.append(det_id)\n else :\n prev_idx = track_ids_dict_prev[track_id]\n prev_to_remove.append(prev_idx[0])\n N_IOU+=1\n\n for index in sorted(prev_to_remove, reverse=True):\n del bbox_list_prev_frame[index]\n\n # For candidates that are not associated yet\n\n if len(bbox_list_prev_frame) == 0 or (not use_features and not use_ReID_module) :\n\n # If no more candidates in previous frame : assign new ids to remaining detections\n for det_id in remaining_det_id_list :\n #print('no matching')\n bbox_dets_list[det_id][\"track_id\"] = next_id\n bbox_dets_list[det_id][\"method\"] = None\n track_ids_dict[next_id].append(det_id)\n next_id += 1\n\n elif len(remaining_det_id_list) > 0 :\n\n # For each remaining detections, perform association with a combinaison of features.\n if (use_ReID_module or use_visual_feat) and not imagenet_model :\n if use_GT_position :\n img_feat, image_sizes = get_img_feat_FasterRCNN(visual_feat_model, bbox_dets_list[0]['imgpath'], rescale_img_factor)\n img_feat_prev, image_sizes = get_img_feat_FasterRCNN(visual_feat_model, bbox_list_prev_frame[0]['imgpath'], rescale_img_factor)\n\n past_track_bbox_list_list = []\n\n for bbox_prev_dict in bbox_list_prev_frame :\n\n prev_track_id = bbox_prev_dict['track_id']\n past_track_idx_list = []\n past_track_bbox_list = []\n for i in range(1,min(N_past_to_keep,img_id)+1):\n past_track_ids_dict = track_ids_dict_list[img_id-i]\n if prev_track_id in past_track_ids_dict.keys() :\n idx = past_track_ids_dict[prev_track_id][0]\n past_track_idx_list.append(idx)\n past_track_bbox_list.append(bbox_dets_list_list[img_id-i][idx])\n\n for past_track_bbox in past_track_bbox_list :\n\n if use_pose :\n if not past_track_bbox[\"keypoints\"] :\n st_time_pose = time.time()\n inf,_ = inference_feat_keypoints(pose_estimator, past_track_bbox)\n keypoints = inf[0][\"keypoints\"]\n end_time_pose = time.time()\n total_time_POSE += (end_time_pose - st_time_pose)\n else :\n keypoints = past_track_bbox[\"keypoints\"]\n else :\n keypoints = []\n\n if use_visual_feat :\n if not list(past_track_bbox[\"visual_feat\"]) :\n st_time_feat = time.time()\n if imagenet_model :\n visual_feat = get_visual_feat_imagenet(visual_feat_model,layer,past_track_bbox, rescale_img_factor)\n else :\n visual_feat = get_visual_feat_fasterRCNN(visual_feat_model,past_track_bbox,img_feat_prev,image_sizes,use_track_branch)\n end_time_feat = time.time()\n total_time_FEAT += (end_time_feat - st_time_feat)\n else :\n visual_feat = past_track_bbox[\"visual_feat\"]\n else :\n visual_feat = []\n\n past_track_bbox[\"keypoints\"] = keypoints\n past_track_bbox[\"visual_feat\"] = visual_feat\n\n past_track_bbox_list_list.append(past_track_bbox_list)\n\n for det_id in remaining_det_id_list :\n\n bbox_det_dict = bbox_dets_list[det_id]\n\n if use_pose :\n st_time_pose = time.time()\n inf,_ = inference_feat_keypoints(pose_estimator, bbox_det_dict, rescale_img_factor)\n keypoints = inf[0][\"keypoints\"]\n end_time_pose = time.time()\n total_time_POSE += (end_time_pose - st_time_pose)\n else :\n keypoints = []\n\n if use_visual_feat :\n st_time_feat = time.time()\n if imagenet_model :\n visual_feat = get_visual_feat_imagenet(visual_feat_model,layer,bbox_det_dict, rescale_img_factor)\n else :\n visual_feat = get_visual_feat_fasterRCNN(visual_feat_model,bbox_det_dict, img_feat,image_sizes,use_track_branch)\n end_time_feat = time.time()\n total_time_FEAT += (end_time_feat - st_time_feat)\n else :\n visual_feat = []\n\n bbox_det_dict[\"keypoints\"] = keypoints\n bbox_det_dict[\"visual_feat\"] = visual_feat\n\n if use_features :\n\n log = ''\n bbox_dets_list, bbox_list_prev_frame, past_track_bbox_list_list, track_ids_dict, N_feat = feature_matching(bbox_dets_list,remaining_det_id_list, bbox_list_prev_frame,\n past_track_bbox_list_list, track_ids_dict, visual_metric, max_dist_factor_feat, max_vis_feat, w_visual, w_spacial, w_pose,\n use_visual_feat, use_pose, weight_by_score_det, image_shape, log, N_past_to_keep, N_feat)\n\n if use_ReID_module :\n\n # Adjust lost player list\n bbox_lost_player_list = [bbox_lost_player for bbox_lost_player in bbox_lost_player_list if img_id - bbox_lost_player['img_id'] < N_frame_lost_keep]\n bbox_lost_player_list += bbox_list_prev_frame\n\n past_track_bbox_list_list_reID = []\n\n for bbox_prev_dict in bbox_lost_player_list :\n prev_track_id = bbox_prev_dict['track_id']\n prev_im_id = bbox_prev_dict['img_id']\n past_track_idx_list = []\n past_track_bbox_list = []\n for i in range(min(N_past_to_keep_reID,prev_im_id+1)):\n past_track_ids_dict = track_ids_dict_list[prev_im_id-i]\n if prev_track_id in past_track_ids_dict.keys() :\n idx = past_track_ids_dict[prev_track_id][0]\n past_track_idx_list.append(idx)\n past_track_bbox_list.append(bbox_dets_list_list[prev_im_id-i][idx])\n\n for past_track_bbox in past_track_bbox_list :\n\n if use_pose :\n if not past_track_bbox[\"keypoints\"] :\n st_time_pose = time.time()\n inf,_ = inference_feat_keypoints(pose_estimator, past_track_bbox)\n keypoints = inf[0][\"keypoints\"]\n end_time_pose = time.time()\n total_time_POSE += (end_time_pose - st_time_pose)\n else :\n keypoints = past_track_bbox[\"keypoints\"]\n else :\n keypoints = []\n\n if use_visual_feat :\n if not list(past_track_bbox[\"visual_feat\"]) :\n st_time_feat = time.time()\n if imagenet_model :\n visual_feat = get_visual_feat_imagenet(visual_feat_model,layer,past_track_bbox, rescale_img_factor)\n else :\n visual_feat = get_visual_feat_fasterRCNN(visual_feat_model,past_track_bbox,img_feat_prev,image_sizes,use_track_branch)\n end_time_feat = time.time()\n total_time_FEAT += (end_time_feat - st_time_feat)\n else :\n visual_feat = past_track_bbox[\"visual_feat\"]\n else :\n visual_feat = []\n\n past_track_bbox[\"keypoints\"] = keypoints\n past_track_bbox[\"visual_feat\"] = visual_feat\n\n past_track_bbox_list_list_reID.append(past_track_bbox_list)\n\n #print(past_track_bbox_list_list_reID)\n\n # Get non_associated dets\n remaining_det_id_list = []\n for det_id in range(num_dets):\n track_id = bbox_dets_list[det_id][\"track_id\"]\n if track_id == -1 :\n remaining_det_id_list.append(det_id)\n\n # Re-ID module\n if len(remaining_det_id_list) > 0 and len(bbox_lost_player_list) > 0 :\n log = ''\n bbox_dets_list, bbox_lost_player_list, past_track_bbox_list_list_reID, track_ids_dict, N_reID = feature_matching(bbox_dets_list,remaining_det_id_list, bbox_lost_player_list,\n past_track_bbox_list_list_reID, track_ids_dict, visual_metric, max_dist_factor_reID, max_vis_reID, w_visual, w_spacial, w_pose, use_visual_feat,\n use_pose, weight_by_score_det, image_shape, log, N_past_to_keep_reID, N_reID)\n\n # if still can not find a match from previous frame, then -1\n for det_id in range(num_dets):\n track_id = bbox_dets_list[det_id][\"track_id\"]\n if track_id == -1 :\n bbox_dets_list[det_id][\"track_id\"] = next_id\n bbox_dets_list[det_id][\"method\"] = None\n track_ids_dict[next_id].append(det_id)\n next_id += 1\n else :\n pass\n\n # update frame\n bbox_dets_list_list.append(bbox_dets_list)\n track_ids_dict_list.append(track_ids_dict)\n frame_prev = frame_cur\n\n else:\n ''' NOT KEYFRAME: multi-target pose tracking '''\n\n print('we only work with keyframes for now')\n\n # bbox_dets_list_next = []\n # keypoints_list_next = []\n #\n # num_dets = len(keypoints_list)\n # total_num_PERSONS += num_dets\n #\n # if num_dets == 0:\n # flag_mandatory_keyframe = True\n #\n # for det_id in range(num_dets):\n # keypoints = keypoints_list[det_id][\"keypoints\"]\n #\n # # for non-keyframes, the tracked target preserves its track_id\n # track_id = keypoints_list[det_id][\"track_id\"]\n #\n # # next frame bbox\n # bbox_det_next = get_bbox_from_keypoints(keypoints)\n # if bbox_det_next[2] == 0 or bbox_det_next[3] == 0:\n # bbox_det_next = [0, 0, 2, 2]\n # total_num_PERSONS -= 1\n # assert(bbox_det_next[2] != 0 and bbox_det_next[3] != 0) # width and height must not be zero\n # bbox_det_dict_next = {\"img_id\":img_id,\n # \"det_id\":det_id,\n # \"track_id\":track_id,\n # \"imgpath\": img_path,\n # \"bbox\":bbox_det_next}\n #\n # # next frame keypoints\n # st_time_pose = time.time()\n # inf_next, feat_next = inference_feat_keypoints(pose_estimator, bbox_det_dict_next)\n # keypoints_next = inf_next[0][\"keypoints\"]\n # end_time_pose = time.time()\n # total_time_POSE += (end_time_pose - st_time_pose)\n # #print(\"time for pose estimation: \", (end_time_pose - st_time_pose))\n #\n # # check whether the target is lost\n # target_lost = is_target_lost(keypoints_next, check_pose_method, check_pose_threshold)\n #\n # if target_lost is False:\n # bbox_dets_list_next.append(bbox_det_dict_next)\n # keypoints_dict_next = {\"img_id\":img_id,\n # \"det_id\":det_id,\n # \"track_id\":track_id,\n # \"imgpath\": img_path,\n # \"keypoints\":keypoints_next}\n # keypoints_list_next.append(keypoints_dict_next)\n #\n # else:\n # # remove this bbox, do not register its keypoints\n # bbox_det_dict_next = {\"img_id\":img_id,\n # \"det_id\": det_id,\n # \"track_id\": None,\n # \"imgpath\": img_path,\n # \"bbox\": [0, 0, 2, 2]}\n # bbox_dets_list_next.append(bbox_det_dict_next)\n #\n # keypoints_null = 45*[0]\n # keypoints_dict_next = {\"img_id\":img_id,\n # \"det_id\":det_id,\n # \"track_id\": None,\n # \"imgpath\": img_path,\n # \"keypoints\": []}\n # keypoints_list_next.append(keypoints_dict_next)\n # print(\"Target lost. Process this frame again as keyframe. \\n\\n\\n\")\n # flag_mandatory_keyframe = True\n #\n # total_num_PERSONS -= 1\n # ## Re-process this frame by treating it as a keyframe\n # if img_id not in [0]:\n # img_id -= 1\n # break\n #\n # # update frame\n # if flag_mandatory_keyframe is False:\n # bbox_dets_list = bbox_dets_list_next\n # keypoints_list = keypoints_list_next\n # bbox_dets_list_list.append(bbox_dets_list)\n # keypoints_list_list.append(keypoints_list)\n # frame_prev = frame_cur\n\n\n\n if use_filter_tracks :\n bbox_dets_list_list = filter_tracks(bbox_dets_list_list, thres_count_ids)\n\n ''' 1. statistics: get total time for lighttrack processing'''\n end_time_total = time.time()\n total_time_ALL += (end_time_total - st_time_total)\n\n print(\"N IOU : \", N_IOU)\n print(\"N FEAT : \", N_feat)\n print(\"N REID : \", N_reID)\n\n # visualization\n if visualize :\n print(\"Visualizing Tracking Results...\")\n # if display_pose :\n # show_all_from_dict(keypoints_list_list, bbox_dets_list_list, classes,\n # joint_pairs, joint_names, image_folder, visualize_folder,\n # display_pose = display_pose, flag_track = True, flag_method = flag_method)\n # else :\n show_all_from_dict([], bbox_dets_list_list, classes, joint_pairs, joint_names,\n rescale_img_factor = rescale_img_factor,\n img_folder_path = image_folder, output_folder_path = visualize_folder,\n display_pose = display_pose, flag_track = True, flag_method = flag_method)\n img_paths = get_immediate_childfile_paths(visualize_folder)\n if write_video:\n make_video_from_images(img_paths, output_video_path, fps=25, size=None, is_color=True, format=\"XVID\")\n print(\"Visualization Finished!\")\n print(\"Finished video {}\".format(output_video_path))\n\n ''' Display statistics '''\n print(\"total_time_ALL: {:.2f}s\".format(total_time_ALL))\n print(\"total_time_DET: {:.2f}s\".format(total_time_DET))\n print(\"total_time_POSE: {:.2f}s\".format(total_time_POSE))\n print(\"total_time_FEAT: {:.2f}s\".format(total_time_FEAT))\n print(\"total_time_TRACK: {:.2f}s\".format(total_time_ALL - total_time_DET - total_time_POSE - total_time_FEAT))\n print(\"total_num_FRAMES: {:d}\".format(total_num_FRAMES))\n print(\"total_num_PERSONS: {:d}\\n\".format(total_num_PERSONS))\n print(\"Average FPS: {:.2f}fps\".format(total_num_FRAMES / total_time_ALL))\n print(\"Average FPS for Detection only : {:.2f}fps\".format(total_num_FRAMES / (total_time_DET)))\n print(\"Average FPS excluding Detection: {:.2f}fps\".format(total_num_FRAMES / (total_time_ALL - total_time_DET)))\n print(\"Average FPS for framework only: {:.2f}fps\".format(total_num_FRAMES / (total_time_ALL - total_time_DET - total_time_POSE - total_time_FEAT) ))\n\n if write_csv is True :\n print(output_csv_path)\n write_tracking_csv(bbox_dets_list_list, output_csv_path)\n print(\"total_time_ALL: {:.2f}s\".format(total_time_ALL))\n\n # compute metrics\n if annotation_folder is not None :\n try :\n mota,mptp,idf1,acc = evaluate_tracking(bbox_dets_list_list, GT_idx_list_list, GT_bbox_list_list)\n return(mota,mptp,idf1,acc)\n except Exception as e :\n print(e)\n print('no evaluation worked')\n return(0,0,0)\n\n\n# def get_track_id_SGCN(bbox_cur_frame, bbox_list_prev_frame, keypoints_cur_frame, keypoints_list_prev_frame):\n# assert(len(bbox_list_prev_frame) == len(keypoints_list_prev_frame))\n#\n# min_index = None\n# min_matching_score = sys.maxsize\n# global pose_matching_threshold\n# # if track_id is still not assigned, the person is really missing or track is really lost\n# track_id = -1\n#\n# for det_index, bbox_det_dict in enumerate(bbox_list_prev_frame):\n# bbox_prev_frame = bbox_det_dict[\"bbox\"]\n#\n# # check the pose matching score\n# keypoints_dict = keypoints_list_prev_frame[det_index]\n# keypoints_prev_frame = keypoints_dict[\"keypoints\"]\n#\n# pose_matching_score = get_pose_matching_score(keypoints_cur_frame, keypoints_prev_frame, bbox_cur_frame, bbox_prev_frame)\n#\n# if pose_matching_score <= pose_matching_threshold and pose_matching_score <= min_matching_score:\n# # match the target based on the pose matching score\n# min_matching_score = pose_matching_score\n# min_index = det_index\n#\n# if min_index is None:\n# return -1, None\n# else:\n# print('matching with GCN')\n# track_id = bbox_list_prev_frame[min_index][\"track_id\"]\n# return track_id, min_index\n\ndef feature_matching(bbox_dets_list, remaining_det_id_list, bbox_list_prev_frame, past_track_bbox_list_list, track_ids_dict,\n visual_metric, max_dist_factor, max_vis, w_visual, w_spacial, w_pose, use_visual_feat,\n use_pose, weight_by_score_det, image_shape, log, N_past_to_keep, N_meth, show_track = False, show_NN = False):\n\n dist_tab = []\n weight_tab = []\n spacial_dist = np.array([list(get_spacial_distance(bbox_dets_list[det_id][\"bbox\"], past_track_bbox_list_list, image_shape)) for det_id in remaining_det_id_list])\n dist_tab.append(spacial_dist)\n weight_tab.append(w_spacial)\n if use_visual_feat :\n visual_dist = np.array([list(get_visual_similarity(bbox_dets_list[det_id]['visual_feat'], past_track_bbox_list_list, N_past_to_keep, metric = visual_metric)) for det_id in remaining_det_id_list])\n dist_tab.append(visual_dist)\n weight_tab.append(w_visual)\n if use_pose :\n pose_dist = np.array([list(1-get_pose_similarity(bbox_dets_list[det_id][\"bbox\"],past_track_bbox_list_list, bbox_dets_list[idx][\"keypoints\"])) for idx,det_id in enumerate(remaining_det_id_list)])\n dist_tab.append(pose_dist)\n weight_tab.append(w_pose)\n\n # if weight_by_score_det :\n # weight_tab = bbox_dets_list[det_id][\"score_det\"]*np.array(weight_tab)\n\n # for 5 players : display first visual similarity players for control\n if show_track :\n for i in range(5):\n bbox_det = bbox_dets_list[-i]\n img_path = bbox_det['imgpath']\n img = Image.open(img_path).convert('RGB')\n img = rescale_img(img,0.6)\n img = np.array(img)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n bbox = bbox_det['bbox']\n patch = img[int(bbox[1]):int(bbox[3]), int(bbox[0]):int(bbox[2])]\n cv2.imshow('ref',patch)\n for j in range(len(past_track_bbox_list_list[i])) :\n bbox_past_frame = past_track_bbox_list_list[i][j]\n img_path = bbox_past_frame['imgpath']\n img = Image.open(img_path).convert('RGB')\n img = rescale_img(img,0.6)\n img = np.array(img)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n bbox = bbox_past_frame['bbox']\n patch = img[int(bbox[1]):int(bbox[3]), int(bbox[0]):int(bbox[2])]\n cv2.imsave(str(id)+'.png',patch)\n\n if show_NN :\n for i in range(3):\n det_id = remaining_det_id_list[i]\n bbox_curr_frame = bbox_dets_list[det_id]\n img_path = bbox_curr_frame['imgpath']\n img = Image.open(img_path).convert('RGB')\n img = rescale_img(img,0.6)\n img = np.array(img)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n bbox = bbox_curr_frame['bbox']\n patch = img[int(bbox[1]):int(bbox[3]), int(bbox[0]):int(bbox[2])]\n best_visual_similarities = np.argsort(visual_dist[i])\n cv2.imshow('ref',patch)\n for id,j in enumerate(best_visual_similarities[:2]) :\n past_track = past_track_bbox_list_list[j]\n bbox_prev_frame = past_track[0]\n img_path = bbox_prev_frame['imgpath']\n img = Image.open(img_path).convert('RGB')\n img = rescale_img(img,0.6)\n img = np.array(img)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n bbox = bbox_prev_frame['bbox']\n patch = img[int(bbox[1]):int(bbox[3]), int(bbox[0]):int(bbox[2])]\n cv2.imsave(str(i)+'_'+str(id)+'.png',patch)\n\n # _, axs = plt.subplots(5, 5, figsize=(12, 12))\n # axs = axs.flatten()\n # for img, ax in zip(imgs, axs):\n # ax.imshow(img)\n # plt.show()\n\n distx = image_shape[0]/max_dist_factor\n disty = image_shape[1]/max_dist_factor\n max_dist = np.sqrt(distx**2+disty**2)/np.sqrt(image_shape[0]**2 + image_shape[1]**2)\n matches = compute_matches(dist_tab, weight_tab, max_dist = max_dist, max_vis = max_vis, bipart_match_algo = 'hungarian')\n\n idx_to_remove_prev = []\n for i,match in enumerate(matches):\n track_id = bbox_list_prev_frame[match][\"track_id\"]\n if match != -1:\n det_id = remaining_det_id_list[i]\n #print('matching with feature matrix')\n bbox_dets_list[det_id][\"track_id\"] = track_id\n bbox_dets_list[det_id][\"method\"] = log\n track_ids_dict[track_id].append(det_id)\n idx_to_remove_prev.append(match)\n N_meth += 1\n #print(log)\n\n # if still can not find a match from previous frame, then -1\n\n if match == -1 :\n #print('no matching with feature matrix')\n det_id = remaining_det_id_list[i]\n bbox_dets_list[det_id][\"track_id\"] = -1\n bbox_dets_list[det_id][\"method\"] = None\n #bbox_dets_list[det_id][\"track_id\"] = next_id\n #bbox_dets_list[det_id][\"method\"] = None\n #track_ids_dict[next_id].append(det_id)\n #next_id += 1\n\n for index in sorted(idx_to_remove_prev, reverse=True):\n del past_track_bbox_list_list[index]\n del bbox_list_prev_frame[index]\n\n return(bbox_dets_list, bbox_list_prev_frame, past_track_bbox_list_list, track_ids_dict, N_meth)\n\ndef evaluate_tracking(bbox_dets_list_list, GT_idx_list_list, GT_bbox_list_list) :\n\n acc = mm.MOTAccumulator(auto_id=True)\n for f, bbox_dets_list in enumerate(bbox_dets_list_list) :\n track_ids = [el['track_id'] for el in bbox_dets_list]\n track_boxes = [el['bbox'] for el in bbox_dets_list]\n if track_ids:\n track_boxes = np.stack(track_boxes, axis=0)\n # x1, y1, x2, y2 --> x1, y1, width, height\n track_boxes = np.stack((track_boxes[:, 0],\n track_boxes[:, 1],\n track_boxes[:, 2] - track_boxes[:, 0],\n track_boxes[:, 3] - track_boxes[:, 1]),\n axis=1)\n else:\n track_boxes = np.array([])\n\n gt_ids = GT_idx_list_list[f]\n gt_boxes = GT_bbox_list_list[f]\n if gt_ids :\n gt_boxes = np.stack(gt_boxes, axis=0)\n # x1, y1, x2, y2 --> x1, y1, width, height\n gt_boxes = np.stack((gt_boxes[:, 0],\n gt_boxes[:, 1],\n gt_boxes[:, 2] - gt_boxes[:, 0],\n gt_boxes[:, 3] - gt_boxes[:, 1]),\n axis=1)\n else:\n gt_boxes = np.array([])\n\n distance = mm.distances.iou_matrix(gt_boxes, track_boxes, max_iou=0.5)\n acc.update(gt_ids, track_ids, distance)\n\n # mh = mm.metrics.create()\n # summary = mh.compute(acc, metrics=['num_frames', 'mota', 'motp'], name='acc')\n # summary1 = mh.compute(acc, metrics=['num_unique_objects','num_detections','precision','recall'], name='acc1')\n # print(summary)\n # print(summary1)\n\n mh = mm.metrics.create()\n\n summary = mh.compute_many(\n [acc],\n metrics=mm.metrics.motchallenge_metrics,\n names=['full'])\n\n strsummary = mm.io.render_summary(\n summary,\n formatters=mh.formatters,\n namemap=mm.io.motchallenge_metric_names\n )\n\n print(strsummary)\n\n out_score = mh.compute(acc, metrics=['mota', 'motp','idf1'], name='acc', return_dataframe=False)\n\n mota = out_score['mota']\n motp = out_score['motp']\n idf1 = out_score['idf1']\n\n return(mota,motp,idf1,acc)\n\n\ndef filter_tracks(bbox_dets_list_list, thres_count_ids = 1):\n all_track_ids = [bbox_det['track_id'] for bbox_dets_list in bbox_dets_list_list for bbox_det in bbox_dets_list]\n ids_counter = Counter(all_track_ids)\n track_ids_to_remove = []\n n = 0\n for k,v in ids_counter.items() :\n if v <= thres_count_ids :\n track_ids_to_remove.append(k)\n n+=1\n print(n, 'tracks removed out of ', len(ids_counter.keys()))\n for b,bbox_dets_list in enumerate(bbox_dets_list_list) :\n remlist = []\n for bb,bbox_det in enumerate(bbox_dets_list) :\n track_id = bbox_det['track_id']\n if track_id in track_ids_to_remove :\n remlist.append(bb)\n for index in sorted(remlist, reverse=True):\n del bbox_dets_list_list[b][index]\n return(bbox_dets_list_list)\n\ndef get_pose_similarity(bbox_cur_frame, bbox_list_prev_frame, keypoints_cur_frame, keypoints_list_prev_frame):\n\n pose_sim = np.zeros(len(bbox_list_prev_frame))\n\n for det_index, bbox_det_dict in enumerate(bbox_list_prev_frame):\n\n bbox_prev_frame = bbox_det_dict[\"bbox\"]\n keypoints_dict = keypoints_list_prev_frame[det_index]\n keypoints_prev_frame = keypoints_dict[\"keypoints\"]\n pose_matching_score = get_pose_matching_score(keypoints_cur_frame, keypoints_prev_frame, bbox_cur_frame, bbox_prev_frame)\n pose_sim[det_index] = pose_matching_score\n\n return(pose_sim)\n\n\ndef get_track_id_SpatialConsistency(spacial_similarities, bbox_list_prev_frame, spacial_thresh):\n\n if len(spacial_similarities) == 1 :\n if spacial_similarities[0] > spacial_thresh :\n max_index = 0\n track_id = bbox_list_prev_frame[max_index][\"track_id\"]\n #print('matching with dist IOU :', spacial_similarities[0])\n return track_id, max_index\n else :\n return -1, None\n\n sim_argsort = np.argsort(spacial_similarities)\n sim_sort = spacial_similarities[sim_argsort]\n\n if sim_sort[-1] <= 0 :\n return -1, None\n elif sim_sort[-1] > 0 and sim_sort[-2] <= 0 :\n max_index = sim_argsort[-1]\n track_id = bbox_list_prev_frame[max_index][\"track_id\"]\n #print('matching with dist IOU :', sim_sort[-1])\n return track_id, max_index\n else :\n if sim_sort[-1]>0.5*sim_sort[-2] and sim_sort[-1] > spacial_thresh :\n max_index = sim_argsort[-1]\n track_id = bbox_list_prev_frame[max_index][\"track_id\"]\n #print('matching with dist IOU :', sim_sort[-1])\n return track_id, max_index\n else :\n return -1, None\n\ndef get_spacial_intersect(bbox_cur_frame, bbox_list_prev_frame):\n\n spacial_sim = np.zeros(len(bbox_list_prev_frame))\n\n for bbox_index, bbox_det_dict in enumerate(bbox_list_prev_frame):\n bbox_prev_frame = bbox_det_dict[\"bbox\"]\n boxA = bbox_cur_frame\n boxB = bbox_prev_frame\n spacial_sim[bbox_index] = iou(boxA, boxB)\n\n return(spacial_sim)\n\ndef get_spacial_distance(bbox_cur_frame, past_track_bbox_list_list, image_shape):\n\n bbox_list_prev_frame = [past_track_bbox_list[0] for past_track_bbox_list in past_track_bbox_list_list]\n\n spacial_sim = np.zeros(len(bbox_list_prev_frame))\n\n for bbox_index, bbox_det_dict in enumerate(bbox_list_prev_frame):\n bbox_prev_frame = bbox_det_dict[\"bbox\"]\n centAx = (bbox_cur_frame[0]+bbox_cur_frame[2])/2.\n centAy = (bbox_cur_frame[1]+bbox_cur_frame[3])/2.\n centBx = (bbox_prev_frame[0]+bbox_prev_frame[2])/2.\n centBy = (bbox_cur_frame[1]+bbox_cur_frame[3])/2.\n distx = np.abs(centAx-centBx)\n disty = np.abs(centAy-centBy)\n dist = np.sqrt(distx**2+disty**2)/np.sqrt(image_shape[0]**2 + image_shape[1]**2)\n spacial_sim[bbox_index] = dist\n\n return(spacial_sim)\n\ndef get_visual_similarity(feat, past_track_bbox_list_list, N_past_to_keep, metric = 'cos_similarity') :\n weights = np.array([(1/2)**n for n in range(N_past_to_keep)])\n weights = np.array([(1)**n for n in range(N_past_to_keep)])\n res = []\n feat = np.array(feat)\n for past_track_bbox_list in past_track_bbox_list_list :\n feat_vector = np.array([past_track_bbox_list[i][\"visual_feat\"].numpy()*weights[i] for i in range(len(past_track_bbox_list))])\n feat_vector = np.mean(feat_vector,axis=0)\n if metric == 'cos_similarity' :\n res.append(np.dot(feat/np.linalg.norm(feat),feat_vector/np.linalg.norm(feat_vector)))\n if metric == 'correlation' :\n res.append(np.dot(feat,feat_vector))\n if metric == 'l1' :\n res.append(np.linalg.norm(feat-feat_vector,1))\n if metric == 'l2' :\n res.append(np.linalg.norm(feat-feat_vector,2))\n return(np.array(res))\n\ndef get_pose_matching_score(keypoints_A, keypoints_B, bbox_A, bbox_B):\n if keypoints_A == [] or keypoints_B == []:\n print(\"a graph not correctly generated!\")\n return sys.maxsize\n\n graph_A, flag_pass_check = keypoints_to_graph(keypoints_A, bbox_A)\n if flag_pass_check is False:\n print(\"c graph not correctly generated!\")\n return sys.maxsize\n\n graph_B, flag_pass_check = keypoints_to_graph(keypoints_B, bbox_B)\n if flag_pass_check is False:\n print(\"d graph not correctly generated!\")\n return sys.maxsize\n\n sample_graph_pair = (graph_A, graph_B)\n data_A, data_B = graph_pair_to_data(sample_graph_pair)\n\n start = time.time()\n flag_match, dist = pose_matching(data_A, data_B)\n end = time.time()\n return dist\n\n\ndef get_iou_score(bbox_gt, bbox_det):\n iou_score = iou(boxA, boxB)\n #print(\"iou_score: \", iou_score)\n return iou_score\n\n\ndef is_target_lost(keypoints, method, check_pose_threshold):\n num_keypoints = int(len(keypoints) / 3.0)\n if method == \"average\":\n # pure average\n score = 0\n for i in range(num_keypoints):\n score += keypoints[3*i + 2]\n score /= num_keypoints*1.0\n print(\"target_score: {}\".format(score))\n elif method == \"max_average\":\n score_list = keypoints[2::3]\n score_list_sorted = sorted(score_list)\n top_N = 4\n assert(top_N < num_keypoints)\n top_scores = [score_list_sorted[-i] for i in range(1, top_N+1)]\n score = sum(top_scores)/top_N\n if score < check_pose_threshold :\n return True\n else:\n return False\n\n\ndef iou(boxA, boxB):\n # box: (x1, y1, x2, y2)\n # determine the (x, y)-coordinates of the intersection rectangle\n xA = max(boxA[0], boxB[0])\n yA = max(boxA[1], boxB[1])\n xB = min(boxA[2], boxB[2])\n yB = min(boxA[3], boxB[3])\n\n # compute the area of intersection rectangle\n interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)\n\n # compute the area of both the prediction and ground-truth\n # rectangles\n boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)\n boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)\n\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n iou = interArea / float(boxAArea + boxBArea - interArea)\n\n # return the intersection over union value\n return iou\n\n\ndef get_bbox_from_keypoints(keypoints_python_data, img_shape):\n if keypoints_python_data == [] or keypoints_python_data == 45*[0]:\n return [0, 0, 2, 2]\n\n num_keypoints = len(keypoints_python_data)\n x_list = []\n y_list = []\n for keypoint_id in range(int(num_keypoints / 3)):\n x = keypoints_python_data[3 * keypoint_id]\n y = keypoints_python_data[3 * keypoint_id + 1]\n vis = keypoints_python_data[3 * keypoint_id + 2]\n if vis != 0 and vis!= 3:\n x_list.append(x)\n y_list.append(y)\n min_x = min(x_list)\n min_y = min(y_list)\n max_x = max(x_list)\n max_y = max(y_list)\n\n if not x_list or not y_list:\n return [0, 0, 2, 2]\n\n scale = enlarge_scale # enlarge bbox by 20% with same center position\n bbox = enlarge_bbox([min_x, min_y, max_x, max_y], [scale,scale], img_shape)\n bbox_in_xywh = x1y1x2y2_to_xywh(bbox)\n return bbox_in_xywh\n\n\n\ndef get_visual_feat_imagenet(model,layer,data, rescale_img_factor):\n with torch.no_grad():\n scaler = transforms.Scale((224, 224))\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n to_tensor = transforms.ToTensor()\n img = Image.open(data['imgpath']).convert('RGB')\n img = rescale_img(img,rescale_img_factor)\n bbox = data['bbox']\n box = (bbox[0],bbox[1],bbox[2],bbox[3])\n patch = img.crop(box)\n t_img = Variable(normalize(to_tensor(scaler(patch))).unsqueeze(0)).to(torch.device('cuda'))\n my_embedding = torch.zeros(2048)\n def copy_data(m, i, o):\n my_embedding.copy_(o.data.squeeze())\n h = layer.register_forward_hook(copy_data)\n model(t_img)\n h.remove()\n feat = my_embedding\n return feat\n\ndef get_img_feat_FasterRCNN(model,img_path,rescale_img_factor):\n with torch.no_grad():\n image = Image.open(img_path).convert('RGB')\n image = rescale_img(image,rescale_img_factor)\n image = [T.ToTensor()(image).to(torch.device('cuda'))]\n image,_ = model.transform(image, None)\n features = model.backbone(image.tensors)\n return(features,image.image_sizes)\n\ndef get_visual_feat_fasterRCNN(model,data,features,image_sizes,use_track_branch):\n with torch.no_grad():\n bbox = data['bbox']\n box = (float(bbox[0]),float(bbox[1]),float(bbox[2]),float(bbox[3]))\n proposals = [torch.tensor([box]).to(torch.device('cuda'))]\n if not use_track_branch :\n feat = model.roi_heads(features, proposals, image_sizes, get_feature_only=True)[0].cpu()\n else :\n feat = model.track_heads(features, proposals, image_sizes)[0].cpu()\n feat2 = model.roi_heads(features, proposals, image_sizes, get_feature_only=True)[0].cpu()\n return feat\n\ndef inference_feat_keypoints(pose_estimator, test_data, flag_nms=False):\n cls_dets = test_data[\"bbox\"]\n # nms on the bboxes\n if flag_nms is True:\n cls_dets, keep = apply_nms(cls_dets, nms_method, nms_thresh)\n test_data = np.asarray(test_data)[keep]\n if len(keep) == 0:\n return -1\n else:\n test_data = [test_data]\n\n # crop and detect pose\n pose_heatmaps, feat, details, cls_skeleton, crops, start_id, end_id = get_pose_feat_from_bbox(pose_estimator, test_data, cfg)\n # get keypoint positions from pose\n keypoints = get_keypoints_from_pose(pose_heatmaps, details, cls_skeleton, crops, start_id, end_id)\n # dump results\n pose_results = prepare_results(test_data[0], keypoints, cls_dets)\n #feat /= np.linalg.norm(feat)\n return pose_results, feat\n\n\ndef apply_nms(cls_dets, nms_method, nms_thresh):\n # nms and filter\n keep = np.where((cls_dets[:, 4] >= min_scores) &\n ((cls_dets[:, 3] - cls_dets[:, 1]) * (cls_dets[:, 2] - cls_dets[:, 0]) >= min_box_size))[0]\n cls_dets = cls_dets[keep]\n if len(cls_dets) > 0:\n if nms_method == 'nms':\n keep = gpu_nms(cls_dets, nms_thresh)\n elif nms_method == 'soft':\n keep = cpu_soft_nms(np.ascontiguousarray(cls_dets, dtype=np.float32), method=2)\n else:\n assert False\n cls_dets = cls_dets[keep]\n return cls_dets, keep\n\n\ndef get_pose_feat_from_bbox(pose_estimator, test_data, cfg):\n cls_skeleton = np.zeros((len(test_data), cfg.nr_skeleton, 3))\n crops = np.zeros((len(test_data), 4))\n\n batch_size = 1\n start_id = 0\n end_id = min(len(test_data), batch_size)\n\n test_imgs = []\n details = []\n for i in range(start_id, end_id):\n test_img, detail = Preprocessing(test_data[i], stage='test')\n test_imgs.append(test_img)\n details.append(detail)\n\n details = np.asarray(details)\n feed = test_imgs\n for i in range(end_id - start_id):\n ori_img = test_imgs[i][0].transpose(1, 2, 0)\n if flag_flip == True:\n flip_img = cv2.flip(ori_img, 1)\n feed.append(flip_img.transpose(2, 0, 1)[np.newaxis, ...])\n feed = np.vstack(feed)\n\n predict = pose_estimator.predict_one([feed.transpose(0, 2, 3, 1).astype(np.float32)])\n res = predict[0]\n res = res.transpose(0, 3, 1, 2)\n\n try :\n feat = predict[1].squeeze()[0,:]\n feat /= np.linalg.norm(feat) # 2 x 1024\n except :\n feat = None\n\n if flag_flip == True:\n for i in range(end_id - start_id):\n fmp = res[end_id - start_id + i].transpose((1, 2, 0))\n fmp = cv2.flip(fmp, 1)\n fmp = list(fmp.transpose((2, 0, 1)))\n for (q, w) in cfg.symmetry:\n fmp[q], fmp[w] = fmp[w], fmp[q]\n fmp = np.array(fmp)\n res[i] += fmp\n res[i] /= 2\n\n pose_heatmaps = res\n\n return pose_heatmaps, feat, details, cls_skeleton, crops, start_id, end_id\n\n\ndef get_keypoints_from_pose(pose_heatmaps, details, cls_skeleton, crops, start_id, end_id):\n res = pose_heatmaps\n\n for test_image_id in range(start_id, end_id):\n\n r0 = res[test_image_id - start_id].copy()\n r0 /= 255.\n r0 += 0.5\n\n for w in range(cfg.nr_skeleton):\n res[test_image_id - start_id, w] /= np.amax(res[test_image_id - start_id, w])\n\n border = 10\n dr = np.zeros((cfg.nr_skeleton, cfg.output_shape[0] + 2 * border, cfg.output_shape[1] + 2 * border))\n dr[:, border:-border, border:-border] = res[test_image_id - start_id][:cfg.nr_skeleton].copy()\n\n for w in range(cfg.nr_skeleton):\n dr[w] = cv2.GaussianBlur(dr[w], (21, 21), 0)\n\n for w in range(cfg.nr_skeleton):\n lb = dr[w].argmax()\n y, x = np.unravel_index(lb, dr[w].shape)\n dr[w, y, x] = 0\n lb = dr[w].argmax()\n py, px = np.unravel_index(lb, dr[w].shape)\n y -= border\n x -= border\n py -= border + y\n px -= border + x\n ln = (px ** 2 + py ** 2) ** 0.5\n delta = 0.25\n if ln > 1e-3:\n x += delta * px / ln\n y += delta * py / ln\n x = max(0, min(x, cfg.output_shape[1] - 1))\n y = max(0, min(y, cfg.output_shape[0] - 1))\n cls_skeleton[test_image_id, w, :2] = (x * 4 + 2, y * 4 + 2)\n cls_skeleton[test_image_id, w, 2] = r0[w, int(round(y) + 1e-10), int(round(x) + 1e-10)]\n\n # map back to original images\n crops[test_image_id, :] = details[test_image_id - start_id, :]\n for w in range(cfg.nr_skeleton):\n cls_skeleton[test_image_id, w, 0] = cls_skeleton[test_image_id, w, 0] / cfg.data_shape[1] * (crops[test_image_id][2] - crops[test_image_id][0]) + crops[test_image_id][0]\n cls_skeleton[test_image_id, w, 1] = cls_skeleton[test_image_id, w, 1] / cfg.data_shape[0] * (crops[test_image_id][3] - crops[test_image_id][1]) + crops[test_image_id][1]\n\n return cls_skeleton\n\n\ndef prepare_results(test_data, cls_skeleton, cls_dets):\n cls_partsco = cls_skeleton[:, :, 2].copy().reshape(-1, cfg.nr_skeleton)\n\n cls_scores = 1\n dump_results = []\n cls_skeleton = np.concatenate(\n [cls_skeleton.reshape(-1, cfg.nr_skeleton * 3), (cls_scores * cls_partsco.mean(axis=1))[:, np.newaxis]],\n axis=1)\n for i in range(len(cls_skeleton)):\n result = dict(image_id=test_data['img_id'],\n category_id=1,\n score=float(round(cls_skeleton[i][-1], 4)),\n keypoints=cls_skeleton[i][:-1].round(3).tolist())\n dump_results.append(result)\n return dump_results\n\ndef is_keyframe(img_id, interval=10):\n if img_id % interval == 0:\n return True\n else:\n return False\n\ndef make_my_json(nframe, dets_list_list,output_file):\n final = {}\n final['frames'] = []\n for img_id in range(nframe):\n current_dict = {}\n current_dict[\"img_id\"] = img_id\n current_dict[\"class\"] = \"frame\"\n current_dict[\"hypotheses\"] = []\n final['frames'].append(current_dict)\n final['class'] = \"video\"\n final['filename'] = \"file.idx\"\n\n for i in range(len(dets_list_list)):\n dets_list = dets_list_list[i]\n if dets_list == []:\n continue\n for j in range(len(dets_list)):\n bbox = dets_dict[\"bbox\"][0:4]\n img_id = dets_dict[\"img_id\"]\n track_id = dets_dict[\"track_id\"]\n current_ann = {\"id\": track_id, \"x\": bbox[0], \"y\": bbox[1], \"width\": bbox[2], \"height\": bbox[3]}\n final['frames'][img_id][\"hypotheses\"].append(current_ann)\n return(final)\n\ndef write_tracking_csv(bbox_dets_list_list, output_file):\n with open(output_file, mode='w') as csv_file:\n writer = csv.writer(csv_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n for frame_id,bbox_dets_list in enumerate(bbox_dets_list_list) :\n for bbox_dets in bbox_dets_list :\n bbox = bbox_dets[\"bbox\"][0:4]\n to_write = [bbox_dets[\"img_id\"],bbox_dets[\"track_id\"], bbox[0], bbox[1], bbox[2], bbox[3], -1, -1, -1, -1]\n writer.writerow(to_write)\n\n\n# def pose_to_standard_mot(keypoints_list_list, dets_list_list):\n# openSVAI_python_data_list = []\n#\n# num_keypoints_list = len(keypoints_list_list)\n# num_dets_list = len(dets_list_list)\n# assert(num_keypoints_list == num_dets_list)\n#\n# for i in range(num_dets_list):\n#\n# dets_list = dets_list_list[i]\n# keypoints_list = keypoints_list_list[i]\n#\n# if dets_list == []:\n# continue\n# img_path = dets_list[0][\"imgpath\"]\n# img_folder_path = os.path.dirname(img_path)\n# img_name = os.path.basename(img_path)\n# img_info = {\"folder\": img_folder_path,\n# \"name\": img_name,\n# \"id\": [int(i)]}\n# openSVAI_python_data = {\"image\":[], \"candidates\":[]}\n# openSVAI_python_data[\"image\"] = img_info\n#\n# num_dets = len(dets_list)\n# num_keypoints = len(keypoints_list) #number of persons, not number of keypoints for each person\n# candidate_list = []\n#\n# for j in range(num_dets):\n# keypoints_dict = keypoints_list[j]\n# dets_dict = dets_list[j]\n#\n# img_id = keypoints_dict[\"img_id\"]\n# det_id = keypoints_dict[\"det_id\"]\n# track_id = keypoints_dict[\"track_id\"]\n# img_path = keypoints_dict[\"imgpath\"]\n#\n# bbox_dets_data = dets_list[det_id]\n# det = dets_dict[\"bbox\"]\n# if det == [0, 0, 2, 2]:\n# # do not provide keypoints\n# candidate = {\"det_bbox\": [0, 0, 2, 2],\n# \"det_score\": 0}\n# else:\n# bbox_in_xywh = det[0:4]\n# keypoints = keypoints_dict[\"keypoints\"]\n#\n# track_score = sum(keypoints[2::3])/len(keypoints)/3.0\n#\n# candidate = {\"det_bbox\": bbox_in_xywh,\n# \"det_score\": 1,\n# \"track_id\": track_id,\n# \"track_score\": track_score,\n# \"pose_keypoints_2d\": keypoints}\n# candidate_list.append(candidate)\n# openSVAI_python_data[\"candidates\"] = candidate_list\n# openSVAI_python_data_list.append(openSVAI_python_data)\n# return openSVAI_python_data_list\n\n\ndef x1y1x2y2_to_xywh(det):\n x1, y1, x2, y2 = det\n w, h = int(x2) - int(x1), int(y2) - int(y1)\n return [x1, y1, w, h]\n\n\ndef xywh_to_x1y1x2y2(det):\n x1, y1, w, h = det\n x2, y2 = x1 + w, y1 + h\n return [x1, y1, x2, y2]\n\ndef bbox_valid(bbox,image_shape):\n valid = 0<=bbox[0]<=image_shape[1] and 0<=bbox[2]<=image_shape[1] and 0<=bbox[1]<=image_shape[0] and 0<=bbox[3]<=image_shape[0]\n if bbox == [0, 0, 2, 2]:\n valid=False\n return valid\n\ndef filter_detections(human_candidates, image_shape):\n res = []\n for det in human_candidates :\n if bbox_valid(det, image_shape) :\n res.append(det)\n return(det)\n\n\ndef bipartite_matching_greedy(C):\n \"\"\"\n Code from https://github.com/facebookresearch/DetectAndTrack/blob/master/lib/core/tracking_engine.py\n Computes the bipartite matching between the rows and columns, given the\n cost matrix, C.\n \"\"\"\n C = C.copy() # to avoid affecting the original matrix\n prev_ids = []\n cur_ids = []\n row_ids = np.arange(C.shape[0])\n col_ids = np.arange(C.shape[1])\n while C.size > 0:\n # Find the lowest cost element\n i, j = np.unravel_index(C.argmin(), C.shape)\n # Add to results and remove from the cost matrix\n row_id = row_ids[i]\n col_id = col_ids[j]\n prev_ids.append(row_id)\n cur_ids.append(col_id)\n C = np.delete(C, i, 0)\n C = np.delete(C, j, 1)\n row_ids = np.delete(row_ids, i, 0)\n col_ids = np.delete(col_ids, j, 0)\n return prev_ids, cur_ids\n\n\ndef compute_matches(similarity_tab, weight_tab, max_dist = 100., max_vis = 100., bipart_match_algo = 'hungarian'):\n\n # matches structure keeps track of which of the current boxes matches to\n # which box in the previous frame. If any idx remains -1, it will be set\n # as a new track.\n\n C = np.average(np.array(similarity_tab), axis = 0, weights=weight_tab).transpose()\n C_dist = np.array(similarity_tab[0]).transpose()\n C_vis = np.array(similarity_tab[1]).transpose()\n\n matches = -np.ones((C.shape[1],), dtype=np.int32)\n\n if bipart_match_algo == 'hungarian':\n prev_inds, next_inds = scipy_opt.linear_sum_assignment(C)\n elif bipart_match_algo == 'greedy':\n prev_inds, next_inds = bipartite_matching_greedy(C)\n else:\n raise NotImplementedError('Unknown matching algo: {}'.format(\n bipart_match_algo))\n assert(len(prev_inds) == len(next_inds))\n\n for i in range(len(prev_inds)):\n cost = C[prev_inds[i], next_inds[i]]\n dist = C_dist[prev_inds[i], next_inds[i]]\n vis = C_vis[prev_inds[i], next_inds[i]]\n if dist < max_dist and vis < max_vis :\n matches[next_inds[i]] = prev_inds[i]\n else :\n matches[next_inds[i]] = -1\n return matches\n","sub_path":"scripts/automatic_annotation/tracking_utils.py","file_name":"tracking_utils.py","file_ext":"py","file_size_in_byte":63664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"29414281","text":"import re\n\nimport feedparser\nfrom django.conf import settings\n\n\ndef get_news_feeds():\n img_re = re.compile(r'')\n feed_result = feedparser.parse(settings.NEWS_FEED_URL)\n for entity in feed_result.entries:\n img_search = img_re.search(entity.description)\n try:\n entity.image = img_search.group(1)\n entity.parsed_description = img_re.sub('', entity.description)\n except AttributeError:\n entity.parsed_description = entity.description\n if not hasattr(entity, 'image') or not entity.image:\n entity.is_default_image = True\n entity.image = settings.NEWS_FEED_DEFAULT_IMAGE\n return feed_result.entries\n","sub_path":"news/news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"75783657","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nfrom Manager import CustomerManager;\n\n\nimport pymysql\n\nconnection = pymysql.connect(\"localhost\", \"root\", \"csss331331\", \"ecommerce\", charset='utf8' )\n\n# 使用cursor()方法获取操作游标\ncursor = connection.cursor(pymysql.cursors.DictCursor)\n\nmanager = CustomerManager()\n\n\n\n# 执行Manager函数\n#manager.create(4,\"test\",\"Number 1\",'1111111','11111@gmail.com','woshi111')\n\n\n#print全表\nmanager.readAll()\n\n\n# 关闭数据库连接\nconnection.close()","sub_path":"UseMySQL.py","file_name":"UseMySQL.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"13490028","text":"import sys\n\nfrom decoding_strategist_visualizations.decoding_strategist_utils import *\n\n\nsys.path.append('/home/mlspeech/gshalev/anaconda3/envs/python3_env/lib')\nsys.path.append('/home/mlspeech/gshalev/gal/image_cap2')\n\nfrom utils import *\nfrom dataset_loader.dataloader import load\nfrom decoding_strategist_visualizations.top_k_top_p_captions.top_k_p_pack_utils import *\n\nimport torch\nimport argparse\nimport en_core_web_sm\n\nimport numpy as np\n\nargs = get_args()\n\n\ndef visualize_att(image, seq, alphas, rev_word_map, top_seq_total_scors, save_dir, image_name, smooth=True):\n image = image.squeeze(0) # remove batch dim\n image = image.numpy()\n\n image = image.transpose((1, 2, 0))\n\n # Undo preprocessing\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n image = std * image + mean\n\n # Image needs to be clipped between 0 and 1 or it looks like noise when displayed\n image = np.clip(image, 0, 1)\n\n words = [rev_word_map[ind] for ind in seq]\n\n nlp = en_core_web_sm.load()\n doc = nlp(' '.join(words[1:-1]))\n pos = [x.pos_ for x in doc]\n pos.insert(0, '-')\n pos.insert(len(pos), '-')\n\n top_seq_total_scors_exp = np.exp(top_seq_total_scors)\n\n return visualization(image, alphas, words, pos, top_seq_total_scors, top_seq_total_scors_exp, smooth, save_dir,\n image_name)\n\n\ndef run(encoder, decoder, word_map, rev_word_map, save_dir, top_k, top_p, image, image_title):\n\n seq, alphas, top_seq_total_scors, seqs_scores_logits = caption_image(encoder,\n decoder,\n image,\n word_map,\n top_k, top_p)\n\n alphas = torch.FloatTensor(alphas)\n\n visualize_att(image, seq, alphas, rev_word_map, top_seq_total_scors, save_dir, image_title, args.smooth)\n\n\nif __name__ == '__main__':\n top_k = 15 # NOTICE: int\n top_p = 0 # NOTICE: double\n\n model_path, save_dir = get_model_path_and_save_path(args, 'top_k_{}'.format(top_k)\n if top_k > 0 else 'top_p_{}'.format(top_p))\n\n # Load model\n encoder, decoder = get_models(model_path)\n\n # Create rev word map\n word_map, rev_word_map = get_word_map()\n\n for ind in range(args.limit_ex):\n img1 = np.random.uniform(low=0., high=255., size=(256, 256, 3))\n img1 = np.uint8(img1)\n img = img1\n\n img = img.transpose(2, 0, 1)\n img = img / 255.\n img = torch.FloatTensor(img).to(device)\n\n transform = transforms.Compose([data_normalization])\n image = transform(img) # (3, 256, 256)\n\n # Encode\n image = image.unsqueeze(0) # (1, 3, 256, 256)\n\n run(encoder, decoder, word_map, rev_word_map, save_dir, top_k, top_p, image, str(ind))\n\n # dataloader = load('custom', True, 1, 1)\n\n # for ind, image_data in enumerate(dataloader):\n # image = image_data[0]\n # image_title = image_data[1][0]\n #\n # run(encoder, decoder, word_map, rev_word_map, save_dir, top_k, top_p, image, image_title)\n","sub_path":"decoding_strategist_visualizations/top_k_top_p_captions/random_noise/top_k_p_random_caption.py","file_name":"top_k_p_random_caption.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"632243099","text":"#\n# Compare basic models with full models\n#\nimport pybamm\n\nimport numpy as np\nimport unittest\n\n\nclass TestCompareBasicModels(unittest.TestCase):\n def test_compare_dfns(self):\n basic_dfn = pybamm.lithium_ion.BasicDFN()\n dfn = pybamm.lithium_ion.DFN()\n\n # Solve basic DFN\n basic_sim = pybamm.Simulation(basic_dfn)\n t_eval = np.linspace(0, 3600)\n basic_sim.solve(t_eval)\n basic_sol = basic_sim.solution\n\n # Solve main DFN\n sim = pybamm.Simulation(dfn)\n t_eval = np.linspace(0, 3600)\n sim.solve(t_eval)\n sol = sim.solution\n\n # Compare solution data\n np.testing.assert_array_almost_equal(basic_sol.y, sol.y, decimal=4)\n np.testing.assert_array_almost_equal(basic_sol.t, sol.t, decimal=4)\n # Compare variables\n for name in basic_dfn.variables:\n np.testing.assert_array_almost_equal(\n basic_sol[name].entries, sol[name].entries, decimal=4\n )\n\n def test_compare_spms(self):\n basic_spm = pybamm.lithium_ion.BasicSPM()\n spm = pybamm.lithium_ion.SPM()\n\n # Solve basic SPM\n basic_sim = pybamm.Simulation(basic_spm)\n t_eval = np.linspace(0, 3600)\n basic_sim.solve(t_eval)\n basic_sol = basic_sim.solution\n\n # Solve main SPM\n sim = pybamm.Simulation(spm)\n t_eval = np.linspace(0, 3600)\n sim.solve(t_eval)\n sol = sim.solution\n\n # Compare solution data\n np.testing.assert_array_almost_equal(basic_sol.y, sol.y)\n np.testing.assert_array_almost_equal(basic_sol.t, sol.t)\n # Compare variables\n for name in basic_spm.variables:\n np.testing.assert_array_almost_equal(\n basic_sol[name].entries, sol[name].entries\n )\n\n\nif __name__ == \"__main__\":\n print(\"Add -v for more debug output\")\n import sys\n\n if \"-v\" in sys.argv:\n debug = True\n unittest.main()\n","sub_path":"tests/integration/test_models/test_full_battery_models/test_lithium_ion/test_compare_basic_models.py","file_name":"test_compare_basic_models.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"310124538","text":"'''\nRandom helper functions.\n\nDesign invariant:\n\n* This should not rely on anything in the system.\n\nWe can relax the design invariant, but we should think carefully\nbefore doing so.\n'''\n\nimport math\n\n\ndef paginate(data_list, nrows):\n '''\n Paginate list `data_list` into `nrows`-item rows.\n\n This should move into the client\n '''\n return [\n data_list[i * nrows:(i + 1) * nrows]\n for i in range(math.ceil(len(data_list) / nrows))\n ]\n","sub_path":"learning_observer/learning_observer/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"146418947","text":"################################################################\n### little prog prints a random sequence sting's and int's\n### and checked on double appearence when this happend's\n### a error massage is printed with the error\n__version__ = 'ver. 1'\n__autor__ = 'Sebastian Weigl'\n__date__ = 2013, 9, 13\n################################################################\nimport random\n\nalph = \"\"\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\"\"\nsymb = \"\"\"§$%&@€µ\"\"\"\n\naa = random.choice(alph)\nab = random.choice(alph)\nac = random.choice(alph)\nad = random.choice(alph)\nae = random.choice(alph)\n\nna = random.choice(alph)\nnb = random.choice(alph)\nnc = random.choice(alph)\nnd = random.choice(alph)\nne = random.choice(alph)\n\nsz = random.choice(symb)\n\nnuma = str(random.randint(0,9))\nnumc = str(random.randint(0,9))\nnumd = str(random.randint(0,9))\nnume = str(random.randint(0,9))\nnumf = str(random.randint(0,9))\nnumg = str(random.randint(0,9))\n\ndef check_alpha_a():\n if aa == ab or aa == ac or aa == ad or aa == ae:\n return False\n elif ab == ac or ab == ad or ab == ae:\n return False\n elif ac == ad or ac == ae:\n return False\n elif ad == ae:\n return False\n else:\n return True\ndef check_alpha_n():\n if na == nb or na == nc or na == nd or na == ne:\n return False\n elif nb == nc or nb == nd or nb == ne:\n return False\n elif nc == nd or nc == ne:\n return False\n elif nd == ne:\n return False\n else:\n return True\ndef check_number_a():\n if numa == numc:\n return False\n else:\n return True\ndef check_number_b():\n if numd == nume or numd == numf or numd == numg:\n return False\n elif nume == numf or nume == numg:\n return False\n elif numf == numg:\n return False\n else:\n return True\n\nif check_alpha_a() == True and check_alpha_n() == True and check_number_a() == True and check_number_b() == True:\n print(aa+ab+ac+ad+ae+'::'+numa+numc+'::'+sz+'::'+na+nb+nc+nd+ne+'::'+numd+nume+numf+numg)\n\nif check_alpha_a() == False:\n print(\"Double in ALPHA-A!\")\n print(aa+ab+ac+ad+ae+'::')\n\nif check_alpha_n() == False:\n print(\"\\nDouble in ALPHA-N!\")\n print(na+nb+nc+nd+ne+'::')\n\nif check_number_a() == False:\n print(\"\\nDouble in NUMBER-A!\")\n print(numa+numc)\n\nif check_number_b() == False:\n print(\"\\nDouble in NUMBER-B!\")\n print(numd+nume+numf+numg)\n## E-o-F\n","sub_path":"random4.py","file_name":"random4.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"245987038","text":"#print\n'''\nprint(a) 打印变量a的值\nprint('a') 打印a\nprint(str(a)) 将a转换为字符\n'''\n\n'''\na='hello world'\nprint(len(a))\n'''\n\n'''\ntime是一个包,里面有很多函数\n调用包里面的函数\ntime.sleep\n'''\n#自定义函数\n'''\n三个要点:\ndef 函数名(参数):\n 函数体\n return #结束函数主体\n'''\n\n'''\ndef greet(name):\n print(name+'你好')\n return\nname=input()\ngreet(name)\n'''\n'''\ndef age_1(age):\n if age<15:\n return '儿童'\n elif 15<=age<34:\n return '青年'\n else: return '中年以上'\nprint(age_1(13))\n'''\nimport random\na=1\nwhile a!=7:\n a=random.randint(1,100)\n print(a)","sub_path":"first_step/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"475351807","text":"# import sys\n# input = sys.stdin.readline \n\nfrom collections import deque\n\nclass StackAndQueue:\n def __init__(self, n, data_type=\"stack\"):\n self.array = deque()\n self.data_type = data_type\n \n def push(self, value):\n self.array.append(value)\n\n def pop(self):\n if self.size() == 0:\n return -1\n\n if self.is_stack():\n return self.array.pop()\n \n return self.array.popleft()\n\n def size(self):\n return len(self.array)\n\n def is_stack(self):\n return self.data_type == \"stack\"\n\n def empty(self):\n if self.size() == 0:\n return 1\n\n return 0\n\n def front(self):\n if self.is_stack() or self.size() == 0:\n return -1\n\n return self.array[0]\n\n def back(self):\n if self.is_stack() or self.size() == 0:\n return -1\n \n return self.array[-1]\n\n def top(self):\n if not self.is_stack() or self.size() == 0:\n return -1\n\n return self.array[-1]\n \n def get_last_val(self):\n return self.array[0]\n\ndef process(instance, command):\n cmd = command\n if cmd[0] == \"push\":\n instance.push(cmd[1])\n elif cmd[0] == \"pop\":\n print(instance.pop())\n elif cmd[0] == \"size\":\n print(instance.size())\n elif cmd[0] == \"empty\":\n print(instance.empty())\n elif cmd[0] == \"front\":\n print(instance.front())\n elif cmd[0] == \"back\":\n print(instance.back())\n elif cmd[0] == \"top\":\n print(instance.top())\n\nn = int(input())\ns_instance = StackAndQueue(n)\n\nfor _ in range(n):\n command = input().split()\n process(s_instance, command)","sub_path":"2_Algorithm_and_Cloud/03_stack_and_queue_by_deque_sol.py","file_name":"03_stack_and_queue_by_deque_sol.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"355358725","text":"import random\r\n#Create the board\r\nboard = [x for x in range(0,9)]\r\ndef show():\r\n print(board[0],'|',board[1],'|', board[2])\r\n print('---------')\r\n print(board[3],'|',board[4],'|', board[5])\r\n print('---------')\r\n print(board[6],'|',board[7],'|', board[8])\r\n \r\n\r\n\r\n#Check Winning Condition\r\n\r\ndef check():\r\n char = 'X'\r\n c = 0\r\n while c<2:\r\n for h in range(0,9,3):\r\n if (board[h] == char and board[h+1] == char and board[h+2] == char):\r\n print(char , 'wins')\r\n return True\r\n for v in range(0,3):\r\n if (board[v] == char and board[v+3] == char and board[v+6] == char):\r\n print(char , 'wins')\r\n return True\r\n for d in range(0,3,2):\r\n if d==0 and (board[d] == char and board[d+4] == char and board[d+8] == char):\r\n print(char , 'wins')\r\n return True\r\n if d==2 and (board[d] == char and board[d+2] == char and board[d+4] == char):\r\n print(char , 'wins')\r\n return True\r\n char = 'O'\r\n c += 1\r\n \r\n#Get User Input\r\ndef user():\r\n global counter\r\n while True:\r\n a = int(input('Please input a number between 0 to 8:'))\r\n if board[a] != 'X' and board[a] != 'O':\r\n board[a] = 'X'\r\n counter += 1\r\n break\r\n else:\r\n print('Space is taken try again')\r\n\r\n#Computers Turn\r\ndef computer():\r\n global counter\r\n while True:\r\n b = random.randint(0,8)\r\n if board[b] != 'X' and board[b] != 'O':\r\n board[b] = 'O'\r\n counter += 1\r\n print(counter,'moves')\r\n break\r\n \r\n\r\n#Draw Check\r\ndef draw():\r\n if counter == 9:\r\n print('Game is a draw')\r\n return True\r\n \r\n \r\n# The game\r\n\r\ncounter = 0\r\nwhile True:\r\n show()\r\n user()\r\n if draw()== True:\r\n show()\r\n break\r\n computer()\r\n if check() == True:\r\n show()\r\n break\r\n \r\n \r\n\r\n\r\n\r\n \r\n\r\n","sub_path":"Tic Tac Toe.py","file_name":"Tic Tac Toe.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"89577149","text":"\"\"\" This file contains defination of Bbox, TrackedBbox and tools \"\"\"\n\n\nfrom copy import deepcopy\n\nimport cv2\n\nclass Bbox(object):\n \"\"\" The defination of bbox class\"\"\"\n def __init__(self, classname, object_id, box, difficult, visible=True):\n \"\"\"\n Arg:\n classname: the name of object class\n object_id: the unique id for this object\n bbox: (xmin, ymin, width, height)\n kwargs: optinal arguments, such as difficult\n \"\"\"\n self.classname = classname\n self.object_id = object_id\n self.box = box\n self.difficult = difficult\n self.visible = visible\n\ndef mergeBboxes(bboxes, bboxes_prev):\n \"\"\" This function merges two sets of bboxes based on unique ids.\n If an id exists in both bboxes and bboxes_prev, the bbox in bboxes\n will be chosen but the tracked box's visibility will follow.\n \"\"\"\n bboxes_merged = deepcopy(bboxes)\n for bbox in bboxes_prev:\n is_exist = False\n for bbox_merged in bboxes_merged:\n if bbox.object_id == bbox_merged.object_id:\n is_exist = True\n bbox_merged.visible = bbox.visible\n break\n if not is_exist:\n bboxes_merged.append(bbox)\n return bboxes_merged\n\nclass TrackedBbox(object):\n \"\"\" The defination of tracked bbox class \"\"\"\n def __init__(self, bbox, image, tracker_type='MEDIANFLOW'):\n (major_ver,minor_ver,subminor_ver)=(cv2.__version__).split('.')\n tracker_types = ['BOOSTING', 'MIL','KCF', 'MEDIANFLOW']\n # 'TLD' and GOTURN not working this moment\n # tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN']\n assert tracker_type in tracker_types, \"tracker type not supported\"\n if int(minor_ver) < 3:\n tracker = cv2.Tracker_create(tracker_type)\n else:\n if tracker_type == 'BOOSTING':\n tracker = cv2.TrackerBoosting_create()\n if tracker_type == 'MIL':\n tracker = cv2.TrackerMIL_create()\n if tracker_type == 'KCF':\n tracker = cv2.TrackerKCF_create()\n if tracker_type == 'TLD':\n tracker = cv2.TrackerTLD_create()\n if tracker_type == 'MEDIANFLOW':\n tracker = cv2.TrackerMedianFlow_create()\n if tracker_type == 'GOTURN':\n tracker = cv2.TrackerGOTURN_create()\n self.tracker_type = tracker_type\n self.tracker = tracker\n self.bbox = bbox\n\n # Initialize tracker with first frame and bounding box\n ok = self.tracker.init(image, bbox.box)\n assert ok, \"can not initialize tracker\"\n def update(self, image):\n ok, box = self.tracker.update(image)\n if ok:\n self.bbox.box = box\n print('tracked box visibility')\n print(self.bbox.visible)\n return self.bbox\n print('tracking failed for object id %d' % self.bbox.object_id)\n return self.bbox\n","sub_path":"LabelImg/libs/bbox.py","file_name":"bbox.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"435557447","text":"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport numpy\nimport scipy.io\nimport tensorflow as tf\nfrom utils_input import load_cifar10, load_stl10\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\n\ndef conv2d_new(conv_name, x, filter_height, filter_width, nInputPlane, nOutputPlane, stride):\n \"\"\" Compute a 2-D convolution with customized stride and padding\n\n Args:\n conv_name: the name string for that convolution, for instance 'conv1'\n x: an input 4-D tensor of shape [batch, in_height, in_width, in_channels]\n x must be one of the following types: half, float32. The dimension order is \n interpreted according to the value of data_format\n filter_height: the height of convolutional filter, for instance 3\n filter_width: the width of the conv filter, for instance 3\n stride: the stride, for instance 2 or 1\n\n Returns:\n A 4-D tensor which has the same type as input x.\n\n \"\"\"\n with tf.variable_scope(conv_name):\n n = filter_height * filter_width * nOutputPlane\n\n kernel = tf.get_variable(\n 'DW', [filter_height, filter_width, nInputPlane, nOutputPlane],\n tf.float32, initializer=tf.random_normal_initializer(\n stddev=numpy.sqrt(2.0 / n)))\n\n strides = [1, stride, stride, 1]\n \n return tf.nn.conv2d(x, kernel, strides, padding='SAME')\n\n\n\ndef weight_decay(weight_decay_rate):\n \"\"\"L2 weight decay loss.\"\"\"\n costs = []\n for var in tf.trainable_variables():\n if var.op.name.find(r'DW') > 0:\n costs.append(tf.nn.l2_loss(var))\n\n return tf.multiply(weight_decay_rate, tf.add_n(costs))\n\n\ndef variable_summaries(scope_name, var):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard Visualization)\"\"\"\n with tf.name_scope(scope_name):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var)\n\n\nclass DataSet(object):\n\n def __init__(self,\n dir,\n filename=None,\n dataset=\"CIFAR10\"):\n \"\"\"Construct a DataSet.\"\"\"\n\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n self._dataset = dataset\n\n \n if self._dataset == \"CIFAR10\":\n cifar10 = load_cifar10(dir)\n self._train_data = normalize_image(cifar10[0][0])\n self._train_labels = cifar10[0][1]\n self._test_data = normalize_image(cifar10[1][0])\n self._test_labels = cifar10[1][1]\n self._height = 32\n self._width = 32\n self._channels = 3\n\n assert self._train_data.shape[0] == self._train_labels.shape[0], (\n '_train_data.shape: %s _train_labels.shape: %s' %\n (self._train_data.shape, self._train_labels.shape))\n assert self._test_data.shape[0] == self._test_labels.shape[0], (\n '_test_data.shape: %s _test_labels.shape: %s' %\n (self._test_data.shape, self._test_labels.shape))\n\n self._num_train = self._train_data.shape[0]\n self._num_test = self._test_data.shape[0]\n\n self._epochs_completed = 0\n self._index_in_epoch = 0\n\n def channels(self):\n # The number of channels of an image\n return self._channels\n\n def height(self):\n # The height of an image\n return self._height\n\n def width(self):\n # The width of an image\n return self._width\n\n def y_dim(self):\n # The dimension of an image\n return self._train_data.shape[1]\n\n def n_class(self):\n # Number of classes\n return self._train_labels.shape[1]\n\n def test_data(self):\n return self._test_data\n\n def test_labels(self):\n return self._test_labels\n\n def train_data(self):\n return self._train_data\n\n def train_labels(self):\n return self._train_labels\n\n def next_batch(self, batch_size, shuffle=True):\n \"\"\"Return the next `batch_size` examples from this data set.\n It returns a tuple:s (data, labels).\n \"\"\"\n # Adapted from\n # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/mnist.py\n\n start = self._index_in_epoch\n # Shuffle for the first epoch\n if self._epochs_completed == 0 and start == 0 and shuffle:\n perm0 = numpy.arange(self._num_train)\n numpy.random.shuffle(perm0)\n self._train_data = self._train_data[perm0]\n self._train_labels = self._train_labels[perm0]\n # Go to the next epoch\n if start + batch_size > self._num_train:\n # Finished epoch\n self._epochs_completed += 1\n # Get the rest examples in this epoch\n rest_num_examples = self._num_train - start\n images_rest_part = self._train_data[start:self._num_train]\n labels_rest_part = self._train_labels[start:self._num_train]\n # Shuffle the data\n if shuffle:\n perm = numpy.arange(self._num_train)\n numpy.random.shuffle(perm)\n self._train_data = self._train_data[perm]\n self._train_labels = self._train_labels[perm]\n # Start next epoch\n start = 0\n self._index_in_epoch = batch_size - rest_num_examples\n end = self._index_in_epoch\n images_new_part = self._train_data[start:end]\n labels_new_part = self._train_labels[start:end]\n return numpy.concatenate((images_rest_part, images_new_part), axis=0), numpy.concatenate((labels_rest_part, labels_new_part), axis=0)\n else:\n self._index_in_epoch += batch_size\n end = self._index_in_epoch\n return self._train_data[start:end], self._train_labels[start:end]\n\n def next_batch_test(self, batch_size, test_batch_start, shuffle=False):\n\n if test_batch_start == 0:\n self._index_in_epoch = 0\n\n start = self._index_in_epoch\n\n end = start + batch_size\n self._index_in_epoch = end\n\n if end > self._num_test:\n end = self._num_test\n\n return self._test_data[start:end], self._test_labels[start:end]\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"548903617","text":"import types\nimport unittest.mock as mock\n\nfrom search_ai.ga.genetic_algorithm import GeneticAlgorithm\n\nfrom search_ai.tests.test_case_with_utils import TestCaseWithUtils\n\n\nclass TestGeneticAlgorithm(TestCaseWithUtils):\n \n def setUp(self):\n super(TestGeneticAlgorithm, self).setUp()\n \n self.u = 10\n self.k = 2\n self.h = self.u * 4\n self.p = 3\n \n self.rec_times = 4\n self.population = [mock.MagicMock() for _ in range(self.u)]\n self.children = [\n mock.MagicMock() for _ in range(self.h // self.rec_times)\n ]\n \n self.fitness = mock.MagicMock()\n self.fitness.run.return_value = None\n \n self.init = mock.MagicMock()\n self.init.run.return_value = self.population\n \n self.sel = mock.MagicMock()\n self.sel.run.return_value = self.population[0:self.p]\n \n self.rec = mock.MagicMock()\n self.rec.run.return_value = self.children\n self.rec_num_of_children = mock.PropertyMock(\n return_value=self.h // self.rec_times\n )\n type(self.rec).number_of_children = self.rec_num_of_children\n \n self.mut = mock.MagicMock()\n self.mut.run.return_value = None\n \n self.replace_dups = mock.MagicMock()\n self.replace_dups.run.return_value = None\n \n self.elitism = mock.MagicMock()\n self.elitism.run.return_value = None\n \n self.stop_criteria = lambda ga: ga.current_generation >= 2\n \n self.ga = GeneticAlgorithm(\n self.u,\n self.k,\n self.h,\n self.p,\n self.fitness,\n self.init,\n self.sel,\n self.rec,\n self.mut,\n self.replace_dups,\n self.elitism,\n self.stop_criteria\n )\n \n def test_genetic_algorithm_constructor(self):\n self.check_genetic_algorithm_attributes(\n self.ga,\n self.u,\n self.k,\n self.h,\n self.p,\n self.fitness,\n self.init,\n self.sel,\n self.rec,\n self.mut,\n self.replace_dups,\n self.elitism\n )\n GeneticAlgorithm(\n 2,\n 1,\n 2,\n 1,\n None,\n None,\n None,\n self.rec,\n None,\n None,\n None,\n None\n )\n \n def test_genetic_algorithm_constructor_exception(self):\n with self.assertRaises(Exception):\n GeneticAlgorithm(\n 2,\n 1,\n 2,\n 1,\n None,\n None,\n None,\n None,\n None,\n None,\n None,\n None\n )\n GeneticAlgorithm(\n 2,\n 1,\n 2,\n 1,\n self.fitness,\n self.init,\n self.sel,\n None,\n self.mut,\n self.replace_dups,\n self.elitism,\n self.stop_criteria\n )\n \n def test_genetic_algorithm_u(self):\n self.assertEqual(self.ga.u, self.u)\n \n self.ga.u = 2\n self.assertEqual(self.ga.u, 2)\n \n self.ga.u = 100\n self.assertEqual(self.ga.u, 100)\n \n def test_genetic_algorithm_u_expection(self):\n with self.assertRaises(ValueError):\n self.ga.u = 1\n self.ga.u = -5\n \n def test_genetic_algorithm_k(self):\n self.assertEqual(self.ga.k, self.k)\n \n self.ga.k = 1\n self.assertEqual(self.ga.k, 1)\n \n self.ga.k = 24\n self.assertEqual(self.ga.k, 24)\n \n def test_genetic_algorithm_k_expection(self):\n with self.assertRaises(ValueError):\n self.ga.k = 0\n self.ga.k = -10\n \n def test_genetic_algorithm_h(self):\n self.assertEqual(self.ga.h, self.h)\n \n self.ga.h = self.u\n self.assertEqual(self.ga.h, self.u)\n \n self.ga.h = 100 * self.u\n self.assertEqual(self.ga.h, 100 * self.u)\n \n def test_genetic_algorithm_h_expection(self):\n with self.assertRaises(ValueError):\n self.ga.h = self.u - 1\n self.ga.h = self.u - 2 * self.u\n \n self.ga.u = 2\n with self.assertRaises(ValueError):\n self.ga.h = 1\n self.ga.h = -2\n \n def test_genetic_algorithm_p(self):\n self.assertEqual(self.ga.p, self.p)\n \n self.ga.p = 2\n self.assertEqual(self.ga.p, 2)\n \n self.ga.p = 110\n self.assertEqual(self.ga.p, 110)\n \n def test_genetic_algorithm_p_expection(self):\n with self.assertRaises(ValueError):\n self.ga.p = 1\n self.ga.p = -3\n \n def test_genetic_algorithm_fitness(self):\n self.check_simple_property(self.ga, 'fitness', self.fitness)\n \n def test_genetic_algorithm_initialization(self):\n self.check_simple_property(self.ga, 'initialization', self.init)\n \n def test_genetic_algorithm_selection(self):\n self.check_simple_property(self.ga, 'selection', self.sel)\n \n def test_genetic_algorithm_recombination(self):\n self.check_simple_property(self.ga, 'recombination', self.rec)\n \n def test_genetic_algorithm_mutation(self):\n self.check_simple_property(self.ga, 'mutation', self.mut)\n \n def test_genetic_algorithm_replace_duplicates(self):\n self.check_simple_property(\n self.ga,\n 'replace_duplicates',\n self.replace_dups\n )\n \n def test_genetic_algorithm_elitism(self):\n self.check_simple_property(self.ga, 'elitism', self.elitism)\n \n def test_genetic_algorithm_run(self):\n self._check_run_method()\n \n def test_genetic_algorithm_update_population(self):\n with mock.patch('search_ai.ga.genetic_algorithm.sorted'\n ) as sorted_mock:\n sorted_mock.return_value = self.children\n ind_age_prop_mock = mock.PropertyMock(\n side_effect=([0,\n 0,\n 1] * len(self.population))\n )\n \n for ind in self.population:\n type(ind).age = ind_age_prop_mock\n \n self.ga.k = 1\n population = list(self.population)\n children = list(self.children)\n self.ga._population = population\n self.ga._children = children\n self.ga.update_population()\n \n self.assertEqual(self.ga.population, children)\n self.assertEqual(self.ga._current_generation, 1)\n self.replace_dups.run.assert_called_once_with(\n population,\n children\n )\n sorted_mock.assert_called_once_with(children, reverse=True)\n self.elitism.run.assert_called_once_with(population)\n self.assertEqual(\n ind_age_prop_mock.call_count,\n 3 * len(self.population)\n )\n self.assertEqual(\n ind_age_prop_mock.call_args_list,\n [mock.call(),\n mock.call(1),\n mock.call()] * len(self.population)\n )\n \n def check_genetic_algorithm_attributes(\n self,\n ga,\n u,\n k,\n h,\n p,\n fitness,\n init,\n sel,\n rec,\n mut,\n replace_dups,\n elitism\n ):\n self.assertEqual(ga.u, u)\n self.assertEqual(ga.k, k)\n self.assertEqual(ga.h, h)\n self.assertEqual(ga.p, p)\n self.assertIs(ga.fitness, fitness)\n self.assertIs(ga.initialization, init)\n self.assertIs(ga.selection, sel)\n self.assertIs(ga.recombination, rec)\n self.assertIs(ga.mutation, mut)\n self.assertIs(ga.replace_duplicates, replace_dups)\n self.assertIs(ga.elitism, elitism)\n self.assertIsInstance(ga._stop_criteria, types.FunctionType)\n self.assertEqual(ga.current_generation, 0)\n self.assertIs(ga.population, None)\n self.assertEqual(ga._recombination_times, self.rec_times)\n \n def _check_run_method(self):\n with mock.patch('search_ai.ga.genetic_algorithm.print'\n ) as print_mock:\n self._check_run_method_assertions(print_mock)\n \n def _check_run_method_assertions(self, print_mock):\n \n def mock_update_population(ga):\n ga._current_generation += 1\n \n self.ga.update_population = types.MethodType(\n mock_update_population,\n self.ga\n )\n self.ga.run()\n \n self.init.run.assert_called_once_with()\n self.assertEqual(self.sel.run.call_count, self.rec_times * 2)\n self.assertEqual(self.rec.run.call_count, self.rec_times * 2)\n self.assertEqual(\n self.sel.run.call_args_list,\n [mock.call(self.population) for _ in range(self.rec_times)]\n * 2\n )\n self.assertEqual(\n self.rec.run.call_args_list,\n [\n mock.call(self.population[0:self.p])\n for _ in range(self.rec_times)\n ] * 2\n )\n self.assertEqual(self.fitness.run.call_count, self.h * 2)\n self.assertEqual(self.mut.run.call_count, self.h * 2)\n self.assertEqual(\n self.fitness.run.call_args_list,\n [mock.call(child) for child in self.children] * 8\n )\n self.assertEqual(\n self.mut.run.call_args_list,\n [mock.call(child) for child in self.children] * 8\n )\n self.assertEqual(self.ga._current_generation, 2)\n self.assertEqual(\n print_mock.call_args_list,\n [mock.call(self.population[0])] * 2\n )\n \n self._reset_mocks()\n self.ga._stop_criteria = lambda ga: True\n self.ga.run()\n \n self.init.run.assert_called_once_with()\n self.assertEqual(self.sel.run.call_count, 0)\n self.assertEqual(self.rec.run.call_count, 0)\n self.assertEqual(self.fitness.run.call_count, 0)\n self.assertEqual(self.mut.run.call_count, 0)\n self.assertEqual(self.ga._current_generation, 2)\n \n def _reset_mocks(self):\n self.fitness.reset_mock()\n self.init.reset_mock()\n self.sel.reset_mock()\n self.rec.reset_mock()\n self.mut.reset_mock()\n self.elitism.reset_mock()\n self.replace_dups.reset_mock()\n","sub_path":"search_ai/tests/ga/test_genetic_algorithm.py","file_name":"test_genetic_algorithm.py","file_ext":"py","file_size_in_byte":10822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"532831043","text":"import requests\nimport os\n\nfrom helper import read_yaml, form_device_params_from_yaml\n\nAPI_ENDPOINT = 'http://192.168.110.100:32768/api/'\nNETBOX_DEVICES_ENDPOINT = 'dcim/devices/'\nNETBOX_SITES_ENDPOINTS = 'dcim/sites/'\n\n\n\n\nclass NetboxAPITokenNotFound(Exception):\n pass\n\ndef form_headers():\n api_token = \"0123456789abcdef0123456789abcdef01234567\"\n if api_token is None:\n raise NetboxAPITokenNotFound('NETBOX_API_TOKEN was not found')\n\n headers = {\n 'Accept':'application/json; indent=4',\n 'Authorization':'Token {}'.format(api_token)\n }\n return headers\n\ndef add_site(name, slug):\n data = {\n 'name': name,\n 'slug': slug,\n }\n headers = form_headers()\n r = requests.post(API_ENDPOINT+NETBOX_SITES_ENDPOINTS, headers=headers, json=data)\n\n if r.status_code == 201:\n print(f'Site {name} created successfully')\n else:\n # raise_for_status raises an exception depending on what kind of error it gets\n r.raise_for_status()\n\ndef add_sites():\n for site in SITES:\n add_site(**site)\n\ndef add_device(name, device_type_id, device_role_id, site_id):\n headers = form_headers()\n data = {\n \"name\": name,\n \"device_type\": device_type_id,\n \"device_role\": device_role_id,\n \"site\": site_id,\n }\n print(data)\n\n r = requests.post(API_ENDPOINT+NETBOX_DEVICES_ENDPOINT, headers=headers, json=data)\n\n if r.status_code == 201:\n print(f'Device {name} created successfully')\n else:\n # raise_for_status raises an exception depending on what kind of error it gets\n r.raise_for_status()\n \ndef add_devices():\n parsed_yaml = read_yaml()\n devices_params_gen = form_device_params_from_yaml(parsed_yaml)\n for device_params in devices_params_gen:\n add_device(**device_params)\n print('All devices imported')\n\ndef main():\n #add_sites()\n add_devices()\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"python-ssh/netbox_api_interaction.py","file_name":"netbox_api_interaction.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"628341831","text":"# coding:utf-8\n\nimport os,time\nfrom openpyxl import Workbook\nfrom openpyxl import load_workbook\nfrom HuShi.Common.readData import Read_Data\n\n\nclass WriteReport:\n\n def __init__(self):\n\n self.address = self.address = os.path.split(os.path.dirname(__file__))[0] + \"\\Reports\"\n # self.report_name = \"test_result.xlsx\"\n self.report_name = time.strftime(\"%Y-%m-%d\")+\".xlsx\"\n self.report_path = os.path.join(self.address,self.report_name)\n\n def Creat_Report(self):\n\n if os.path.exists(self.report_path):\n pass\n else:\n ex = Workbook(self.report_path) # 创建一个Excel\n sh = ex.create_sheet(\"result\") # 创建一个sheet\n ex.save(self.report_path)\n\n file = load_workbook(self.report_path)\n sheet = file.get_sheet_by_name(\"result\")\n\n sheet.cell(row=1, column=1).value = \"Name\"\n sheet.cell(row=1, column=2).value = \"Api\"\n sheet.cell(row=1, column=3).value = \"Params\"\n sheet.cell(row=1, column=4).value = \"Check\"\n sheet.cell(row=1, column=5).value = \"Response\"\n sheet.cell(row=1, column=6).value = \"Result\"\n\n file.save(self.report_path)\n\n def Write_Report(self,x,name,api,params,code,response,result = \"False\"):\n\n file = load_workbook(self.report_path)\n sheet = file.get_sheet_by_name(\"result\")\n\n sheet.cell(row=x, column=1).value = name\n sheet.cell(row=x, column=2).value = api\n sheet.cell(row=x, column=3).value = params\n sheet.cell(row=x, column=4).value = code\n sheet.cell(row=x, column=5).value = response\n sheet.cell(row=x, column=6).value = result\n\n file.save(self.report_path)\n\n def Get_MaxRow(self):\n\n file = load_workbook(self.report_path)\n sheet = file.get_sheet_by_name(\"result\")\n return sheet.max_row\n file.save(self.report_path)\n\n\nif __name__ == \"__main__\":\n # name = 11\n # api = 22\n # params =33\n # code =44\n # response =55\n # WriteReport().Write_Report(name,api,params,code,response)\n x = WriteReport().Get_MaxRow()\n print(x)\n print(type(x))","sub_path":"venv/HuShi/Common/writeReport.py","file_name":"writeReport.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"454699626","text":"# Importing the dependancies\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom planar_utils import *\n# Loading the data \nX, y = load_data()\n\n# Visualizing the data\nplot_planar_data(X, y)\n\n# Defining the sigmoid function\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\n# Defining the relu function\ndef relu(z):\n return z * (z > 0)\n\n# Defining the derivative during back propagation\ndef relu_derivative(z):\n return 1 * (z > 0)\n\n# Defining some global variables\nhidden_neurons = 10 \nepochs = 10000\nm = X.shape[1]\nlearning_rate = 1.2\ncost = [0]*epochs # For visualizaion\nepsilon = 1e-8\n\n# Initializing the weights\nW1 = np.random.randn(hidden_neurons, X.shape[0])*0.01\nb1 = np.zeros((hidden_neurons, 1)) \nW2 = np.random.randn(y.shape[0], hidden_neurons)*0.01\nb2 = np.zeros((y.shape[0], 1))\n\n\nv_t = np.zeros((4,))\n\nfor epoch in range(epochs):\n \n # Forward propagation\n Z1 = np.dot(W1, X) + b1\n A1 = np.tanh(Z1)\n \n Z2 = np.dot(W2, A1) + b2\n A2 = sigmoid(Z2)\n \n # Cost \n logprobs = np.multiply(np.log(A2 + epsilon), y) + np.multiply((1 - y), np.log(1 - A2 + epsilon))\n\n cost[epoch] = - np.sum(logprobs) / m\n if epoch%1000 == 0: # Printing the cost after every 1000 iterations for debugging\n print(f'Cost after {epoch} iterations = {cost[epoch]}') \n \n # Backward propagation\n dZ2= A2 - y\n dW2 = (1/m) * np.dot(dZ2, A1.T)\n db2 = (1/m) * np.sum(dZ2, axis=1, keepdims=True)\n dZ1 = np.multiply(np.dot(W2.T, dZ2), 1-np.power(A1, 2))\n dW1 = (1/m) * np.dot(dZ1, X.T)\n db1 = (1/m) * np.sum(dZ1, axis=1, keepdims=True)\n \n grads = np.array([dW2, db2, dW1, db1])\n # caculating the exponential average.\n v_t = 0.8*v_t + learning_rate*grads\n # Updating the parameters\n W2 -= v_t[0]\n b2 -= v_t[1]\n W1 -= v_t[2]\n b1 -= v_t[3]\n\nplt.style.use('fivethirtyeight')\n \n# Visualizing the cost function\nplt.plot(cost, label = 'cost')\nplt.xlabel('Epochs')\nplt.ylabel('Cost')\nplt.legend()\nplt.show()\n\n# Predicting \nZ1 = np.dot(W1, X) + b1\nA1 = np.tanh(Z1)\n\nZ2 = np.dot(W2, A1) + b2\ny_pred = sigmoid(Z2)\n\nprint ('Accuracy: %d' % float((np.dot(y, y_pred.T) + np.dot(1-y, 1-y_pred.T))/float(y.size)*100) + '%')","sub_path":"Neural Network/single_layer_momentum.py","file_name":"single_layer_momentum.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"448730490","text":"import numpy as np\nimport os\nimport sys\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nimport torch.nn.init as init\nimport torch.utils.data as data\nimport torch.utils.data.dataset as dataset\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport torchvision.utils as v_utils\nimport matplotlib.pyplot as plt\nimport skimage\nimport skimage.io as io\nimport skimage.transform as trans\nimport math\nfrom collections import OrderedDict # 容器包\nimport copy\nimport time\nfrom sklearn.metrics import roc_auc_score\nfrom utils import DataLoader\nimport random\nfrom pytorch_msssim import ms_ssim\nimport argparse\nfrom sirui import mymodel,recons_loss\nimport os\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\nparser = argparse.ArgumentParser(description=\"sirui\")\nparser.add_argument('--gpus', nargs='+', type=str, help='gpus')\nparser.add_argument('--batch_size', type=int, default=4, help='batch size for training')\nparser.add_argument('--test_batch_size', type=int, default=1, help='batch size for test')\nparser.add_argument('--epochs', type=int, default=60, help='number of epochs for training')\nparser.add_argument('--h', type=int, default=256, help='height of input images')\nparser.add_argument('--w', type=int, default=256, help='width of input images')\nparser.add_argument('--c', type=int, default=3, help='channel of input images')\nparser.add_argument('--lr', type=float, default=2e-4, help='initial learning rate')\nparser.add_argument('--t_length', type=int, default=5, help='length of the frame sequences')\nparser.add_argument('--alpha', type=float, default=0.6, help='weight for the anomality score')\nparser.add_argument('--num_workers', type=int, default=2, help='number of workers for the train loader')\nparser.add_argument('--num_workers_test', type=int, default=1, help='number of workers for the test loader')\nparser.add_argument('--dataset_type', type=str, default='ped2', help='type of dataset: ped2, avenue, shanghai')\nparser.add_argument('--dataset_path', type=str, default='./dataset/', help='directory of data')\nparser.add_argument('--exp_dir', type=str, default='log', help='directory of log')\nparser.add_argument('--vali',type = float, default = 0.2,help = 'validation split')\n\nargs = parser.parse_args()\n\ntorch.manual_seed(2020) # #为CPU设置种子用于生成随机数,以使得结果是确定的\n\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nif args.gpus is None:\n gpus = \"0\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = gpus\nelse:\n gpus = \"\"\n for i in range(len(args.gpus)):\n gpus = gpus + args.gpus[i] + \",\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = gpus[:-1]\n#os.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2'\ntorch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance 确保使用cudnn\n\ntrain_folder = args.dataset_path + args.dataset_type + \"/training/frames/\"\n#train_folder = args.dataset_path + args.dataset_type + \"/videos/training_frames/\"\ntest_folder = args.dataset_path + args.dataset_type + \"/testing/frames/\"\n\ntrain_dataset = DataLoader(train_folder, transforms.Compose([transforms.ToTensor(), ]), resize_height=args.h, resize_width=args.w, time_step=args.t_length - 1)\n# transforms.ToTensor() 将numpy的ndarray或PIL.Image读的图片转换成形状为(C,H, W)的Tensor格式,且/255归一化到[0,1.0]之间\n\ntrain_size = len(train_dataset)\nprint(train_size)\nsplit = int(np.floor(args.vali * train_size))\n# 在训练模型时使用到此函数,用来把训练数据分成多个小组,此函数每次抛出一组数据。直至把所有的数据都抛出。就是做一个数据的初始化\nval_size = int(args.vali*len(train_dataset)) #验证用20%的训练集\ntrain_size = int(len(train_dataset)-val_size) #训练集就是剩下80%\ntrain_dataset, valid_dataset = torch.utils.data.random_split(train_dataset, [train_size, val_size])\ntrain_loader = data.DataLoader(train_dataset, batch_size=args.batch_size,\n shuffle=True, num_workers = args.num_workers, drop_last=True)\nvalid_loader = data.DataLoader(valid_dataset, batch_size=args.batch_size,shuffle=True,\n num_workers = args.num_workers, drop_last=True)\n\n# Model setting\nmodel = mymodel(input_size=(32,32),input_dim=128,hidden_dim=128,kernel_size=(3,3),num_layers=1)\n\noptimizer = torch.optim.Adam(model.parameters(), lr=args.lr) # 设置学习率\nscheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs) # 学习率调整函数 这里使用余弦退火\nmodel = nn.DataParallel(module = model)\nmodel.cuda() # 把模型放到显卡上\n\n# Report the training process\nlog_dir = os.path.join('./exp/', args.dataset_type, args.exp_dir)\n\nif not os.path.exists(log_dir): # 若没有这个文件夹就创建\n os.makedirs(log_dir)\n\n# Training\nfor epoch in range(args.epochs):\n labels_list = []\n model.train()\n print('This is the {} th training.'.format(epoch+1))\n start = time.time()\n \"\"\"将数据喂入神经网络进行训练,通过enumerate输出我们想要的经过shuffle的bachsize大小的feature和label数据\"\"\"\n for j, (imgs) in enumerate(tqdm(train_loader)): # 承接上面的dataloader函数,这个是一套固定用法\n imgs = Variable(imgs).cuda() # Variable和tensor其实是一个东西,Variable实际上是一个容器,里面面装个tensor\n\n # 接下来就是跑模型的环节\n output = model.forward(x = imgs[:,0:12,:,:],train = True)\n optimizer.zero_grad()\n '''\n 在每次backward后,grad值是会累加的,所以利用BP算法,每次迭代是需要将grad清零的。\n x.grad.data.zero_()\n '''\n # 最后一张是预测出来的 既12:(12,13,14)用于和生成出来的��损失函数 既计算重构误差\n loss = recons_loss(output,imgs[:,12:,:,:])\n loss.backward(retain_graph=True) # 反向传递函数\n optimizer.step() # 所有的optimizer都实现了step()方法,这个方法会更新所有的参数。它能按两种方式来使用\n\n model.eval()\n for i , (imgs) in enumerate(valid_loader):\n imgs = Variable(imgs).cuda() # Variable和tensor其实是一个东西,Variable实际上是一个容器,里面面装个tensor\n # 接下来就是跑模型的环节\n output = model.forward(x=imgs[:, 0:12, :, :], train=True)\n # 最后一张是预测出来的 既12:(12,13,14)用于和生成出来的做损失函数 既计算重构误差\n valloss = recons_loss(output, imgs[:, 12:, :, :])\n\n\n scheduler.step() # scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer,T_max =args.epochs)\n\n print(\n 'Epoch [{}/{}], Step [{}/{}], Loss: {:.5f},valloss: {:.5f}'.format(\n epoch + 1, args.epochs, j + 1, train_size, loss.item(),valloss.item()))\n print('----------------------------------------')\n print(os.path.join(log_dir, 'model_{:.3f}_{:.5f}_{:.5f}.pth'.format(epoch+1,loss,valloss)))\n\n\n torch.save(model, os.path.join(log_dir, 'model_{:.3f}_{:.5f}_{:.5f}.pth'.format(epoch+1,loss,valloss)))\n\nprint('Training is finished')\n\n\n\n\n","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":7226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"325438322","text":"#!/usr/bin/python3\n\nimport untangle\nfrom Command import Command\n\nclass CommandAggregator():\n\tdef __init__(self ):\n\t\tself.config = \"\"\n\tdef getCommandObj(self):\n\t\tconfObj = untangle.parse(self.config)\n\t\tcommandObj = untangle.parse(confObj.config.files.commands.cdata)\n\t\treturn commandObj\n\tdef buildCommandDict(self):\n\t\tcommandObj = self.getCommandObj()\n\t\tfinalDict = {}\n\t\tfor c in commandObj.commands.command:\n\t\t\ttempCommand = Command(c)\n\t\t\ttempCommand.build()\n\t\t\tfinalDict[tempCommand.get('title')] = tempCommand\n\t\treturn finalDict\n\tdef buildKeywordDict(self):\n\t\tcommandObj = self.getCommandObj()\n\t\tfinalDict = {}\n\t\tfor c in commandObj.commands.command:\n\t\t\ttempCommand = Command(c)\n\t\t\ttempCommand.build()\n\t\t\tfor keyword in tempCommand.get('keywords').split(','):\n\t\t\t\tif( keyword not in finalDict):\n\t\t\t\t\tfinalDict[keyword] = {}\n\t\t\t\tfinalDict[keyword][tempCommand.get('title')] = tempCommand\n\t\treturn finalDict\n\tdef buildAll(self, config):\n\t\tself.config = config\n\t\tcommandDict = self.buildCommandDict()\n\t\tkeywordDict = self.buildKeywordDict()\n\t\treturn commandDict, keywordDict\n","sub_path":"src/CommandAggregator.py","file_name":"CommandAggregator.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"485487120","text":"# Exercício 021: Faça um programa em Python que abra e reproduza o áudio de um arquivo MP3.\n\nimport time\nimport mp3play\n\nprint(5*'='+' EXERCISE 021 '+5*'=')\n\nfilename = r'C:\\music.mp3'\nclip = mp3play.load(filename)\n\nclip.play()\n\ntime.sleep(min(30, clip.seconds()))\nclip.stop()\n","sub_path":"Exercicios/ex021.py","file_name":"ex021.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"162605841","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\nfrom typing import Callable, Dict, List, Optional, Tuple, Type, Union\n\nimport numpy as np\nimport torch\nfrom ax.core.data import Data\nfrom ax.core.experiment import Experiment\nfrom ax.core.observation import ObservationData, ObservationFeatures\nfrom ax.core.optimization_config import OptimizationConfig\nfrom ax.core.search_space import SearchSpace\nfrom ax.core.types import TCandidateMetadata, TConfig, TGenMetadata\nfrom ax.modelbridge.array import FIT_MODEL_ERROR, ArrayModelBridge\nfrom ax.modelbridge.modelbridge_utils import (\n validate_and_apply_final_transform,\n SearchSpaceDigest,\n)\nfrom ax.modelbridge.transforms.base import Transform\nfrom ax.models.torch_base import TorchModel\nfrom ax.utils.common.typeutils import not_none\nfrom torch import Tensor\n\n\n# pyre-fixme[13]: Attribute `model` is never initialized.\n# pyre-fixme[13]: Attribute `outcomes` is never initialized.\n# pyre-fixme[13]: Attribute `parameters` is never initialized.\nclass TorchModelBridge(ArrayModelBridge):\n \"\"\"A model bridge for using torch-based models.\n\n Specifies an interface that is implemented by TorchModel. In particular,\n model should have methods fit, predict, and gen. See TorchModel for the\n API for each of these methods.\n\n Requires that all parameters have been transformed to RangeParameters\n or FixedParameters with float type and no log scale.\n\n This class converts Ax parameter types to torch tensors before passing\n them to the model.\n \"\"\"\n\n model: Optional[TorchModel]\n _default_model_gen_options: TConfig\n\n def __init__(\n self,\n experiment: Experiment,\n search_space: SearchSpace,\n data: Data,\n model: TorchModel,\n transforms: List[Type[Transform]],\n transform_configs: Optional[Dict[str, TConfig]] = None,\n torch_dtype: Optional[torch.dtype] = None, # noqa T484\n torch_device: Optional[torch.device] = None,\n status_quo_name: Optional[str] = None,\n status_quo_features: Optional[ObservationFeatures] = None,\n optimization_config: Optional[OptimizationConfig] = None,\n fit_out_of_design: bool = False,\n default_model_gen_options: Optional[TConfig] = None,\n ) -> None:\n if torch_dtype is None: # pragma: no cover\n torch_dtype = torch.float # noqa T484\n self.dtype = torch_dtype\n self.device = torch_device\n self._default_model_gen_options = default_model_gen_options or {}\n super().__init__(\n experiment=experiment,\n search_space=search_space,\n data=data,\n model=model,\n transforms=transforms,\n transform_configs=transform_configs,\n status_quo_name=status_quo_name,\n status_quo_features=status_quo_features,\n optimization_config=optimization_config,\n fit_out_of_design=fit_out_of_design,\n )\n\n def _validate_observation_data(\n self, observation_data: List[ObservationData]\n ) -> None:\n if len(observation_data) == 0:\n raise ValueError(\n \"Torch models cannot be fit without observation data. Possible \"\n \"reasons include empty data being passed to the model's constructor \"\n \"or data being excluded because it is out-of-design. Try setting \"\n \"`fit_out_of_design`=True during construction to fix the latter.\"\n )\n\n def _fit(\n self,\n model: TorchModel,\n search_space: SearchSpace,\n observation_features: List[ObservationFeatures],\n observation_data: List[ObservationData],\n ) -> None: # pragma: no cover\n self._validate_observation_data(observation_data)\n super()._fit(\n model=model,\n search_space=search_space,\n observation_features=observation_features,\n observation_data=observation_data,\n )\n\n def _model_evaluate_acquisition_function(self, X: np.ndarray) -> np.ndarray:\n if not self.model: # pragma: no cover\n raise ValueError(\n FIT_MODEL_ERROR.format(action=\"_model_evaluate_acquisition_function\")\n )\n evals = not_none(self.model).evaluate_acquisition_function(\n X=self._array_to_tensor(X)\n )\n return evals.detach().cpu().clone().numpy()\n\n def _model_fit(\n self,\n model: TorchModel,\n Xs: List[np.ndarray],\n Ys: List[np.ndarray],\n Yvars: List[np.ndarray],\n search_space_digest: SearchSpaceDigest,\n metric_names: List[str],\n candidate_metadata: Optional[List[List[TCandidateMetadata]]],\n ) -> None:\n self.model = model\n # Convert numpy arrays to torch tensors\n # pyre-fixme[35]: Target cannot be annotated.\n Xs: List[Tensor] = self._array_list_to_tensors(Xs)\n # pyre-fixme[35]: Target cannot be annotated.\n Ys: List[Tensor] = self._array_list_to_tensors(Ys)\n # pyre-fixme[35]: Target cannot be annotated.\n Yvars: List[Tensor] = self._array_list_to_tensors(Yvars)\n # pyre-fixme[16]: `Optional` has no attribute `fit`.\n self.model.fit(\n Xs=Xs,\n Ys=Ys,\n Yvars=Yvars,\n search_space_digest=search_space_digest,\n metric_names=metric_names,\n candidate_metadata=candidate_metadata,\n )\n\n def _model_update(\n self,\n Xs: List[np.ndarray],\n Ys: List[np.ndarray],\n Yvars: List[np.ndarray],\n search_space_digest: SearchSpaceDigest,\n candidate_metadata: Optional[List[List[TCandidateMetadata]]],\n metric_names: List[str],\n ) -> None:\n if not self.model: # pragma: no cover\n raise ValueError(FIT_MODEL_ERROR.format(action=\"_model_update\"))\n # pyre-fixme[35]: Target cannot be annotated.\n Xs: List[Tensor] = self._array_list_to_tensors(Xs)\n # pyre-fixme[35]: Target cannot be annotated.\n Ys: List[Tensor] = self._array_list_to_tensors(Ys)\n # pyre-fixme[35]: Target cannot be annotated.\n Yvars: List[Tensor] = self._array_list_to_tensors(Yvars)\n # pyre-fixme[16]: `Optional` has no attribute `update`.\n self.model.update(\n Xs=Xs,\n Ys=Ys,\n Yvars=Yvars,\n search_space_digest=search_space_digest,\n metric_names=self.outcomes,\n candidate_metadata=candidate_metadata,\n )\n\n def _model_predict(self, X: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n if not self.model: # pragma: no cover\n raise ValueError(FIT_MODEL_ERROR.format(action=\"_model_predict\"))\n f, var = not_none(self.model).predict(X=self._array_to_tensor(X))\n return f.detach().cpu().clone().numpy(), var.detach().cpu().clone().numpy()\n\n def _model_gen(\n self,\n n: int,\n bounds: List[Tuple[float, float]],\n objective_weights: np.ndarray,\n outcome_constraints: Optional[Tuple[np.ndarray, np.ndarray]],\n linear_constraints: Optional[Tuple[np.ndarray, np.ndarray]],\n fixed_features: Optional[Dict[int, float]],\n pending_observations: Optional[List[np.ndarray]],\n model_gen_options: Optional[TConfig],\n rounding_func: Callable[[np.ndarray], np.ndarray],\n target_fidelities: Optional[Dict[int, float]],\n ) -> Tuple[np.ndarray, np.ndarray, TGenMetadata, List[TCandidateMetadata]]:\n if not self.model: # pragma: no cover\n raise ValueError(FIT_MODEL_ERROR.format(action=\"_model_gen\"))\n obj_w, oc_c, l_c, pend_obs, _ = validate_and_apply_final_transform(\n objective_weights=objective_weights,\n outcome_constraints=outcome_constraints,\n linear_constraints=linear_constraints,\n pending_observations=pending_observations,\n final_transform=self._array_to_tensor,\n )\n tensor_rounding_func = self._array_callable_to_tensor_callable(rounding_func)\n augmented_model_gen_options = {\n **self._default_model_gen_options,\n **(model_gen_options or {}),\n }\n # pyre-fixme[16]: `Optional` has no attribute `gen`.\n X, w, gen_metadata, candidate_metadata = self.model.gen(\n n=n,\n bounds=bounds,\n objective_weights=obj_w,\n outcome_constraints=oc_c,\n linear_constraints=l_c,\n fixed_features=fixed_features,\n pending_observations=pend_obs,\n model_gen_options=augmented_model_gen_options,\n rounding_func=tensor_rounding_func,\n target_fidelities=target_fidelities,\n )\n return (\n X.detach().cpu().clone().numpy(),\n w.detach().cpu().clone().numpy(),\n gen_metadata,\n candidate_metadata,\n )\n\n def _model_best_point(\n self,\n bounds: List[Tuple[float, float]],\n objective_weights: np.ndarray,\n outcome_constraints: Optional[Tuple[np.ndarray, np.ndarray]],\n linear_constraints: Optional[Tuple[np.ndarray, np.ndarray]],\n fixed_features: Optional[Dict[int, float]],\n model_gen_options: Optional[TConfig],\n target_fidelities: Optional[Dict[int, float]],\n ) -> Optional[np.ndarray]: # pragma: no cover\n if not self.model: # pragma: no cover\n raise ValueError(FIT_MODEL_ERROR.format(action=\"_model_gen\"))\n obj_w, oc_c, l_c, _, _ = validate_and_apply_final_transform(\n objective_weights=objective_weights,\n outcome_constraints=outcome_constraints,\n linear_constraints=linear_constraints,\n pending_observations=None,\n final_transform=self._array_to_tensor,\n )\n try:\n # pyre-fixme[16]: `Optional` has no attribute `best_point`.\n X = self.model.best_point(\n bounds=bounds,\n objective_weights=obj_w,\n outcome_constraints=oc_c,\n linear_constraints=l_c,\n fixed_features=fixed_features,\n model_gen_options=model_gen_options,\n target_fidelities=target_fidelities,\n )\n return None if X is None else X.detach().cpu().clone().numpy()\n\n except NotImplementedError:\n return None\n\n def _model_cross_validate(\n self,\n Xs_train: List[np.ndarray],\n Ys_train: List[np.ndarray],\n Yvars_train: List[np.ndarray],\n X_test: np.ndarray,\n search_space_digest: SearchSpaceDigest,\n metric_names: List[str],\n ) -> Tuple[np.ndarray, np.ndarray]:\n if not self.model: # pragma: no cover\n raise ValueError(FIT_MODEL_ERROR.format(action=\"_model_cross_validate\"))\n # pyre-fixme[35]: Target cannot be annotated.\n Xs_train: List[Tensor] = self._array_list_to_tensors(Xs_train)\n # pyre-fixme[35]: Target cannot be annotated.\n Ys_train: List[Tensor] = self._array_list_to_tensors(Ys_train)\n # pyre-fixme[35]: Target cannot be annotated.\n Yvars_train: List[Tensor] = self._array_list_to_tensors(Yvars_train)\n # pyre-fixme[35]: Target cannot be annotated.\n X_test: Tensor = self._array_to_tensor(X_test)\n # pyre-fixme[16]: `Optional` has no attribute `cross_validate`.\n f_test, cov_test = self.model.cross_validate(\n Xs_train=Xs_train,\n Ys_train=Ys_train,\n Yvars_train=Yvars_train,\n X_test=X_test,\n search_space_digest=search_space_digest,\n metric_names=metric_names,\n )\n return (\n f_test.detach().cpu().clone().numpy(),\n cov_test.detach().cpu().clone().numpy(),\n )\n\n def _array_to_tensor(self, array: Union[np.ndarray, List[float]]) -> Tensor:\n return torch.as_tensor(array, dtype=self.dtype, device=self.device)\n\n def _array_list_to_tensors(self, arrays: List[np.ndarray]) -> List[Tensor]:\n return [self._array_to_tensor(x) for x in arrays]\n\n def _array_callable_to_tensor_callable(\n self, array_func: Callable[[np.ndarray], np.ndarray]\n ) -> Callable[[Tensor], Tensor]:\n tensor_func: Callable[[Tensor], Tensor] = lambda x: (\n self._array_to_tensor(array_func(x.detach().cpu().clone().numpy()))\n )\n return tensor_func\n\n def _transform_observation_features(\n self, observation_features: List[ObservationFeatures]\n ) -> Tensor:\n return self._array_to_tensor(\n super()._transform_observation_features(observation_features)\n )\n\n def _transform_observation_data(\n self, observation_data: List[ObservationData]\n ) -> Tuple[Tensor, Tensor]:\n mean, cov = super()._transform_observation_data(observation_data)\n return self._array_to_tensor(mean), self._array_to_tensor(cov)\n","sub_path":"ax/modelbridge/torch.py","file_name":"torch.py","file_ext":"py","file_size_in_byte":13071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"41553635","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\nfrom singa import device\nfrom singa import initializer\nfrom singa import layer\nfrom singa import loss\nfrom singa import net as ffnet\nfrom singa import optimizer\nfrom singa import tensor\n\nimport argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\nfrom utils import load_data\nfrom utils import print_log\n\nclass LSGAN():\n\tdef __init__(self, dev, rows=28, cols=28, channels=1, noise_size=100, hidden_size=128, batch=128, \n\t\tinterval=1000, learning_rate=0.001, epochs=1000000, d_steps=3, g_steps=1, \n\t\tdataset_filepath='mnist.pkl.gz', file_dir='lsgan_images/'):\n\t\tself.dev = dev\n\t\tself.rows = rows\n\t\tself.cols = cols\n\t\tself.channels = channels\n\t\tself.feature_size = self.rows * self.cols * self.channels\n\t\tself.noise_size = noise_size\n\t\tself.hidden_size = hidden_size\n\t\tself.batch = batch\n\t\tself.batch_size = self.batch//2\n\t\tself.interval = interval\n\t\tself.learning_rate = learning_rate\n\t\tself.epochs = epochs\n\t\tself.d_steps = d_steps\n\t\tself.g_steps = g_steps\n\t\tself.dataset_filepath = dataset_filepath\n\t\tself.file_dir = file_dir\n\n\t\tself.g_w0_specs = {'init': 'xavier',}\n\t\tself.g_b0_specs = {'init': 'constant', 'value': 0,}\n\t\tself.g_w1_specs = {'init': 'xavier',}\n\t\tself.g_b1_specs = {'init': 'constant', 'value': 0,}\n\t\tself.gen_net = ffnet.FeedForwardNet(loss.SquaredError(),)\n\t\tself.gen_net_fc_0 = layer.Dense(name='g_fc_0', num_output=self.hidden_size, use_bias=True, \n\t\t\tW_specs=self.g_w0_specs, b_specs=self.g_b0_specs, input_sample_shape=(self.noise_size,))\n\t\tself.gen_net_relu_0 = layer.Activation(name='g_relu_0', mode='relu',input_sample_shape=(self.hidden_size,))\n\t\tself.gen_net_fc_1 = layer.Dense(name='g_fc_1', num_output=self.feature_size, use_bias=True, \n\t\t\tW_specs=self.g_w1_specs, b_specs=self.g_b1_specs, input_sample_shape=(self.hidden_size,))\n\t\tself.gen_net_sigmoid_1 = layer.Activation(name='g_relu_1', mode='sigmoid', input_sample_shape=(self.feature_size,))\n\t\tself.gen_net.add(self.gen_net_fc_0)\n\t\tself.gen_net.add(self.gen_net_relu_0)\n\t\tself.gen_net.add(self.gen_net_fc_1)\n\t\tself.gen_net.add(self.gen_net_sigmoid_1)\n\t\tfor (p, specs) in zip(self.gen_net.param_values(), self.gen_net.param_specs()):\n\t\t\tfiller = specs.filler\n\t\t\tif filler.type == 'gaussian':\n\t\t\t\tp.gaussian(filler.mean, filler.std)\n\t\t\telif filler.type == 'xavier':\n\t\t\t\tinitializer.xavier(p)\n\t\t\telse: \n\t\t\t\tp.set_value(0)\n\t\t\tprint(specs.name, filler.type, p.l1())\t\n\t\tself.gen_net.to_device(self.dev)\t\t\n\n\t\tself.d_w0_specs = {'init': 'xavier',}\n\t\tself.d_b0_specs = {'init': 'constant', 'value': 0,}\n\t\tself.d_w1_specs = {'init': 'xavier',}\n\t\tself.d_b1_specs = {'init': 'constant', 'value': 0,}\t\t\t\n\t\tself.dis_net = ffnet.FeedForwardNet(loss.SquaredError(),)\n\t\tself.dis_net_fc_0 = layer.Dense(name='d_fc_0', num_output=self.hidden_size, use_bias=True, \n\t\t\tW_specs=self.d_w0_specs, b_specs=self.d_b0_specs, input_sample_shape=(self.feature_size,))\n\t\tself.dis_net_relu_0 = layer.Activation(name='d_relu_0', mode='relu',input_sample_shape=(self.hidden_size,))\n\t\tself.dis_net_fc_1 = layer.Dense(name='d_fc_1', num_output=1, use_bias=True, \n\t\t\tW_specs=self.d_w1_specs, b_specs=self.d_b1_specs, input_sample_shape=(self.hidden_size,))\n\t\tself.dis_net.add(self.dis_net_fc_0)\n\t\tself.dis_net.add(self.dis_net_relu_0)\n\t\tself.dis_net.add(self.dis_net_fc_1)\t\t\t\n\t\tfor (p, specs) in zip(self.dis_net.param_values(), self.dis_net.param_specs()):\n\t\t\tfiller = specs.filler\n\t\t\tif filler.type == 'gaussian':\n\t\t\t\tp.gaussian(filler.mean, filler.std)\n\t\t\telif filler.type == 'xavier':\n\t\t\t\tinitializer.xavier(p)\n\t\t\telse: \n\t\t\t\tp.set_value(0)\n\t\t\tprint(specs.name, filler.type, p.l1())\n\t\tself.dis_net.to_device(self.dev)\n\n\t\tself.combined_net = ffnet.FeedForwardNet(loss.SquaredError(), )\n\t\tfor l in self.gen_net.layers:\n\t\t\tself.combined_net.add(l)\n\t\tfor l in self.dis_net.layers:\n\t\t\tself.combined_net.add(l)\n\t\tself.combined_net.to_device(self.dev)\n\n\tdef train(self):\n\t\ttrain_data, _, _, _, _, _ = load_data(self.dataset_filepath)\n\t\topt_0 = optimizer.Adam(lr=self.learning_rate) # optimizer for discriminator \n\t\topt_1 = optimizer.Adam(lr=self.learning_rate) # optimizer for generator, aka the combined model\n\t\tfor (p, specs) in zip(self.dis_net.param_names(), self.dis_net.param_specs()):\n\t\t\topt_0.register(p, specs)\n\t\tfor (p, specs) in zip(self.gen_net.param_names(), self.gen_net.param_specs()):\n\t\t\topt_1.register(p, specs)\n\n\t\tfor epoch in range(self.epochs):\n\t\t\tfor d_step in range(self.d_steps):\n\t\t\t\tidx = np.random.randint(0, train_data.shape[0], self.batch_size)\n\t\t\t\treal_imgs = train_data[idx]\n\t\t\t\treal_imgs = tensor.from_numpy(real_imgs)\n\t\t\t\treal_imgs.to_device(self.dev)\n\t\t\t\tnoise = tensor.Tensor((self.batch_size, self.noise_size))\n\t\t\t\tnoise.uniform(-1, 1)\n\t\t\t\tnoise.to_device(self.dev)\n\t\t\t\tfake_imgs = self.gen_net.forward(flag=False, x=noise)\n\t\t\t\tsubstrahend = tensor.Tensor((real_imgs.shape[0], 1))\n\t\t\t\tsubstrahend.set_value(1.0)\n\t\t\t\tsubstrahend.to_device(self.dev)\n\t\t\t\tgrads, (d_loss_real, _) = self.dis_net.train(real_imgs, substrahend)\n\t\t\t\tfor (s, p ,g) in zip(self.dis_net.param_names(), self.dis_net.param_values(), grads):\n\t\t\t\t\topt_0.apply_with_lr(epoch, self.learning_rate, g, p, str(s), epoch)\n\t\t\t\tsubstrahend.set_value(-1.0)\n\t\t\t\tgrads, (d_loss_fake, _) = self.dis_net.train(fake_imgs, substrahend)\n\t\t\t\tfor (s, p ,g) in zip(self.dis_net.param_names(), self.dis_net.param_values(), grads):\n\t\t\t\t\topt_0.apply_with_lr(epoch, self.learning_rate, g, p, str(s), epoch)\n\t\t\t\td_loss = d_loss_real + d_loss_fake\n\t\t\t\n\t\t\tfor g_step in range(self.g_steps): \n\t\t\t\tnoise = tensor.Tensor((self.batch_size, self.noise_size))\n\t\t\t\tnoise.uniform(-1, 1)\n\t\t\t\tnoise.to_device(self.dev)\n\t\t\t\tsubstrahend = tensor.Tensor((real_imgs.shape[0], 1))\n\t\t\t\tsubstrahend.set_value(0.0)\n\t\t\t\tsubstrahend.to_device(self.dev)\n\t\t\t\tgrads, (g_loss, _) = self.combined_net.train(noise, substrahend)\n\t\t\t\tfor (s, p ,g) in zip(self.gen_net.param_names(), self.gen_net.param_values(), grads):\n\t\t\t\t\topt_1.apply_with_lr(epoch, self.learning_rate, g, p, str(s), epoch)\n\t\t\t\n\t\t\tif epoch % self.interval == 0:\n\t\t\t\tself.save_image(epoch)\n\t\t\t\tprint_log('The {} epoch, G_LOSS: {}, D_LOSS: {}'.format(epoch, g_loss, d_loss))\n\n\tdef save_image(self, epoch):\n\t\trows = 5\n\t\tcols = 5\n\t\tchannels = self.channels\n\t\tnoise = tensor.Tensor((rows*cols*channels, self.noise_size))\n\t\tnoise.uniform(-1,1)\n\t\tnoise.to_device(self.dev)\n\t\tgen_imgs = self.gen_net.forward(flag=False, x=noise)\n\t\tgen_imgs = tensor.to_numpy(gen_imgs)\n\t\tshow_imgs = np.reshape(gen_imgs, (gen_imgs.shape[0], self.rows, self.cols, self.channels))\n\t\tfig, axs = plt.subplots(rows, cols)\n\t\tcnt = 0\n\t\tfor r in range(rows):\n\t\t\tfor c in range(cols):\n\t\t\t\taxs[r,c].imshow(show_imgs[cnt, :, :, 0], cmap='gray')\n\t\t\t\taxs[r,c].axis('off')\n\t\t\t\tcnt += 1\n\t\tfig.savefig(\"{}{}.png\".format(self.file_dir, epoch))\n\t\tplt.close()\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Train GAN over MNIST')\n\tparser.add_argument('filepath', type=str, help='the dataset path')\n\tparser.add_argument('--use_gpu', action='store_true')\n\targs = parser.parse_args()\n\t\n\tif args.use_gpu:\n\t\tprint('Using GPU')\n\t\tdev = device.create_cuda_gpu()\n\t\tlayer.engine = 'cudnn'\n\telse:\n\t\tprint('Using CPU')\n\t\tdev = device.get_default_device()\n\t\tlayer.engine = 'singacpp'\n\n\tif not os.path.exists('lsgan_images/'):\n\t\tos.makedirs('lsgan_images/')\n\n\trows = 28\n\tcols = 28\n\tchannels = 1\n\tnoise_size = 100\n\thidden_size = 128\n\tbatch = 128\n\tinterval = 1000\n\tlearning_rate = 0.001\n\tepochs = 1000000\n\td_steps = 3\n\tg_steps = 1\n\tdataset_filepath = 'mnist.pkl.gz'\n\tfile_dir = 'lsgan_images/'\n\tlsgan = LSGAN(dev, rows, cols, channels, noise_size, hidden_size, batch, interval, \n\t\tlearning_rate, epochs, d_steps, g_steps, dataset_filepath, file_dir)\n\tlsgan.train()","sub_path":"examples/gan/lsgan.py","file_name":"lsgan.py","file_ext":"py","file_size_in_byte":8405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"95027745","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 14 19:10:39 2019\r\n\r\n@author: Sneha\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Apr 21 11:57:42 2019\r\n\r\n@author: Sneha\r\n\"\"\"\r\n\r\nimport random\r\nimport math\r\nimport copy\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nfrom IPython import get_ipython\r\nget_ipython().run_line_magic('matplotlib','qt')\r\nshow_animation =False\r\n\r\n\r\nclass RRT():\r\n \"\"\"\r\n Class for RRT Planning\r\n \"\"\"\r\n\r\n def __init__(self, start, goal, obstacleList, randArea,\r\n expandDis=0.1, goalSampleRate=5, maxIter=30000):\r\n \"\"\"\r\n Setting Parameter\r\n start:Start Position [x,y]\r\n goal:Goal Position [x,y]\r\n obstacleList:obstacle Positions [[x,y,size],...]\r\n randArea:Ramdom Samping Area [min,max]\r\n \"\"\"\r\n self.start = Node(start[0], start[1])\r\n self.end = Node(goal[0], goal[1])\r\n self.randx = randArea[0]\r\n self.randy = randArea[1]\r\n self.expandDis = expandDis\r\n self.goalSampleRate = goalSampleRate\r\n self.maxIter = maxIter\r\n self.obstacleList = obstacleList\r\n\r\n def Planning(self,n,circles,rectangles, animation=True):\r\n \"\"\"\r\n Pathplanning\r\n animation: flag for animation on or off\r\n \"\"\"\r\n\r\n self.nodeList = [self.start]\r\n for i in range(self.maxIter):\r\n rnd = self.get_random_point()\r\n nind = self.GetNearestListIndex(self.nodeList, rnd)\r\n\r\n newNode = self.change_course(rnd, nind)\r\n # print(newNode.cost)\r\n# if (np.abs(newNode.x - self.end.x)< (0.1) and np.abs(newNode.y - self.end.y)< (0.1)):\r\n# break;\r\n if self.verify_node(n,newNode, self.obstacleList):\r\n# print('true')\r\n nearinds = self.find_near_nodes(newNode)\r\n newNode = self.select_parent(n,newNode, nearinds)\r\n self.nodeList.append(newNode)\r\n self.rewire(n,newNode, nearinds)\r\n# else:\r\n# print('False')\r\n if animation and i % 1000 == 0:\r\n self.DrawGraph(n,circles,rectangles,rnd)\r\n\r\n # generate coruse\r\n lastIndex = self.get_best_last_index()\r\n if lastIndex is None:\r\n return None\r\n path = self.gen_final(lastIndex)\r\n print(len(self.nodeList))\r\n return path\r\n\r\n def select_parent(self,n, newNode, nearinds):\r\n if not nearinds:\r\n return newNode\r\n\r\n dlist = []\r\n for i in nearinds:\r\n dx = newNode.x - self.nodeList[i].x\r\n dy = newNode.y - self.nodeList[i].y\r\n d = math.sqrt(dx ** 2 + dy ** 2)\r\n theta = math.atan2(dy, dx)\r\n if self.check_collide(n,self.nodeList[i], theta, d):\r\n dlist.append(self.nodeList[i].cost + d)\r\n else:\r\n dlist.append(float(\"inf\"))\r\n\r\n mincost = min(dlist)\r\n minind = nearinds[dlist.index(mincost)]\r\n\r\n if mincost == float(\"inf\"):\r\n print(\"mincost is inf\")\r\n return newNode\r\n\r\n newNode.cost = mincost\r\n newNode.parent = minind\r\n\r\n return newNode\r\n\r\n def change_course(self, rnd, nind):\r\n\r\n # expand tree\r\n nearestNode = self.nodeList[nind]\r\n \r\n theta = math.atan2(rnd[1] - nearestNode.y, rnd[0] - nearestNode.x)\r\n newNode = Node(rnd[0], rnd[1])\r\n currentDistance = math.sqrt(\r\n (rnd[1] - nearestNode.y) ** 2 + (rnd[0] - nearestNode.x) ** 2)\r\n # Find a point within expandDis of nind, and closest to rnd\r\n if currentDistance <= self.expandDis:\r\n pass\r\n else:\r\n newNode.x = nearestNode.x + self.expandDis * math.cos(theta)\r\n newNode.y = nearestNode.y + self.expandDis * math.sin(theta)\r\n newNode.cost = float(\"inf\")\r\n newNode.parent = None\r\n return newNode\r\n\r\n def get_random_point(self):\r\n\r\n if random.randint(0, 100) > self.goalSampleRate:\r\n rnd = [random.uniform(self.randx[0], self.randx[1]),\r\n random.uniform(self.randy[0], self.randy[1])]\r\n else: # goal point sampling\r\n rnd = [self.end.x, self.end.y]\r\n\r\n return rnd\r\n\r\n def get_best_last_index(self):\r\n\r\n disglist = [self.calc_dist_to_goal(\r\n node.x, node.y) for node in self.nodeList]\r\n goalinds = [disglist.index(i) for i in disglist if i <= self.expandDis]\r\n\r\n if not goalinds:\r\n return None\r\n\r\n mincost = min([self.nodeList[i].cost for i in goalinds])\r\n for i in goalinds:\r\n if self.nodeList[i].cost == mincost:\r\n return i\r\n\r\n return None\r\n\r\n def gen_final(self, goalind):\r\n path = [[self.end.x, self.end.y]]\r\n while self.nodeList[goalind].parent is not None:\r\n node = self.nodeList[goalind]\r\n path.append([node.x, node.y])\r\n goalind = node.parent\r\n path.append([self.start.x, self.start.y])\r\n return path\r\n\r\n def calc_dist_to_goal(self, x, y):\r\n return np.linalg.norm([x - self.end.x, y - self.end.y])\r\n\r\n def find_near_nodes(self, newNode):\r\n nnode = len(self.nodeList)\r\n r = 50.0 * math.sqrt((math.log(nnode) / nnode))\r\n # r = self.expandDis * 5.0\r\n dlist = [(node.x - newNode.x) ** 2 +\r\n (node.y - newNode.y) ** 2 for node in self.nodeList]\r\n nearinds = [dlist.index(i) for i in dlist if i <= r ** 2]\r\n return nearinds\r\n\r\n def rewire(self,n, newNode, nearinds):\r\n nnode = len(self.nodeList)\r\n for i in nearinds:\r\n nearNode = self.nodeList[i]\r\n\r\n dx = newNode.x - nearNode.x\r\n dy = newNode.y - nearNode.y\r\n d = math.sqrt(dx ** \r\n 2 + dy ** 2)\r\n\r\n scost = newNode.cost + d\r\n\r\n if nearNode.cost > scost:\r\n theta = math.atan2(dy, dx)\r\n if self.check_collide(n,nearNode, theta, d):\r\n nearNode.parent = nnode - 1\r\n nearNode.cost = scost\r\n\r\n def check_collide(self,n, nearNode, theta, d):\r\n\r\n tmpNode = copy.deepcopy(nearNode)\r\n\r\n for i in range(int(d / self.expandDis)):\r\n tmpNode.x += self.expandDis * math.cos(theta)\r\n tmpNode.y += self.expandDis * math.sin(theta)\r\n if not self.verify_node(n,tmpNode, self.obstacleList):\r\n return False\r\n\r\n return True\r\n\r\n def DrawGraph(self,n,circles,rectangles, rnd=None):\r\n \"\"\"\r\n Draw Graph\r\n \"\"\"\r\n plt.clf()\r\n if rnd is not None:\r\n plt.plot(rnd[0], rnd[1], \"^k\")\r\n for node in self.nodeList:\r\n if node.parent is not None:\r\n plt.plot([node.x, self.nodeList[node.parent].x], [\r\n node.y, self.nodeList[node.parent].y], \"-g\")\r\n# plt.axis([0,0,250,150])\r\n plt.xticks(np.arange(-12.5,12.5,1))\r\n plt.yticks(np.arange(-7.5,7.5,1))\r\n plt.plot(self.start.x, self.start.y, \"xr\")\r\n plt.plot(self.end.x, self.end.y, \"xr\")\r\n# for (ox, oy, size) in self.obstacleList:\r\n# plt.plot(ox, oy, \"ok\", ms=30 * size)\r\n# fig, ax = plt.subplots()\r\n \r\n for i in range(5):\r\n# print(i[0])\r\n# print(i[3],i[4])\r\n# print(i[3])\r\n for j in range(n):\r\n# pri\r\n plt.fill(circles[3][j],circles[4][j], color = 'b' )\r\n# plt.fill(i[3],i[4], color = 'r' )\r\n for i in (rectangles):\r\n# \r\n for k in i[0]:\r\n plt.fill(k[0],k[1], color = i[1])\r\n \r\n \r\n# ax.legend()\r\n# ax.grid(color=(0,0,0), linestyle='-', linewidth=1) \r\n \r\n## plt.axis([0,0,250,150])\r\n# plt.xticks(np.arange(0,25,2))\r\n# plt.yticks(np.arange(0,15,1))\r\n# plt.grid(True)\r\n plt.pause(0.01)\r\n\r\n def GetNearestListIndex(self, nodeList, rnd):\r\n dlist = [(node.x - rnd[0]) ** 2 + (node.y - rnd[1])\r\n ** 2 for node in nodeList]\r\n minind = dlist.index(min(dlist))\r\n\r\n return minind\r\n\r\n def verify_node(self,n, node, obstacleList):\r\n# global radius,clearance\r\n res=1\r\n radius=0.35/2\r\n clearance=0.1\r\n x=node.x\r\n y=node.y\r\n \r\n d=(radius)+(clearance)\r\n \r\n circ=[]\r\n for i in range(n):\r\n# print(obstacleList[1][0])\r\n circ.append(((x-(obstacleList[1][1][i]/res))*(x-(obstacleList[1][1][i]/res))+ (y-(obstacleList[1][2][i]/res))*(y-(obstacleList[1][2][i]/res)) - ((obstacleList[1][0][i]/res)+d)*((obstacleList[1][0][i]/res)+d)))\r\n# c2= ((x-(-1.17/res))*(x-(-1.17/res))+ (y-(2.31/res))*(y-(2.31/res)) - ((0.81/res)+d)*((0.81/res)+d))\r\n# c3= ((x-(-1.17/res))*(x-(-1.17/res))+ (y-(-2.31/res))*(y-(-2.31/res)) - ((0.81/res)+d)*((0.81/res)+d))\r\n# c4= ((x-(-1.65/res))*(x-(-1.65/res))+ (y-(-4.6/res))*(y-(-4.6/res))- ((0.81/res)+d)*((0.81/res)+d))\r\n# #Capsule\r\n# u=-3.2516 #x-position of the center\r\n# v=3.2505 #y-position of the center\r\n# \r\n# a=(3.1968-1.599)/2 #radius on the x-axis\r\n# b=1.599/2 #radius on the y-axis\r\n# r = [u-a, u+a,u+a, u-a]\r\n# s = [v-b, v-b, v+b,v+b]\r\n# \r\n# u1=u-a\r\n# u2=u+a\r\n# e1= ((x-(u1/res))*(x-(u1/res))+ (y-(v/res))*(y-(v/res)) - ((b/res)+d)*((b/res)+d))\r\n# e2= ((x-(u2/res))*(x-(u2/res))+ (y-(v/res))*(y-(v/res)) - ((b/res)+d)*((b/res)+d))\r\n exist=True\r\n if (x>=(-12.5)+d and x<=(12.5/res)-d and y>=(-7.5/res)+d and y<=(7.5/res)-d):\r\n for c in obstacleList[0]:\r\n \r\n if( x>=c[0][0]-d and x<=c[0][1]+d and y>=c[1][0]-d and y<=c[1][2]+d):\r\n# print('1')\r\n exist = False \r\n if(exist is True):\r\n for j in circ:\r\n if(j<=0):\r\n exist=False\r\n# if( x>=((r[0]/res)-d) and x<=((r[1]/res)+d) and y>=((s[0]/res)-d) and y<=((s[2]/res)+d)):\r\n# exist = False\r\n# print('2')\r\n# elif (e1<=0):\r\n# exist=False\r\n# print('3')\r\n# elif (e2<=0):\r\n# exist=False \r\n# elif (c1<=0):\r\n# exist=False\r\n# elif (c2<=0):\r\n# exist=False\r\n# elif (c3<=0):\r\n# exist=False\r\n# elif (c4<=0):\r\n# exist=False \r\n# else:\r\n# exist=True\r\n \r\n else:\r\n exist=False\r\n \r\n return exist\r\n\r\n\r\nclass Node():\r\n \"\"\"\r\n RRT Node\r\n \"\"\"\r\n\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n self.cost = 0.0\r\n self.parent = None\r\n\r\ndef getxs_ys(xs,ys,n):\r\n radius=0\r\n# global resolution,radius,clearance,init,final\r\n t = np.linspace(0, 2*np.pi, 100)\r\n# res=resolution\r\n resolution=1\r\n# n=20\r\n r=[]\r\n x=[]\r\n y=[]\r\n p=[]\r\n q=[]\r\n# #Circles\r\n for i in range(n):\r\n rad=random.uniform(0.1,0.2)\r\n x1=random.uniform(-12.5,12.5)\r\n y1=random.uniform(-7.5,7.5)\r\n r.append(rad)\r\n x.append(x1) \r\n y.append(y1) \r\n p.append(x1+rad*np.cos(t))\r\n q.append(y1+rad*np.sin(t))\r\n# plt.fill((x1+rad*np.cos(t)),(y1+rad*np.sin(t)),'r',edgecolor='b')\r\n circles=[r,x,y,p,q]\r\n# print(r,x,y)\r\n# #Circle 1\r\n# r1 = (0.81/2)/resolution\r\n# n1=-1.65/resolution #x-position of the center\r\n# m1=4.6/resolution #radius on the y-axis\r\n# p1=n1+r1*np.cos(t)\r\n# q1=m1+r1*np.sin(t)\r\n# for i in p1:\r\n# xs.append(i)\r\n# for i in q1:\r\n# ys.append(i)\r\n# #Circle 2\r\n# r2 =( 0.81/2)/resolution\r\n# n2=-1.17 /resolution #x-position of the center\r\n# m2=2.31/resolution #radius on the y-axis\r\n# p2=n2+r2*np.cos(t)\r\n# q2=m2+r2*np.sin(t)\r\n# for i in p2:\r\n# xs.append(i)\r\n# for i in q2:\r\n# ys.append(i)\r\n# #Circle 3\r\n# r3 = (0.81/2)/resolution\r\n# n3=-1.17/resolution #x-position of the center\r\n# m3=-2.31/resolution #radius on the y-axis\r\n# p3=n3+r3*np.cos(t)\r\n# q3=m3+r3*np.sin(t)\r\n# for i in p3:\r\n# xs.append(i)\r\n# for i in q3:\r\n# ys.append(i)\r\n# #Circle 4\r\n# r4 = (0.81/2)/resolution\r\n# n4=-1.65 /resolution #x-position of the center\r\n# m4=-4.6 /resolution #radius on the y-axis\r\n# p4=n4+r4*np.cos(t)\r\n# q4=m4+r4*np.sin(t)\r\n# for i in p4:\r\n# xs.append(i)\r\n# for i in q4:\r\n# ys.append(i)\r\n# #Capsule\r\n# u=-3.2516/resolution #x-position of the center\r\n# v=3.2505/resolution #y-position of the center\r\n# \r\n# a=(((3.1968/resolution)-(1.599/resolution))/2) #radius on the x-axis\r\n# b=(1.599/2)/resolution #radius on the y-axis\r\n# r = [u-a, u+a,u+a, u-a]\r\n# s = [v-b, v-b, v+b,v+b]\r\n# for i in r:\r\n# xs.append(i)\r\n# for i in s:\r\n# ys.append(i)\r\n# u1=u-a\r\n# u2=u+a\r\n# r1=u1+b*np.cos(t)\r\n# s1=v+b*np.sin(t)\r\n# r2=u2+b*np.cos(t)\r\n# s2=v+b*np.sin(t)\r\n# for i in r1:\r\n# xs.append(i)\r\n# for i in s1:\r\n# ys.append(i)\r\n# for i in r2:\r\n# xs.append(i)\r\n# for i in s2:\r\n# ys.append(i)\r\n# #Rectangles\r\n rectangles =[[-11.5,6,0.1,3],[-10.5,0.5,0.1,6],[-7,4,0.1,7],\r\n [-3.7,-1,1.5,0.1],[-4.5,-1,0.1,3],[0.45,5.5,4,0.1],\r\n [2.5,5.5,0.1,4],[7.5,5,0.1,5],[11,4.5,3,0.1],\r\n [11.25,-1.5,2.5,0.1],[9,-4.575,2,0.1],[9.95,-2.5,0.1,4],\r\n [5,-6,0.1,3],[4.3,-4.45,1.5,0.1],[-3,-6.5,0.1,2],\r\n [-1.55,-5.45,3,0.1],[0,-1.5,0.1,8],[1.55,-1.5,3,0.1],\r\n [-1.3,2.5,2.5,0.1],[-2.5,3.55,0.1,2],[4.05,0.5,2,0.1],\r\n [3,-0.45,0.1,2],[5,2.05,0.1,3],[-10.5,3.55,4,0.1],\r\n [-9.5,-5.25,0.1,1.5],[-7.5,-3.5,0.1,2],[-9.5,-6.05,2,0.1],\r\n [-9.55,-4.45,4,0.1],[-9.05,-2.55,3,0.1],[-7.7,0.45,1.5,0.1],[-8.54,4.5,0.1,2]]\r\n for i in range(len(rectangles)):\r\n for j in range(4):\r\n rectangles[i][j]=rectangles[i][j]/resolution\r\n\r\n# fig, ax = plt.subplots()\r\n## \r\n##\r\n# ax.fill(r,s,'r',edgecolor='b')\r\n# ax.fill(r1,s1,'r')\r\n# ax.fill(r2,s2,'r')\r\n# ax.fill(p1,q1,'r',edgecolor='b')\r\n# ax.fill(p2,q2,'r',edgecolor='b')\r\n# ax.fill(p3,q3,'r',edgecolor='b')\r\n# ax.fill(p4,q4,'r',edgecolor='b')\r\n # ax.fill(uelpx, uelpy,'b')\r\n rectangle_corner=[]\r\n for i in (rectangles):\r\n\r\n x = [i[0]-(i[2]/2), i[0]+(i[2]/2),i[0]+(i[2]/2), i[0]-(i[2]/2)]\r\n y = [i[1]-(i[3]/2), i[1]-(i[3]/2), i[1]+(i[3]/2),i[1]+(i[3]/2)]\r\n for j in x:\r\n xs.append(j)\r\n for j in y:\r\n ys.append(j)\r\n rectangle_corner.append([x,y])\r\n# ax.fill(x, y,'r',edgecolor='b')\r\n# ucir1x=[]\r\n# ucir1y=[]\r\n# for i in range(len(p1)):\r\n# ucir1x.append(p1[i]+radius*np.cos(t))\r\n# ucir1y.append(q1[i]+radius*np.sin(t))\r\n# ucir2x=[]\r\n# ucir2y=[]\r\n# for i in range(len(p2)):\r\n# ucir2x.append(p2[i]+radius*np.cos(t))\r\n# ucir2y.append(q2[i]+radius*np.sin(t))\r\n# ucir3x=[]\r\n# ucir3y=[]\r\n# for i in range(len(p3)):\r\n# ucir3x.append(p3[i]+radius*np.cos(t))\r\n# ucir3y.append(q3[i]+radius*np.sin(t))\r\n# ucir4x=[]\r\n# ucir4y=[]\r\n# for i in range(len(p4)):\r\n# ucir4x.append(p4[i]+radius*np.cos(t))\r\n# ucir4y.append(q4[i]+radius*np.sin(t))\r\n# ucap1x=[]\r\n# ucap1y=[]\r\n# for i in range(len(r1)):\r\n# ucap1x.append(r1[i]+radius*np.cos(t))\r\n# ucap1y.append(s1[i]+radius*np.sin(t))\r\n# ucap2x=[]\r\n# ucap2y=[]\r\n# for i in range(len(r2)):\r\n# ucap2x.append(r2[i]+radius*np.cos(t))\r\n# ucap2y.append(s2[i]+radius*np.sin(t))\r\n# uboxx=[]\r\n# uboxy=[]\r\n# for i in range(4):\r\n# uboxx.append(r[i]+radius*np.cos(t))\r\n# uboxy.append(s[i]+radius*np.sin(t) )\r\n urecBoxes=[]\r\n \r\n for i in rectangle_corner:\r\n \r\n uboxrx=[] \r\n uboxry=[]\r\n \r\n for j in range(4):\r\n \r\n uboxrx.append(i[0][j]+radius*np.cos(t))\r\n uboxry.append(i[1][j]+radius*np.sin(t) )\r\n urecBoxes.append([uboxrx,uboxry])\r\n\r\n \r\n return rectangle_corner,circles,[[urecBoxes,'b'],[rectangle_corner,'r']]\r\n else:\r\n return \"Please enter both Initial and Final Points\",[],[]\r\n\r\ndef main():\r\n start = time.time()\r\n print(\"Start \" + __file__)\r\n\r\n # ====Search Path with RRT====\r\n ox, oy = [], []\r\n n=10\r\n rect_corners,circles,rectangles=getxs_ys(ox,oy,n)\r\n \r\n# obstacleList = [\r\n## (5, 5, 1),\r\n## (5, 5.5, 1),\r\n## (5, 6, 1)\r\n## ,\r\n## (3, 6, 2),\r\n## (3, 8, 2),\r\n## (3, 10, 2),\r\n## (7, 5, 2),\r\n## (9, 5, 2)\r\n# ] # [x,y,size(radius)]\r\n# for i in range(4):\r\n## for j in ([2]):\r\n## obstacleList.append((0+(i/j),4,0.5))\r\n# obstacleList.append((0+(i),4,0.5))\r\n# for i in range(2):\r\n## for j in ([2]):\r\n## obstacleList.append((0+(i/j),8,0.5))\r\n# obstacleList.append((0+(i),8,0.5))\r\n# obstacleList.append((0+(i+0.5),8,0.5))\r\n# for i in range(2):\r\n## for j in ([2]):\r\n## obstacleList.append((3+(i/j),6,0.5))\r\n# obstacleList.append((3+(i),6,0.5))\r\n# obstacleList.append((3+(i+0.5),6,0.5))\r\n# for i in range(9):\r\n## for j in ([2]):\r\n## obstacleList.append((4,15-(i/j),0.5))\r\n# obstacleList.append((4,15-i,0.5))\r\n# obstacleList.append((4,15-(i+0.5),0.5))\r\n# for i in range(6):\r\n## for j in ([2]):\r\n## obstacleList.append((8,15-(i/j),0.5))\r\n# obstacleList.append((8,15-i,0.5))\r\n# obstacleList.append((8,15-(i+0.5),0.5))\r\n# for i in range(6):\r\n## for j in ([2]):\r\n## obstacleList.append((8,0+(i/j),0.5))\r\n# obstacleList.append((8,0+i,0.5))\r\n# obstacleList.append((8,0+i+0.5,0.5))\r\n# for i in range(4):\r\n## for j in ([2]):\r\n## obstacleList.append((25-(i/j),7,0.5))\r\n# obstacleList.append((25-(i),7,0.5))\r\n# obstacleList.append((25-(i+0.5),7,0.5))\r\n# # Set Initial parameters\r\n rrt = RRT(start=[-9,-1], goal=[1.5,6.8],\r\n randArea=[[-12.5, 12.5],[-7.5,7.5]], obstacleList=[rect_corners,circles])\r\n path = rrt.Planning(n,circles,rectangles,animation=show_animation)\r\n\r\n if path is None:\r\n print(\"Cannot find path\")\r\n else:\r\n print(\"found path!!\")\r\n print('Path: ',path)\r\n # Draw final path\r\n if show_animation:\r\n rrt.DrawGraph(n,circles,rectangles)\r\n plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')\r\n plt.grid(True)\r\n plt.pause(0.01) # Need for Mac\r\n plt.show()\r\n end = time.time()\r\n print('Execution time - ', end - start)\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"Comparative Study of Planning Algorithms in Maze Environment/Codes/RRTStar/rrtstr.py","file_name":"rrtstr.py","file_ext":"py","file_size_in_byte":19167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"315950412","text":"'''\nResnet18 (with some change in full connected layer) Estimator for X-ray image classification.\n'''\nimport numpy as np\nimport tensorflow as tf\nimport time\nimport random\n\nIMG_WIDTH = 600\nIMG_HEIGHT = 600\nIMG_CHANNEL = 1\nL2_RATE = 20.0\nBATCH_SIZE = 32\nTRAINING_STEP = 2000\nUSE_FOCAL = True\n\n\ndef flip(x: tf.Tensor) -> tf.Tensor:\n \"\"\"Flip augmentation\n\n Args:\n x: Image to flip\n\n Returns:\n Augmented image\n \"\"\"\n x = tf.image.random_flip_left_right(x)\n x = tf.image.random_flip_up_down(x)\n\n return x\n\n\ndef rotate(x: tf.Tensor) -> tf.Tensor:\n \"\"\"Rotation augmentation\n\n Args:\n x: Image\n\n Returns:\n Augmented image\n \"\"\"\n\n return tf.image.rot90(x, tf.random_uniform(shape=[], minval=0, maxval=4, dtype=tf.int32))\n\n\ndef focal_loss(labels, logits, gamma=2):\n y_pred = tf.nn.softmax(logits, dim=-1) # [BATCH_SIZE,num_classes]\n labels = tf.one_hot(labels, depth=y_pred.shape[1])\n loss = -labels * ((1 - y_pred) ** gamma) * tf.log(tf.clip_by_value(y_pred, 1e-10, 1.0))\n loss = tf.reduce_mean(loss)\n return loss\n\n\ndef resnet_block(inputs, num_filters, kernel_size, strides, activation='relu'):\n x = tf.layers.Conv2D(num_filters, kernel_size=kernel_size, strides=strides, \n padding='same', kernel_initializer='he_normal',\n kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_RATE))(inputs)\n x = tf.layers.BatchNormalization()(x)\n if(activation):\n x = tf.nn.relu(x)\n return x\n\n\ndef cnn_model_fn(features, labels, mode):\n \"\"\"The model function for the network.\"\"\"\n # Input feature x should be of shape (BATCH_SIZE, image_width, image_height, color_channels).\n # Image shape should be checked for safety reasons at early stages, and could be removed\n # before training actually starts.\n # assert features['x'].shape[1:] == (\n # IMG_WIDTH, IMG_HEIGHT, IMG_CHANNEL), 'Image size does not match.'\n # Concat front image and side image for input image \n img = tf.concat([features['side_img'], features['front_img']], -1)\n inputs = 2 * (tf.to_float(img, name='input_to_float') / 256) - 1\n\n # conv1\n x = resnet_block(inputs, 64, [7, 7], 2)\n\n # conv2\n x = tf.layers.MaxPooling2D([3, 3], 2, 'same')(x)\n for i in range(2):\n a = resnet_block(x, 64, [3, 3], 1)\n b = resnet_block(a, 64, [3,3], 1, activation=None)\n x = tf.math.add(x, b)\n x = tf.nn.relu(x)\n \n # conv3\n a = resnet_block(x, 128, [1, 1], 2)\n b = resnet_block(a, 128, [3, 3], 1, activation=None)\n x = tf.layers.Conv2D(128, kernel_size=[1, 1],strides=2, padding = 'same',\n kernel_initializer='he_normal', kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_RATE))(x)\n x = tf.math.add(x, b)\n x = tf.nn.relu(x)\n\n a = resnet_block(x, 128, [3, 3], 1)\n b = resnet_block(a, 128, [3, 3], 1, activation=None)\n #x=tf.keras.layers.add([x,b])\n x = tf.math.add(x, b)\n x = tf.nn.relu(x)\n\n # conv4\n a = resnet_block(x, 256, [1, 1], 2)\n b = resnet_block(a, 256, [3, 3], 1, activation=None)\n x = tf.layers.Conv2D(256, kernel_size=[1, 1], strides=2, padding='same',\n kernel_initializer='he_normal', kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_RATE))(x)\n #x=tf.keras.layers.add([x,b])\n x = tf.math.add(x, b)\n x = tf.nn.relu(x)\n\n a = resnet_block(x, 256, [3, 3], 1)\n b = resnet_block(a, 256, [3, 3], 1, activation=None)\n #x=tf.keras.layers.add([x,b])\n x = tf.math.add(x, b)\n x = tf.nn.relu(x)\n\n # conv5\n a = resnet_block(x, 512, [1, 1], 2)\n b = resnet_block(a, 512, [3, 3], 1, activation=None)\n x = tf.layers.Conv2D(512, kernel_size=[1, 1], strides=2, padding='same',\n kernel_initializer='he_normal', kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_RATE))(x)\n #x=tf.keras.layers.add([x,b])\n x = tf.math.add(x, b)\n x = tf.nn.relu(x)\n\n a = resnet_block(x, 512, [3, 3], 1)\n b = resnet_block(a, 512, [3, 3], 1, activation=None)\n #x=tf.keras.layers.add([x,b])\n x = tf.math.add(x, b)\n x = tf.nn.relu(x)\n x = tf.layers.AveragePooling2D(pool_size=10, strides=3, data_format='channels_last')(x)\n\n # Flatten tensor into a batch of vectors\n y = tf.layers.Flatten()(x)\n\n # Use sex, weight and height infomation to help model predict more accuracy\n sex = features['sex'] # tf.expand_dims(features['sex'], 1)\n sex = tf.one_hot(sex, 2, 1.0, 0.0, dtype=tf.float32)\n height = tf.expand_dims(features['height'], 1)\n weight = tf.expand_dims(features['weight'], 1)\n more_info = tf.concat([sex, height, weight], -1)\n # Pass a dense layer to make those information has a dimension comparable with feature map\n more_info = tf.layers.Dense(512, kernel_initializer='he_normal',\n kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_RATE))(more_info)\n more_info = tf.nn.relu(more_info)\n y = tf.concat([y, more_info], -1)\n # y = tf.concat([y, sex, height, weight], -1)\n y = tf.layers.Dense(1024, kernel_initializer='he_normal', \n kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_RATE))(y)\n y = tf.nn.relu(y)\n logits = tf.layers.Dense(17, kernel_initializer='he_normal', \n kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_RATE))(y)\n \n # Split predict logits, the first 8 for thigh, the rest 9 for shin\n logits_thigh = logits[:, :8]\n logits_shin = logits[:, 8:]\n\n # Prediction output\n probabilities_thigh = tf.nn.softmax(logits_thigh)\n predicted_thigh_classes = tf.argmax(logits_thigh, 1)\n predict_thigh_val_top3, predict_thigh_index_top3 = tf.nn.top_k(probabilities_thigh, k=3)\n\n probabilities_shin = tf.nn.softmax(logits_shin)\n predicted_shin_classes = tf.argmax(logits_shin, 1)\n predict_shin_val_top3, predict_shin_index_top3 = tf.nn.top_k(probabilities_shin, k=3)\n # Make prediction for PREDICATION mode.\n predictions_dict = {\n # 'probabilities_thigh': probabilities_thigh,\n 'Index of Picture': features['index'],\n 'Top3 Class of Thigh Bone': predict_thigh_index_top3,\n 'Top3 Probability of Thigh Bone': predict_thigh_val_top3,\n 'Label of Thigh Bone': features['thigh_bone'],\n # 'probabilities_shin': probabilities_shin,\n 'Top3 Class of Shin Bone': predict_shin_index_top3,\n 'Top3 Probability of Shin Bone': predict_shin_val_top3,\n 'Label of Shin Bone': features['shin_bone']\n }\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions_dict)\n\n label_thigh_tensor = tf.convert_to_tensor(labels['thigh_bone'], dtype=tf.int64)\n label_shin_tensor = tf.convert_to_tensor(labels['shin_bone'], dtype=tf.int64)\n # Caculate loss using mean squared error.\n # Sparse softmaxcrossentropy\n \n if USE_FOCAL:\n # Focal loss\n loss_thigh = focal_loss(label_thigh_tensor, logits_thigh)\n # pre_thigh_label = label_thigh_tensor - tf.cast(label_thigh_tensor > 0, tf.int64)\n # next_thigh_label = label_thigh_tensor + tf.cast(label_thigh_tensor < 7, tf.int64)\n # loss_thigh += 0.1 * focal_loss(pre_thigh_label, logits_thigh) + 0.1 * focal_loss(next_thigh_label, logits_thigh)\n loss_shin = focal_loss(label_shin_tensor, logits_shin)\n # pre_shin_label = label_shin_tensor - tf.cast(label_shin_tensor > 0, tf.int64)\n # next_shin_label = label_shin_tensor + tf.cast(label_shin_tensor < 8, tf.int64)\n # loss_shin += 0.1 * focal_loss(pre_shin_label, logits_shin) + 0.1 * focal_loss(next_shin_label, logits_shin)\n else:\n # Sparse softmaxcrossentropy\n loss_thigh = tf.losses.sparse_softmax_cross_entropy(\n labels=label_thigh_tensor, logits=logits_thigh)\n loss_shin = tf.losses.sparse_softmax_cross_entropy(\n labels=label_shin_tensor, logits=logits_shin)\n\n loss = loss_thigh + loss_shin\n # Regularization loss\n reg_loss = tf.losses.get_total_loss()\n loss += reg_loss\n\n # Configure the train OP for TRAIN mode.\n if mode == tf.estimator.ModeKeys.TRAIN:\n global_steps = tf.train.get_global_step()\n # Decay learning rate\n # learning_rate = tf.train.exponential_decay(0.0001, global_steps, 10, 0.9, staircase=False)\n optimizer = tf.train.AdamOptimizer(learning_rate=0.0001)\n train_op = optimizer.minimize(\n loss=loss,\n global_step=tf.train.get_global_step())\n return tf.estimator.EstimatorSpec(\n mode=mode,\n loss=loss,\n train_op=train_op,\n export_outputs={'marks': tf.estimator.export.RegressionOutput(logits)})\n\n # Add evaluation metrics (for EVAL mode)\n accuracy_thigh = tf.metrics.accuracy(\n labels=label_thigh_tensor,\n predictions=predicted_thigh_classes)\n accuracy_in_top_3_thigh = tf.metrics.mean(\n tf.cast(tf.nn.in_top_k(probabilities_thigh, label_thigh_tensor, 3), tf.float32))\n accuracy_shin = tf.metrics.accuracy(\n labels=label_shin_tensor,\n predictions=predicted_shin_classes)\n accuracy_in_top_3_shin = tf.metrics.mean(\n tf.cast(tf.nn.in_top_k(probabilities_shin, label_shin_tensor, 3), tf.float32))\n eval_metric_ops = {\n 'Loss of Thigh Bone': tf.metrics.mean(loss_thigh),\n 'Loss of Shin Bone': tf.metrics.mean(loss_shin),\n 'Accuracy of Thigh Bone': accuracy_thigh,\n 'Top3 Accuracy of Thigh Bone': accuracy_in_top_3_thigh,\n 'Accuracy of Shin Bone': accuracy_shin,\n 'Top3 Accuracy of Shin Bone': accuracy_in_top_3_shin}\n return tf.estimator.EstimatorSpec(\n mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)\n\n\ndef _parse_function(record):\n \"\"\"Extract data from a `tf.Example` protocol buffer.\"\"\"\n keys_to_features = {\n 'index': tf.FixedLenFeature([], tf.int64), \n 'front_img': tf.FixedLenFeature([], tf.string),\n 'side_img': tf.FixedLenFeature([], tf.string),\n 'sex': tf.FixedLenFeature([], tf.int64),\n 'height': tf.FixedLenFeature([], tf.float32),\n 'weight': tf.FixedLenFeature([], tf.float32),\n 'direction': tf.FixedLenFeature([], tf.int64),\n 'thigh_bone': tf.FixedLenFeature([], tf.int64),\n 'shin_bone': tf.FixedLenFeature([], tf.int64),\n }\n parsed_features = tf.parse_single_example(record, keys_to_features)\n\n # Extract features from single example\n # Front image\n front_image_decoded = tf.decode_raw(parsed_features['front_img'], tf.uint8)\n front_image_reshaped = tf.reshape(\n front_image_decoded, [IMG_WIDTH, IMG_HEIGHT, IMG_CHANNEL])\n # Side image\n side_image_decoded = tf.decode_raw(parsed_features['side_img'], tf.uint8)\n side_image_reshaped = tf.reshape(\n side_image_decoded, [IMG_WIDTH, IMG_HEIGHT, IMG_CHANNEL])\n \n features = {'index': parsed_features['index'],\n 'front_img': front_image_reshaped,\n 'side_img': side_image_reshaped,\n 'sex': parsed_features['sex'],\n 'height': parsed_features['height'],\n 'weight': parsed_features['weight'],\n 'direction': parsed_features['direction'],\n 'thigh_bone': parsed_features['thigh_bone'], # just for prediction ouput, DO NOT use it for training\n 'shin_bone': parsed_features['shin_bone'] # just for prediction ouput, DO NOT use it for training\n }\n labels = {'thigh_bone':parsed_features['thigh_bone'],\n 'shin_bone':parsed_features['shin_bone']}\n\n return features, labels\n\n\ndef train_input_fn(record_file, BATCH_SIZE):\n \"\"\"Input function required for TensorFlow Estimator.\"\"\"\n dataset = tf.data.TFRecordDataset(record_file)\n\n # Use `Dataset.map()` to build a pair of a feature dictionary and a label\n # tensor for each example.\n dataset = dataset.map(_parse_function)\n dataset = dataset.shuffle(1000).repeat().batch(BATCH_SIZE)\n\n # Make dataset iteratable.\n iterator = dataset.make_one_shot_iterator()\n\n # `features` is a dictionary in which each value is a batch of values for\n # that feature; `labels` is a batch of labels.\n features, labels = iterator.get_next()\n\n features['side_img'] = tf.to_float(features['side_img'])\n features['front_img'] = tf.to_float(features['front_img'])\n augmentations = [flip, rotate]\n for f in augmentations:\n if random.random() > 0.75:\n features['side_img'] = f(features['side_img'])\n features['front_img'] = f(features['front_img'])\n\n return features, labels\n\n\ndef eval_and_predict_input_fn(record_file, BATCH_SIZE, mod='eval'):\n \"\"\"Input function required for TensorFlow Estimator.\"\"\"\n dataset = tf.data.TFRecordDataset(record_file)\n\n # Use `Dataset.map()` to build a pair of a feature dictionary and a label\n # tensor for each example.\n dataset = dataset.map(_parse_function)\n \n dataset = dataset.batch(BATCH_SIZE)\n \n # Make dataset iteratable.\n iterator = dataset.make_one_shot_iterator()\n\n # `features` is a dictionary in which each value is a batch of values for\n # that feature; `labels` is a batch of labels.\n features, labels = iterator.get_next()\n \n if mod == 'predict':\n return features\n else:\n return features, labels \n\n\ndef main(unused_argv):\n # Create the Estimator\n \"\"\"\n # gpu config\n session_config = tf.ConfigProto(\n log_device_placement=True, \n inter_op_parallelism_threads=0, \n intra_op_parallelism_threads=0, \n allow_soft_placement=True,\n device_count={'GPU': 0})\n session_config.gpu_options.per_process_gpu_memory_fraction = 0.99\n run_config = tf.estimator.RunConfig().replace(session_config=session_config)\n \"\"\"\n\n estimator = tf.estimator.Estimator(\n model_fn=cnn_model_fn, model_dir='./train') #, config=run_config)\n\n # Choose mode between Train, Evaluate and Predict\n mode_dict = {\n 'train': tf.estimator.ModeKeys.TRAIN,\n 'eval': tf.estimator.ModeKeys.EVAL,\n 'predict': tf.estimator.ModeKeys.PREDICT\n }\n\n # Training stage\n print('\\nStart to train model')\n start = time.time()\n estimator.train(\n input_fn=lambda: train_input_fn('./train_data.tfrecords', BATCH_SIZE), steps=TRAINING_STEP)\n end = time.time()\n print('End to train model')\n print('-' * 100)\n print(f'Training Time: {(end - start):.3f}sec!')\n print('-' * 100)\n\n # Export result as SavedModel.\n # estimator.export_savedmodel('./saved_model', serving_input_receiver_fn)\n\n # Evaluating stage\n print('\\nStart to evaluate model in training set')\n start = time.time()\n evaluation = estimator.evaluate(\n input_fn=lambda: eval_and_predict_input_fn('./train_data.tfrecords', BATCH_SIZE))\n end = time.time()\n print('End to evaluate model in training set')\n print('-' * 100)\n print(f'Eval time in training set: {(end - start):.3f}sec!')\n for key in evaluation:\n print('{}\\t{}'.format(key, evaluation[key]))\n print('-' * 100)\n\n print('\\nStart to evaluate model in validation set')\n start = time.time()\n evaluation = estimator.evaluate(input_fn=lambda: eval_and_predict_input_fn('./val_data.tfrecords', BATCH_SIZE))\n end = time.time()\n print('End to evaluate model in validation set')\n print('-' * 100)\n print(f'Eval Time in validation set: {(end - start):.3f}sec!')\n for key in evaluation:\n print('{}\\t{}'.format(key, evaluation[key]))\n print('-' * 100)\n \n predictions = estimator.predict(\n input_fn=lambda: eval_and_predict_input_fn('./val_data.tfrecords', BATCH_SIZE, 'predict'))\n # Print 10 of predictions\n print ('\\nInformation of the Predictions')\n for index, result in enumerate(predictions):\n print('-' * 100)\n for key in result:\n print ('key: {}\\t value: {}'.format(key, result[key]))\n print('-' * 100)\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"combine_train/augmentation.py","file_name":"augmentation.py","file_ext":"py","file_size_in_byte":15931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"75050992","text":"import paxos.essential as paxos\nimport logging\n\nclass Messenger (paxos.Messenger):\n proposers = {}\n acceptors = {}\n learners = {}\n queue = []\n\n processing = False\n\n def add_proposer(self, prop):\n self.proposers[prop.proposer_uid] = prop\n prop.messenger = self\n\n def add_acceptor(self, acc):\n self.acceptors[acc.acceptor_uid] = acc\n acc.messenger = self\n\n def add_learner(self, lrn):\n self.learners[lrn.learner_uid] = lrn\n lrn.messenger = self\n\n def send_prepare(self, proposal_id):\n '''\n Broadcasts a Prepare message to all Acceptors\n '''\n\n logging.info(\"PREPARE {}: bcast from proposer {}\".format(proposal_id.number, proposal_id.uid))\n\n for acc in self.acceptors.itervalues():\n self.queue.append((acc.recv_prepare, (proposal_id.uid, proposal_id)))\n\n self.process_queue()\n\n def send_promise(self, proposer_uid, acceptor_uid, proposal_id, previous_id, accepted_value):\n '''\n Sends a Promise message to the specified Proposer\n '''\n\n logging.info(\"PROMISE {} from {}: to proposer {}, prev {}, accepted {}\".format(proposal_id.number, acceptor_uid, proposer_uid, previous_id, accepted_value))\n\n self.queue.append((self.proposers[proposer_uid].recv_promise, (acceptor_uid, proposal_id, previous_id, accepted_value)))\n\n self.process_queue()\n\n def send_accept(self, proposal_id, proposal_value):\n '''\n Broadcasts an Accept! message to all Acceptors\n '''\n\n logging.info(\"ACCEPT! {}: bcast from proposer {}, value {}\".format(proposal_id.number, proposal_id.uid, proposal_value))\n\n for acc in self.acceptors.itervalues():\n self.queue.append((acc.recv_accept_request, (proposal_id.uid, proposal_id, proposal_value)))\n\n self.process_queue()\n\n def send_accepted(self, proposal_id, acceptor_uid, accepted_value):\n '''\n Broadcasts an Accepted message to all Learners\n '''\n\n logging.info(\"ACCEPTED %r: acceptor %r, value %r\", proposal_id.number, acceptor_uid, accepted_value)\n\n for lrn in self.learners.itervalues():\n self.queue.append((lrn.recv_accepted, (acceptor_uid, proposal_id, accepted_value)))\n\n self.process_queue()\n\n def on_resolution(self, proposal_id, value):\n '''\n Called when a resolution is reached\n '''\n\n logging.info(\"RESOLUTION %r: %r\", proposal_id.number, value)\n\n def process_queue(self):\n if self.processing:\n return\n\n self.processing = True\n\n while self.queue:\n msg = self.queue.pop(0)\n msg[0](*msg[1])\n\n self.processing = False\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n\n proposer_uid_base = 0\n acceptor_uid_base = 0\n learner_uid_base = 0\n quorum = 2\n\n m = Messenger()\n\n p = paxos.Proposer()\n p.proposer_uid = 1\n p.quorum_size = quorum\n m.add_proposer(p)\n\n for i in xrange((quorum - 1) * 2 + 1):\n a = paxos.Acceptor()\n acceptor_uid_base += 1\n a.acceptor_uid = acceptor_uid_base\n m.add_acceptor(a)\n\n for i in xrange((quorum - 1) * 2 + 1):\n l = paxos.Learner()\n learner_uid_base += 1\n l.learner_uid = learner_uid_base\n l.quorum_size = quorum\n m.add_learner(l)\n\n p.set_proposal(1)\n p.prepare()\n p.set_proposal(2)\n p.prepare()\n","sub_path":"demo_essent.py","file_name":"demo_essent.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"3546534","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# 元类\n# class 元类\n\nclass UpperAttrMetaClass(type):\n\tdef __new__(cls, name, parents, attrs):\n\t\tattr = ((name, value) for name, value in attrs.items() if not name.startswith('__'))\n\t\tupdated_attr = dict((name.upper(), value) for name, value in attr)\n\t\treturn type.__new__(cls, name, parents, updated_attr)\n\nclass Foo(object, metaclass=UpperAttrMetaClass):\n\tname = 'Foo' \nprint(hasattr(Foo, 'name'))\nprint(hasattr(Foo, 'NAME'))\n\nprint(Foo.NAME)\n\n\n\n# 为什么要使用元类\n# ORM\n'''\nclass Person(models.Model):\n name = models.CharField(max_length=30)\n age = models.IntegerField()\n\n下面的代码age不会被解释为 IntegerField\nguy = Person(name='bob', age='35')\nprint guy.age\n'''","sub_path":"Python/python3/example30-metaclass-3.py","file_name":"example30-metaclass-3.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"503456162","text":"\ndef fib(n, computed = {0: 0, 1: 1}):\n\tif n not in computed:\n\t\tcomputed[n] = fib(n-1, computed) + fib(n-2, computed)\n\treturn computed[n]\ndef fib_to(n):\n\tfibs = [1, 1]\n\tfor i in range(3, n+1):\n\t\tfibs.append(fibs[-1] + fibs[-2])\n\treturn fibs\n\n\n# for i in range(1,4000):\n# \tprint float(i)/len(str(fib(i)))\n\n\nx = fib_to(500)\n\n\nc = [float(i+1)/len(str(x[i])) for i in range(len(x))]\n\n\n\n","sub_path":"25.digi_fib_num.py","file_name":"25.digi_fib_num.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"53709695","text":"from django.shortcuts import render\nfrom hc.models import *\nfrom hc.forms import *\nfrom django.http import *\nfrom django.core.urlresolvers import reverse\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'index.html')\n\ndef colaboradores_lista(request):\n colaboradores = Colaborador.objects.all()\n return render(request, 'colaboradores_list.html', {\"colaboradores\": colaboradores})\n\ndef colaboradores(request):\n is_post = True if request.method == 'POST' else False\n if is_post:\n print(request.POST['coordenador'])\n colaborador = Colaborador(\n nome=request.POST['nome'],\n email=request.POST['email'],\n funcao=request.POST['funcao'],\n coordenador_id=int(request.POST['coordenador']),\n )\n colaborador.save()\n return HttpResponseRedirect(reverse(\"home\"))\n else:\n coordenadores = Colaborador.objects.all()\n return render(request, 'colaboradores_form.html', {\"coordenadores\": coordenadores,\n \"funcoes\": Choices.FUNCAO})","sub_path":"hc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"642826118","text":"# obican generator\r\ndef svaki_drugi(m, n):\r\n a = m + 1\r\n while a <= n:\r\n yield a\r\n a += 2\r\n\r\n\r\ndef zbir(a, b):\r\n return a + b\r\n\r\nl1 = [1, 5, 2, 7, 8]\r\nl2 = [2, 4, 6]\r\n\r\nrez = tuple(map(zbir, l1, l2))\r\nprint(rez)\r\n\r\n\r\ndef prosti(pocetak=None, kraj=None):\r\n if pocetak is None and kraj is None:\r\n pocetak = 2\r\n elif pocetak is None:\r\n pocetak = 2\r\n elif kraj is None:\r\n kraj = pocetak\r\n pocetak = 2\r\n\r\n if not isinstance(pocetak, (int, float)):\r\n raise TypeError('Pogresan tip argumenta pocetak: %s'% repr(pocetak))\r\n if kraj is not None and not isinstance(kraj, (int, float)):\r\n raise TypeError('Pogresan tip argumenta kraj: %s'% repr(kraj))\r\n\r\n if type(pocetak) is float:\r\n pocetak = round(pocetak)\r\n if kraj is not None:\r\n kraj = round(kraj)\r\n\r\n broj = pocetak\r\n while kraj is None or broj <= kraj:\r\n delilac = 2\r\n while delilac*delilac <= broj:\r\n if broj % delilac == 0:\r\n break\r\n delilac += 1\r\n else:\r\n # broj je prost jer smo prosli sve delioce\r\n yield broj\r\n broj += 1\r\n\r\n","sub_path":"SkriptJezici/Termin 04/cas4_20181023.py","file_name":"cas4_20181023.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"268764308","text":"#!/usr/bin/env python\n\n__author__ = \"Mageswaran Dhandapani\"\n__copyright__ = \"Copyright 2020, The Spark Structured Playground Project\"\n__credits__ = []\n__license__ = \"Apache License\"\n__version__ = \"2.0\"\n__maintainer__ = \"Mageswaran Dhandapani\"\n__email__ = \"mageswaran1989@gmail.com\"\n__status__ = \"Education Purpose\"\n\nfrom ssp.spark.streaming.analytics import SentimentAnalysis\n\n\ndef test_sentiment_analysis_members():\n for item in ['_get_schema', '_get_source_stream', '_get_spark', '_hdfs_process',\n '_online_process', 'process', 'structured_streaming_dump', 'visualize']:\n assert item in dir(SentimentAnalysis)\n\n","sub_path":"src/ssp/spark/streaming/analytics/sentiment_analysis_test.py","file_name":"sentiment_analysis_test.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"342111930","text":"INPUT_FILE = \"day10-input\"\nTEST_INPUT_FILE_1 = \"day10-input-test\"\nTEST_INPUT_FILE_2 = \"day10-input-test-2\"\nTEST_INPUT_FILE_3 = \"day10-input-test-3\"\n\nDEVICE_ADAPTER_JOLTAGE_ADJ = 3\nMAX_JOLTAGE_DIFFERENCE = 3\nOUTLET_JOLTAGE = 0\n\ndef read_input(file):\n with open(file, \"r\") as fin:\n return [int(l) for l in fin.readlines()]\n\ndef connect(adapters):\n working_adapters = adapters.copy()\n joltage = adapters[0]\n\n # we always connect the built-in adapter to the last adapter\n deltas = [DEVICE_ADAPTER_JOLTAGE_ADJ]\n\n for adapter in adapters:\n working_adapters.remove(adapter)\n next_adapter_options = set(filter(lambda adapter_joltage: adapter_joltage - joltage <= MAX_JOLTAGE_DIFFERENCE, working_adapters))\n\n if not next_adapter_options:\n break\n\n # always connect to the lowest joltage adapter option to ensure all adapters are used\n next_adapter = min(next_adapter_options)\n\n deltas.append(next_adapter - joltage)\n joltage = next_adapter\n\n return deltas.count(1) * deltas.count(3)\n\ndef count_paths(adapters):\n graph = {}\n for i, adapter in enumerate(adapters):\n remaining_adapters = adapters[i + 1:]\n graph[adapter] = set(filter(lambda other_adapter: other_adapter - adapter <= MAX_JOLTAGE_DIFFERENCE, remaining_adapters))\n \n path_counts = {}\n for adapter in reversed(adapters):\n adapter_options = graph[adapter]\n if not adapter_options:\n path_counts[adapter] = 1\n else:\n path_counts[adapter] = sum([path_counts[i] for i in adapter_options])\n \n return path_counts[min(adapters)]\n\ndef run(label, file):\n adapters = read_input(file)\n adapters.sort()\n adapters.insert(0, OUTLET_JOLTAGE)\n\n print(\"{} 1: {}\".format(label, connect(adapters)))\n print(\"{} 2: {}\".format(label, count_paths(adapters)))\n\nrun(\"test_1\", TEST_INPUT_FILE_1)\nrun(\"test_2\", TEST_INPUT_FILE_2)\nrun(\"test_3\", TEST_INPUT_FILE_3)\nrun(\"part\", INPUT_FILE)\n","sub_path":"day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"46319266","text":"from common_fixtures import * # NOQA\nfrom test_docker import docker_client, TEST_IMAGE_UUID, if_docker\n\nimport jwt\n\ndocker_client\n\n\n@if_docker\ndef test_stats_container(docker_client, cattle_url):\n uuid = TEST_IMAGE_UUID\n container = docker_client.create_container(imageUuid=uuid,\n networkMode='bridge')\n container = docker_client.wait_success(container)\n\n assert len(container.hosts()) == 1\n\n stats_access = container.containerStats()\n\n assert stats_access.token.index('.') > 0\n assert '/v1/containerstats/' in stats_access.url\n try:\n payload = jwt.decode(stats_access.token, verify=False)\n assert 'containerIds' in payload\n containerIds = payload['containerIds']\n assert len(containerIds) == 1\n except jwt.InvalidTokenError:\n assert False\n\n\n@if_docker\ndef test_stats_service(docker_client, context, cattle_url):\n env = docker_client.create_stack(name=random_str())\n env = docker_client.wait_success(env)\n assert env.state == \"active\"\n\n image_uuid = context.image_uuid\n launch_config = {\"imageUuid\": image_uuid}\n\n service = docker_client.create_service(name=random_str(),\n stackId=env.id,\n launchConfig=launch_config)\n service = docker_client.wait_success(service)\n assert service.state == \"inactive\"\n stats_access = service.containerStats()\n\n try:\n payload = jwt.decode(stats_access.token, verify=False)\n\n assert 'service' in payload\n except jwt.InvalidTokenError:\n assert False\n","sub_path":"tests/integration/cattletest/core/test_container_stats.py","file_name":"test_container_stats.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"185677907","text":"# -*- coding: utf-8 -*-\n\nimport re\nimport os\nimport httplib2\nimport HTMLParser\n\nmessage = ('\\nThis is short programm which get stderr log'\n '\\nand stdout log from oozie with format:'\n '\\nfirst: STDERRLOG_ONLY and second STDOUT_LOG\\n')\ncreate = \"Log files Create on Desktop\"\nnot_parse = \"cannot parse url %s from\\n %s\"\nincorrect_link = \"incorrect link or ID request return %s code\"\ncrash_url = 'can\\'t get the url_log wrong address %s'\nincorrect_id = \"incorrect ID-format. Please set correct ID (for example: 123456789_123456)\"\n\nenv = os.getenv('HOMEPATH')\n\nany_cluster_node = \"http://etl-hdp-yarn.bi.b2e.prod.maxus.lan:19888\"\noozie_api = 'http://etl-hdp-apps.bi.b2e.prod.maxus.lan:11000/oozie/v2/job/'\noozie_gui = \"http://etl-hdp-yarn.bi.b2e.prod.maxus.lan:8088/proxy/application_\"\n\npat1 = re.compile('(?<=href=\").*(?=\">1)')\npat2 = re.compile('/jobhistory/logs.*n')\npat3 = re.compile('
([\\s\\S]*)
')\npat4 = '^\\d.*_\\d.*'\npat5 = re.compile('2\\d{2}')\ndelimiter = '#' * 50 + '\\n'\nhttp = httplib2.Http()\nh = HTMLParser.HTMLParser()\n\n\n\n","sub_path":"oozieStderrDloadGUI/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"460877135","text":"import os\nimport sys\nimport logging\n\nfrom PyQt5.QtCore import *\n\n\nclass QtHandler(QObject, logging.Handler):\n \"\"\"\n Version of logging handler \"emitting\" the message to custom stdout()\n \"\"\"\n messageWritten = pyqtSignal(str)\n\n def __init__(self):\n QObject.__init__(self)\n logging.Handler.__init__(self)\n\n def emit(self, record):\n record = self.format(record)\n if record:\n self.messageWritten.emit('%s\\n'%record)\n\n\ndef setup_qt_logging():\n # Define the default logger\n logger = logging.getLogger()\n\n # Add the qt-signal logger\n handler = QtHandler()\n handler.setFormatter(logging.Formatter(\n fmt=\"%(asctime)s - %(levelname)s: %(message)s\",\n datefmt=\"%H:%M:%S\"\n ))\n logger.addHandler(handler)\n\n return handler\n","sub_path":"src/sas/qtgui/Utilities/SasviewLogger.py","file_name":"SasviewLogger.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"342070730","text":"from flask import jsonify\nfrom lin import route_meta, group_required, login_required\nfrom lin.exception import Success\nfrom lin.redprint import Redprint\nfrom lin.exception import NotFound\nfrom app.validators.forms import ThirdClientForm,WxClientForm,SearchAllForm,SearchNameForm,CreateGoodsForm\nfrom app.models.third_client.third_bind import ThirdBind\nfrom app.models.goods.goods import Goods\n\ngoods_api = Redprint('goods')\n\n@goods_api.route('/', methods=['GET'])\ndef get_brand(id):\n resp = {'code': 200, 'msg': '操作成功~', 'data': {}}\n goods = Goods.get_detail(id)\n if goods is None:\n resp['code'] = -1\n resp['msg'] = \"暂无此商品,请稍后重试\"\n return jsonify(resp)\n resp['data']['goods'] = goods\n return jsonify(resp)\n \n@goods_api.route('/', methods=['GET'])\ndef get_brands():\n resp = {'code': 200, 'msg': '操作成功~', 'data': {}}\n form = SearchAllForm().validate_for_api()\n goods = Goods.get_all({'page':int(form.page.data),'size':int(form.size.data)})\n if goods is None:\n resp['code'] = -1\n resp['msg'] = \"暂无商品,请先创建\"\n return jsonify(resp)\n resp['data']['goods'] = goods\n return jsonify(resp)\n\n@goods_api.route('/search',methods=['POST'])\ndef search_brand():\n resp = {'code': 200, 'msg': '操作成功~', 'data': {}}\n form = SearchNameForm().validate_for_api()\n goods = Goods.search_by_name(form.name.data)\n if goods is None:\n resp['code'] = -1\n resp['msg'] = \"未查询到相关信息\"\n return jsonify(resp)\n resp['data']['goods'] = goods\n return jsonify(resp)\n\n@goods_api.route('/',methods=['POST'])\ndef new_brand():\n resp = {'code': 200, 'msg': '操作成功~', 'data': {}}\n form = CreateGoodsForm().validate_for_api()\n goods = Goods.new(form)\n if goods is False:\n resp['code'] = -1\n resp['msg'] = \"已存在商品或商品分类不存在\"\n return jsonify(resp)\n resp['data']['goods'] = goods\n return jsonify(resp)\n\n@goods_api.route('/',methods=['PUT'])\ndef update_brand(id):\n resp = {'code': 200, 'msg': '操作成功~', 'data': {}}\n form = CreateGoodsForm().validate_for_api()\n goods = Goods.edit(id,form)\n if goods is False:\n resp['code'] = -1\n resp['msg'] = \"该商品不存在或名称重复\"\n return jsonify(resp)\n resp['data']['goods'] = goods\n return jsonify(resp)\n\n@goods_api.route('/',methods=['DELETE'])\ndef delete_brand(id):\n resp = {'code': 200, 'msg': '操作成功~', 'data': {}}\n goods = Goods.remove(id)\n if goods is False:\n resp['code'] = -1\n resp['msg'] = \"该商品不存在或已删除\"\n return jsonify(resp)\n return jsonify(resp)","sub_path":"app/api/wx/shop/goods.py","file_name":"goods.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"534546028","text":"class Solution:\n def trailingZeroes(self, n: int) -> int:\n d = 0\n res = 0\n while(5**d < n):\n d += 1\n while(d):\n res += n // 5**d\n d -= 1\n return res\n\n# 给定一个整数 n,返回 n! 结果尾数中零的数量。\n\n# 示例 1:\n# 输入: 3\n# 输出: 0\n# 解释: 3! = 6, 尾数中没有零。\n\n# 示例 2:\n# 输入: 5\n# 输出: 1\n\n# 解释: 5! = 120, 尾数中有 1 个零.\n# 说明: 你算法的时间复杂度应为 O(log n) 。\n\n# 链接:https://leetcode-cn.com/problems/factorial-trailing-zeroes","sub_path":"172. 阶乘后的零/pythonCode.py","file_name":"pythonCode.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"433013253","text":"import os\nfrom Crypto.Cipher import AES\nimport time\nfrom datetime import datetime\n\ndef decryption(key, fileName):\n\n #timer start\n # start_time = datetime.now()\n\n #In seconds\n start_time = time.time()\n\n textSize = 64 * 1024\n outPutFile = fileName[10:]\n \n with open(fileName, 'rb') as inputFile:\n fileSize = int(inputFile.read(16))\n IV = inputFile.read(16)\n\n decryptor = AES.new(key, AES.MODE_CBC, IV)\n\n with open(outPutFile,'wb') as oFile:\n while True:\n text = inputFile.read(textSize)\n\n if len(text) == 0:\n break\n\n oFile.write(decryptor.decrypt(text))\n oFile.truncate(fileSize)\n #timer counting \n # time_elapsed = datetime.now() - start_time\n # print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))\n\n #main()\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n \n","sub_path":"Encryption-For-Any-File-master/Dec.py","file_name":"Dec.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"325265121","text":"import os\nimport argparse\nimport random\nimport soundfile as sf\nimport torch\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom model import *\nfrom utils import *\n\ndef gradient_ascent(opt, model, input_tensor, iteration):\n \"one gradient ascent iteration\"\n\n activations = model(input_tensor) # model returns dict of activations\n\n # calculate losses over activations\n losses = []\n for layer in opt.layers_to_use:\n\n # MSE with zero vector\n if not layer == \"output\":\n target_vector = torch.zeros_like(activations[layer])\n loss_component = torch.nn.MSELoss(reduction='mean')(activations[layer], target_vector)\n\n # CrossEntropyLoss with target class\n elif layer == \"output\": \n target_vector = torch.tensor([opt.target_class_index], device=\"cuda\")\n loss_component = torch.nn.CrossEntropyLoss()(activations[layer], target_vector)\n \n losses.append(loss_component)\n\n loss = torch.mean(torch.stack(losses))\n loss.backward()\n\n # smooth gradients with gaussian kernels\n grad = input_tensor.grad.detach()\n sigma = ((iteration + 1) / opt.num_iterations) * 2.0 + opt.smoothing_coefficient\n smooth_grad = CascadeGaussianSmoothing(kernel_size=9, sigma=sigma)(grad) # \"magic number\" 9 just works well\n\n # normalise gradients\n smooth_grad = (smooth_grad - smooth_grad.mean()) / smooth_grad.std()\n\n # update image with gradient ascent\n input_tensor.data += opt.lr * smooth_grad\n\n # clear gradients\n input_tensor.grad.data.zero_()\n\n # clamp input\n input_tensor.data = torch.clamp(input_tensor, min=-3, max=3)\n\ndef deep_dream_spectrogram(opt, input_spec, model):\n \"applies DeemDream to single spectrogram\"\n\n # convert to tensor and add batch / chan dims\n input_spec = torch.from_numpy(input_spec).unsqueeze(0).unsqueeze(0).float().cuda()\n\n input_spec = standardise(input_spec, opt.mean, opt.std) # standardise with stats of training data\n\n base_shape = input_spec.shape # save initial height and width\n\n unprocessed = input_spec.clone() # for detail recovery\n\n # iterate over sizes in pyramid (small to big)\n for pyramid_level in range(opt.pyramid_size):\n\n new_shape = get_new_shape(opt, base_shape, pyramid_level) # get new shape\n input_spec = F.interpolate(input_spec, size=(new_shape[0], new_shape[1])) # resize to new shape\n \n if pyramid_level != 0 and opt.replace_detail:\n \"help from: https://keras.io/examples/generative/deep_dream/\"\n # replace detail lost by interpolation\n upsampled_shrunk_unprocessed = F.interpolate(shrunk_unprocessed, size=(new_shape[0], new_shape[1])) # upsample previous size to current size\n same_size_unprocessed = F.interpolate(unprocessed, size=(new_shape[0], new_shape[1])) # downsample original to current size\n lost_detail = same_size_unprocessed - upsampled_shrunk_unprocessed # lost detail is difference\n \n input_spec = input_spec + lost_detail * opt.detail_factor # factor can be used to add less detail\n\n # roll patch horizontally\n pyramid_roll_max = get_pyramid_roll_max(opt, base_shape, pyramid_level) # get max roll for pyramid level\n pyramid_roll = torch.randint(pyramid_roll_max, size=(1,)).item() # get random roll value in range\n input_spec = input_spec.roll(pyramid_roll, dims=-1)\n\n input_spec.requires_grad_()\n\n # gradient ascent iterations\n for iteration in range(opt.num_iterations):\n gradient_ascent(opt, model, input_spec, iteration)\n\n input_spec = input_spec.detach()\n\n # unroll patch\n input_spec = input_spec.roll(-pyramid_roll, dims=-1)\n\n shrunk_unprocessed = F.interpolate(unprocessed, size=(new_shape[0], new_shape[1])) # for replacing detail at next size\n\n input_spec = destandardise(input_spec, opt.mean, opt.std) # destandardise with stats of training data\n\n return input_spec.cpu().detach().numpy()[0][0]\n\ndef dream_sound_single(opt, input_wav, model):\n \"single clip dream\"\n\n # convert input to spectrogram\n input_spec = wav_to_mel_dB(input_wav)\n\n print(\"dreaming single spectrogram\")\n dream_spec = deep_dream_spectrogram(opt, input_spec, model)\n\n print(\"converting to wav\")\n dream_wav = mel_dB_to_wav(dream_spec)\n\n print(\"writing to file\")\n sf.write(opt.save_path+\"/dream.wav\", dream_wav, samplerate=opt.sample_rate)\n\n print(\"plotting\")\n fig, ax = plt.subplots(4)\n plot_mel_dB(input_spec, fig, ax, 0)\n plot_mel_dB(dream_spec, fig, ax, 1)\n plot_wav(input_wav, fig, ax, 2)\n plot_wav(dream_wav, fig, ax, 3)\n plt.show()\n\ndef dream_sound_ouroboros(opt, input_wav, model):\n \"repeatedly feeds output spectrogram back into input\"\n\n print(opt.layers_to_use)\n\n if opt.layers_to_use == [\"iterate\"]:\n iterate_flag = True\n print(\"iterating over layers\")\n else:\n iterate_flag = False\n\n transform_output_length = input_wav.shape[0]\n\n # convert input to spectrogram\n input_spec = wav_to_mel_dB(input_wav)\n\n print(\"dreaming ouroboros\")\n\n dream_specs = [input_spec]\n dream_wavs = [input_wav]\n\n # iterate over length of ouroboros\n for i in range(opt.ouroboros_length):\n\n if iterate_flag:\n # iterate backwards over layers in model\n opt.layers_to_use = [opt.layers[-(i+1)]]\n print(\"maximising\",opt.layers_to_use)\n\n print(f'ouroboros iteration {i+1}.')\n\n # generate dream for this iteration\n dream_spec = deep_dream_spectrogram(opt, input_spec, model) \n dream_specs.append(dream_spec)\n\n # convert to wav\n dream_wav = mel_dB_to_wav(dream_spec)\n dream_wavs.append(dream_wav)\n\n if not opt.ouroboros_transform == \"none\":\n input_wav = ouroboros_transform(opt, dream_wav, transform_output_length) # apply transformation to dream wav\n input_spec = wav_to_mel_dB(input_wav) # generate spec from transformed dream wav\n else:\n input_spec = dream_spec # use mel that hasn't been converted to and from audio\n\n # fade between oouroboros clips\n if opt.crossfade:\n clips = [dream_wavs[0]]\n clip_length = dream_wavs[-1].size # quick fix for audio files shorted by wav -> mel -> wav\n\n fade_in = np.linspace(0.0, 1.0, num = clip_length) # amplitude envelope vectors\n fade_out = np.linspace(1.0, 0.0, num = clip_length)\n\n for i in range(len(dream_wavs) - 1):\n fade_out_clip = dream_wavs[i][:clip_length] * fade_out\n fade_in_clip = dream_wavs[i+1][:clip_length] * fade_in\n clips.append(fade_out_clip + fade_in_clip)\n\n dream_ouroboros = np.concatenate(clips)\n\n # no fading\n else:\n dream_ouroboros = np.concatenate(dream_wavs)\n\n print(\"writing to file\")\n sf.write(opt.save_path+\"/dream_ouroboros.wav\", dream_ouroboros, samplerate=opt.sample_rate)\n\n print(\"plotting\")\n fig, ax = plt.subplots(opt.ouroboros_length+1)\n for i, dream_spec in enumerate(dream_specs):\n plot_mel_dB(dream_spec, fig, ax, i)\n plt.show()\n \nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n\n # input / output params\n parser.add_argument(\"--input\", type=str, help=\"input wav for dreaming, or 'noise' / 'sine' \", default=\"noise\")\n parser.add_argument(\"--clip_length\", type=int, help=\"length of noise / sine clip to use\", default=51200)\n parser.add_argument(\"--sine_freq\", type=int, help=\"frequency of sine wave\", default=250)\n parser.add_argument(\"--sample_rate\", type=int, help=\"sample rate to use\", default=22050)\n\n # model params\n parser.add_argument(\"--model\", type=str, help=\"model to use\", default=\"fma-small\", choices=[\"UrbanSounds8k\", \"fma-small\"])\n parser.add_argument(\"--layers_to_use\", type=str, nargs='+', help=\"Layer whose activations we should maximize while dreaming\", default=[\"relu5_4\"])\n parser.add_argument(\"--target_class_index\", type=int, help=\"class of final output layer to target, -1 for random, no effect if 'output' not in layers_to_use\", default=-1)\n\n # dreaming params\n parser.add_argument(\"--pyramid_size\", type=int, help=\"number of levels in a pyramid\", default=3)\n parser.add_argument(\"--pyramid_ratio\", type=float, help=\"ratio of sizes in the pyramid\", default=2)\n parser.add_argument(\"--replace_detail\", type=bool, help=\"to replace detail lost by interpolation\", default=True)\n parser.add_argument(\"--detail_factor\", type=float, help=\"multiplying factor to add less detail\", default=1.0)\n parser.add_argument(\"--pyramid_roll\", type=int, help=\"max horizontal rolling each iteration (scales with pyramid)\", default=20)\n parser.add_argument(\"--num_iterations\", type=int, help=\"number of gradient ascent iterations per pyramid level\", default=10)\n parser.add_argument(\"--lr\", type=float, help=\"learning rate i.e. step size in gradient ascent\", default=0.02)\n parser.add_argument(\"--smoothing_coefficient\", type=float, help='directly controls standard deviation for gradient smoothing', default=0.5)\n\n # ourobors dreaming params\n parser.add_argument(\"--create_ouroboros\", type=bool, help=\"create ouroboros audio\", default=False)\n parser.add_argument(\"--ouroboros_length\", type=int, help=\"number of clips in ouroboros audio\", default=10)\n parser.add_argument(\"--ouroboros_transform\", type=str, help=\"transform to apply between each dream iteration\", default=\"none\", choices=[\"none\", \"time_stretch\", \"resample\"])\n parser.add_argument(\"--ouroboros_stretch\", type=float, help=\"factor for 'stretch' transform\", default=0.95)\n parser.add_argument(\"--ouroboros_sr_offset\", type=int, help=\"sample rate offset for 'resample' transform\", default=500)\n parser.add_argument(\"--crossfade\", type=bool, help=\"fade between ouroboros clips\", default=True)\n\n opt = parser.parse_args()\n\n # classes / mean / std of models\n if opt.model == \"UrbanSounds8k\":\n opt.num_classes = 10\n opt.mean = -23.5891\n opt.std = 16.3979\n elif opt.model == \"fma-small\":\n opt.num_classes = 8\n opt.mean = -24.1847 \n opt.std = 16.8729 \n\n if opt.layers_to_use == [\"iterate\"]:\n # list of all layers in model\n opt.layers = [\"conv1_1\", \"relu1_1\", \"conv1_2\", \"relu1_2\", \"mp1\",\n \"conv2_1\", \"relu2_1\", \"conv2_2\", \"relu2_2\", \"mp2\",\n \"conv3_1\", \"relu3_1\", \"conv3_2\", \"relu3_2\", \"conv3_3\", \"relu3_3\", \"conv3_4\", \"relu3_4\", \"mp3\",\n \"conv4_1\", \"relu4_1\", \"conv4_2\", \"relu4_2\", \"conv4_3\", \"relu4_3\", \"conv4_4\", \"relu4_4\", \"mp4\",\n \"conv5_1\", \"relu5_1\", \"conv5_2\", \"relu5_2\", \"conv5_3\", \"relu5_3\", \"conv5_4\", \"relu5_4\", \"mp5\",\n \"avgpool\", \"linear1\", \"reluC_1\", \"dropout1\", \"linear2\", \"reluC_2\", \"dropout2\", \"output\"]\n opt.ouroboros_iterations = len(opt.layers)\n \n # initalise model\n model = Vgg19Activations(\"models/\"+opt.model+\".pth\", opt.layers_to_use, opt.num_classes).cuda()\n\n # random target class\n if opt.target_class_index == -1:\n opt.target_class_index = random.randint(0, opt.num_classes)\n\n # folder prep\n os.makedirs(\"outputs\", exist_ok=True)\n\n for i in range(1000):\n opt.save_path = \"outputs/\"+str(i)\n try:\n os.makedirs(opt.save_path, exist_ok=False)\n break\n except FileExistsError:\n pass\n\n # write params to file\n with open (opt.save_path + \"/params.txt\", \"w\") as f:\n f.write(str(vars(opt)))\n\n # generate / load input\n if opt.input == \"noise\":\n rng = np.random.default_rng()\n input_wav = rng.random(opt.clip_length)\n input_wav = input_wav * 2 - 1\n elif opt.input == \"sine\":\n sine = np.arange(0, opt.clip_length) / opt.sample_rate\n input_wav = np.sin(sine*2*np.pi*opt.sine_freq)\n else:\n input_wav, sr = librosa.load(opt.input, sr=opt.sample_rate)\n\n input_wav = librosa.util.normalize(input_wav)\n\n\n if not opt.create_ouroboros:\n # create a single DeepDream audio\n dreamed_spec = dream_sound_single(opt, input_wav, model) \n else: \n # create ouroboros audio (feeding neural network's output to it's input)\n dream_sound_ouroboros(opt, input_wav, model)\n","sub_path":"dreamsound.py","file_name":"dreamsound.py","file_ext":"py","file_size_in_byte":12291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"618076776","text":"from django.shortcuts import render\nimport csv\nimport json\nfrom urllib.error import URLError,HTTPError\nfrom urllib.request import urlopen\nimport os\ndef result_new(x,y,sour,dest,dat):\n#for bus\n\tfp=open(x,'r')\n\treader=csv.reader(fp)\n\tnext(reader)\n\tdata1=[]\n\tfor row in reader:\n\t\tdata1.append(row)\n\tstr1=''\n\tfor row in data1:\n\t\tfor r in row:\n\t\t\tr=r+','\n\t\t\tstr1=str1+''.join(r)+'\\n'\n\tstr1=str1[:-2]\n\t#dict={'file':str1}\n\tfp.close()\n#for flight\n\twith open(y) as fp:\n\t\treader=csv.reader(fp)\n\t\tnext(reader)\n\t\tstr2=''\n\t\tfor row in reader:\n\t\t\tstr2 = str2+''.join(row)+'!\\n'\n\n\t\tstr2=str2[:-2]\n\t#dict={'file_bus':str1,'file_flight':str2}\n\tfp.close()\n#for train\n\tstr3=\"\"\n\turl='https://api.railwayapi.com/v2/between/source/'+sour+'/dest/'+dest+'/date/'+dat+'/apikey/jx16978zj1/'\n\t#url='https://api.railwayapi.com/v2/between/source/tata/des/hwh/date/27-03-2019/apikey/jx16978zj1/'\n\tprint(url)\n\ttry:\n\t conn = urlopen(url)\n\texcept HTTPError as e:\n\t # Return code error (e.g. 404, 501, ...)\n\t # ...\n\t\tprint('HTTPError: {}'.format(e.code))\n\t\tfile_train=sour+dest+dat+'.json'\n\t\tprint(file_train)\n\t\tfp=open(file_train,\"r\")\n\t\tstr3=json.load(fp)\n\t\tprint(str3)\n\t\tfp.close()\n\n\texcept URLError as e:\n\t # Not an HTTP-specific error (e.g. connection refused)\n\t # ...\n\t print('URLError: {}'.format(e.reason))\n\telse:\n\t # 200\n\t # ...\n\t #print('good')\n\t\tsource=conn.read()\n\t\tstr3 = json.loads(source)\n\t\tfile_train=sour+dest+dat+'.json'\n\t\tfp=open(file_train,\"w\")\n\t\tjson.dump(str3,fp)\n\t\tfp.close()\n\t#print(str3['trains'])\n\tava_dict={}\n\ti=0\n\t'''\n\tfor x in str3['trains']:\n\t\t#print(x['number'])\n\t\t#print(x['from_station']['code'])\n\t\t#print(x['to_station']['code'])\n\t\tseat_url='https://api.railwayapi.com/v2/check-seat/train/'+x['number']+'/source/'+x['from_station']['code']+'/dest/'+x['to_station']['code']+'/date/08-04-2019/pref/CC/quota/GN/apikey/jx16978zj1/'\n\t\tprint(seat_url)\n\t\twith urlopen(seat_url) as response:\n\t\t\tseat_source=response.read()\n\t\tava_dict[i] = json.loads(seat_source)\n\t\ti=i+1\n\tprint(ava_dict)\n\t'''\n\tdict={'file_bus':str1,'file_flight':str2,'file_train':str3}\n\treturn dict\n\t#return render(request,'basicapp/result.html',context=dict)\n# Create your views here.\n\ndef index(request):\n\tif(request.method=='POST'):\n\t\tsour=request.POST.get('source')\n\t\tdest=request.POST.get('destination')\n\t\tdat=request.POST.get('j_date')\n\n\t\tsubmitbutton=request.POST.get('Submit')\n\t\tprint(sour)\n\t\tprint(dest)\n\t\tprint(dat)\n\t\tl=dat.split('-')\n\t\tif(int(l[0])<10):\n\t\t\tl[0]=l[0][1:]\n\t\tbus_dat=l[0]+'_'+l[1][:3]+l[2]\n\t\tflight_dat=l[0]+'_'+l[1]+l[2]\n\t\tfile_bus='sorted_'+sour+'_'+dest+'_'+bus_dat+'.csv'\n\t\tfile_flight='flight/'+sour+'_'+dest+'_'+flight_dat+'.csv'\n\t\t#print(file_flight)\n\t\tprint(sour)\n\t\tprint(dest)\n\t\tmonth={\"Jan\":\"01\",\"Feb\":\"02\",\"Mar\":\"03\",\"Apr\":\"04\",\"May\":\"05\",\"Jun\":\"06\",\"Jul\":\"07\",\"Aug\":\"08\",\"Sep\":\"09\",\"Oct\":\"10\",\"Nov\":\"11\",\"Dec\":\"12\"}\n\t\ttrain_dat=l[0]+'-'+month[l[1]]+'-2019'\n\t\t#print(train_dat)\n\t\tfp=open('city.json','r')\n\t\ttrain_list=json.load(fp)\n\t\tfp.close()\n\t\ttrain_sour=train_list[sour]\n\t\ttrain_dest=train_list[dest]\n\t\tprint(train_sour)\n\t\tprint(train_dest)\n\t\tdict=result_new(file_bus,file_flight,train_sour,train_dest,train_dat)\n\t\tdict['source']=sour\n\t\tdict['destination']=dest\n\t\tdict['date']=dat\n\t\treturn render(request,'basicapp/result.html',context=dict)\n\treturn render(request,'basicapp/home.html')\ndef train(request):\n\treturn render(request,'basicapp/train.html')\ndef stod(request):\n\treturn render(request,'basicapp/stod.html')\ndef bus(request):\n\treturn render(request,'basicapp/bus.html')\ndef flight(request):\n\treturn render(request,'basicapp/flight.html')\ndef signin(request):\n\treturn render(request,'basicapp/signin.html')\n\n\n\ndef result(request):\n#for bus\n\tfp=open('cheap_copy.csv','r')\n\treader=csv.reader(fp)\n\tnext(reader)\n\tdata1=[]\n\tfor row in reader:\n\t\tdata1.append(row)\n\tstr1=''\n\tfor row in data1:\n\t\tfor r in row:\n\t\t\tr=r+','\n\t\t\tstr1=str1+''.join(r)+'\\n'\n\tstr1=str1[:-2]\n\tdict={'file':str1}\n\tfp.close()\n#for flight\n\twith open(\"ixigo.csv\") as fp:\n\t\treader=csv.reader(fp)\n\t\tnext(reader)\n\t\tstr2=''\n\t\tfor row in reader:\n\t\t\tstr2 = str2+''.join(row)+'!\\n'\n\n\t\tstr2=str2[:-2]\n\t#dict={'file_bus':str1,'file_flight':str2}\n\tfp.close()\n#for train\n\twith urlopen('https://api.railwayapi.com/v2/between/source/tata/dest/hwh/date/30-04-2019/apikey/jx16978zj1/') as response:\n\t\tsource=response.read()\n\tstr3 = json.loads(source)\n\n\t#print(str3['trains'])\n\tava_dict={}\n\ti=0\n\tfor x in str3['trains']:\n\t\t#print(x['number'])\n\t\t#print(x['from_station']['code'])\n\t\t#print(x['to_station']['code'])\n\t\tseat_url='https://api.railwayapi.com/v2/check-seat/train/'+x['number']+'/source/'+x['from_station']['code']+'/dest/'+x['to_station']['code']+'/date/30-04-2019/pref/CC/quota/GN/apikey/jx16978zj1/'\n\t\tprint(seat_url)\n\t\twith urlopen(seat_url) as response:\n\t\t\tseat_source=response.read()\n\t\tava_dict[i] = json.loads(seat_source)\n\t\ti=i+1\n\tprint(ava_dict)\n\n\tdict={'file_bus':str1,'file_flight':str2,'file_train':str3}\n\treturn render(request,'basicapp/result.html',context=dict)\n","sub_path":"project/goraahi/basicapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"604402633","text":"import numpy as np\nimport cv2\nfrom sklearn.cluster import DBSCAN\n\n\ndef distance(p1, p2):\n \"\"\"\n distance between two points and vectorize function for it\n\n Arguments:\n p1 - first point, numpy array of int with shape (2,)\n p2 - second point, numpy array of int with shape (2,)\n\n Return:\n distance\n \"\"\"\n return np.linalg.norm(p1-p2)\n\n\ndef check_for_maxhull(point, max_hull, measure):\n \"\"\"\n Check if point are near to max_hull contour (not only point)\n\n Arguments:\n point -- numpy array of int with shape (2,) (point)\n max_hull -- numpy array with shape (n, 1, 2) (desribe contour)\n measure -- how far away from max_hull point need to be\n\n Returns:\n bool result of check\n \"\"\"\n for index in range(len(max_hull)-1):\n if per_distance(max_hull[index],max_hull[index+1],point) < measure:\n return False\n return True\n\n\ndef per_distance(lp1, lp2, p):\n \"\"\"\n Compute distance from two point line to one point\n\n Arguments:\n lp1 -- first point of line, numpy array of int with shape (2,)\n lp2 -- second point of line, numpy array of int with shape (2,)\n p -- third point outside line, numpy array of int with shape (2,)\n\n Returns:\n distance\n \"\"\"\n return np.linalg.norm(np.cross(lp2-lp1, lp1-p))/np.linalg.norm(lp2-lp1)\n\n\ndef peakdet(v, delta, x=None):\n \"\"\"\n Finds the local maxima and minima (\"peaks\") in the vector V\n\n Arguments:\n v -- array of shape (n,2)\n delta -- measure for define observed range for local min or max\n\n Returns:\n\n \"\"\"\n maxtab = []\n mintab = []\n if x is None:\n x = np.arange(len(v))\n v = np.asarray(v)\n mn, mx = np.Inf, -np.Inf\n mnpos, mxpos = np.NaN, np.NaN\n lookformax = True\n for i in np.arange(len(v)):\n this = v[i]\n if this > mx:\n mx = this\n mxpos = x[i]\n if this < mn:\n mn = this\n mnpos = x[i]\n if lookformax:\n if this < mx-delta:\n maxtab.append((mxpos, mx))\n mn = this\n mnpos = x[i]\n lookformax = False\n else:\n if this > mn+delta:\n mintab.append((mnpos, mn))\n mx = this\n mxpos = x[i]\n lookformax = True\n\n return np.array(maxtab), np.array(mintab)\n\n\ndef get_angle(p1, p2, p3):\n \"\"\"\n Find angle between three points\n\n Arguments:\n p1 -- first (base) point, numpy array of int with shape (2,)\n p2 -- second point, numpy array of int with shape (2,)\n p3 -- third point , numpy array of int with shape (2,)\n\n Return:\n angle\n \"\"\"\n line1 = p2 - p1\n line2 = p3 - p1\n cosine = np.dot(line1, line2) / (np.linalg.norm(line1) * np.linalg.norm(line2))\n angle = np.arccos(cosine)\n # print(angle * 180 / np.pi)\n return angle * 180 / np.pi\n\n\ndef find_nearest(means, roots, image):\n \"\"\"\n Built angles between fingers and count fingers\n\n Arguments:\n means -- array of tuples (point on the finger's edge)\n roots -- array of tuples (point between fingers)\n image -- numpy array of shape (n, m, 3)\n\n Return:\n None\n \"\"\"\n means = sorted(means, key=lambda x: x[0])\n roots = sorted(roots, key=lambda x: x[0])\n\n means = np.array(means)\n roots = np.array(roots)\n n = len(means)-len(roots)\n #if n > 1:\n # for _ in range(n-1):\n # roots = np.vstack([roots, roots[-1]])\n\n count_finger = 0\n for i in range(len(means)-1):\n if i == len(roots):\n break\n angle = get_angle(roots[count_finger], means[i], means[i+1])\n\n if angle > 10 and angle < 80 and distance(roots[count_finger], means[i+1]) > 70 \\\n and distance(roots[count_finger], means[i]) > 70 \\\n and means[i+1][1] < roots[count_finger][1] \\\n and means[i][1] < roots[count_finger][1]:\n\n cv2.line(image, tuple(roots[count_finger]), tuple(means[i+1]), (0,255,0),4)\n cv2.line(image, tuple(roots[count_finger]), tuple(means[i]), (0,255,0),4)\n count_finger += 1\n\n if count_finger >= 1 and count_finger <= 5:\n cv2.putText(frame, str(count_finger+1),(0,50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,0,255), 3, cv2.LINE_AA)\n if count_finger == 0:\n cv2.putText(frame, str(1),(0,50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,0,255), 3, cv2.LINE_AA)\n\n\n\ncap = cv2.VideoCapture(0)\n\nwhile True:\n _, frame = cap.read()\n\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n\n # Color ranges for human skin\n # (very sensitive from brightness and often need to adjust in file hsv_color.py)\n lower = np.array([0, 0, 140])\n upper = np.array([255, 90, 255])\n mask = cv2.GaussianBlur(hsv, (5, 5), 100)\n mask = cv2.inRange(mask, lower, upper)\n\n\n # Find max contours of mask\n contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n if contours == []:\n continue\n max_contour = max(contours, key=lambda x: cv2.contourArea(x))\n\n cnt = contours[0] # delete excess dim for list\n max_hull = cv2.convexHull(max_contour)\n\n # Approximate area of hand\n epsilon = 0.003*cv2.arcLength(max_contour, True)\n approx = cv2.approxPolyDP(max_contour, epsilon, True)\n\n\n # edges of max_hull\n leftmost = max_hull[max_hull[:, :, 0].argmin()][0]\n rightmost = max_hull[max_hull[:, :, 0].argmax()][0]\n\n # use delta like some measure of size max_hull\n # for dicrease amount of Magic Numbers\n delta = np.linalg.norm(leftmost-rightmost) // 6\n\n # Compute center of max_hull area\n # for throw out max hull points from bottom (not from fingers)\n center = np.mean(max_hull, axis=0, dtype=np.uint32)\n cx, cy = tuple(center[0])\n cy += (delta*2.5 ) # little shift center to downside\n # final = cv2.drawContours(frame, max_hull, -1, (255, 0, 0), 3)\n # final = cv2.drawContours(frame, approx, -1, (0,0,0),5)\n\n\n # find local min (points between fingers)\n # also remove points which close to max_hull\n data = np.array(np.squeeze(approx, axis=1))[:,1]\n indexes, _ = peakdet(data,.2)\n if indexes.size > 0:\n real_points = []\n corner_points = np.take(np.array(np.squeeze(approx, axis=1)), indexes[:,0], axis=0)\n for point in corner_points:\n if check_for_maxhull(point,max_hull,20) is True and point[1]= 0 and np.count_nonzero(labels == i) >= 2: \n array = [max_hull[num] for num, j in enumerate(labels) if j == i]\n if array != []:\n ax, ay = tuple(np.squeeze(np.mean(np.array(array), axis=0)))\n cv2.circle(frame, (int(ax), int(ay)), 10, (0, 0, 255), 1)\n means.append((int(ax),int(ay)))\n\n\n\n if list(real_points) and means and len(means) >= len(real_points):\n find_nearest(means, real_points, frame)\n\n\n cv2.imshow('image', mask)\n cv2.imshow('frame', frame)\n\n # Esc for exit\n k = cv2.waitKey(1) & 0xFF\n if k == 27:\n break\n\n\ncv2.destroyAllWindows()\ncap.release()\n","sub_path":"finger_detect_video.py","file_name":"finger_detect_video.py","file_ext":"py","file_size_in_byte":7838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"553796829","text":"def roots_of_quadratic_equation(a, b, c):\n if a == 0:\n if b == 0:\n if c == 0:\n return ['all']\n else:\n return []\n else:\n return [-c / b]\n else:\n D = b ** 2 - 4 * a * c\n if D < 0:\n return []\n elif D == 0:\n return [-b / (2 * a)]\n else:\n x1 = (-b - D ** 0.5) / (2 * a)\n x2 = (-b + D ** 0.5) / (2 * a)\n return [x1, x2]\n\n\ndef solve(*coefficients):\n if len(coefficients) == 0 or len(coefficients) > 3:\n return None\n elif len(coefficients) == 3:\n a, b, c = coefficients\n elif len(coefficients) == 2:\n a = 0\n b, c = coefficients\n else:\n a = b = 0\n c, = coefficients\n return roots_of_quadratic_equation(a, b, c)\n","sub_path":"Функции: передача параметров/dop/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"118893522","text":"# https://www.spoj.com/problems/GIVEAWAY/\n\nimport math\nimport bisect\n\nclass GiveAway:\n def __init__(self, N, arr):\n self.nums = arr\n self.N = N\n self.b = int(math.sqrt(N)) # Block Size\n self.sz = math.ceil(N/self.b) # Number of blocks\n self.blocks = []\n for i in range(self.sz):\n self.blocks.append(sorted([self.nums[i] for i in range(i*self.b, min(N, i*self.b+self.b))]))\n\n def update(self, index, val):\n block_no = index//self.b\n self.nums[index] = val\n self.blocks[block_no] = sorted([self.nums[i] for i in range(block_no*self.b, min(N, block_no*self.b+self.b))])\n\n def rangeQuery(self, left, right, val):\n l_block, r_block = left//self.b, right//self.b\n ans = 0\n\n for i in range(left, min(right, l_block*self.b+self.b-1)+1):\n if self.nums[i] >= val:\n ans += 1\n\n if l_block == r_block:\n print(ans)\n return\n\n for block in range(l_block+1, r_block):\n ans += len(self.blocks[block]) - bisect.bisect_left(self.blocks[block], val)\n\n for i in range(r_block*self.b, right+1):\n if self.nums[i] >= val:\n ans += 1 \n print(ans)\n\nN = int(input())\nnums = list(map(int, input().split()))\nQ = int(input())\nG = GiveAway(N, nums)\n\nfor _ in range(Q):\n query = list(map(int, input().split()))\n \n if query[0]: # update query\n G.update(query[1]-1, query[2])\n else:\n G.rangeQuery(query[1]-1, query[2]-1, query[3])\n","sub_path":"sqrt_decomposition/give_away.py","file_name":"give_away.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"331211038","text":"data = '''kohli ind pak 98\nrohit ind ban 69\nwarner aus s 98\npollard wi ind 49\nkohli ind wi 108\nrohit ind sl 149'''\nl = []\nbatsman = input (\"enter batsman name:\")\nfor row in data.splitlines():\n\td = row.split()\n\tif d[0]==batsman:\n\t\tprint(l.append(int(d[-1])))\n\t\t\n\n","sub_path":"cric1.py","file_name":"cric1.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"405600387","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.bloghome, name='bloghome'),\n path('insert/', views.insertBlog, name='insertBlog'),\n path('delete/', views.delete, name='deleteBlog'),\n path('read/', views.readMore, name='readMore'),\n path('edit/', views.editBlog, name='editBlog')\n]\n","sub_path":"Myblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"543329114","text":"# Written by *** and Eric Martin for COMP9021\nfrom random import seed, shuffle\nimport sys\nimport pysnooper\nimport time\nfrom functools import wraps\n\n\ndef timefn(fn):\n \"\"\"计算性能的修饰器\"\"\"\n @wraps(fn)\n def measure_time(*args, **kwargs):\n t1 = time.time()\n result = fn(*args, **kwargs)\n t2 = time.time()\n print(f\"@timefn: {fn.__name__} took {t2 - t1: .5f} s\")\n return result\n return measure_time\n\n\n# for_seed is meant to be an integer, length a strictly positive integer.\n# length will not be large for most tests, but can be as large as 10_000_000.\ndef generate_permutation(for_seed, length):\n seed(for_seed)\n values = list(range(1, length + 1))\n shuffle(values)\n return values\n\n# Question 1\ndef maps_to(values, x):\n id = values.index(x) + 1\n return id\n\n\n# ———————————————————— Question 1 Test ——————————————————————————\nvalues = generate_permutation(1, 10)\nmaps_to(values, 8)\nmaps_to(values, 7)\n# ———————————————————— Question 1 Test ——————————————————————————\n\n\n@pysnooper.snoop()\ndef test(values, x):\n counter = 1 # Counter of length of cycle\n pointer = values[x-1] # Pointer: point to next value\n if pointer == x:\n pass # There is no cycle\n else:\n for _ in range(len(values)):\n if values[pointer-1] != x:\n counter += 1\n pointer = values[pointer-1]\n else:\n counter += 1\n break\n return counter\n\n# test1\nvalues = generate_permutation(0, 10)\ntest(values, 1)\ntest(values, 3)\ntest(values, 6)\n# test2\nvalues = generate_permutation(1, 15)\ntest(values, 1)\ntest(values, 2)\n# test3\nt1 = time.time()\nvalues = generate_permutation(2, 1000)\ntest(values, 500)\nt2 = time.time()\nprint(f'Costs {t2-t1}s')\n# Question 2\n\n@pysnooper.snoop()\ndef length_of_cycle_containing(values, x):\n counter = 1 # Counter of length of cycle\n pointer = values[x-1] # Pointer: point to next value\n if pointer == x:\n pass # There is no cycle\n else:\n for _ in range(len(values)):\n if values[pointer-1] != x:\n counter += 1\n pointer = values[pointer-1]\n else:\n counter += 1\n break\n return counter\n\n# Returns a list of length len(values) + 1, with 0 at index 0\n# and for all x in {1, ..., len(values)}, the length of the cycle\n# containing x at index x.\ndef analyse(values):\n cycle_dict = {} # Dictionary storing calculated cycle\n for x in range(len(values)):\n if str(x+1) not in cycle_dict.keys():\n list_of_pointer = []\n counter = 1 # Counter of length of cycle\n pointer = values[x] # Pointer: point to next value\n list_of_pointer.append(x + 1)\n if pointer == x+1:\n pass # There is no cycle\n else:\n for _ in range(len(values)):\n if values[pointer-1] != x+1: # Determine if current value = 1st value\n list_of_pointer.append(pointer)\n counter += 1\n pointer = values[pointer-1]\n else:\n list_of_pointer.append(pointer)\n counter += 1\n break\n\n # Store calculated cycle into dictionary to reduce times of calculation\n for val in list_of_pointer:\n cycle_dict[str(val)] = counter\n # If this cycle has been calculated, skip it\n else:\n continue\n\n # Generate cycle list\n cycle_list = [0]\n for index in range(1, len(values)+1):\n cycle_list.append(cycle_dict[str(index)])\n\n return cycle_list\n\n\n\n# ----------------- method 1-----------------\n# dict = {f'{x}' : 1 for x in range(5)}\n# dict.keys()\n# dict[str(1)]\n\n@timefn\ndef analyse_test(values):\n cycle_dict = {}\n for x in range(len(values)):\n if str(x+1) not in cycle_dict.keys():\n list_of_pointer = []\n counter = 1 # Counter of length of cycle\n pointer = values[x]\n list_of_pointer.append(x + 1)\n if pointer == x+1:\n pass # There is no cycle\n else:\n for _ in range(len(values)):\n if values[pointer-1] != x+1: # Determine if current value = 1st value\n list_of_pointer.append(pointer)\n counter += 1\n pointer = values[pointer-1]\n else:\n list_of_pointer.append(pointer)\n counter += 1\n break\n\n # Store calculated cycle into dictionary to reduce times of calculation\n for val in list_of_pointer:\n cycle_dict[str(val)] = counter\n else:\n continue\n\n # Generate cycle list\n cycle_list = [0]\n for index in range(1, len(values)+1):\n cycle_list.append(cycle_dict[str(index)])\n\n return cycle_list\n\n\n# test 1\nvalues = generate_permutation(0, 10)\nanalyse_test(values)\n# test 2\nvalues = generate_permutation(1, 15)\nvalues\nc = analyse_test(values)\nc\n# test 3\nvalues = generate_permutation(2, 1000)\ncycle_lengths = analyse_test(values)\nlen(cycle_lengths)\ncycle_lengths[500]\n\n# Large number test\n\n# Tradition method\n@timefn\ndef tradition(values):\n c_list = [0]\n for i in range(len(values)):\n c_list.append(test(values, i+1))\n return c_list\n\n# Large number tese\nvalues = generate_permutation(2, 1_000_00)\ncycle_lengths = analyse_test(values)\ncycle_lengths_t = tradition(values)\n\n\n","sub_path":"Quiz/quiz_2/quiz_2.py","file_name":"quiz_2.py","file_ext":"py","file_size_in_byte":5792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"233544462","text":"import redis\n\n\npool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)\nr = redis.Redis(connection_pool=pool)\n\n\ndef get_partner_code(code):\n\tif code:\n\t\tfor code_obj in code:\n\t\t\tres = r.setnx('test.partner_%s' % code_obj['code'], 1)\n\t\t\tif res:\n\t\t\t\treturn code_obj\n\treturn None\n\n\nif __name__ == '__main__':\n\tresult = r.set('key_hello', 'value_hello', nx=True)\n\tprint('3=%s' % result)\n\tresult = r.set('key_hello', 'value_hello', nx=True)\n\tprint('4=%s' % result)\n","sub_path":"python_redis/python_redis_07.py","file_name":"python_redis_07.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"298834993","text":"\n\nimport os.path as op\n\nfrom .utils import resource\nfrom .qtcompat import QtWidgets, QtCore, QtGui\nfrom .plugins import list_plugins, get_plugin\nfrom .views import list_views, get_view\nfrom .components import *\nfrom .modal import ModalManager\nfrom .control import Launcher\n\nfrom survos2.utils import get_logger\nfrom survos2.config import Config\n\n\nlogger = get_logger()\n\n\nclass IconContainer(QCSWidget):\n\n plugin_selected = QtCore.pyqtSignal(str)\n\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self.vbox = VBox(self)\n self.btn_group = QtWidgets.QButtonGroup()\n self.btn_group.setExclusive(True)\n self.plugins = {}\n\n def load_plugin(self, name, icon, title=''):\n if name in self.plugins:\n return\n btn = ToolIconButton(icon, title, color='white', size=(24, 24), checkable=True)\n self.plugins[name] = btn\n self.vbox.addWidget(btn)\n self.btn_group.addButton(btn)\n btn.toggled.connect(lambda flag: flag and self.select_plugin(name))\n\n def unload_plugin(self, name):\n if name in self.plugins:\n btn = self.plugins[name]\n btn.setParent(None)\n btn.clicked.disconnect()\n self.btn_group.removeButton(btn)\n del self.plugins[name]\n\n def select_plugin(self, name):\n if name not in self.plugins:\n return\n self.plugins[name].setChecked(True)\n self.plugin_selected.emit(name)\n\n\nclass PluginContainer(QCSWidget):\n\n view_requested = QtCore.pyqtSignal(str, dict)\n\n __sidebar_width__ = 350\n\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self.setMinimumWidth(self.__sidebar_width__)\n self.setMaximumWidth(self.__sidebar_width__)\n\n self.title = Header('Plugin')\n self.container = ScrollPane(parent=self)\n\n vbox = VBox(self, margin=(1, 0, 2, 0), spacing=5)\n vbox.addWidget(self.title)\n vbox.addWidget(self.container, 1)\n\n self.plugins = {}\n self.selected_name = None\n self.selected = None\n\n def load_plugin(self, name, title, cls):\n if name in self.plugins:\n return\n widget = cls()\n widget.change_view.connect(self.view_requested)\n self.plugins[name] = dict(widget=widget, title=title)\n return widget\n\n def unload_plugin(self, name):\n self.plugins.pop(name, None)\n\n def show_plugin(self, name):\n if name in self.plugins and name != self.selected_name:\n if self.selected is not None:\n self.selected['widget'].setParent(None)\n self.selected_name = name\n self.selected = self.plugins[name]\n self.title.setText(self.selected['title'])\n self.container.addWidget(self.selected['widget'], 1)\n if hasattr(self.selected['widget'], 'setup'):\n self.selected['widget'].setup()\n\n\nclass ViewContainer(QCSWidget):\n\n __empty_view__ = dict(idx=0, title=None)\n\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self.header = TabBar()\n self.container = QtWidgets.QStackedWidget()\n self.container.addWidget(QtWidgets.QWidget())\n\n vbox = VBox(self, margin=(1, 0, 0, 0), spacing=5)\n vbox.addWidget(self.header)\n vbox.addWidget(self.container, 1)\n\n self.views = {}\n self.current_view = None\n self.header.tabSelected.connect(self.select_view)\n\n def set_available_views(self, views):\n if not self.current_view in views:\n self.container.setCurrentIndex(0)\n self.current_view = None\n\n self.header.clear()\n views = [v for v in views if v in self.views]\n\n for view in views:\n self.header.addTab(view, self.views[view]['title'])\n\n if self.current_view is None:\n self.select_view(views[0])\n else:\n widget = self.views[self.current_view]['widget']\n if hasattr(widget, 'setup'):\n widget.setup()\n\n def select_view(self, name):\n if name in self.views:\n self.container.setCurrentIndex(self.views[name]['idx'])\n self.current_view = name\n self.header.setSelected(name)\n widget = self.views[self.current_view]['widget']\n if hasattr(widget, 'setup'):\n widget.setup()\n\n def load_view(self, name, title, cls):\n if name in self.views:\n return\n idx = len(self.views) + 1\n widget = cls()\n self.container.addWidget(widget)\n self.views[name] = dict(title=title, idx=idx, widget=widget)\n return widget\n\n def unload_view(self, name):\n pass\n\n def propagate_keybinding(self, evt):\n if self.current_view is not None:\n widget = self.views[self.current_view]['widget']\n if hasattr(widget, 'triggerKeybinding'):\n widget.triggerKeybinding(evt.key(), evt.modifiers())\n\n if not evt.isAccepted():\n evt.accept()\n\n\nimport time\nfrom multiprocessing import Process\n\n\ndef update_ui():\n logger.info('Updating UI')\n QtCore.QCoreApplication.processEvents()\n time.sleep(0.1)\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n\n resized = QtCore.pyqtSignal()\n\n __title__ = \"SuRVoS: Super-Region Volume Segmentation workbench\"\n\n def __init__(self, plugins=None, views=None, maximize=False, title=__title__):\n super().__init__()\n\n self.p = Process(target=update_ui)\n self.p.start()\n\n material_font = resource('iconfont', 'MaterialIcons-Regular.ttf')\n QtGui.QFontDatabase.addApplicationFont(material_font)\n\n qcs_path = resource('qcs', 'survos.qcs')\n if op.isfile(qcs_path):\n with open(qcs_path, 'r') as f:\n self.setStyleSheet(f.read())\n\n self.setWindowTitle(title)\n\n self._loaded_views = {}\n self._loaded_plugins = {}\n self._setup_layout()\n\n self.setMinimumSize(1024, 768)\n if maximize:\n self.showMaximized()\n else:\n self.show()\n\n ModalManager.instance(self).show_loading('Populating workspace')\n self._load_views(views)\n name = self._load_plugins(plugins)\n self.select_plugin(name)\n\n if Launcher.g.connected:\n ModalManager.g.hide()\n\n def resizeEvent(self, event):\n super().resizeEvent(event)\n self.resized.emit()\n\n def _setup_layout(self):\n container = QtWidgets.QWidget()\n self.setCentralWidget(container)\n\n self.iconContainer = IconContainer()\n self.pluginContainer = PluginContainer()\n self.viewContainer = ViewContainer()\n\n hbox = HBox(container)\n hbox.addWidget(self.iconContainer)\n hbox.addWidget(self.pluginContainer)\n hbox.addWidget(self.viewContainer, 1)\n\n self.iconContainer.plugin_selected.connect(self.show_plugin)\n self.pluginContainer.view_requested.connect(self.show_view)\n self.plugin2views = dict()\n\n def _load_plugins(self, plugins=None):\n all_plugins = list_plugins() if plugins is None else plugins\n for pname in all_plugins:\n plugin = self.load_plugin(pname)\n for view in self.plugin2views[pname]:\n if view in self._loaded_views:\n plugin.register_view(view, self._loaded_views[view])\n plugin.on_created()\n return all_plugins[0]\n\n def _load_views(self, views=None):\n all_views = list_views() if views is None else views\n for vname in all_views:\n view = self.load_view(vname)\n self._loaded_views[vname] = view\n\n def load_plugin(self, name):\n if name in self.plugin2views:\n return\n plugin = get_plugin(name)\n name = plugin['name']\n title = plugin['title']\n plugin_cls = plugin['cls']\n self.plugin2views[name] = plugin['views']\n self.iconContainer.load_plugin(name, plugin['icon'], title)\n return self.pluginContainer.load_plugin(name, title, plugin_cls)\n\n def unload_plugin(self, name):\n self.iconContainer.unload_plugin(name)\n self.pluginContainer.unload_plugin(name)\n\n def load_view(self, name):\n view = get_view(name)\n name, cls, title = view['name'], view['cls'], view['title']\n return self.viewContainer.load_view(name, title, cls)\n\n def unload_view(self, name):\n self.viewContainer.unload_view(name)\n\n def select_plugin(self, name):\n self.iconContainer.select_plugin(name)\n\n def show_view(self, name, **kwargs):\n self.viewContainer.select_view(name, **kwargs)\n\n def show_plugin(self, name):\n if name in self.plugin2views:\n self.viewContainer.set_available_views(self.plugin2views[name])\n self.pluginContainer.show_plugin(name)\n\n def keyPressEvent(self, e):\n if e.key() == QtCore.Qt.Key_Escape:\n self.setFocus()\n e.accept()\n elif e.key() == ord(Config['qtui.menuKey']):\n current = self.pluginContainer.minimumWidth()\n stop = self.pluginContainer.__sidebar_width__ - current\n start = self.pluginContainer.__sidebar_width__ - stop\n\n group = QtCore.QParallelAnimationGroup()\n\n for anim in [b'maximumWidth', b'minimumWidth']:\n anim = QtCore.QPropertyAnimation(self.pluginContainer, anim)\n anim.setDuration(100)\n anim.setStartValue(start)\n anim.setEndValue(stop)\n group.addAnimation(anim)\n\n group.start()\n self.__anim = group\n e.accept()\n else:\n logger.debug(\"Propagating event: {}\".format(e))\n self.viewContainer.propagate_keybinding(e)\n\n def closeEvent(self, event):\n \"\"\"if Launcher.g.terminated or Launcher.g.connected:\n return event.accept()\n Launcher.g.terminated = True\n ModalManager.g.accept()\n QtWidgets.QApplication.processEvents()\n ModalManager.g.terminate()\n event.ignore()\"\"\"\n pass\n","sub_path":"survos2/ui/qt/mainwindow.py","file_name":"mainwindow.py","file_ext":"py","file_size_in_byte":10142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"384447917","text":"import argparse\r\nimport sys\r\n\r\nimport portscan\r\n\r\n\r\ndef parse(args):\r\n parser = argparse.ArgumentParser(description=\"Script for checking ports on host. Allows TCP and UDP ports,\"\r\n \"and define define protocol, using this port.\")\r\n\r\n parser.add_argument('-t', dest='tcp', action='store_true', help='Scan tcp ports. '\r\n 'If tcp and udp flags both are absent,'\r\n 'scanner checks only tcp ports.')\r\n parser.add_argument('-u', dest='udp', action='store_true', help='Scan udp ports. Require root user.')\r\n parser.add_argument('-p', '--ports', action='store', nargs=2, type=int, default=[1, 65535], help='Ports range to '\r\n 'scan. By default '\r\n 'scan all ports.')\r\n parser.add_argument('host', action='store', help='Host for scanning')\r\n\r\n args = parser.parse_args(args)\r\n if not args.tcp and not args.udp:\r\n args.tcp = True\r\n\r\n return args\r\n\r\n\r\ndef main(args):\r\n args = parse(args[1:])\r\n\r\n scanner = portscan.Scanner(args.host, args.ports[0], args.ports[1], args.tcp, args.udp, workers=20)\r\n try:\r\n scanner.start()\r\n except KeyboardInterrupt:\r\n scanner.stop()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv)\r\n","sub_path":"tasks/PortScan/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"377187593","text":"\"\"\"\"\"\"\nimport time\nimport codecs\nimport sqlite3\nfrom two1.lib.bitcoin import Transaction\n\n\n###############################################################################\n# Payment Channel Models #\n###############################################################################\n\n# *************************** Base Data Models ****************************** #\n\nclass ChannelError(Exception):\n pass\n\n\nclass ModelNotFound(ChannelError):\n pass\n\n\nclass DuplicateRequestError(ChannelError):\n pass\n\n\nclass InvalidPaymentError(ChannelError):\n pass\n\n\nclass ChannelDatabase:\n\n def __init__(self):\n pass\n\n def create(self, refund_tx, merch_pubkey):\n raise NotImplementedError()\n\n def lookup(self, deposit_txid):\n raise NotImplementedError()\n\n def update_deposit(self, deposit_txid, deposit_tx, amount):\n raise NotImplementedError()\n\n def update_payment(self, deposit_txid, payment_tx, pmt_amt):\n raise NotImplementedError()\n\n def delete(self, deposit_txid):\n raise NotImplementedError()\n\n\nclass PaymentDatabase:\n\n def __init__(self):\n pass\n\n def create(self, payment_tx):\n raise NotImplementedError()\n\n def lookup(self, payment_txid):\n raise NotImplementedError()\n\n def redeem(self, payment_txid):\n raise NotImplementedError()\n\n\n# *************************** Django Data ORM ****************************** #\n\n\nclass DatabaseDjango:\n\n \"\"\"Payment channel data bindings for django models.\"\"\"\n\n def __init__(self, Channel, Payment):\n self.Channel = ChannelDjango(Channel)\n self.Payment = PaymentDjango(Payment)\n\n\nclass ChannelDjango(ChannelDatabase):\n\n def __init__(self, Channel):\n self.Channel = Channel\n\n def create(self, refund_tx, merch_pubkey):\n \"\"\"Create a payment channel entry.\"\"\"\n deposit_txid = str(refund_tx.inputs[0].outpoint)\n state = 'opening'\n now = time.time()\n expiry = refund_tx.lock_time\n mp = codecs.encode(merch_pubkey.compressed_bytes, 'hex_codec').decode()\n self.Channel.create(deposit_txid=deposit_txid, state=state,\n refund_tx=refund_tx.to_hex(), merchant_pubkey=mp,\n expires_at=expiry)\n return True\n\n def lookup(self, deposit_txid):\n \"\"\"Look up a payment channel entry by deposit txid.\"\"\"\n rv = self.Channel.objects.get(deposit_txid=deposit_txid)\n deposit_tx = Transaction.from_hex(rv.deposit_tx) if rv.deposit_tx else None\n payment_tx = Transaction.from_hex(rv.payment_tx) if rv.payment_tx else None\n refund_tx = Transaction.from_hex(rv.refund_tx) if rv.refund_tx else None\n return {'deposit_txid': rv.deposit_txid, 'state': rv.state,\n 'deposit_tx': deposit_tx, 'payment_tx': payment_tx,\n 'refund_tx': refund_tx, 'merchant_pubkey': rv.merchant_pubkey,\n 'created_at': rv.created_at, 'expires_at': rv.expires_at,\n 'amount': rv.amount, 'last_payment_amount': rv.last_payment_amount}\n\n def update_deposit(self, deposit_txid, deposit_tx, amount):\n \"\"\"Update a payment channel with the deposit transaction.\"\"\"\n # Make sure there isn't already a deposit in this channel\n rv = self.Channel.objects.get(deposit_txid=deposit_txid)\n if rv.deposit is not None:\n raise DuplicateRequestError()\n # Update the channel with the new deposit\n rv.update(deposit_tx=deposit_tx.to_hex(), amount=amount)\n return True\n\n def update_payment(self, deposit_txid, payment_tx, pmt_amt):\n \"\"\"Update a payment channel with a new payment transaction.\"\"\"\n self.Channel.objects.get(deposit_txid=deposit_txid).update(\n payment_tx=payment_tx, last_payment_amount=pmt_amt)\n return True\n\n def update_state(self, deposit_txid, new_state):\n \"\"\"Update payment channel state.\"\"\"\n self.Channel.objects.get(deposit_txid=deposit_txid).update(state=new_state)\n return True\n\n\nclass PaymentDjango(ChannelDatabase):\n\n def __init__(self, Payment):\n self.Payment = Payment\n\n def create(self, deposit_txid, payment_tx, amount):\n \"\"\"Create a payment entry.\"\"\"\n self.Payment.create(payment_txid=payment_txid, amount=amount,\n payment_tx=payment_tx.to_hex(),\n deposit_txid=deposit_txid)\n return True\n\n def lookup(self, payment_txid):\n \"\"\"Look up a payment entry by deposit txid.\"\"\"\n rv = self.Payment.objects.get(payment_txid=payment_txid)\n return {'payment_txid': rv.payment_txid,\n 'payment_tx': Transaction.from_hex(rv.payment_tx),\n 'amount': rv.amount, 'is_redeemed': rv.is_redeemed,\n 'deposit_txid': rv.deposit_txid}\n\n def redeem(self, payment_txid):\n \"\"\"Update payment entry to be redeemed.\"\"\"\n self.Payment.objects.get(payment_txid=txid).update(is_redeemed=True)\n return True\n\n\nclass DatabaseSQLite3:\n\n \"\"\"Default payment channel data bindings when no data service is provided.\"\"\"\n\n def __init__(self, db='payment.sqlite3'):\n self.connection = sqlite3.connect(db, check_same_thread=False)\n self.c = self.connection.cursor()\n self.pc = ChannelSQLite3(self)\n self.pmt = PaymentSQLite3(self)\n\n\n# *************************** Default SQLite3 ****************************** #\n\nclass ChannelSQLite3(ChannelDatabase):\n\n def __init__(self, db):\n \"\"\"Instantiate SQLite3 for storing channel transaction data.\"\"\"\n self.c = db.c\n self.connection = db.connection\n self.c.execute(\"CREATE TABLE IF NOT EXISTS 'payment_channel' \"\n \"(deposit_txid text unique, state text,\"\n \"deposit_tx text, payment_tx text, refund_tx text, \"\n \"merchant_pubkey text, created_at timestamp, \"\n \"expires_at timestamp, amount integer, \"\n \"last_payment_amount integer)\")\n\n def create(self, refund_tx, merch_pubkey):\n \"\"\"Create a payment channel entry.\"\"\"\n deposit_txid = str(refund_tx.inputs[0].outpoint)\n state = 'opening'\n now = time.time()\n expiry = refund_tx.lock_time\n mp = codecs.encode(merch_pubkey.compressed_bytes, 'hex_codec').decode()\n insert = 'INSERT INTO payment_channel VALUES (?' + ',?' * 9 + ')'\n self.c.execute(insert, (deposit_txid, state, None, None,\n refund_tx.to_hex(), mp, now, expiry, 0, 0))\n self.connection.commit()\n return True\n\n def lookup(self, deposit_txid):\n \"\"\"Look up a payment channel entry by deposit txid.\"\"\"\n select = 'SELECT * FROM payment_channel WHERE deposit_txid=?'\n self.c.execute(select, (deposit_txid,))\n rv = self.c.fetchone()\n if rv is None:\n raise ModelNotFound()\n deposit_tx = Transaction.from_hex(rv[2]) if rv[2] else None\n payment_tx = Transaction.from_hex(rv[3]) if rv[3] else None\n refund_tx = Transaction.from_hex(rv[4]) if rv[4] else None\n return {'deposit_txid': rv[0], 'state': rv[1],\n 'deposit_tx': deposit_tx, 'payment_tx': payment_tx,\n 'refund_tx': refund_tx, 'merchant_pubkey': rv[5],\n 'created_at': rv[6], 'expires_at': rv[7], 'amount': rv[8],\n 'last_payment_amount': rv[9]}\n\n def update_deposit(self, deposit_txid, deposit_tx, amount):\n \"\"\"Update a payment channel with the deposit transaction.\"\"\"\n # Make sure there isn't already a deposit in this channel\n select = 'SELECT deposit_tx FROM payment_channel WHERE deposit_txid=?'\n self.c.execute(select, (deposit_txid,))\n deposit = self.c.fetchone()[0]\n if deposit is not None:\n raise DuplicateRequestError()\n # Update the channel with the new deposit\n update = ('UPDATE payment_channel SET deposit_tx=?, amount=? '\n 'WHERE deposit_txid=?')\n self.c.execute(update, (deposit_tx.to_hex(), amount, deposit_txid))\n self.connection.commit()\n return True\n\n def update_payment(self, deposit_txid, payment_tx, pmt_amt):\n \"\"\"Update a payment channel with a new payment transaction.\"\"\"\n update = ('UPDATE payment_channel SET payment_tx=?,'\n 'last_payment_amount=? WHERE deposit_txid=?')\n self.c.execute(update, (payment_tx.to_hex(), pmt_amt, deposit_txid))\n return True\n\n def update_state(self, deposit_txid, new_state):\n \"\"\"Update payment channel state.\"\"\"\n update = 'UPDATE payment_channel SET state=? WHERE deposit_txid=?'\n self.c.execute(update, (new_state, deposit_txid))\n self.connection.commit()\n return True\n\n\nclass PaymentSQLite3(PaymentDatabase):\n\n def __init__(self, db):\n \"\"\"Instantiate SQLite3 for storing channel payment data.\"\"\"\n self.c = db.c\n self.connection = db.connection\n self.c.execute(\"CREATE TABLE IF NOT EXISTS 'payment_channel_spend' \"\n \"(payment_txid text unique, payment_tx text, \"\n \"amount integer, is_redeemed integer, \"\n \"deposit_txid text)\")\n\n def create(self, deposit_txid, payment_tx, amount):\n \"\"\"Create a payment entry.\"\"\"\n insert = 'INSERT INTO payment_channel_spend VALUES (?,?,?,?,?)'\n self.c.execute(insert, (str(payment_tx.hash), payment_tx.to_hex(),\n amount, 0, deposit_txid))\n self.connection.commit()\n return True\n\n def lookup(self, payment_txid):\n \"\"\"Look up a payment entry by deposit txid.\"\"\"\n select = 'SELECT * FROM payment_channel_spend WHERE payment_txid=?'\n self.c.execute(select, (payment_txid,))\n rv = self.c.fetchone()\n if rv is None:\n raise ModelNotFound()\n return {'payment_txid': rv[0],\n 'payment_tx': Transaction.from_hex(rv[1]),\n 'amount': rv[2], 'is_redeemed': (rv[3] == 1),\n 'deposit_txid': rv[4]}\n\n def redeem(self, payment_txid):\n \"\"\"Update payment entry to be redeemed.\"\"\"\n update = ('UPDATE payment_channel_spend SET is_redeemed=? '\n 'WHERE payment_txid=?')\n self.c.execute(update, (1, payment_txid))\n self.connection.commit()\n return True\n\n\n##############################################################################\n# On-Chain Transaction Models #\n##############################################################################\n\n# *************************** Base Data Models ****************************** #\n\nclass OnChainError(Exception):\n pass\n\n\nclass OnChainDatabase:\n\n def __init__(self):\n pass\n\n def create(txid):\n pass\n\n def lookup(txid):\n pass\n\n def delete(txid):\n pass\n\n# *************************** Django Data ORM ****************************** #\n\n\nclass OnChainDjango(OnChainDatabase):\n\n def __init__(self, BlockchainTransaction):\n self.BlockchainTransaction = BlockchainTransaction\n\n def create(self, txid, amount):\n \"\"\"Create a transaction entry.\"\"\"\n bt = self.BlockchainTransaction(txid=txid, amount=amount)\n bt.save()\n return True\n\n def lookup(self, txid):\n \"\"\"Look up a transaction entry.\"\"\"\n try:\n rv = self.BlockchainTransaction.objects.get(txid=txid)\n return {'txid': rv.txid, 'amount': rv.amount}\n except self.BlockchainTransaction.DoesNotExist:\n return None\n\n def delete(self, txid):\n \"\"\"Delete a transaction entry.\"\"\"\n try:\n txn = self.BlockchainTransaction.objects.get(txid=txid)\n txn.delete()\n except self.BlockchainTransaction.DoesNotExist:\n return None\n\n# *************************** Default SQLite3 ****************************** #\n\n\nclass OnChainSQLite3(OnChainDatabase):\n\n def __init__(self, db='payment.sqlite3'):\n \"\"\"Instantiate SQLite3 for storing on chain transaction data.\"\"\"\n self.connection = sqlite3.connect(db, check_same_thread=False)\n self.c = self.connection.cursor()\n self.c.execute(\"CREATE TABLE IF NOT EXISTS 'payment_onchain' (txid text, amount integer)\")\n\n def create(self, txid, amount):\n \"\"\"Create a transaction entry.\"\"\"\n insert = 'INSERT INTO payment_onchain VALUES (?, ?)'\n self.c.execute(insert, (txid, amount))\n self.connection.commit()\n return {'txid': txid, 'amount': amount}\n\n def lookup(self, txid):\n \"\"\"Look up a transaction entry.\"\"\"\n select = 'SELECT txid, amount FROM payment_onchain WHERE txid=?'\n self.c.execute(select, (txid,))\n rv = self.c.fetchone()\n if rv is None:\n return rv\n return {'txid': rv[0], 'amount': rv[1]}\n\n def delete(self, txid):\n \"\"\"Delete a transaction entry.\"\"\"\n delete = 'DELETE FROM payment_onchain WHERE txid=?'\n self.c.execute(delete, (txid,))\n self.connection.commit()\n","sub_path":"two1/lib/bitserv/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"312375265","text":"from django.utils.encoding import python_2_unicode_compatible\nfrom django.db import models\n\nfrom mapping.common.mixins import TimestampsMixin\n\n\n@python_2_unicode_compatible\nclass WorkShift(TimestampsMixin):\n \"Working Period Shift\"\n\n SUNDAY = 0\n MONDAY = 1\n TUESDAY = 2\n WEDNESDAY = 3\n THURSDAY = 4\n FRIDAY = 5\n SATURDAY = 6\n\n DAY_OF_WEEK_CHOICES = (\n (SUNDAY, 'Sunday'),\n (MONDAY, 'Monday'),\n (TUESDAY, 'Tuesday'),\n (WEDNESDAY, 'Wednesday'),\n (THURSDAY, 'Thursday'),\n (FRIDAY, 'Friday'),\n (SATURDAY, 'Saturday'))\n\n day_of_week = models.PositiveSmallIntegerField(\n 'day of week',\n help_text='Day of week shift starts on.',\n choices=DAY_OF_WEEK_CHOICES,\n default=MONDAY,)\n\n time_shift_starts = models.TimeField(\n 'shift start time',\n help_text='Shift start',)\n\n time_shift_ends = models.TimeField(\n 'shift end time',\n help_text='Shift end',)\n\n work_period = models.ForeignKey(\n 'WorkPeriod',\n related_name='work_shifts',)\n\n class Meta:\n db_table = 'accounts_work_shift'\n ordering = ['day_of_week', 'time_shift_starts']\n\n def __str__(self):\n return \"%s from: %s until: %s\" % (\n self.DAY_OF_WEEK_CHOICES[self.day_of_week][1],\n self.time_shift_starts,\n self.time_shift_ends,)\n","sub_path":"mapping/accounts/models/work_shift.py","file_name":"work_shift.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"160729381","text":"from mhcflurry.dataset import Dataset\nfrom mhcflurry.paths import CLASS1_DATA_CSV_PATH\nfrom mhcflurry import Class1BindingPredictor\n\nfrom nose.tools import eq_\nimport numpy as np\n\n\ndef class1_binding_predictor_A0205_training_accuracy():\n dataset = Dataset.from_csv(CLASS1_DATA_CSV_PATH)\n dataset_a0205 = dataset.get_allele(\"HLA-A0205\")\n\n predictor = Class1BindingPredictor.from_hyperparameters(name=\"A0205\")\n predictor.fit_dataset(dataset_a0205)\n peptides = dataset_a0205.peptides\n ic50_pred = predictor.predict(peptides)\n ic50_true = dataset_a0205.affinities\n eq_(len(ic50_pred), len(ic50_true))\n assert np.allclose(ic50_pred, ic50_true)\n\nif __name__ == \"__main__\":\n class1_binding_predictor_A0205_training_accuracy()\n","sub_path":"test/test_class1_binding_predictor_A0205.py","file_name":"test_class1_binding_predictor_A0205.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"372501458","text":"# Copyright (c) 2010-2013, Regents of the University of California. \n# All rights reserved. \n# \n# Released under the BSD 3-Clause license as published at the link below.\n# https://openwsn.atlassian.net/wiki/display/OW/License\nimport logging\nlog = logging.getLogger('openPcapLinux')\n# Do not set the default null log handlers here. Logging already will have been\n# configured, because this class is imported later, on the fly, by OpenTun.\n\nimport threading\nimport sys\nimport re\nimport netifaces\nimport pcap\n\nimport openPcap\nfrom pydispatch import dispatcher\nimport openvisualizer.openvisualizer_utils as u\n\n#============================ defines =========================================\n\n#============================ helper classes ==================================\n\nclass PcapReadThread(threading.Thread):\n '''\n Thread which continously reads input from a TUN interface.\n \n When data is received from the interface, it calls a callback configured\n during instantiation.\n '''\n \n def __init__(self,pcapIf,callback):\n \n # store params\n self.adapter = pcapIf\n self.callback = callback\n \n # local variables\n self.goOn = True\n \n # initialize parent\n threading.Thread.__init__(self)\n \n # give this thread a name\n self.name = 'PcapReadThread'\n \n # start myself\n self.start()\n \n def run(self):\n \n while self.goOn: \n try:\n for ts,pk in self.adapter:\n self.callback(pk)\n\n except Exception as err:\n log.error(err)\n pass\n \n #======================== public ==========================================\n \n def close(self):\n self.goOn = False\n \n #======================== private =========================================\n\n \n#============================ main class ======================================\n\nclass OpenPcapLinux(openPcap.OpenPcap):\n '''\n Class which interfaces between a pcap interface and an EventBus.\n '''\n \n def __init__(self):\n # log\n log.info(\"create instance\")\n \n # initialize parent class\n openPcap.OpenPcap.__init__(self)\n \n #======================== public ==========================================\n \n #======================== private =========================================\n \n def _v6ToInternet_notif(self,sender,signal,data):\n \n with self.datalock:\n self.txBuf = ''\n self.txBufFill = 0\n \n # ethernet header\n\n # destination \n self._addToTxBuff(self.MAC_BROADCAST)\n # source\n self._addToTxBuff(self.adapterMac)\n # ethertype\n self._addToTxBuff(self.ETHERTYPE_IPv6)\n\n # payload\n self._addToTxBuff(data)\n \n # send\n self.PcapIf.inject(self.txBuf,self.txBufFill) # works with linux pypcap\n\n\n def _createPcapIf(self):\n '''\n Open a pcap interface \n \n :returns: The handler of the interface, which can be used for later\n read/write operations.\n ''' \n\n #===== open PCAP adapter\n adapter = pcap.pcap(self.adapterName)\n \n #===== apply PCAP filter \n adapter.setfilter('ip6')\n\n return adapter\n\n\n def _createPcapReadThread(self):\n '''\n Creates and starts the thread to read messages arriving from the pcap interface.\n '''\n return PcapReadThread(\n self.PcapIf,\n self._rxpacket_handler\n )\n","sub_path":"software/openvisualizer/openvisualizer/openPcap/openPcapLinux.py","file_name":"openPcapLinux.py","file_ext":"py","file_size_in_byte":3763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"124662037","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom stock.items import DongfangYanBao\n\n\nclass DongfangSpider(scrapy.Spider):\n name = 'stockdfpj'\n\n headers = {\n # 'Cookie' : 'xq_q_token=62c76bcb2dcc3aa55d754d345301ac59fbd80d07',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36',\n }\n\n def start_requests(self):\n # urls=[]\n # with open(\"MyGitlabScrapy/spiders/gitlabweb.csv\") as file:\n # for url in file:\n # urls.append(url)\n count = 0\n\n base = 'http://guba.eastmoney.com/list'\n urls = []\n ids = ids = ['300719', '300696', '002297', '002023', '300397', '600862', '300581', '002413', '002933', '600391',\n '300424', '000768', '300159', '000738', '600316', '600372', '600038', '002013', '600893', '002190',\n '600760']\n for id in ids:\n while count < 5:\n count = count + 1\n url = base + ',' + str(id) + ',' + str(2) + ',' + 'f_' + str(count) + '.html'\n urls.append(url)\n print(url)\n count = 0\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n\n stockall = response.xpath('//*[@id=\"articlelistnew\"]/div')\n\n #t = response.xpath('//*[@id=\"stockname\"]/@data-popstock').extract()\n # print(t)\n\n pinglun = DongfangYanBao()\n for single in stockall[1:]:\n pinglun['id'] = response.xpath('//*[@id=\"stockname\"]/@data-popstock').extract()\n pinglun['yuedu'] = single.xpath('span[1]/text()').extract()\n pinglun['pinglun'] = single.xpath('span[2]/text()').extract()\n pinglun['title'] = single.xpath('span[3]/a/@title').extract()\n pinglun['pingji'] = single.xpath('span[4]/text()').extract()\n pinglun['jigou'] = single.xpath('span[5]/text()').extract()\n pinglun['fatieshijian'] = single.xpath('span[6]/text()').extract()\n\n yield pinglun\n","sub_path":"src/main/java/com/example/stock/python/stock/spiders/DongfangYanBao.py","file_name":"DongfangYanBao.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"605670698","text":"import jinja2 as j2\nfrom pathlib import Path\nimport os\n\nPIPELINE_TEMPLATE_J2_FILE = 'templates/bitbucket-pipelines.yml.j2'\nROLES_DIR = 'roles/'\n\n\ndef find_all_scenarios():\n scenario_dirs = []\n for root, dirs, files in os.walk('..'):\n [scenario_dirs.append(Path(root)) for f in files if f.endswith(\"molecule.yml\")]\n return sorted(scenario_dirs)\n\n\ndef load_template():\n jenv = j2.Environment(\n loader=j2.FileSystemLoader('.'),\n lstrip_blocks=True,\n trim_blocks=True)\n return jenv.get_template(PIPELINE_TEMPLATE_J2_FILE)\n\ndef main():\n scenario_paths = find_all_scenarios()\n\n template = load_template()\n generated_output = template.render(scenario_paths=scenario_paths)\n\n print(generated_output)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pipeline_generator/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"271005183","text":"from sklearn.cluster import KMeans\r\nimport numpy as np\r\nimport pylab as pl\r\nimport pandas as pd\r\nfrom sklearn.decomposition import PCA\r\n\r\ndef normal_X(X):\r\n \"\"\"\r\n :param X:二维矩阵,N*D,N个D维的数据\r\n :return: 将X归一化的结果\r\n \"\"\"\r\n N, D = X.shape\r\n for i in range(N):\r\n temp = np.sum(np.multiply(X[i], X[i]))\r\n X[i] /= np.sqrt(temp)\r\n return X\r\ndef normal_W(W):\r\n \"\"\"\r\n :param W:二维矩阵,D*(n*m),D个n*m维的数据\r\n :return: 将W归一化的结果\r\n \"\"\"\r\n for i in range(W.shape[1]):\r\n temp = np.sum(np.multiply(W[:,i], W[:,i]))\r\n W[:, i] /= np.sqrt(temp)\r\n return W\r\n\r\n#画图\r\ndef draw(C):\r\n colValue = ['r', 'y', 'g', 'b', 'c', 'k', 'm']\r\n for i in range(len(C)):\r\n coo_X = [] #x坐标列表\r\n coo_Y = [] #y坐标列表\r\n for j in range(len(C[i])):\r\n coo_X.append(C[i][j][0])\r\n coo_Y.append(C[i][j][1])\r\n pl.scatter(coo_X, coo_Y, marker='x', color=colValue[i%len(colValue)], label=i)\r\n pl.title(\"K-Means\")\r\n pl.legend(loc='upper right')\r\n pl.show()\r\n\r\n#用的数据集\r\ndataxl_true = pd.DataFrame(np.array(pd.read_excel(\"清洗后的数据2.xlsx\")))\r\n# print(max( dataxl_true[0]))\r\nfor i in range(dataxl_true.columns.size):\r\n dataxl_true[i] = dataxl_true[i].apply(lambda x: (x - min(dataxl_true[i])) / (max(dataxl_true[i]) - min(dataxl_true[i])))\r\n# dataxl_true.to_excel(\"归一化后的数据.xlsx\")\r\n # dataxl_true[i] = (dataxl_true[i]-min(dataxl_true[i])/(max(dataxl_true[i])-min(dataxl_true[i])))\r\n# print(dataxl_true)\r\n# data_yz = pd.DataFrame(np.array(pd.read_csv(\"test.csv\",index_col=0)))\r\n# dataxl_true = pd.concat([data_xl[0],data_xl[1],data_xl[2],data_xl[3]],axis=1)\r\n# dataxl_true_result = data_xl[4]\r\n# datayz_true = pd.concat([data_yz[0],data_yz[1],data_yz[2],data_yz[3]],axis=1)\r\n# datayz_true_result = list(data_yz[4])\r\n\r\n# dataxl_true_guiyi = normal_X(dataxl_true)\r\n# dataset = dataxl_true\r\n# dataset_old = dataxl_true_guiyi\r\n\r\npca = PCA(n_components=2)\r\ndataset = pca.fit_transform(dataxl_true)\r\ndataset = np.array(dataset)\r\n# pd.DataFrame(dataset).to_excel(\"毕业聚类数据.xlsx\")\r\n# print(dataset)\r\n# dataset_old = dataset.copy()\r\n\r\n#对数据进行归一化\r\n# dataset = normal_X(dataset)\r\n\r\nfrom sklearn.cluster import SpectralClustering\r\nkmeans = SpectralClustering(n_clusters=3).fit(dataxl_true)\r\n\r\n\r\nres = kmeans.labels_\r\n# pd.concat([pd.DataFrame(dataxl_true),pd.DataFrame(res)],axis=1).to_excel(\"k-means_clustering.xlsx\")\r\n# 计算轮廓系数\r\nfrom sklearn import metrics\r\nscore = metrics.silhouette_score(dataxl_true,res,metric='euclidean')\r\nprint(score)\r\n\r\ncolValue = ['r', 'y', 'g', 'b', 'c', 'k', 'm']\r\n# print(dataset)\r\n# print(len(res))\r\nfor i in range(len(res)):\r\n pl.scatter(dataset[i][0], dataset[i][1], marker='x', color=colValue[res[i]],s=60)\r\n\r\npl.title(\"spectral-clustering\")\r\npl.legend(loc='upper right')\r\npl.show()\r\n","sub_path":"spectral-clustering.py","file_name":"spectral-clustering.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"286913288","text":"from os.path import join, abspath, dirname\n\nimport click\nimport itertools\nimport re\nimport json\n\n\ndef natural_sort(l):\n convert = lambda text: int(text) if text.isdigit() else text.lower()\n alphanum_key = lambda key: [convert(c) for c in re.split(\"([0-9]+)\", key)]\n return sorted(l, key=alphanum_key)\n\n\ndef flatmap(func, items):\n return itertools.chain.from_iterable(map(func, items))\n\n\ndef ascii_encode(non_compatible_string):\n \"\"\"Primarily used for ensuring terminal display compatibility\"\"\"\n if non_compatible_string:\n return non_compatible_string.encode(\"ascii\", errors=\"ignore\").decode(\"ascii\")\n else:\n return \"\"\n\n\ndef pull(nested_dict):\n if \"type\" in nested_dict and \"inputs\" not in nested_dict:\n return nested_dict\n else:\n inputs = {}\n if \"type\" in nested_dict and \"inputs\" in nested_dict:\n for param, input in list(nested_dict[\"inputs\"].items()):\n inputs[str(param)] = pull(input)\n return inputs\n else:\n return nested_dict\n\n\ndef regex_manifest(protocol, input):\n \"\"\"Special input types, gets updated as more input types are added\"\"\"\n if \"type\" in input and input[\"type\"] == \"choice\":\n if \"options\" in input:\n pattern = \"\\[(.*?)\\]\"\n match = re.search(pattern, str(input[\"options\"]))\n if not match:\n click.echo(\n 'Error in %s: input type \"choice\" options must '\n 'be in the form of: \\n[\\n {\\n \"value\": '\n ', \\n \"label\": \\n '\n \"},\\n ...\\n]\" % protocol[\"name\"]\n )\n raise RuntimeError\n else:\n click.echo(\n f\"Must have options for 'choice' input type. Error in: {protocol['name']}\"\n )\n raise RuntimeError\n\n\ndef iter_json(manifest):\n all_types = {}\n try:\n protocol = manifest[\"protocols\"]\n except TypeError:\n raise RuntimeError(\n \"Error: Your manifest.json file doesn't contain \"\n \"valid JSON and cannot be formatted.\"\n )\n for protocol in manifest[\"protocols\"]:\n types = {}\n for param, input in list(protocol[\"inputs\"].items()):\n types[param] = pull(input)\n if isinstance(input, dict):\n if input[\"type\"] == \"group\" or input[\"type\"] == \"group+\":\n for i, j in list(input.items()):\n if isinstance(j, dict):\n for k, l in list(j.items()):\n regex_manifest(protocol, l)\n else:\n regex_manifest(protocol, input)\n all_types[protocol[\"name\"]] = types\n return all_types\n\n\ndef by_well(datasets, well):\n return [\n datasets[reading].props[\"data\"][well][0] for reading in list(datasets.keys())\n ]\n\n\ndef makedirs(name, mode=None, exist_ok=False):\n \"\"\"Forward ports `exist_ok` flag for Py2 makedirs. Retains mode defaults\"\"\"\n from os import makedirs\n\n mode = mode if mode is not None else 0o777\n makedirs(name, mode, exist_ok)\n\n\ndef is_valid_jwt_token(token: str):\n regex = r\"Bearer ([a-zA-Z0-9_=]+)\\.([a-zA-Z0-9_=]+)\\.([a-zA-Z0-9_\\-\\+\\/=]*)\"\n return re.fullmatch(regex, token) is not None\n\n\ndef load_sampledata_json(filename: str) -> dict:\n with open(sampledata_path(filename)) as fh:\n return json.load(fh)\n\n\ndef sampledata_path(filename: str) -> str:\n return join(sampledata_dir(), filename)\n\n\ndef sampledata_dir() -> str:\n return abspath(join(dirname(__file__), \"sampledata\", \"_data\"))\n","sub_path":"transcriptic/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"84360842","text":"\"\"\"Main Module for the Streamlit App\"\"\"\n\n#local file imports\nfrom users import User\nfrom app import App\n\ndef main():\n #Creating instance of App class\n app = App()\n\n #Handling user creation\n users = app.get_users_from_api(100)\n User.create_users(users)\n\n #Handling login\n app.login()\n\nif __name__ == '__main__':\n main()","sub_path":"person_dashboard.py","file_name":"person_dashboard.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"368492758","text":"class Solution:\n class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n def allPossibleFBT(self, N):\n if N % 2 == 0: return []\n if N == 1: return [TreeNode(0)]\n rs = []\n for i in range(1,N,2):\n allLeft = self.allPossibleFBT(i)\n allRight = self.allPossibleFBT(N-1-i)\n for l in allLeft:\n for r in allRight:\n root = TreeNode(0)\n root.left, root.right = l, r\n rs.append(root)\n return rs\n","sub_path":"pr/894.py","file_name":"894.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"55302388","text":"class OwnIterator:\n\tdef __init__(self,num=0):\n\t\tself.number=num\n\tdef __iter__(self):\n\t\tself.x=1\n\t\treturn self\n\tdef __next__(self):\n\t\tif self.x<=self.number:\n\t\t\town_iterator=self.x\n\t\t\tself.x+=1\n\t\t\treturn own_iterator\n\t\telse:\n\t\t\traise StopIteration\nfor x in OwnIterator(10):\n\tprint(\"Num = \",x)\n","sub_path":"Iterators/basic_2.py","file_name":"basic_2.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"381448575","text":"#!/usr/bin/env python\n# -*- coding: latin-1 -*-\n# Copyright (c) 2007 John Markus Bjørndalen, jmb@cs.uit.no.\n# See LICENSE.txt for licensing details (MIT License).\n\nimport common # noqa : E402\nfrom pycsp import process, One2OneChannel, Any2OneChannel, BlackHoleChannel, Parallel, poisonChannel\nfrom pycsp.plugNplay import Identity\n\n\n@process\ndef PoisonTest(cout):\n for i in range(100):\n print(i)\n cout(i)\n poisonChannel(cout)\n\n\ndef test():\n a = One2OneChannel(\"a\")\n b = One2OneChannel(\"b\")\n c = One2OneChannel(\"c\")\n d = BlackHoleChannel(\"d\")\n\n Parallel(PoisonTest(a.write),\n Identity(a.read, b.write),\n Identity(b.read, c.write),\n Identity(c.read, d.write))\n for ch in [a, b, c, d]:\n print(\"State of channel\", ch.name, \"- poisoned is\", ch.poisoned)\n\n\n@process\ndef PoisonReader(cin):\n for i in range(100):\n r = cin()\n print(i, r)\n cin.poison()\n\n\n@process\ndef Count(cout):\n i = 0\n while 1:\n cout(i)\n i += 1\n\n\ndef test2():\n a = Any2OneChannel()\n Parallel(Count(a.write),\n Count(a.write),\n PoisonReader(a.read))\n print(\"Processes done\")\n\n\nif __name__ == \"__main__\":\n test()\n test2()\n","sub_path":"test/poisoncheck.py","file_name":"poisoncheck.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"48801187","text":"#!/usr/bin/python\n\n# Copyright: (c) 2020, NS1\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {\n \"metadata_version\": \"1.1\",\n \"status\": [\"preview\"],\n \"supported_by\": \"community\",\n}\n\nDOCUMENTATION = r\"\"\"\n---\nmodule: ns1_zone\n\nshort_description: Create, modify and delete NS1 account teams.\n\nversion_added: \"3.1\"\n\ndescription:\n - Create, modify and delete team objects along with permissions to control access to portal or API.\n\noptions:\n apiKey:\n description: Unique client api key that can be created via the NS1 portal.\n type: str\n required: true\n endpoint:\n description: NS1 API endpoint. Defaults to https://api.nsone.net/v1/\n type: str\n required: false\n ignore_ssl:\n description: Whether to ignore SSL errors. Defaults to false\n type: bool\n required: false\n name:\n description: Name of the team being created, updated, or deleted.\n type: str\n required: true\n state:\n description: Whether the team should be present or not. Use C(present) to create or update and C(absent) to delete.\n type: str\n default: present\n choices:\n - absent\n - present\n required: false\n ip_whitelist:\n description: Array of IP addresses/networks to which to grant the API key access.\n type: list\n required: false\n permissions:\n description: All supported permissions\n type: dict\n required: false\n default: None\n suboptions:\n monitoring:\n description: Group of monitoring-related permissions.\n required: false\n suboptions:\n manage_jobs:\n description: Allows (or prevents, if false) the team to create or modify monitoring jobs.\n type: bool\n default: flase\n required: false\n view_jobs:\n description: Allows (or prevents, if false) the team to view monitoring jobs.\n type: bool\n default: flase\n required: false\n manage_lists:\n description: Allows (or prevents, if false) the team to create or modify notification lists.\n type: bool\n default: flase\n required: false\n account:\n description: Group of account-related permissions.\n required: false\n suboptions:\n manage_users:\n description: Allows (or prevents, if false) the team to create or update users.\n type: bool\n default: flase\n required: false\n view_invoices:\n description: Allows (or prevents, if false) the team to view account invoices.\n type: bool\n default: flase\n required: false\n manage_teams:\n description: Allows (or prevents, if false) the team to create or update teams.\n type: bool\n default: flase\n required: false\n view_activity_log:\n description: Allows (or prevents, if false) the team to view the account activity log.\n type: bool\n default: flase\n required: false\n manage_account_settings:\n description: Allows (or prevents, if false) the team to manage account settings.\n type: bool\n default: flase\n required: false\n manage_apikeys:\n description: Allows (or prevents, if false) the team to create or update API keys.\n type: bool\n default: flase\n required: false\n manage_payment_methods:\n description: Allows (or prevents, if false) the team to manage account payment methods.\n type: bool\n default: flase\n required: false\n manage_ip_whitelist:\n description: Allows (or prevents, if false) the team to create or update IP \"allow\" lists.\n type: bool\n default: flase\n required: false\n data:\n description: Group of data-related permissions.\n required: false\n suboptions:\n push_to_datafeeds:\n description: Allows (or prevents, if false) the team to push data to NS1 data feeds.\n type: bool\n default: flase\n required: false\n manage_datasources:\n description: Allows (or prevents, if false) the team to create and modify data sources.\n type: bool\n default: flase\n required: false\n manage_datafeeds:\n description: Allows (or prevents, if false) the team to create and modify data feeds.\n type: bool\n default: flase\n required: false\n security:\n description: Group of security-related permissions.\n required: false\n suboptions:\n manage_global_2fa:\n description: Allows (or prevents, if false) the team to manage global two-factor authentication (2FA) settings.\n type: bool\n default: flase\n required: false\n dns:\n description: Group of DNS-related permissions.\n required: false\n suboptions:\n zones_allow:\n description: List of specific zones to which the API key is allowed access.\n type: list\n required: false\n manage_zones:\n description: Allows (or prevents, if false) the team to create or modify zones.\n type: bool\n default: flase\n required: false\n zones_deny:\n description: List of specific zones to which the team is denied access.\n type: list\n required: false\n view_zones:\n description: Allows (or prevents, if false) the team to view zones.\n type: bool\n default: flase\n required: false\n zones_allow_by_default:\n description: Set to true to allow access to all zones except for those listed under zones_deny. Set to false to deny access to all zones by default except for those listed under zones_allow.\n type: bool\n default: flase\n required: false\n\nrequirements:\n - python >= 2.7\n - ns1-python >= 0.16.0\n\nseealso:\n - name: Documentation for NS1 API\n description: Complete reference for the NS1 API.\n link: https://ns1.com/api/\n\nauthor:\n - 'NS1'\n\"\"\"\n\nEXAMPLES = r\"\"\"\n- name: add read only team\n local_action:\n module: ns1_team\n name: RO-Only\n permissions:\n monitoring:\n view_jobs: true\n account:\n view_invoices: true\n view_activity_log: true\n dns:\n view_zones: true\n\n- name: delete team\n local_action:\n module: ns1_team\n apiKey: \"{{ ns1_token }}\"\n name: NoLongerAdmin\n state: absent\n\"\"\"\n\nRETURN = r\"\"\"\n\"\"\"\n\nimport functools # noqa\nimport copy\n\ntry:\n from ansible.module_utils.ns1 import NS1ModuleBase, HAS_NS1, Decorators\nexcept ImportError:\n # import via absolute path when running via pytest\n from module_utils.ns1 import NS1ModuleBase, HAS_NS1, Decorators # noqa\n\ntry:\n from ns1.rest.errors import ResourceException\n from ns1.rest.permissions import _default_perms\nexcept ImportError:\n # This is handled in NS1 module_utils\n pass\n\n\nclass NS1Team(NS1ModuleBase):\n \"\"\"Represents the NS1 Team module implementation\"\"\"\n\n def __init__(self):\n \"\"\"Constructor method\"\"\"\n self.module_arg_spec = dict(\n name=dict(required=True, type=\"str\"),\n ip_whitelist=dict(required=False, type=\"list\", default=None),\n permissions=dict(\n required=False,\n type=\"dict\",\n default=None,\n options=dict(\n monitoring=dict(\n required=False,\n type=\"dict\",\n default=None,\n options=dict(\n manage_jobs=dict(type=\"bool\", default=False),\n view_jobs=dict(type=\"bool\", default=False),\n manage_lists=dict(type=\"bool\", default=False),\n ),\n ),\n account=dict(\n required=False,\n type=\"dict\",\n default=None,\n options=dict(\n manage_users=dict(type=\"bool\", default=False),\n view_invoices=dict(type=\"bool\", default=False),\n manage_teams=dict(type=\"bool\", default=False),\n view_activity_log=dict(type=\"bool\", default=False),\n manage_account_settings=dict(type=\"bool\", default=False),\n manage_apikeys=dict(type=\"bool\", default=False),\n manage_payment_methods=dict(type=\"bool\", default=False),\n manage_ip_whitelist=dict(type=\"bool\", default=False),\n ),\n ),\n data=dict(\n required=False,\n type=\"dict\",\n default=None,\n options=dict(\n push_to_datafeeds=dict(type=\"bool\", default=False),\n manage_datasources=dict(type=\"bool\", default=False),\n manage_datafeeds=dict(type=\"bool\", default=False),\n ),\n ),\n security=dict(\n required=False,\n type=\"dict\",\n default=None,\n options=dict(\n manage_global_2fa=dict(type=\"bool\", default=False),\n ),\n ),\n dns=dict(\n required=False,\n type=\"dict\",\n default=None,\n options=dict(\n zones_allow=dict(type=\"list\", default=False),\n manage_zones=dict(type=\"bool\", default=False),\n zones_deny=dict(type=\"list\", default=False),\n view_zones=dict(type=\"bool\", default=False),\n zones_allow_by_default=dict(type=\"bool\", default=False),\n ),\n ),\n ),\n ),\n state=dict(\n required=False,\n type=\"str\",\n default=\"present\",\n choices=[\"present\", \"absent\"],\n ),\n )\n\n NS1ModuleBase.__init__(\n self,\n self.module_arg_spec,\n supports_check_mode=True,\n )\n\n @Decorators.skip_in_check_mode\n def update(self, team_id, built_changes):\n \"\"\"Updates a team with permissions from task\n\n :param team_id: Zone object of existing zone returned by NS1\n :type team_id: str\n :param built_changes: Dict of permissions to be applied to a new\n team.\n :type built_changes: dict\n :return: The updated zone object returned by NS1\n :rtype: dict\n \"\"\"\n team_update = self.ns1.team()\n return team_update.update(team_id, **built_changes)\n\n @Decorators.skip_in_check_mode\n def create(self, built_changes):\n \"\"\"Creates a team with the given permissions.\n\n :param built_changes: Dict of permissions to be applied to a new\n team.\n :type built_changes: dict\n :return: [description]\n :rtype: [type]\n \"\"\"\n team_create = self.ns1.team()\n return team_create.create(**built_changes)\n\n @Decorators.skip_in_check_mode\n def delete(self, team_id):\n \"\"\"Deletes a team.\n\n :param team_id: Id of an existing team.\n :type team_id: str\n \"\"\"\n team_delete = self.ns1.team()\n team_delete.delete(team_id)\n\n def build_permissions(self):\n \"\"\"Builds a complete set of permissions based on defaults with values\n updated by task parameters.\n\n :return: A complete set of permissions.\n parameters.\n :rtype: dict\n \"\"\"\n default_permissions = dict(permissions=_default_perms)\n built_permissions = copy.deepcopy(default_permissions)\n for key in default_permissions[\"permissions\"]:\n if self.module.params[\"permissions\"] is None:\n built_permissions = default_permissions\n else:\n if self.module.params[\"permissions\"][key] is not None:\n for key_2, value_2 in self.module.params[\"permissions\"][\n key\n ].items():\n built_permissions[\"permissions\"][key][key_2] = value_2\n return built_permissions\n\n def build_ip_whitelist(self):\n \"\"\"Builds a list of dicts modeled to be the same as the API call.\n\n :return: A list of dicts\n :rtype: list\n \"\"\"\n built_ip_whitelist = dict(ip_whitelist=[])\n if self.module.params[\"ip_whitelist\"] is not None:\n built_ip_whitelist[\"ip_whitelist\"] = self.module.params[\"ip_whitelist\"]\n return built_ip_whitelist\n\n def build_changes(self):\n \"\"\"Builds a complete API call by assembling returned data from functions.\n\n :return: A complete API call.\n parameters.\n :rtype: dict\n \"\"\"\n built_changes = dict(\n name=self.module.params.get(\"name\"),\n )\n built_changes.update(self.build_permissions())\n built_changes.update(self.build_ip_whitelist())\n return built_changes\n\n def present(self, before, team_id):\n \"\"\"Goes through the process of creating a new team, if needed, or\n updating a pre-existing one with new permissions.\n\n :param team_id: Previously collected id if the team exists.\n :type team_id: str\n :return: Tuple in which first value reflects whether or not a change\n occurred and second value is new or updated team object\n :rtype: tuple(bool, dict)\n \"\"\"\n changed = False\n team = None\n built_changes = self.build_changes()\n if self.module.check_mode:\n team = built_changes\n else:\n if team_id is None:\n team = self.create(built_changes)\n else:\n team = self.update(team_id, built_changes)\n if team != before:\n changed = True\n return changed, team\n\n def absent(self, team_id):\n \"\"\"Deletes an existing team or reports back no change if the team\n does not exist to start with.\n\n :param team_id: Previously collected id if the team exists.\n :type team_id: str\n :return: Tuple in which first value reflects whether or not a change\n occurred and second value is the removed team object\n :rtype: tuple(bool, dict)\n \"\"\"\n if team_id is None:\n return False\n else:\n self.delete(team_id)\n return True\n\n def get_team_id(self, before):\n \"\"\"Takes gathered information of a pre-existing team and looks for the\n id required by update and delete actions.\n\n :param before: Existing team info\n :type before: dict\n :return: Id of an existing team\n :rtype: str\n \"\"\"\n if before is not None:\n team_id = before[\"id\"]\n return team_id\n\n def check_existence(self, team_name):\n \"\"\"Does a call to see if the team given in ansible task params already\n exists to establish existing state before changes are made. Also, this\n is the first step in getting team_id for later changes.\n\n :param team_name: Existing set of parameters\n :type have: str\n :return: Team info before changes. If no info found then None will be returned.\n :rtype: dict\n \"\"\"\n team_list = self.ns1.team()\n for team in team_list.list():\n if team[\"name\"].lower() == team_name.lower():\n team_found = team\n return team_found\n\n def exec_module(self):\n \"\"\"Main execution method of module. Creates, updates or deletes a\n team based on Ansible parameters.\n\n :return: Results of module execution\n :rtype: dict\n \"\"\"\n # Setup and gather info\n ## Retreive the name passed into the module from a task.\n team_name = self.module.params.get(\"name\")\n ## Creates a var that will contain data of an existing team or be a None Type.\n ## The None type is used for determining state.\n before = self.check_existence(team_name)\n ## Passes in the `before` var for type comparision and returning required data for later calls if a team already exists.\n team_id = self.get_team_id(before)\n # Take action based on module params with gathered info passed in.\n ## Retreive desired state passed into the module from a task.\n state = self.module.params.get(\"state\")\n ## Action based on a team state being set to present.\n ## Will result in a team being created or updated.\n if state == \"present\":\n changed, team = self.present(before, team_id)\n ## Action based on a team state being set to absent.\n ## Assumes a team to remove already exists.\n if state == \"absent\":\n changed = self.absent(team_id)\n team = {}\n # Takes passed in state changes for id scrubbing and building of final output.\n return self.build_result(changed, team, before, team_name)\n\n def build_result(self, changed, team, before, team_name):\n \"\"\"Builds dict of results from module execution to pass to module.exit_json()\n\n :param changed: Whether or not a change occurred\n :type changed: bool\n :param zone: Zone object returned by NS1 of new or updated zone\n :type zone: dict\n :return: Results of module execution\n :rtype: dict\n \"\"\"\n result = {\"changed\": changed}\n if self.module._diff:\n result.update(diff={\"before\": {}, \"after\": {}, \"team\": team_name})\n if before is not None:\n result[\"diff\"][\"before\"] = before\n if team is not None:\n result[\"diff\"][\"after\"] = team\n return self.remove_ids(result)\n\n def remove_ids(self, result):\n result_2 = copy.deepcopy(result)\n for k, v in result[\"diff\"].items():\n if not isinstance(v, str):\n # ? Is there a better way to do this?\n # ? Is this a good use of try/except?\n if \"id\" in result_2[\"diff\"][k]:\n del result_2[\"diff\"][k][\"id\"]\n try:\n for entry in result_2[\"diff\"][k][\"ip_whitelist\"]:\n del entry[\"id\"]\n except KeyError:\n pass\n return result_2\n\n\ndef main():\n t = NS1Team()\n result = t.exec_module()\n t.module.exit_json(**result)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"library/ns1_team.py","file_name":"ns1_team.py","file_ext":"py","file_size_in_byte":19227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"56896925","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport re\r\nimport pickle\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\ncar_df = pd.read_csv(\"Car details v3.csv\")\r\nbike_df = pd.read_csv(\"Bikes Best Buy.csv\")\r\n\r\ncar_df['Year_Old'] = 2020 - car_df['year']\r\ncar_df.drop([\"owner\", \"seats\", \"seller_type\", \"name\", \"max_power\", \"torque\", \"year\"], axis = 1, inplace = True)\r\n\r\ncar_df.drop_duplicates(inplace=True)\r\ncar_df.dropna(subset = ['mileage'], inplace = True)\r\n\r\ndef find_number(text):\r\n num = re.findall(r'[0-9]+',text)\r\n return \" \".join(num)\r\n\r\ncar_df['engine']=car_df['engine'].apply(lambda x: find_number(x))\r\ncar_df['mileage']=car_df['mileage'].apply(lambda x: find_number(x))\r\ncar_df['mileage'] = car_df['mileage'].str.replace(' ', '.')\r\n\r\ncar_df[['engine']] = car_df[['engine']].astype(\"int\")\r\ncar_df[['mileage']] = car_df[['mileage']].astype(\"float\")\r\n\r\na = pd.get_dummies(car_df['transmission'], drop_first=True)\r\ncar_df = car_df.join(a)\r\ncar_df['fuel'].replace('LPG', 'CNG', inplace = True)\r\na = pd.get_dummies(car_df['fuel'])\r\ncar_df = car_df.join(a)\r\ncar_df.drop([\"fuel\", \"transmission\"], axis = 1, inplace = True)\r\ncar_df[\"E\"] = 0\r\n\r\ncar_df.rename({'selling_price':'Price (INR)', 'mileage':'Mileage', 'km_driven':'KM_Driven', 'engine':'Engine (cc)', 'Diesel':'D', 'CNG':'G', 'Petrol':'P'}, axis = 1, inplace = True)\r\ntitles = ['Price (INR)', 'Engine (cc)', 'Year_Old', 'KM_Driven', 'Manual', 'D', 'G', 'P', 'E', 'Mileage']\r\ncar_df = car_df[titles]\r\n\r\na = pd.get_dummies(bike_df['Fuel'])\r\nbike_df = bike_df.join(a)\r\nbike_df[\"Manual\"] = 1\r\nbike_df[\"G\"] = 0\r\nbike_df[\"KM_Driven\"] = 0\r\nbike_df[\"Year_Old\"] = 0\r\n\r\nbike_df.drop([\"Bike Name\", \"Company\", \"Fuel\"], axis = 1, inplace = True)\r\nbike_df.rename({'Price(INR)':'Price (INR)', 'Milage (kM/L)':'Mileage', 'Tank size (cc) ':'Engine (cc)'}, axis = 1, inplace =True)\r\ntitles = ['Price (INR)', 'Engine (cc)', 'Year_Old', 'KM_Driven', 'Manual', 'D', 'G', 'P', 'E', 'Mileage']\r\nbike_df = bike_df[titles]\r\n\r\nconvert_dict = {'Price (INR)': int,\r\n 'Engine (cc)': int,\r\n 'Year_Old' : int,\r\n 'KM_Driven': int,\r\n 'Manual': int,\r\n 'D': int,\r\n 'G': int,\r\n 'P': int,\r\n 'E': int,\r\n 'Mileage': float\r\n }\r\n\r\nbike_df = bike_df.astype(convert_dict)\r\ncar_df = car_df.astype(convert_dict)\r\ndf = car_df.append(bike_df)\r\n\r\ndf = df[df['Mileage']!=0]\r\ndf = df[df['Engine (cc)']!=0]\r\ndf = df[df['E']==0]\r\n\r\ndf.drop(['E', 'G'], axis = 1, inplace = True)\r\n\r\ny = df.pop('Mileage')\r\nX = df\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\r\n\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nclf = RandomForestRegressor()\r\n# Hyperparameters\r\nn_estimators = [100,200,300,500]\r\nmax_features = ['auto', 'sqrt']\r\nmax_depth = [5, 10, 15, 20]\r\n\r\nfrom sklearn.model_selection import RandomizedSearchCV\r\ngrid = {'n_estimators': n_estimators,\r\n 'max_features': max_features,\r\n 'max_depth': max_depth\r\n}\r\n\r\nclf_cv = RandomizedSearchCV(estimator=clf, param_distributions=grid, scoring='neg_mean_squared_error', n_iter=10, cv=5, verbose=2, random_state=42)\r\n\r\nclf_cv.fit(X_train, y_train)\r\n\r\npickle.dump(clf_cv, open('model.pkl','wb'))","sub_path":"mini_project.py","file_name":"mini_project.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"405639260","text":"import argparse\nfrom typing import Text\nimport yaml\nimport logging\nimport os\nfrom src.data.dataset import get_dataset\n\n\nlogging_str=\"[% (asctime)s: %(levelname)s: %(module)s] %(module)s\"\nlog_dir=\"logs\"\nos.makedirs(log_dir,exist_ok=True)\nlogging.basicConfig(filename=os.path.join(log_dir,\"running_logs.log\",level=logging.INFO,format=logging_str))\n\ndef data_load(config_path: Text) -> None:\n \"\"\" Load raw data.\n Args:\n config_path{Text}:path to config\n base_config_path{Text}:path to base config\n \"\"\"\n logging.info(\"Let start the creation of data load pipeline:\")\n config = yaml.safe_load(open(config_path))\n dataset = get_dataset()\n dataset.to_csv(config['data_load']['dataset_csv'], index=False)\n\n\nif __name__ == \"__main__\":\n args_parser = argparse.ArgumentParser()\n args_parser.add_argument('--config', dest='config', required=True)\n args = args_parser.parse_args()\n\n data_load(config_path= args.config)\n","sub_path":"DVC/dvc/dvc/src/pipelines/data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"647575702","text":"# Copyright 2015 VMware, Inc.\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\nimport abc\nimport collections\nimport six\n\nfrom oslo_config import cfg\n\nfrom vmware_nsx._i18n import _\nfrom vmware_nsx.common import exceptions as nsx_exc\nfrom vmware_nsx.common import nsx_constants\nfrom vmware_nsx.common import utils\nfrom vmware_nsx.nsxlib.v3 import client\n\n\nSwitchingProfileTypeId = collections.namedtuple(\n 'SwitchingProfileTypeId', 'profile_type, profile_id')\n\n\nPacketAddressClassifier = collections.namedtuple(\n 'PacketAddressClassifier', 'ip_address, mac_address, vlan')\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass AbstractRESTResource(object):\n\n def __init__(self, rest_client, *args, **kwargs):\n self._client = rest_client.new_client_for(self.uri_segment)\n\n @abc.abstractproperty\n def uri_segment(self):\n pass\n\n def list(self):\n return self._client.list()\n\n def get(self, uuid):\n return self._client.get(uuid)\n\n def delete(self, uuid):\n return self._client.delete(uuid)\n\n @abc.abstractmethod\n def create(self, *args, **kwargs):\n pass\n\n @abc.abstractmethod\n def update(self, uuid, *args, **kwargs):\n pass\n\n def find_by_display_name(self, display_name):\n found = []\n for resource in self.list()['results']:\n if resource['display_name'] == display_name:\n found.append(resource)\n return found\n\n\nclass SwitchingProfileTypes(object):\n IP_DISCOVERY = 'IpDiscoverySwitchingProfile'\n PORT_MIRRORING = 'PortMirroringSwitchingProfile'\n QOS = 'QosSwitchingProfile'\n SPOOF_GUARD = 'SpoofGuardSwitchingProfile'\n SWITCH_SECURITY = 'SwitchSecuritySwitchingProfile'\n\n\nclass WhiteListAddressTypes(object):\n PORT = 'LPORT_BINDINGS'\n SWITCH = 'LSWITCH_BINDINGS'\n\n\nclass SwitchingProfile(AbstractRESTResource):\n\n @property\n def uri_segment(self):\n return 'switching-profiles'\n\n def list(self):\n return self._client.url_get('?include_system_owned=True')\n\n def create(self, profile_type, display_name=None,\n description=None, **api_args):\n body = {\n 'resource_type': profile_type,\n 'display_name': display_name or '',\n 'description': description or ''\n }\n body.update(api_args)\n\n return self._client.create(body=body)\n\n def update(self, uuid, profile_type, **api_args):\n body = {\n 'resource_type': profile_type\n }\n body.update(api_args)\n\n return self._client.update(uuid, body=body)\n\n def create_spoofguard_profile(self, display_name,\n description,\n whitelist_ports=False,\n whitelist_switches=False,\n tags=None):\n whitelist_providers = []\n if whitelist_ports:\n whitelist_providers.append(WhiteListAddressTypes.PORT)\n if whitelist_switches:\n whitelist_providers.append(WhiteListAddressTypes.SWITCH)\n\n return self.create(SwitchingProfileTypes.SPOOF_GUARD,\n display_name=display_name,\n description=description,\n white_list_providers=whitelist_providers,\n tags=tags or [])\n\n def create_dhcp_profile(self, display_name,\n description, tags=None):\n dhcp_filter = {\n 'client_block_enabled': True,\n 'server_block_enabled': False\n }\n rate_limits = {\n 'enabled': False,\n 'rx_broadcast': 0,\n 'tx_broadcast': 0,\n 'rx_multicast': 0,\n 'tx_multicast': 0\n }\n bpdu_filter = {\n 'enabled': True,\n 'white_list': []\n }\n return self.create(SwitchingProfileTypes.SWITCH_SECURITY,\n display_name=display_name,\n description=description,\n tags=tags or [],\n dhcp_filter=dhcp_filter,\n rate_limits=rate_limits,\n bpdu_filter=bpdu_filter,\n block_non_ip_traffic=True)\n\n @classmethod\n def build_switch_profile_ids(cls, client, *profiles):\n ids = []\n for profile in profiles:\n if type(profile) is str:\n profile = client.get(profile)\n if not isinstance(profile, SwitchingProfileTypeId):\n profile = SwitchingProfileTypeId(\n profile.get('key', profile.get('resource_type')),\n profile.get('value', profile.get('id')))\n ids.append(profile)\n return ids\n\n\nclass LogicalPort(AbstractRESTResource):\n\n @property\n def uri_segment(self):\n return 'logical-ports'\n\n def _build_body_attrs(\n self, display_name=None,\n admin_state=True, tags=None,\n address_bindings=None,\n switch_profile_ids=None,\n attachment=None):\n tags = tags or []\n address_bindings = address_bindings or []\n switch_profile_ids = switch_profile_ids or []\n body = {}\n if tags:\n body['tags'] = tags\n if display_name is not None:\n body['display_name'] = display_name\n\n if admin_state is not None:\n if admin_state:\n body['admin_state'] = nsx_constants.ADMIN_STATE_UP\n else:\n body['admin_state'] = nsx_constants.ADMIN_STATE_DOWN\n\n if address_bindings:\n bindings = []\n for binding in address_bindings:\n address_classifier = {\n 'ip_address': binding.ip_address,\n 'mac_address': binding.mac_address\n }\n if binding.vlan is not None:\n address_classifier['vlan'] = int(binding.vlan)\n bindings.append(address_classifier)\n body['address_bindings'] = bindings\n elif address_bindings == []:\n # explicitly clear out address bindings\n body['address_bindings'] = []\n\n if switch_profile_ids:\n profiles = []\n for profile in switch_profile_ids:\n profiles.append({\n 'value': profile.profile_id,\n 'key': profile.profile_type\n })\n body['switching_profile_ids'] = profiles\n\n if attachment:\n body['attachment'] = attachment\n\n return body\n\n def _prepare_attachment(self, vif_uuid, parent_name, parent_tag,\n address_bindings, attachment_type):\n # NOTE(arosen): if a parent_name is specified we need to use the\n # CIF's attachment.\n key_values = None\n if parent_name:\n attachment_type = nsx_constants.ATTACHMENT_CIF\n key_values = [\n {'key': 'VLAN_ID', 'value': parent_tag},\n {'key': 'Host_VIF_ID', 'value': parent_name},\n {'key': 'IP', 'value': address_bindings[0].ip_address},\n {'key': 'MAC', 'value': address_bindings[0].mac_address}]\n # NOTE(arosen): The above api body structure might change\n # in the future\n\n if attachment_type and vif_uuid:\n attachment = {'attachment_type': attachment_type,\n 'id': vif_uuid}\n\n if key_values:\n attachment['context'] = {'key_values': key_values}\n attachment['context']['resource_type'] = \\\n nsx_constants.CIF_RESOURCE_TYPE\n return attachment\n\n def create(self, lswitch_id, vif_uuid, tags=None,\n attachment_type=nsx_constants.ATTACHMENT_VIF,\n admin_state=True, name=None, address_bindings=None,\n parent_name=None, parent_tag=None,\n switch_profile_ids=None):\n tags = tags or []\n\n body = {'logical_switch_id': lswitch_id}\n attachment = self._prepare_attachment(vif_uuid, parent_name,\n parent_tag, address_bindings,\n attachment_type)\n body.update(self._build_body_attrs(\n display_name=name,\n admin_state=admin_state, tags=tags,\n address_bindings=address_bindings,\n switch_profile_ids=switch_profile_ids,\n attachment=attachment))\n return self._client.create(body=body)\n\n @utils.retry_upon_exception_nsxv3(\n nsx_exc.StaleRevision,\n max_attempts=cfg.CONF.nsx_v3.retries)\n def delete(self, lport_id):\n return self._client.url_delete('%s?detach=true' % lport_id)\n\n @utils.retry_upon_exception_nsxv3(\n nsx_exc.StaleRevision,\n max_attempts=cfg.CONF.nsx_v3.retries)\n def update(self, lport_id, vif_uuid,\n name=None, admin_state=None,\n address_bindings=None, switch_profile_ids=None,\n resources=None,\n attachment_type=nsx_constants.ATTACHMENT_VIF,\n parent_name=None, parent_tag=None):\n lport = self.get(lport_id)\n tags = lport.get('tags', [])\n if resources:\n tags = utils.update_v3_tags(tags, resources)\n attachment = self._prepare_attachment(vif_uuid, parent_name,\n parent_tag, address_bindings,\n attachment_type)\n lport.update(self._build_body_attrs(\n display_name=name,\n admin_state=admin_state, tags=tags,\n address_bindings=address_bindings,\n switch_profile_ids=switch_profile_ids,\n attachment=attachment))\n\n # If revision_id of the payload that we send is older than what NSX has\n # then we will get a 412: Precondition Failed. In that case we need to\n # re-fetch, patch the response and send it again with the\n # new revision_id\n return self._client.update(lport_id, body=lport)\n\n\nclass LogicalRouter(AbstractRESTResource):\n\n @property\n def uri_segment(self):\n return 'logical-routers'\n\n def create(self, display_name, tags, edge_cluster_uuid=None, tier_0=False):\n # TODO(salv-orlando): If possible do not manage edge clusters\n # in the main plugin logic.\n router_type = (nsx_constants.ROUTER_TYPE_TIER0 if tier_0 else\n nsx_constants.ROUTER_TYPE_TIER1)\n body = {'display_name': display_name,\n 'router_type': router_type,\n 'tags': tags}\n if edge_cluster_uuid:\n body['edge_cluster_id'] = edge_cluster_uuid\n return self._client.create(body=body)\n\n def delete(self, lrouter_id):\n return self._client.url_delete(lrouter_id)\n\n @utils.retry_upon_exception_nsxv3(\n nsx_exc.StaleRevision,\n max_attempts=cfg.CONF.nsx_v3.retries)\n def update(self, lrouter_id, *args, **kwargs):\n lrouter = self.get(lrouter_id)\n for k in kwargs:\n lrouter[k] = kwargs[k]\n # If revision_id of the payload that we send is older than what NSX has\n # then we will get a 412: Precondition Failed. In that case we need to\n # re-fetch, patch the response and send it again with the\n # new revision_id\n return self._client.update(lrouter_id, body=lrouter)\n\n\nclass LogicalRouterPort(AbstractRESTResource):\n\n @property\n def uri_segment(self):\n return 'logical-router-ports'\n\n def create(self, logical_router_id,\n display_name,\n tags,\n resource_type,\n logical_port_id,\n address_groups,\n edge_cluster_member_index=None):\n body = {'display_name': display_name,\n 'resource_type': resource_type,\n 'logical_router_id': logical_router_id,\n 'tags': tags or []}\n if address_groups:\n body['subnets'] = address_groups\n if resource_type in [nsx_constants.LROUTERPORT_UPLINK,\n nsx_constants.LROUTERPORT_DOWNLINK]:\n body['linked_logical_switch_port_id'] = {\n 'target_id': logical_port_id}\n elif resource_type == nsx_constants.LROUTERPORT_LINKONTIER1:\n body['linked_logical_router_port_id'] = {\n 'target_id': logical_port_id}\n elif logical_port_id:\n body['linked_logical_router_port_id'] = logical_port_id\n if edge_cluster_member_index:\n body['edge_cluster_member_index'] = edge_cluster_member_index\n\n return self._client.create(body)\n\n @utils.retry_upon_exception_nsxv3(\n nsx_exc.StaleRevision,\n max_attempts=cfg.CONF.nsx_v3.retries)\n def update(self, logical_port_id, **kwargs):\n logical_router_port = self.get(logical_port_id)\n for k in kwargs:\n logical_router_port[k] = kwargs[k]\n # If revision_id of the payload that we send is older than what NSX has\n # then we will get a 412: Precondition Failed. In that case we need to\n # re-fetch, patch the response and send it again with the\n # new revision_id\n return self._client.update(logical_port_id, body=logical_router_port)\n\n def delete(self, logical_port_id):\n return self._client.url_delete(logical_port_id)\n\n def get_by_lswitch_id(self, logical_switch_id):\n resource = '?logical_switch_id=%s' % logical_switch_id\n router_ports = self._client.url_get(resource)\n result_count = int(router_ports.get('result_count', \"0\"))\n if result_count >= 2:\n raise nsx_exc.NsxPluginException(\n err_msg=_(\"Can't support more than one logical router ports \"\n \"on same logical switch %s \") % logical_switch_id)\n elif result_count == 1:\n return router_ports['results'][0]\n else:\n err_msg = (_(\"Logical router link port not found on logical \"\n \"switch %s\") % logical_switch_id)\n raise nsx_exc.ResourceNotFound(\n manager=client._get_nsx_managers_from_conf(),\n operation=err_msg)\n\n def update_by_lswitch_id(self, logical_router_id, ls_id, **payload):\n port = self.get_by_lswitch_id(ls_id)\n return self.update(port['id'], **payload)\n\n def delete_by_lswitch_id(self, ls_id):\n port = self.get_by_lswitch_id(ls_id)\n self.delete(port['id'])\n\n def get_by_router_id(self, logical_router_id):\n resource = '?logical_router_id=%s' % logical_router_id\n logical_router_ports = self._client.url_get(resource)\n return logical_router_ports['results']\n\n def get_tier1_link_port(self, logical_router_id):\n logical_router_ports = self.get_by_router_id(logical_router_id)\n for port in logical_router_ports:\n if port['resource_type'] == nsx_constants.LROUTERPORT_LINKONTIER1:\n return port\n raise nsx_exc.ResourceNotFound(\n manager=client._get_nsx_managers_from_conf(),\n operation=\"get router link port\")\n","sub_path":"vmware_nsx/nsxlib/v3/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":15777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"553768494","text":"import urlTime\nimport func\nimport time\nimport schedule\nfrom datetime import datetime\n# import os, sys\n\n\n\n# schedule.every(5).seconds.do(func.Run)\n\n\n# schedule.every().day.at(\"22:04\").do(func.Thursday)\n\n\nnow = datetime.now() # current date and time\n\nDay = now.strftime(\"%a\")\n\n\ndef File_1():\n\n \n\n Time = now.strftime(\"%H:%M:%S\")\n print(Time)\n\n schedule.every().monday.at(\"09:20\").do(func.Monday)\n schedule.every().tuesday.at(\"09:20\").do(func.Tuesday)\n schedule.every().wednesday.at(\"09:20\").do(func.Wednesday)\n schedule.every().thursday.at(\"09:20\").do(func.Thursday)\n schedule.every().friday.at(\"09:20\").do(func.Friday)\n\n# def DaYs():\n# if Day == \"Mon\":\n# print(\"M\")\n# schedule.every().day.at(\"09:20\").do(func.Monday)\n# if Day == \"Tue\":\n# print(\"T\")\n# schedule.every().day.at(\"09:20\").do(func.Tuesday)\n# if Day == \"Wed\":\n# print(\"W\")\n\n# schedule.every().day.at(\"09:20\").do(func.Wednesday)\n# if Day == \"Thu\":\n# print(\"TH\")\n# schedule.every().day.at(\"09:20\").do(func.Thursday)\n# if Day == \"Fri\":\n# print(\"F\")\n# schedule.every().day.at(\"09:20\").do(func.Friday)\n# if Day == \"Sat\":\n# print(\"ELSE\")\n# time.sleep(86400)\n# if Day == \"Sun\":\n# print(\"el2\")\n# time.sleep(86400)\n\n# schedule.every().day.at(\"9:20\").do(DaYs)\n\n# schedule.every(86400).seconds.days.at(\"09:20\").do(DaYs) # refresh every 24Hrs (no much useful)\n\n while 1:\n schedule.run_pending()\n time.sleep(1)\n\nFile_1()\n# def ExitMain():\n# sys.exit(r\"D:\\Projects\\MyBot\\main.py\")","sub_path":"consoleApp1.0/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"464464781","text":"import time\nimport sys\nfrom epics import ca\n\nimport pvnames\n\npvname = pvnames.double_pv\nhost = pvnames.double_pv_host\n\n\nchid = ca.create_channel(pvname)\nret = ca.connect_channel(chid)\nca.pend_event(1.e-3)\n \nftype = ca.field_type(chid)\ncount = ca.element_count(chid)\nhost = ca.host_name(chid)\nrwacc = ca.access(chid)\n \nif ftype ==6 and count == 1 and host.startswith(host) and rwacc.startswith('read'):\n sys.stdout.write('OK!\\n')\nelse:\n sys.stdout.write(\"Error\\n\")\n\n","sub_path":"tests/ca_simpletest.py","file_name":"ca_simpletest.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"539161631","text":"import hashlib\n\nclass lockCoinBlock:\n\n def __init__(self, previousblockhash, transactionlist):\n \n self.previousblockhash = previousblockhash\n self.transactionlist = transactionlist\n\n self.blockdata = \" - \".join(transactionlist) + \" - \" + previousblockhash\n self.blockhash = hashlib.sha256(self.blockdata.encode()).hexdigest()\n\n\nt1 = \"Bob send 2 LC to Bill\"\nt2 = \"Jim send 4.1 LC to Bob\"\nt3 = \"Joe send 3.2 LC to Jim\"\nt4 = \"Trimson send 0.3 LC to Bill\"\nt5 = \"Mill send 1 LC to Joe\"\nt6 = \"Jimbo send 5.4 LC to Mill\"\n\ninitialBlock = lockCoinBlock(\"Initial Message\", [t1, t2])\n\nprint(initialBlock.blockdata)\nprint(initialBlock.blockhash)\n\nsecondBlock = lockCoinBlock(initialBlock.blockhash, [t3, t4])\n\nprint(secondBlock.blockdata)\nprint(secondBlock.blockhash)\n\nthirdBlock = lockCoinBlock(secondBlock.blockhash, [t5, t6])\n\nprint(thirdBlock.blockdata)\nprint(thirdBlock.blockhash)\n","sub_path":"NeuralnineTutorialBlockchain.py","file_name":"NeuralnineTutorialBlockchain.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"239093860","text":"\"\"\"Core PixyWerk functionality.\"\"\"\n\nfrom .utils import response, sanitize_path\nimport mimetypes\nmimetypes.init()\nimport os\nimport re\nfrom jinja2 import Environment, FileSystemLoader\nimport time\nimport logging\n\nlog = logging.getLogger('pixywerk.werk')\n\nMARKDOWN_SUPPORT = False\nBBCODE_SUPPORT = False\nSCSS_SUPPORT = False\n\ntry:\n import markdown\n MARKDOWN_SUPPORT = True\nexcept:\n pass\n\ntry:\n import ppcode\n BBCODE_SUPPORT = True\nexcept:\n pass\n\ntry:\n import scss\n SCSS_SUPPORT = True\n scssdecoder = scss.Scss()\nexcept:\n pass\n\nDEBUG = True\n\nfrom . import config\n\nDEFAULT_PROPS = {('header', 'Content-type'): 'text/html',\n 'template': 'default.html',\n 'fstemplate': 'default-fs.html',\n 'title': '{path}',\n 'dereference': ('title',)}\n\nhmatch = re.compile('^header:')\n\n\ndef datetimeformat(value, fmat='%Y-%m-%d %T %Z'):\n \"\"\"Format date/time for jinja.\"\"\"\n return time.strftime(fmat, time.localtime(value))\n\n\ndef process_md(cont):\n if MARKDOWN_SUPPORT:\n return markdown.markdown(cont)\n else:\n return cont\n\n\ndef process_bb(cont):\n if BBCODE_SUPPORT:\n return ppcode.decode(cont)\n else:\n return cont\n\n\ndef process_scss(cont):\n if SCSS_SUPPORT:\n return scssdecoder.compile(cont)\n else:\n return cont\n\n\nbbcode_file_spec = {'mimeinfo': 'bbcode content',\n 'mime-type': 'text/html',\n 'templatable': True,\n 'processor': process_bb}\nfile_types = {'.md': {'mimeinfo': 'markdown content',\n 'mime-type': 'text/html',\n 'templatable': True,\n 'processor': process_md},\n '.pp': bbcode_file_spec,\n '.bb': bbcode_file_spec,\n '.scss': {'mimeinfo': 'SCSS file',\n 'mime-type': 'text/css',\n 'templatable': False,\n 'processor': process_scss}}\n\n\nclass PixyWerk(object):\n \"\"\"A full CMS system based on mapping a portion of the filesystem to web,\n with templates, automatic format handling and per-file heirarchical\n metadata.\"\"\"\n def __init__(self, config):\n self.config = config\n if not ('root' in config and\n 'template_paths' in config and\n 'name' in config):\n raise ValueError('REQ root, template_paths, & name conf')\n\n tmplpaths = [os.path.join(config['root'], x)\n for x in config['template_paths']]\n self.template_env = Environment(loader=FileSystemLoader(tmplpaths))\n # some convenience functions for making dynamic content\n self.template_env.globals['getmetadata'] = self.get_metadata\n self.template_env.globals['getcontent'] = self.get_content\n self.template_env.globals['getlist'] = self.get_list\n # a useful filter for formatting dates\n self.template_env.filters['date'] = datetimeformat\n\n def get_metadata(self, relpath):\n \"\"\"Return the metadata (dict) for a path relative to the root path.\"\"\"\n # FIXME this would be trivial to cache\n # FIXME this could be stored in a database too.\n meta = dict(DEFAULT_PROPS)\n pthcomps = os.path.split(relpath)\n curpath = self.config['root']\n for p in pthcomps:\n metafn = os.path.join(curpath, '.meta')\n if os.access(metafn, os.F_OK):\n meta = config.load_config_file(file(metafn, 'r'), meta)\n curpath = os.path.join(curpath, p)\n extspl = os.path.splitext(curpath)\n if len(extspl) > 1 and extspl[1] == '.cont':\n metafn = os.path.join(extspl[0] + '.meta')\n elif os.path.isdir(curpath):\n metafn = os.path.join(curpath, '.meta')\n else:\n metafn = curpath+'.meta'\n if os.access(metafn, os.F_OK):\n meta = config.load_config_file(file(metafn, 'r'), meta)\n return meta\n\n def get_list(self, relpath):\n \"\"\"Return a list of files within a relative path, with some minor\n metadata.\"\"\"\n items = list(os.listdir(os.path.join(self.config['root'], relpath)))\n items.sort(lambda x, y: cmp(y, x))\n output = list()\n for item in items:\n output.append((item, os.path.isdir(item)))\n return output\n\n def get_content(self, path):\n \"\"\"Return the rendered content for an absolute path.\"\"\"\n # FIXME this should contain the actual filesystem access blob instead\n # of do_handle.\n (code,\n content,\n metadata,\n mimetype,\n enctype) = self.do_handle(path, template_override=True)\n if isinstance(content, file):\n content = content.read().decode('utf-8')\n return content\n\n def generate_index(self, path, metadata):\n \"\"\"Use the template contained in fstemplate to generate a content blob\n representing a filesystem index.\"\"\"\n template = self.template_env.get_template(metadata['fstemplate'])\n\n dcont = os.listdir(path)\n files = dict()\n for item in dcont:\n st = os.stat(os.path.join(path, item))\n if item in self.config['pathelement_blacklist']:\n continue\n mimetype = 'UNK'\n if os.path.isdir(os.path.join(path, item)):\n mimetype = 'DIR'\n else:\n mtypes = mimetypes.guess_type(os.path.join(path, item))\n\n if mtypes[0]:\n mimetype = mtypes[0]\n else:\n mimetype = 'application/octet-stream'\n\n try:\n res = os.path.splitext(item)\n bname = '.'.join(res[0:-1])\n ext = res[-1].lower().strip()\n except:\n ext = ''\n bname = item\n\n if ext in file_types:\n mimetype = file_types[ext]['mimeinfo']\n elif ext == '.meta':\n continue\n elif ext == '.cont':\n item = bname\n mimetype = 'content'\n\n files[item] = {'type': mimetype,\n 'size': st.st_size,\n 'atime': st.st_atime,\n 'ctime': st.st_ctime,\n 'mtime': st.st_mtime,\n 'fullpath': os.path.join(path, item),\n 'relpath': os.path.join(metadata['path'], item)}\n if files:\n return template.render(files=files)\n else:\n return \"no files\"\n\n def dereference_metadata(self, metadata):\n \"\"\"Stub. Derefernces metadata refrenced in the derefernce config option\n with other metadata values.\"\"\"\n for m in metadata['dereference']:\n # this is so meta\n metadata[m] = metadata[m].format(**metadata)\n\n def path_info(self, path):\n relpth = sanitize_path(path)\n pth = os.path.join(self.config['root'], relpth)\n is_dir = os.path.isdir(pth)\n return relpth, pth, is_dir\n\n def do_handle(self, path, environ=None, template_override=False):\n \"\"\"Guts of single access handling. Here be dragons.\"\"\"\n relpth, pth, is_dir = self.path_info(path)\n\n try:\n if 'HTTP_X_REAL_IP' in environ:\n ip = environ['HTTP_X_REAL_IP']\n else:\n ip = environ['REMOTE_ADDR']\n except (KeyError, AttributeError, TypeError):\n ip = 'unk'\n\n log.debug('handle: <{0}> entering handle for {1}'.format(ip, pth))\n content = ''\n templatable = False\n formatable = False\n mimetype = ''\n enctype = ''\n code = 200\n\n # Load metadata tree\n metadata = self.get_metadata(relpth)\n metadata['path'] = relpth\n metadata['abspath'] = pth\n\n # handle redirects from the metadata file\n if 'redirect' in metadata:\n code = metadata['redirect'][0]\n location = metadata['redirect'][1]\n log.info('handle: <{0}> {1} -> {2} => {3}'.format(ip,\n pth,\n code,\n location))\n return (code,\n 'Moved',\n {('header', 'Location'): location,\n 'message': 'Mowed'},\n None,\n None)\n # Locate content file\n elif is_dir:\n # search for index file\n for idxf in ('index',\n 'index.html',\n 'index.md',\n 'index.pp',\n 'index.bb'):\n trg = path + '/' + idxf\n c, cont, mt, mimet, enct = self.do_handle(trg, environ)\n if c == 200:\n return c, cont, mt, mimet, enct\n # directory with no index - render an index\n content = self.generate_index(pth, metadata)\n templatable = True\n elif os.access(pth+'.cont', os.F_OK):\n # cont file - magical pathname\n content = file(pth+'.cont', 'r').read().decode('utf-8')\n templatable = True\n formatable = True\n elif os.access(pth, os.F_OK):\n # normal file - load and inspect\n try:\n ext = os.path.splitext(pth)[-1].lower().strip()\n except:\n ext = ''\n if ext in file_types:\n content = file_types[ext]['processor'](\n file(pth, 'r').read().decode('utf-8'))\n templatable = file_types[ext]['templatable']\n mimetype = file_types[ext]['mime-type']\n elif ext == '.cont':\n content = file(pth, 'r').read().decode('utf-8')\n templatable = True\n formatable = True\n else:\n mtypes = mimetypes.guess_type(pth)\n if mtypes[0]:\n mimetype = mtypes[0]\n else:\n mimetype = 'application/octet-stream'\n if mtypes[1]:\n enctype = mtypes[1]\n\n content = file(pth, 'r')\n else:\n # 404\n log.info('handle: <{0}> {1} -> 404'.format(ip, pth))\n return 404, None, None, None, None\n # tweak metadata\n metadata['mimetype'] = mimetype\n metadata['enctype'] = enctype\n self.dereference_metadata(metadata)\n # Render file\n if templatable and content and not template_override:\n if formatable:\n glbls = {'getmetadata': self.get_metadata}\n conttp = self.template_env.from_string(content,\n globals=glbls)\n content = conttp.render(environ=environ,\n path=relpth,\n metadata=metadata)\n template = self.template_env.get_template(metadata['template'])\n content = template.render(content=content,\n environ=environ,\n path=relpth,\n metadata=metadata)\n mimetype = 'text/html'\n\n log.info('handle: <{0}> {1} -> 200'.format(ip, pth))\n return code, content, metadata, mimetype, enctype\n\n def handle(self, path, environ):\n \"\"\"Handle one access, wrapping results in a response object.\"\"\"\n code, content, metadata, mimetype, enctype = self.do_handle(path,\n environ)\n if code == 404:\n return response(code=404,\n message='Not found',\n contenttype='text/plain').done('404 Not Found')\n resp = response(code=code)\n for mdkey in metadata:\n if len(mdkey) == 2 and mdkey[0] == 'header':\n resp.headers[mdkey[1]] = metadata[mdkey]\n if 'message' in metadata:\n resp.message = metadata['message']\n if mimetype:\n resp.headers['Content-type'] = mimetype\n if enctype:\n resp.headers['Content-encoding'] = enctype\n # Send contents\n return resp.done(content)\n","sub_path":"pixywerk/werk.py","file_name":"werk.py","file_ext":"py","file_size_in_byte":12479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"46273199","text":"import eosfactory.eosf as eosf\nfrom eosfactory.eosf import *\nimport eosfactory\nimport sys, os\nimport json\nimport argparse\n#import subprocess\n#import time\nimport numpy as np\nimport pandas as pd\n\n''' NOTES:\n\n run this with:\n python variable_unstake_test.py myjungle -b\n\n '''\n\n\nBOID_TOKEN_CONTRACT_PATH = \\\n os.path.abspath(\n os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n '..'))\n\n# default min_stake = 100000.0\n_STAKE1 = 50000.0 # stake less than minimum stake amount (w/ nothing initially staked)\n_STAKE2 = 100000000.0 # stake more than account balance amount (w/ nothing initially staked)\n_STAKE3 = 150000.0 # stake a valid amount (w/ nothing initially staked)\n_STAKE4 = 100000000.0 # stake more on top of initial stake, thats more than un-staked tokens\n_STAKE5 = 50000.0 # stake more on top of initial stake, that is a valid amount\n_UNSTAKE1 = 120000.0 # unstake an amount that would put the staked amount below the minimum staked threshhold\n_UNSTAKE2 = 20000.0 # unstake an amount that would put the staked amount above the minimum staked threshhold\n_UNSTAKE3 = 100000000.0 # unstake an amount that would put the staked amount to zero\n\n_INIT_BALANCE = 500000.0 # INIT_BALANCE = a valid balance of unstaked tokens master account must initially have that is unstaked \n\nSTAKE1 = '%.4f BOID' % _STAKE1\nSTAKE2 = '%.4f BOID' % _STAKE2\nSTAKE3 = '%.4f BOID' % _STAKE3\nSTAKE4 = '%.4f BOID' % _STAKE4\nSTAKE5 = '%.4f BOID' % _STAKE5\nUNSTAKE1 = '%.4f BOID' % _UNSTAKE1\nUNSTAKE2 = '%.4f BOID' % _UNSTAKE2\nUNSTAKE3 = '%.4f BOID' % _UNSTAKE3\nINIT_BALANCE = '%.4f BOID' % _INIT_BALANCE\n\n\n\n# parse json of account balance\ndef getBalance(x):\n if len(x.json['rows']) > 0:\n return float(x.json['rows'][0]['balance'].split()[0])\n else:\n return 0\n\n# parse json of stakes table\ndef getStakeParams(x):\n ret = {}\n for i in range(len(x.json['rows'])):\n ret[x.json['rows'][i]['stake_account']] = \\\n {\n 'auto_stake': x.json['rows'][i]['auto_stake'],\n 'staked': x.json['rows'][i]['staked']\n }\n return ret\n\n# return True or False if acct has staked tokens or not\ndef acct_has_staked_tokens(contract, acct):\n stake_params = getStakeParams(contract.table('stakes', master))\n return str(acct) in stake_params.keys()\n\n# return the number of staked tokens\ndef num_staked_tokens(contract, acct):\n stake_params = getStakeParams(contract.table('stakes', master))\n if str(acct) in stake_params.keys():\n return float(stake_params[str(acct)]['staked'].split()[0])\n return 0.0\n\n# contract action calls\ndef transfer(contract, from_acct, to_acct, quantity):\n contract.push_action(\n 'transfer',\n {\n 'from':from_acct,\n 'to':to_acct,\n 'quantity':quantity,\n 'memo':'memo'\n }, permission=[from_acct]\n )\ndef transtaked(contract, to_acct, quantity, perm):\n contract.push_action(\n 'transtaked',\n {\n 'to':to_acct,\n 'quantity':quantity,\n 'memo':'memo'\n }, permission=[perm]\n )\ndef issue(contract, to_acct, quantity, perm):\n contract.push_action(\n 'issue',\n {\n 'to': to_acct,\n 'quantity': quantity,\n 'memo': \"memo\"\n }, permission=[perm]\n )\ndef stake(contract, acct, quantity):\n contract.push_action(\n 'stake',\n {\n '_stake_account': acct,\n '_staked': quantity\n }, permission=[acct]\n )\ndef unstake(contract, acct, quantity):\n contract.push_action(\n 'unstake',\n {\n '_stake_account': acct,\n 'quantity': quantity\n }, permission=[acct]\n )\ndef stakebreak(contract, on_switch, acct):\n print('\\nsetting stakebreak to %s' % on_switch)\n contract.push_action( # stakebreak - activate/deactivate staking for users\n 'stakebreak',\n {\n 'on_switch': on_switch,\n }, [acct])\n\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='''\n This is a unit test for the transtaked action of the\n BOID Token smart contract.\n ''')\n\n # testnet alias = myjungle\n parser.add_argument(\n \"alias\", nargs=\"?\",\n help=\"Testnet alias\")\n\n parser.add_argument(\n \"-t\", \"--testnet\", nargs=4,\n help=\" \")\n\n parser.add_argument(\n \"-b\",\"--build\",\n action=\"store_true\",\n help=\"build new contract ABIs\")\n\n args = parser.parse_args()\n\n testnet = get_testnet(args.alias, args.testnet)\n testnet.configure()\n\n ################ test begins here #################\n\n eosf.create_master_account('master')\n\n # make build directory if it does not exist\n build_dir = os.path.join(BOID_TOKEN_CONTRACT_PATH, 'build')\n if not os.path.exists(build_dir):\n os.mkdir(build_dir)\n\n # create reference to the token staking contract\n # build and deploy the contracts on the testnet\n contract = eosf.Contract(master, BOID_TOKEN_CONTRACT_PATH)\n if args.build:\n contract.build()\n contract.deploy()\n\n\n balance = getBalance(contract.table(\"accounts\", master))\n print('master balance')\n print(balance)\n\n balance = getBalance(contract.table(\"accounts\", alice))\n print('alice balance')\n print(balance)\n\n stake_params = getStakeParams(contract.table('stakes', master))\n print('stake_params')\n print(stake_params)\n\n transtaked(\n contract,\n alice,\n '100000.0000 BOID',\n master)\n\n balance = getBalance(contract.table(\"accounts\", master))\n print('master balance')\n print(balance)\n\n balance = getBalance(contract.table(\"accounts\", alice))\n print('alice balance')\n print(balance)\n\n stake_params = getStakeParams(contract.table('stakes', master))\n print('stake_params')\n print(stake_params)\n\n # stop the testnet and exit python\n eosf.stop()\n sys.exit()\n\n\n\n\n\n\n\n\n\n\n\n\n\n # setup contract (1st time)\n try:\n contract.push_action(\n 'create',\n {\n 'issuer': master,\n 'maximum_supply': '10000000000.0000 BOID'\n }, permission=[master]\n )\n contract.push_action(\n 'initstats',\n '{}', permission=[master]\n )\n issue(contract, master, INIT_BALANCE, master)\n except:\n pass\n\n # turn on staking\n stakebreak(contract, \"1\", master)\n\n # verify that master's balance is completely unstaked\n staked = acct_has_staked_tokens(contract, master)\n if not staked:\n print('%s\\'s balance is completely unstaked\\n' % master)\n else:\n print('%s\\'s balance is not completely unstaked ... unstaking' % master)\n while staked:\n unstake(contract, master, UNSTAKE3)\n staked = acct_has_staked_tokens(contract, master)\n print('%s\\'s balance is completely unstaked\\n' % master)\n\n # verify that master's balance = INIT_BALANCE\n balance = getBalance(contract.table(\"accounts\", master))\n while balance != _INIT_BALANCE:\n if balance > _INIT_BALANCE:\n print('%s\\'s balance is greater than %s' % (master, INIT_BALANCE))\n print('transfering the difference to %s' % alice)\n transfer(contract, master, alice, '%.4f BOID' % (balance - _INIT_BALANCE))\n elif balance < _INIT_BALANCE:\n # issue tokens to master\n print('%s\\'s balance is less than %s' % (master, INIT_BALANCE))\n print('issuing the difference to %s' % master)\n issue(contract, master, '%.4f BOID' % (_INIT_BALANCE - balance), master)\n balance = getBalance(contract.table(\"accounts\", master))\n print('%s\\'s balance equals INIT_BALANCE\\n' % master)\n\n\n ################### staking tests ########################################\n\n # stake less than minimum stake amount (w/ nothing initially staked)\n try:\n stake(contract, master, STAKE1)\n print('TEST FAILED: accounts are not supposed to be able to')\n print('stake less than minimum stake amount')\n print('(w/ nothing initially staked)\\n')\n sys.exit()\n except eosfactory.core.errors.Error as e:\n print(e)\n print('PASSED minimum stake test\\n')\n\n # stake more than account balance amount (w/ nothing initially staked)\n try:\n stake(contract, master, STAKE2)\n print('TEST FAILED: accounts are not supposed to be able to')\n print('stake more than the account\\'s balance')\n print('(w/ nothing initially staked)\\n')\n sys.exit()\n except eosfactory.core.errors.Error as e:\n print(e)\n print('PASSED maximum stake test 1\\n')\n\n # stake a valid amount (w/ nothing initially staked)\n try:\n stake(contract, master, STAKE3)\n print('PASSED valid stake amount (w/ nothing initially staked) test 1\\n')\n except eosfactory.core.errors.Error as e:\n print(e)\n print('TEST FAILED: accounts should be able to stake valid amounts')\n print('(w/ nothing initially staked)\\n')\n sys.exit()\n\n # stake more on top of initial stake, thats more than un-staked tokens\n try:\n stake(contract, master, STAKE4)\n print('TEST FAILED: accounts are not supposed to be able to')\n print('stake more than the account\\'s unstaked balance')\n print('(on top of a previous valid stake)\\n')\n sys.exit()\n except eosfactory.core.errors.Error as e:\n print(e)\n print('PASSED maximum stake test 2\\n')\n\n\n # stake more on top of initial stake, that is a valid amount\n try:\n stake(contract, master, STAKE5)\n print('PASSED valid stake amount (on top of a previous valid stake) test 2\\n')\n except eosfactory.core.errors.Error as e:\n print(e)\n print('TEST FAILED: accounts should be able to stake valid amounts')\n print('(on top of a previous valid stake)\\n')\n sys.exit()\n\n\n ################### unstaking tests ######################################\n\n # unstake an amount that would put the staked amount below the minimum staked threshhold\n try:\n unstake(contract, master, UNSTAKE1)\n print('TEST FAILED: accounts are not supposed to be able to')\n print('unstake to less than the minimum staked threshhold')\n sys.exit()\n except eosfactory.core.errors.Error as e:\n print(e)\n print('PASSED unstake below minimum stake\\n')\n\n # unstake an amount that would put the staked amount above the minimum staked threshhold\n try:\n unstake(contract, master, UNSTAKE2)\n staked = num_staked_tokens(contract, master)\n assert(staked == _STAKE3 + _STAKE5 - _UNSTAKE2)\n print('PASSED valid unstake amount (above minimum stake threshhold)\\n')\n except eosfactory.core.errors.Error as e:\n print(e)\n print('TEST FAILED: accounts should be able to unstake')\n print('(amounts above the minimum stake threshhold)\\n')\n sys.exit()\n\n # unstake an amount that would put the staked amount to zero\n try:\n unstake(contract, master, UNSTAKE3)\n staked = num_staked_tokens(contract, master)\n assert(staked == 0.0)\n print('PASSED valid unstake amount (above minimum stake threshhold)\\n')\n except eosfactory.core.errors.Error as e:\n print(e)\n print('TEST FAILED: accounts should be able to unstake')\n print('(amounts above the minimum stake threshhold)\\n')\n sys.exit()\n\n\n\n # stop the testnet and exit python\n eosf.stop()\n sys.exit()\n\n\n","sub_path":"tests/transtaked_test.py","file_name":"transtaked_test.py","file_ext":"py","file_size_in_byte":11652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"178646362","text":"# file that is used to graph the data\nimport os\nimport itertools\nimport numpy as np\nimport matplotlib.lines as mlines\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nfrom matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker\nfrom mpl_toolkits.mplot3d import axes3d, Axes3D\nimport re\nimport pdb\nimport classification\n\nfrom feature_extraction import Extractor\nimport dataformatter\n\nimport seaborn as sns\n\n'''\n Definition is used to set unique markers for each type of car. When adding a new type of car, simply\n modify the definition by adding the type of car mapped to the marker\n'''\ndef set_marker(car):\n # For reference:\n # filled_markers = ('o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', 'P', 'X')\n\n # Delimiter lines used to distinguish each type of vehicle\n delimiters = \"_\", \".xlsx\", \"\\\\\"\n regexPattern = '|'.join(map(re.escape, delimiters))\n tokens = re.split(regexPattern, car)\n carType = tokens[1] # 1 Should be the position of the Make of the vehicle in the string\n\n return {\n 'Hatchback' : 'o',\n 'Sedan' : 'v',\n 'Truck' : '*'\n }.get(carType, 'x') # returns value pointed to by key(carType), or returns default value if not found\n\ndef make_neat_text_box(ax, text):\n # ax = plot to apply text box to\n # title = title string\n # elements = list of elements to be displayed in content\n # Makes Text box at the right of the graph which lists all the features used\n\n textarea = TextArea(text, textprops=dict(color=\"k\"))\n box = HPacker(children=[textarea], align=\"center\", pad=0, sep=5)\n\n anchored_title_box = AnchoredOffsetbox(loc=6, child=box, pad=0.4, frameon=True, bbox_to_anchor=(1.02, 0.5),\n bbox_transform=ax.transAxes, borderpad=0.)\n\n ax.add_artist(anchored_title_box)\n\n\ndef plot_PCA_FFT(x_r, target, target_names, type='', ratio=[], features='', before=None, save=False):\n pcafig = plot_PCA(x_r, target, target_names, type, ratio, features, before)\n axs = pcafig.axes\n axs[0].set_title('FFT Data')\n\n if save:\n features = '_'.join(features.split(' ')) # Separates features by underscores instead of spaces\n filename = features + '_' + type + '_PCA.png' # IE: min_max_median_xyz_PCA.png\n if (os.name == 'nt'): # Windows\n pcafig.savefig('..\\\\Figures\\\\FFTFigures\\\\' + features + ' ' + type + '_Car_PCA.png', bbox_inches='tight', dpi=200)\n else:\n pcafig.savefig('../Figures/FFTFigures/' + features + ' ' + type + '_Car_PCA.png', bbox_inches='tight', dpi=200)\n return pcafig\n\ndef plot_PCA(x_r, target, target_names, type='', ratio=[], features='', before=None, save=False):\n colors = ['navy', 'turquoise', 'darkorange', 'brown', 'green', 'red', 'magenta', 'gray'] * 2\n if len(target_names) > len(colors):\n assert False, \"Not enough colors to support %d cars\" % len(target_names)\n lw = 2\n\n fig = plt.figure(figsize=(12, 7))\n if before is not None:\n ax = fig.add_subplot(121, projection='3d') # Axes3D(fig) # Changed fig.add_subplot(121, projection='3d') because of some issues\n for color, i, target_name in zip(colors, range(len(target_names)), target_names):\n c1, c2, c3 = before[target == i, 0], before[target == i, 1], before[target == i, 2]\n ax.scatter(c1, c2, c3, color=color, alpha=.8, lw=lw,\n label=target_name, marker=set_marker(target_name))\n feats = features.split(' ')\n ax.set_xlabel(feats[0])\n ax.set_ylabel(feats[1])\n ax.set_zlabel(feats[2])\n ax.set_title('Normal Data')\n ax = fig.add_subplot(122, projection='3d')\n for color, i, target_name in zip(colors, range(len(target_names)), target_names):\n ax.scatter(x_r[target == i, 0], x_r[target == i, 1], x_r[target == i, 2], color=color, alpha=.8, lw=lw,\n label=target_name, marker=set_marker(target_name))\n ax.set_xlabel('Component 1')\n ax.set_ylabel('Component 2')\n ax.set_zlabel('Component 3')\n ax.set_title('PCA Data')\n\n plt.suptitle(type + ' data')\n\n props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n\n evr = ['%.5f' % n for n in ratio]\n if len(ratio) != 0 and len(features) != 0:\n ax.text(0.05, 0.95, z=0.5, s=features + '\\n Variance Ratio: [' + \", \".join(evr) + ']',\n transform=ax.transAxes, fontsize=14,\n verticalalignment='top', bbox=props)\n\n plt.legend(loc='center right', shadow=False, scatterpoints=1, bbox_to_anchor=(1.25, .5), bbox_transform=plt.gcf().transFigure)\n plt.tight_layout()\n if save:\n features = '_'.join(features.split(' ')) # Separates features by underscores instead of spaces\n filename = features + '_' + type + '_PCA.png' # IE: min_max_median_xyz_PCA.png\n if (os.name == 'nt'): # Windows\n fig.savefig('..\\\\Figures\\\\PCAFigures\\\\' + features + ' ' + type + '_Car_PCA.png', bbox_inches='tight', dpi=200)\n else:\n fig.savefig('../Figures/PCAFigures/' + features + ' ' + type + '_Car_PCA.png', bbox_inches='tight', dpi=200)\n return fig\n\ndef plot_scatter_matrix(featuredata, run_type, save):\n\n matrices = dataformatter.format_matrix_data(featuredata) # returns a list of 3 pandas.DataFrame() objects, which\n # contain our organized/formatted featuredata (Z, XY, XYZ)\n sns.set(style='ticks', font_scale=2) # Set aesthetic properties for the seaborn Scatterplots\n\n filenames = [file for file in sorted(featuredata)]\n markers = {'marker':[set_marker(file) for file in filenames]} # makes the 'point shapes' for plot/legend\n\n plots = ('Z', 'XY', 'XYZ') # Helps with saving/printing\n i = 0\n for matrix in matrices:\n pg = sns.PairGrid(matrix, hue='Car', hue_order=filenames, hue_kws=markers)\n pg.map_offdiag(plt.scatter, alpha=0.7) # sets properties for non-diagonal plots [.']\n pg.map_diag(plt.hist) # sets properties for diagonal plots [\\]\n pg.add_legend(bbox_to_anchor=(1.25, .5), borderaxespad=0.)\n fig = pg.fig\n fig.suptitle('Scatter Matrix for ' + plots[i] + ' Values', fontsize=28, fontweight='bold', x=0.5, y=1.02)\n if save:\n if (os.name == 'nt'): # Windows\n fig.savefig('..\\\\Figures\\\\ScatterPlotMatrices\\\\'+ run_type+plots[i]+'_Car_Scatter_Matrix.png', bbox_inches='tight')\n else:\n fig.savefig('../Figures/ScatterPlotMatrices/'+run_type +plots[i]+'_Car_Scatter_Matrix.png', bbox_inches='tight')\n i += 1\n\n\ndef plot_all_features(featuredata, run_type, enable_pca, pca_components, save_images,\n show_figures):\n print(\"Using backend - \" + plt.get_backend())\n features = Extractor.features\n for i, feature in enumerate(features):\n plot_feature(featuredata, feature, run_type, enable_pca, pca_components, figure=i, save=save_images)\n\n if show_figures:\n show()\n\ndef plot_feature(featuredata, feature, run_type, enable_pca, pca_components, figure, save):\n colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'w']\n\n fig = plt.figure(figure)\n ax = plt.subplot(1, 1, 1) # subplot(rows, columns, currentgraph)\n if enable_pca:\n run_type += \" with PCA of \" + str(pca_components) + \" components\"\n\n fig.canvas.set_window_title('Figure ' + str(plt.gcf().number + 1) + ' - ' + feature + \" \" + run_type) # More detailed window titles\n plt.title(feature)\n\n i = 0\n legends = []\n for file, filedata in featuredata.items():\n\n legends.append(mlines.Line2D([], [], color=colors[i], marker=set_marker(file), markersize=8, label=file))\n # ^^Creates a legend with marker-shape, color, and name of file\n\n samples = np.arange(0, len(filedata[feature]), 1) # Creates X-Axis\n ax.scatter(samples, filedata[feature], color=colors[i], alpha=0.6, marker=set_marker(file))\n ax.set_xlabel('samples')\n ax.set_ylabel('signal level')\n i += 1\n # Shrink current axis by 10%\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 0.9, box.height])\n # Put a legend to the right of the current axis\n legend = plt.legend(handles=legends, loc='center left', bbox_to_anchor=(1, 0.5), fontsize='small')\n plt.subplots_adjust(hspace=.75)\n\n\n # The following lines will detect the type of backend being used and maximize all figures accordingly\n mng = plt.get_current_fig_manager()\n\n if (plt.get_backend() == 'TkAgg'):\n mng.window.state('normal') # works fine on Windows!\n elif (plt.get_backend() == 'wxAgg'):\n mng.frame.MAXIMIZED(True)\n elif (plt.get_backend() == 'Qt5Agg'):\n mng.window.showMaximized()\n\n run_type += '.png'\n\n\n if (save):\n if (os.name == 'nt'): # If windows...\n fig.savefig('..\\\\Figures\\\\FeatureData\\\\Figure ' + str(plt.gcf().number + 1) + ' - ' + feature + \" \" + run_type, bbox_extra_artists=(legend,), bbox_inches='tight', dpi=250)\n else:\n fig.savefig('../Figures/FeatureData/Figure ' + str(plt.gcf().number + 1) + ' - ' + feature + \" \" + run_type, bbox_extra_artists=(legend,), bbox_inches='tight', dpi=250)\n return plt\n\ndef plot_confusion_matrix(algorithm, feature, runtype, enable_pca,\n pca_components, confusion_matrix, classes, normalize=False, save=False,\n show=False, title='Confusion Matrix', cmap=plt.cm.Blues):\n fig = plt.figure()\n\n if normalize:\n confusion_matrix = confusion_matrix.astype('float') / confusion_matrix.sum(axis=1)[:, np.newaxis]\n # feature += \" Normalized\"\n print(\"Generating Normalized Confusion Matrix...\")\n else:\n print('Generating Confusion Matrix, without Normalization...')\n\n # print(confusion_matrix)\n if enable_pca:\n runtype += \" with PCA of \" + str(pca_components) + \" components\"\n\n plt.imshow(confusion_matrix, interpolation='nearest', cmap=cmap)\n # plt.suptitle(title + ' - ' + feature, fontsize=20)\n plt.title(title + ': ' + algorithm + \" \" + feature + ' - ' + runtype)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = confusion_matrix.max() / 2.\n for i, j in itertools.product(range(confusion_matrix.shape[0]), range(confusion_matrix.shape[1])):\n plt.text(j, i, format(confusion_matrix[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if confusion_matrix[i, j] > thresh else \"black\")\n\n # plt.tight_layout()\n plt.ylabel('True Label')\n plt.xlabel('Predicted Label')\n\n name = algorithm + \" - \"\n\n if (len(feature) == 33):\n name += \"All Statistical Features\"\n elif (len(feature) == 27):\n name += \"Reliable Statistical Features\"\n elif (len(feature) == 9):\n name += \"Frequency Based Features\"\n else:\n name += feature\n # if (len(name) > 80):\n # name = name[:70] + '(cont).png'\n\n name += \" - \" + runtype\n\n name += '.png'\n\n if (save):\n if (os.name == 'nt'): # If windows...\n fig.savefig('..\\\\Figures\\\\ConfusionMatrix\\\\' + ' - ' + name, bbox_extra_artists=(), bbox_inches='tight')\n else:\n fig.savefig('../Figures/ConfusionMatrix/' + ' - ' + name, bbox_extra_artists=(), bbox_inches='tight')\n \n if show:\n show()\n\n plt.clf()\n return plt\n\n\ndef plot_mlp_alphas(alphas, accuracies, seg_alphas, seg_preds, features,\n save, show, runtype, is_pca, pca_components):\n fig = plt.figure()\n ax = plt.subplot(111)\n # plot Alphas on X axis, Prediction Accuracies on Y axis\n plt.plot(alphas, accuracies, color='darkorange', label='Predictions')\n # plot Smoothed line graph\n plt.plot([alphas[alp] for alp in seg_alphas], seg_preds, color='blue', alpha=.5, label='Average')\n plt.title('MLP Classifier\\nPrediction Accuracy vs Alpha')\n plt.xlabel('Alpha')\n plt.ylabel('Prediction Accuracy (%)')\n make_neat_text_box(ax, 'Features\\n\\n' + '\\n'.join(features))\n\n plt.legend()\n\n if is_pca:\n runtype += \" with PCA of \" + str(pca_components) + \" components\"\n\n name = 'mlp_alphas_'\n if (len(features) == 33):\n name += \"All Stat Features\"\n elif (len(features) == 27):\n name += \"Reliable Stat Features\"\n elif (len(features) == 9):\n name += \"Frequency Based Features\"\n else:\n name += ', '.join(features)\n # if (len(name) > 80):\n # name = name[:70] + '(cont).png'\n\n name += \"_\" + runtype\n\n name += '.png'\n\n if save:\n filepath = str(Path('../Figures/MLPFigures') / name)\n print('Saving to ' + filepath)\n fig.savefig(filepath, bbox_inches='tight', dpi=200)\n if show:\n plt.show()\n\n plt.clf()\n\ndef plot_mlp_layers(layers, accuracies, seg_layers, seg_preds, features,\n save, show, runtype, is_pca, pca_components):\n # pdb.set_trace()\n fig = plt.figure()\n ax = plt.subplot(111)\n plt.plot(layers, accuracies, color='purple', label='Predictions')\n plt.plot([layers[alp] for alp in seg_layers], seg_preds, color='blue', alpha=.5, label='Average')\n plt.title('MLP Classifier\\nPrediction Accuracy vs Hidden Layers')\n plt.xlabel('Hidden Layers')\n plt.ylabel('Prediction Accuracy (%)')\n make_neat_text_box(ax, 'Features\\n\\n' + '\\n'.join(features))\n\n plt.legend()\n\n if is_pca:\n runtype += \" with PCA of \" + str(pca_components) + \" components\"\n\n name = 'mlp_layers_'\n \n if (len(features) == 33):\n name += \"All Stat Features\"\n elif (len(features) == 27):\n name += \"Reliable Stat Features\"\n elif (len(features) == 9):\n name += \"Frequency Based Features\"\n else:\n name += ', '.join(features)\n # if (len(name) > 80):\n # name = name[:70] + '(cont).png'\n\n name += \"_\" + runtype\n\n name += '.png'\n\n if save:\n filepath = str(Path('../Figures/MLPFigures') / name)\n print('Saving to ' + filepath)\n fig.savefig(filepath, bbox_inches='tight', dpi=200)\n if show:\n plt.show()\n\n plt.clf()\n\n\ndef plot_mlp_surface(mesh_alphas, mesh_layers, preds, top_score, features,\n save, show, runtype, is_pca, pca_components):\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n\n cm = plt.cm.coolwarm\n surf = ax.plot_surface(mesh_alphas, mesh_layers, preds, cmap=cm,\n linewidth=1, antialiased=True, shade=True)\n #text = \"Top Score: %.2f%%, (%.2f, %.2f)\" % (top_score[2], top_score[0], top_score[1])\n #ax.text(*top_score, text)\n\n # Customize the z axis.\n ax.set_zlim(0, 100)\n ax.zaxis.set_major_locator(LinearLocator(10))\n ax.zaxis.set_major_formatter(FormatStrFormatter('%d'))\n # Add a color bar which maps values to colors.\n fig.colorbar(surf, shrink=0.5, aspect=5)\n plt.title('Predictions of MLP')\n ax.set_xlabel('Alpha Values')\n ax.set_ylabel('Number of Hidden Layers')\n ax.set_zlabel('Test Prediction Accuracy (%)')\n make_neat_text_box(ax, 'Features\\n\\n' + '\\n'.join(features))\n\n if is_pca:\n runtype += \" with PCA of \" + str(pca_components) + \" components\"\n\n name = 'mlp_surface_'\n\n if (len(features) == 33):\n name += \"All Stat Features\"\n elif (len(features) == 27):\n name += \"Reliable Stat Features\"\n elif (len(features) == 9):\n name += \"Frequency Based Features\"\n else:\n name += ', '.join(features)\n # if (len(name) > 80):\n # name = name[:70] + '(cont).png'\n\n name += \"_\" + runtype\n\n name += '.png'\n\n if save:\n filepath = str(Path('../Figures/MLPFigures') / name)\n print('Saving to ' + filepath)\n fig.savefig(filepath, bbox_inches='tight', dpi=200)\n if show:\n plt.show()\n plt.clf()\n\n\ndef plot_alpha(title, results, save, runtype):\n fig = plt.gcf()\n iterations = classification.alphas\n plt.title(title, fontsize=25)\n plt.xlabel('Alpha', fontsize=20)\n plt.ylabel('Accuracy', fontsize=20)\n plt.plot(iterations, results)\n if save:\n if (os.name == 'nt'): # If windows...\n fig.savefig('..\\\\Figures\\\\AlphaPlot\\\\Figure ' + runtype + ' - ' + title, bbox_extra_artists=(), bbox_inches='tight')\n else:\n fig.savefig('../Figures/AlphaPlot/Figure ' + runtype + ' - ' + title, bbox_extra_artists=(), bbox_inches='tight')\n plt.clf()\n\ndef plot_tree(title, results, save, show, runtype):\n fig = plt.gcf()\n iterations = classification.num_of_trees\n plt.title(title, fontsize=25)\n plt.xlabel('Num of Trees', fontsize=20)\n plt.ylabel('Prediction Accuracy (%)', fontsize=20)\n plt.plot(classification.num_of_trees, results)\n\n title += '.png'\n\n\n if save:\n if (os.name == 'nt'): # If windows...\n fig.savefig('..\\\\Figures\\\\TreePlot\\\\Figure ' + runtype + ' - ' + title, bbox_extra_artists=(), bbox_inches='tight')\n else:\n fig.savefig('../Figures/TreePlot/Figure ' + runtype + ' - ' + title, bbox_extra_artists=(), bbox_inches='tight')\n\n if show:\n show()\n\n plt.clf()\n\n\ndef plot_depth(title, depths, results, save, show, runtype):\n # import pdb; pdb.set_trace()\n fig = plt.gcf()\n iterations = depths\n plt.title(title, fontsize=25)\n plt.xlabel('Level of Depth', fontsize=20)\n plt.ylabel('Prediction Accuracy (%)', fontsize=20)\n plt.plot(iterations, results)\n\n\n title += '.png'\n\n if save:\n if (os.name == 'nt'): # If windows...\n fig.savefig('..\\\\Figures\\\\TreePlot\\\\Figure ' + runtype + ' - ' + title, bbox_extra_artists=(), bbox_inches='tight')\n else:\n fig.savefig('../Figures/TreePlot/Figure ' + runtype + ' - ' + title, bbox_extra_artists=(), bbox_inches='tight')\n\n if show:\n show()\n\n plt.clf()\n\n# OLD STUFF BELOW ################################\n\ndef plot_xyz(runs, title='XYZ Plot'):\n # Old function that was used to plots xyz values separately all in one neat window\n fig = plt.figure()\n fig.canvas.set_window_title(title)\n for run in runs:\n x = run['x']\n y = run['y']\n z = run['z']\n time = np.arange(0, len(x), 1) # we have 100 values in the xyz of each run\n plt.subplot(3, 1, 1) # subplot(rows, columns, currentgraph)\n plt.plot(time, x, color='r', alpha=0.4) # plot(x, y, color)\n plt.title('X Values')\n\n plt.subplot(3, 1, 2)\n plt.plot(time, y, color='g', alpha=0.4)\n plt.title('Y Values')\n\n plt.subplot(3, 1, 3)\n plt.plot(time, z, color='b', alpha=0.4)\n plt.title('Z Values')\n\n plt.tight_layout()\n show()\n\n\ndef plot_magnitude(runsSummary):\n # Old function we used when we wanted to see the magnitude of XYZ values early on\n global figures\n figures += 1\n plt.figure(figures) # creates new plot that will be shown when show() is called\n time = np.arange(0, 100, 1) # we have 100 values in the xyz of each run\n # shade helps to visually differentiate between the different lines (earlier runs = darker, later runs = lighter)\n shade = 100 # 0 - 255 (RGB)\n for run in runsSummary:\n x = run['data']['x']\n y = run['data']['y']\n z = run['data']['z']\n\n mag = [xv**2 + yv**2 + zv**2 for xv, yv, zv in zip(x, y, z)]\n vertex_vals = []\n vertex_x = []\n prevnum = None\n dir = ''\n for i, num in enumerate(mag):\n if prevnum == None:\n prevnum = num\n else:\n if dir == '':\n if (prevnum < num):\n dir = '+'\n elif (prevnum > num):\n dir = '-'\n elif dir == '+':\n if (prevnum > num):\n vertex_x.append(i-1)\n vertex_vals.append(prevnum)\n dir = '-'\n elif dir == '-':\n if (prevnum < num):\n vertex_x.append(i-1)\n vertex_vals.append(prevnum)\n dir = '+'\n prevnum = num\n plt.plot(time, mag, color='#%.2X%.2X%.2X' % (shade, shade, shade), linewidth=0.4)\n # '%.2X' translates to -> 'Hexidecimal with 2 digit precision'\n # '#%.2X%.2X%.2X' % (5, 5, 5) = '#050505'\n plt.scatter(vertex_x, vertex_vals, c='r', s=4)\n # [c='r' ----> color = 'red'] [s=4 ----> size=4]\n if shade < 255:\n shade += 2\n\n\nclass SGDPlotter:\n # I made a class for SGD because I was doing a lot of dynamic plotting (I didn't want to deal with global\n # variables and other craziness), I wanted specific methods to describe what was happening, and I wanted to\n # experiment to see if this would be a better structure in the future.\n def __init__(self, before, features, type):\n self.before = before\n self.features = features\n self.type = type\n self.colors = 'bry' # Blue Red Yellow\n\n self.fig = plt.figure(figsize=(12, 7)) # Make the initial figure\n self.fig.suptitle(\"Decision surface of multi-class Stochastic Gradient Descent\\n(%s)\" % ', '.join(\n type + s for s in features.split(' ')))\n\n self.leftax = self.fig.add_subplot(121, projection='3d') # Left is Three Dimensional\n self.rightax = self.fig.add_subplot(122) # Right is Two Dimensional\n self.rightax.set_title('SGD classification on PCA Data')\n self.rightax.set_xlabel('Component 1')\n self.rightax.set_ylabel('Component 2')\n self.plot_left(before, features, type)\n\n def plot_left(self, before, features, type):\n # plots the left graph as a 3D PCA Graph\n data = before['data']\n target_names = before['target_names']\n target = before['target']\n\n for color, i, target_name in zip(self.colors, range(len(target_names)), target_names):\n c1, c2, c3 = data[target == i, 0], data[target == i, 1], data[target == i, 2]\n self.leftax.scatter(c1, c2, c3, color=color, alpha=.5, lw=2, label=target_name, marker='o')\n self.leftax.set_title('Original Data\\n (No PCA)')\n self.leftax.set_xlabel(type + features.split(' ')[0])\n self.leftax.set_ylabel(type + features.split(' ')[1])\n self.leftax.set_zlabel(type + features.split(' ')[2])\n\n def draw_contour(self, xx, yy, Z, cmap, alpha):\n # Draws the colored sectional background in right graph\n cs = self.rightax.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=.5)\n self.rightax.axis('tight')\n\n def plot_right(self, X, classes_, target, target_names, cmap, alpha):\n # Draws points in right graph\n # classes_ = [0, 1, 2, ..., (number of different types of vehicles)]\n for i, color in zip(classes_, self.colors):\n idx = np.where(target == i)[0] # use only rows that are associated with current cartype\n self.rightax.scatter(X[idx, 0], X[idx, 1], c=color, edgecolor='black', label=target_names[i], cmap=cmap, alpha=alpha)\n\n def plot_predictions(self, X, results, target, target_names, score):\n for i, color in zip(range(len(target_names)), self.colors):\n idx = np.where(target == i) # use only rows that are associated with current cartype\n self.rightax.scatter(X[idx, 0], X[idx, 1], c=color, edgecolor='black')\n\n rightorwrong = np.array([1 if results[i] == target[i] else 0 for i in range(len(results))])\n for i, color in zip(range(2), ['black', 'white']):\n idx = np.where(rightorwrong == i) # use only rows that are associated with current cartype\n self.rightax.scatter(X[idx, 0], X[idx, 1], c=color,\n label=['Incorrect Test', 'Correct Test'][i], marker='+')\n self.rightax.set_title('SGD classification on PCA Data\\nWith Predictions (Score: %.3f%%)' % score)\n self.finalize()\n\n\n def plot_line(self, x_values, y_values, ls, color):\n # Draws dashed line in right graph\n self.rightax.plot(x_values, y_values, ls=ls, color=color)\n\n def finalize(self):\n self.leftax.legend()\n self.rightax.legend()\n plt.tight_layout()\n plt.subplots_adjust(bottom=0.07, left=0.01, right=0.99, top=0.85)\n\n def save(self, predictions):\n # Saves the figure. Matplotlib uses a standard image quality of 100 DPI, but we can change that in parameters\n features = '_'.join(self.features.split(' ')) # Separates features by underscores instead of spaces\n if predictions:\n if (os.name == 'nt'): # Windows\n self.fig.savefig('..\\\\Figures\\\\SGDFigures\\\\Predictions\\\\' + features + ' ' + self.type + '_Car_SGD.png', bbox_inches='tight', dpi=200)\n else:\n self.fig.savefig('../Figures/SGDFigures/Predictions/' + features + ' ' + self.type + '_Car_SGD.png', bbox_inches='tight', dpi=200)\n else:\n if (os.name == 'nt'): # Windows\n self.fig.savefig('..\\\\Figures\\\\SGDFigures\\\\' + features + ' ' + self.type + '_Car_SGD.png', bbox_inches='tight', dpi=200)\n else:\n self.fig.savefig('../Figures/SGDFigures/' + features + ' ' + self.type + '_Car_SGD.png', bbox_inches='tight', dpi=200)\n\n def show(self):\n plt.show()\n\n\ndef show():\n plt.show()\n\ndef close():\n plt.close('all')\n","sub_path":"src/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":25528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"146314805","text":"import re\n\nWHITE_RGBA = (255, 255, 255)\nBLACK_RGBA = (0, 0, 0)\n\n\ndef _get_size(size):\n for m in _SIZE_RE:\n match = m[0].match(size)\n if match:\n return m[1](match.groupdict())\n raise ValueError('Invalid size')\n\n\ndef _get_RGBA(opt, index):\n if len(opt) > index + 6:\n return tuple(int(opt[i * 2 + 3: i * 2 + 5], 16) for i in xrange(3))\n raise ValueError('Invalid color format, not xRRGGBB')\n\n\ndef _get_options(opt):\n def not_keep_aspect_ratio(opt_result, opt_string, index):\n opt_result['adjh'] = False\n opt_result['adjw'] = False\n return 0\n\n def crop(opt_result, opt_string, index):\n opt_result['crop'] = True\n return 0\n\n def frame(opt_result, opt_string, index):\n opt_result['frame'] = True\n return 0\n\n def window(opt_result, opt_string, index):\n opt_result['window'] = True\n return 0\n\n def fcolor(opt_result, opt_string, index):\n if opt_string[index] == 'w':\n opt_result['bgc'] = WHITE_RGBA\n return 1\n elif opt_string[index] == 'b':\n opt_result['bgc'] = BLACK_RGBA\n return 1\n elif opt_string[index] == 'x':\n opt_result['bgc'] = _get_RGBA(opt_string, index)\n return 7\n raise ValueError('Invalid color format')\n\n opt_result = dict()\n opt_map = dict(\n a=not_keep_aspect_ratio,\n c=crop,\n f=frame,\n w=window,\n F=fcolor,\n )\n i = 0\n while i < len(opt):\n try:\n i += opt_map[opt[i]](opt_result, opt, i + 1)\n except LookupError:\n raise ValueError('Invalid option')\n i += 1\n return opt_result\n\n\ndef adjust(img, w=0, h=0, adjust_width=False, adjust_height=False, crop=False,\n frame=False, bgc=None):\n if adjust_width:\n w = w or int(h * img.size[0] / img.size[1])\n if adjust_height:\n h = h or int(w * img.size[1] / img.size[0])\n if w == 0:\n w = img.size[0]\n if h == 0:\n h = img.size[1]\n if frame:\n img_w = img.size[0]\n img_h = img.size[1]\n offset_x = 0\n offset_y = 0\n resize_w = w\n resize_h = h\n if img_w * h > img_h * w:\n resize_h = int(img_h * w / img_w)\n offset_y = (h - resize_h) / 2\n else:\n resize_w = int(img_w * h / img_h)\n offset_x = (w - resize_w) / 2\n framed = img.resize((resize_w, resize_h), PIL.Image.ANTIALIAS)\n if offset_x == 0 and offset_y == 0:\n return framed\n bg = PIL.Image.new('RGBA', (w, h), bgc or WHITE_RGBA)\n bg.paste(framed, (offset_x, offset_y))\n return bg\n if crop:\n offset_x = max((w - img.size[0]) / 2, 0)\n offset_y = max((h - img.size[1]) / 2, 0)\n crop_x = max((img.size[0] - w) / 2, 0)\n crop_y = max((img.size[1] - h) / 2, 0)\n crop_w = min(w, img.size[0])\n crop_h = min(h, img.size[1])\n cropped = img.crop((crop_x, crop_y, crop_x + crop_w, crop_y + crop_h))\n if offset_x == 0 and offset_y == 0:\n return cropped\n bg = PIL.Image.new('RGBA', (w, h), bgc or WHITE_RGBA)\n bg.paste(cropped, (offset_x, offset_y))\n return bg\n return img.resize((w, h), PIL.Image.ANTIALIAS)\n\n\ndef parse(mode):\n parts = mode.split('-')\n args = _get_size(parts[0])\n if 1 < len(parts):\n for opt, value in _get_options(parts[1]).iteritems():\n args[opt] = value\n return args\n\n_SIZE_RE = (\n (re.compile('^w(?P[0-9]+)h(?P[0-9]+)$'),\n lambda d: dict(w=int(d['w']), h=int(d['h']))),\n (re.compile('^w(?P[0-9]+)$'),\n lambda d: dict(w=int(d['w']), adjh=True)),\n (re.compile('^h(?P[0-9]+)$'),\n lambda d: dict(h=int(d['h']), adjw=True)),\n (re.compile('^(?P[0-9]+)$'),\n lambda d: dict(w=int(d['s']), h=int(d['s']), crop=True)),\n)\n","sub_path":"src/eirx/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":3898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"22869015","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import IsolationForest\nfields = ['Time','EC','grade','qnt','per']\ndf = pd.read_csv('data2.csv', skipinitialspace=True, usecols=fields)\ndf.info()\n\nX = df.iloc[:, 3:5].values\nY =df.iloc[:, 2].values\n\n# Encoding categorical data\n\n# Encoding the Independent Variable\n\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X = LabelEncoder()\nX[:, 1] = labelencoder_X.fit_transform(X[:, 1])\nonehotencoder = OneHotEncoder(categorical_features = [1])\nX = onehotencoder.fit_transform(X).toarray()\n\n# Avoiding the Dummy Variable Trap\nX = X[:, 1:]\n\n# Splitting the dataset into the Training set and Test set\n\nfrom sklearn.model_selection import train_test_split\nX_Train, X_Test, Y_Train, Y_Test = train_test_split(X, Y, test_size = 0.2, random_state = 0)\n\n# Fitting the Multiple Linear Regression in the Training set\n\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_Train, Y_Train)\n\n# Predicting the Test set results\n\nY_Pred = regressor.predict(X_Test)\n\n# Building the optimal model using Backward Elimination\n\nimport statsmodels.formula.api as sm\nX = np.append(arr = np.ones((50, 1)).astype(int), values = X, axis = 1)\n\nX_Optimal = X[:, [0,1,2,3,4,5]]\nregressor_OLS = sm.OLS(endog = Y, exog = X_Optimal).fit()\nregressor_OLS.summary()\n\nX_Optimal = X[:, [0,1,2,4,5]]\nregressor_OLS = sm.OLS(endog = Y, exog = X_Optimal).fit()\nregressor_OLS.summary()\n\nX_Optimal = X[:, [0,1,4,5]]\nregressor_OLS = sm.OLS(endog = Y, exog = X_Optimal).fit()\nregressor_OLS.summary()\n\nX_Optimal = X[:, [0,1,4]]\nregressor_OLS = sm.OLS(endog = Y, exog = X_Optimal).fit()\nregressor_OLS.summary()\n\n# Fitting the Multiple Linear Regression in the Optimal Training set\n\nX_Optimal_Train, X_Optimal_Test = train_test_split(X_Optimal,test_size = 0.2, random_state = 0)\nregressor.fit(X_Optimal_Train, Y_Train)\n\n# Predicting the Optimal Test set results\n\nY_Optimal_Pred = regressor.predict(X_Optimal_Test)","sub_path":"summer intern/project 1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"326957323","text":"import os, subprocess, sys\n\nclass GetPackages:\n\n def __init__(self, package):\n try:\n import pip\n except ModuleNotFoundError:\n #fix this to download from pip website\n os.system('python mypip.py')\n try:\n import package\n except ModuleNotFoundError as e:\n self.intall(package)\n\n def intall(self, tool_name):\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", tool_name, \"--user\"])\n\n#usage sample\n#check_packages = GetPackages('folium')\n\n#pdf.load_pages()","sub_path":"GetPackages.py","file_name":"GetPackages.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"279348949","text":"from datetime import datetime\n\nfrom sqlalchemy import create_engine, or_, and_, desc, func, distinct\nfrom sqlalchemy.orm import sessionmaker\nimport pandas as pd\nimport json\nimport sqlite3\nimport time\nimport pymysql\nimport xlrd\nimport xlsxwriter\nfrom sqlalchemy.sql.functions import count, char_length\n\nimport operator as op\n\n\ndef connectDBgetSesion():\n # engine = create_engine('sqlite:///db.sqlite3', echo=True)\n engine = create_engine('sqlite:///db.sqlite3', echo=False)\n # engine = create_engine(\"mysql+pymysql://root:123456@localhost:3306/testpymysql?charset=utf8\", echo=True)\n\n Session = sessionmaker(bind=engine)\n session = Session()\n return session\n\n\ndef close(session):\n session.commit()\n session.close()\n\n\ndef find_all(json_str=False):\n pass\n\n\ndef newCutWordTOdb(newicdword, newperfword):\n try:\n session = connectDBgetSesion()\n # \"INSERT INTO custom_icd_desc (icd,word_desc) VALUES (%s,%s) \"\n custom_icd_desc = Custom_icd_desc(icd=newicdword, word_desc=newperfword)\n\n session.add(custom_icd_desc)\n except Exception as e:\n print(e)\n finally:\n close(session)\n updatetempdict()\n\n\ndef updatetempdict():\n try:\n session = connectDBgetSesion()\n # sql = \"SELECT DISTINCT word_desc FROM custom_icd_desc\"\n all_custom_icd = session.query(distinct(Custom_icd_desc.word_desc)).all()\n\n fout = open(\"tempdict.txt\", 'w', encoding='utf-8') # 以写得方式打开文件\n for row in all_custom_icd:\n r1 = row[0]\n fout.write(r1 + '\\n') # 将分词好的结果写入到输出文件\n fout.close()\n\n except Exception as e:\n print(e)\n finally:\n close(session)\n\n\ndef updateCustom_icd(cid, icd):\n try:\n session = connectDBgetSesion()\n objquery = session.query(Custom_icd_desc).filter(Custom_icd_desc.id == cid)\n\n obj = objquery.one()\n oldicd = obj.icd\n\n objquery.update({Custom_icd_desc.icd: icd})\n\n if icd != oldicd:\n modifyRecord = ModifyRecord(timestamp=datetime.now(), operator='操作人', fromold=oldicd, tonew=icd,\n originalid=cid)\n session.add(modifyRecord)\n\n except Exception as e:\n print(e)\n session.rollback()\n finally:\n close(session)\n updatetempdict()\n\n\ndef updateCustom_icd_word(cid, word_desc):\n try:\n session = connectDBgetSesion()\n # session.query(Custom_icd_desc).filter(Custom_icd_desc.id == cid).update(\n # {Custom_icd_desc.word_desc: word_desc})\n objquery = session.query(Custom_icd_desc).filter(Custom_icd_desc.id == cid)\n\n obj = objquery.one()\n oldword_desc = obj.word_desc\n\n objquery.update({Custom_icd_desc.word_desc: word_desc})\n if oldword_desc != word_desc:\n modifyRecord = ModifyRecord(timestamp=datetime.now(), operator='操作人', fromold=oldword_desc, tonew=word_desc,\n originalid=cid)\n session.add(modifyRecord)\n\n except Exception as e:\n print(e)\n session.rollback()\n finally:\n close(session)\n updatetempdict()\n\n\ndef getCustom_icd():\n try:\n session = connectDBgetSesion()\n rows1 = session.query(Icd_desc.icd, Icd_desc.word_desc).all()\n # how make it to map and have the index for quickly search\n standard_icds = {}\n for row in rows1:\n standard_icds[row[0]] = row[1]\n\n print(standard_icds)\n rows2 = session.query(Custom_icd_desc.id, Custom_icd_desc.icd, Custom_icd_desc.word_desc).all()\n l = []\n dict1 = {}\n for row in rows2:\n row = row._asdict()\n icd = row['icd']\n if icd in standard_icds:\n standard_word_desc = standard_icds[icd]\n row['standard_word_desc'] = standard_word_desc\n else:\n row['standard_word_desc'] = ''\n l.append(row)\n\n return json.dumps(l, ensure_ascii=False)\n except Exception as e:\n print(e)\n l = []\n return json.dumps(l, ensure_ascii=False)\n finally:\n close(session)\n\n\ndef getModify_record():\n try:\n session = connectDBgetSesion()\n\n rows2 = session.query(ModifyRecord.id, ModifyRecord.timestamp, ModifyRecord.operator,\n ModifyRecord.fromold, ModifyRecord.tonew).order_by(desc(ModifyRecord.timestamp)).offset(\n 0).limit(100).all()\n l = []\n dict1 = {}\n for row in rows2:\n row = row._asdict()\n timestamp = row['timestamp']\n timestamp1 = str(timestamp)[:-7] # .rstrip('.')\n row['timestamp'] = timestamp1\n\n l.append(row)\n\n return json.dumps(l, ensure_ascii=False)\n except Exception as e:\n print(e)\n l = []\n return json.dumps(l, ensure_ascii=False)\n finally:\n close(session)\n\n\n# 获取未确认的诊断语句\ndef getAdiagnosis():\n try:\n session = connectDBgetSesion()\n # sql = \"SELECT id,diagnosis_desc FROM diagnosis where diagnosed is NULL GROUP BY id DESC LIMIT 0,1\"\n\n # count = session.query(DiagnosisNoRepeat) \\\n # .filter(DiagnosisNoRepeat.diagnosed != None).count()\n\n query = session.query(DiagnosisNoRepeat.id, DiagnosisNoRepeat.diagnosis_desc) \\\n .filter(DiagnosisNoRepeat.diagnosed == None).order_by(desc(DiagnosisNoRepeat.manualicd),\n desc(DiagnosisNoRepeat.standardicd))\n rows = query.first()\n\n DiagnosisNoRepeatids = session.query(DiagnosisNoRepeat.id).order_by(desc(DiagnosisNoRepeat.manualicd),\n desc(DiagnosisNoRepeat.standardicd)).all()\n count = 0\n for row in DiagnosisNoRepeatids:\n count = count + 1\n if rows[0] == row[0]:\n break;\n\n # count = query.count()\n return count, rows[0], rows[1]\n\n except Exception as e:\n print(e)\n return 0, 0\n finally:\n close(session)\n\n\n# 获取未确认的诊断语句\ndef getdiagnosisby(id):\n try:\n session = connectDBgetSesion()\n # sql = \"SELECT id,diagnosis_desc FROM diagnosis where diagnosed is NULL GROUP BY id DESC LIMIT 0,1\"\n\n query = session.query(DiagnosisNoRepeat.id, DiagnosisNoRepeat.diagnosis_desc) \\\n .filter(DiagnosisNoRepeat.id == id).order_by(desc(DiagnosisNoRepeat.manualicd),\n desc(DiagnosisNoRepeat.standardicd))\n rows = query.first()\n return rows[0], rows[1]\n\n except Exception as e:\n print(e)\n return 0, 0\n finally:\n close(session)\n\n\ndef sureiagnosis(diagnosisid, reverseicds):\n try:\n session = connectDBgetSesion()\n # sql = \"UPDATE diagnosis SET diagnosed = 1,manualicd=%s WHERE id =%s \"\n session.query(DiagnosisNoRepeat).filter(DiagnosisNoRepeat.id == diagnosisid).update(\n {DiagnosisNoRepeat.manualsure: reverseicds, DiagnosisNoRepeat.diagnosed: 1})\n except Exception as e:\n print(e)\n session.rollback()\n return 0, 0\n finally:\n close(session)\n\n\ndef getICDBy(perfword):\n try:\n session = connectDBgetSesion()\n # sql = \"SELECT icd FROM icd_desc where word_desc=%s UNION SELECT icd FROM custom_icd_desc where word_desc=%s \"\n icd = session.query(Icd_desc.icd).filter(Icd_desc.word_desc == perfword).first()\n if icd == None:\n icd = session.query(Custom_icd_desc.icd).filter(Custom_icd_desc.word_desc == perfword).first()\n if icd != None:\n icd = icd[0]\n return icd\n except Exception as e:\n print(e)\n return 0\n finally:\n close(session)\n\n\n# 从ICD到多个 描述\ndef getICDDescBy(icd):\n try:\n session = connectDBgetSesion()\n # sql = \"SELECT word_desc FROM icd_desc where icd=%s \\\n # UNION SELECT word_desc FROM custom_icd_desc where icd=%s \"\n word_desc1 = session.query(Icd_desc.word_desc).filter(Icd_desc.icd == icd).first()\n word_desc2 = session.query(Custom_icd_desc.word_desc).filter(Custom_icd_desc.icd == icd).all()\n\n word_desc = \"\"\n for wd in word_desc2:\n r1 = wd[0]\n word_desc = word_desc + r1 + \" ; \"\n\n if word_desc1 != None:\n return word_desc1[0] + \" ; \" + word_desc\n else:\n return word_desc\n\n except Exception as e:\n print(e)\n return 'something wrong'\n finally:\n close(session)\n\n\n# diagnosis_desc,manualicd\ndef read_excel2diagnosis(filepath):\n workbook = xlrd.open_workbook(filepath)\n sheet = workbook.sheet_by_index(0)\n count = sheet.nrows\n datalist = []\n # count = 3\n for i in range(1, count):\n datalist.append([sheet.row_values(i)[0], sheet.row_values(i)[1]])\n # datalist.append([sheet.row_values(i)[0],sheet.row_values(i)[1], sheet.row_values(i)[2], sheet.row_values(i)[3],\n # sheet.row_values(i)[4],sheet.row_values(i)[5]])\n batch2diagnosis(datalist)\n\n\ndef batch2diagnosis(datalist):\n try:\n setit = set()\n setdict = {}\n session = connectDBgetSesion()\n session.query(Diagnosis).delete()\n session.query(DiagnosisNoRepeat).delete()\n\n for data in datalist:\n str0 = data[0]\n str1 = data[1]\n d = Diagnosis(diagnosis_desc=str0, manualicd=str1)\n\n setit.add(str0)\n session.add(d)\n setdict[str0] = str1\n for skey in setit:\n if str(skey).strip(' ') == '':\n continue\n if skey in setdict:\n svalue = setdict[skey]\n d2 = DiagnosisNoRepeat(diagnosis_desc=skey, manualicd=svalue)\n else:\n d2 = DiagnosisNoRepeat(diagnosis_desc=skey)\n\n session.add(d2)\n\n except Exception as e:\n print(data)\n print(e)\n finally:\n close(session)\n\n\ndef export2excelfromdiagnosis(filepath):\n try:\n session = connectDBgetSesion()\n\n results = session.query(Diagnosis.diagnosis_desc, Diagnosis.manualicd, Diagnosis.standardicd,\n Diagnosis.customicd, Diagnosis.alldesc, Diagnosis.subtyle, Diagnosis.manualsure)\n df = pd.read_sql(sql=results.statement, con=results.session.bind)\n # df.columns = ['诊断文字', '人工转icd', '程序转icd', '描述', '标准转', '自定义转']\n # df.columns = ['诊断文字', '原人工转ICD', '标准句转', '自定义词转', '标准描述', '分类','人工确认']\n df.columns = [COL1, COL2, COL3, COL4, COL5, COL6, COL7]\n\n writer = pd.ExcelWriter(filepath, engine='xlsxwriter')\n df.to_excel(writer, sheet_name='diagnosis', index=False)\n\n except Exception as e:\n print(e)\n finally:\n close(session)\n\n\ndef export2excelfromDISTINCTdiagnosis(filepath):\n try:\n session = connectDBgetSesion()\n\n results = session.query(DiagnosisNoRepeat.diagnosis_desc, DiagnosisNoRepeat.manualicd,\n DiagnosisNoRepeat.standardicd,\n DiagnosisNoRepeat.customicd, DiagnosisNoRepeat.alldesc, DiagnosisNoRepeat.subtyle,\n # DiagnosisNoRepeat.manualsure).order_by(DiagnosisNoRepeat.standardicd)\n DiagnosisNoRepeat.manualsure).order_by(DiagnosisNoRepeat.manualicd,\n DiagnosisNoRepeat.standardicd)\n df = pd.read_sql(sql=results.statement, con=results.session.bind)\n\n # df.columns = ['诊断文字', '原人工转ICD', '标准句转', '自定义词转', '标准描述', '分类', '人工确认']\n df.columns = [COL1, COL2, COL3, COL4, COL5, COL6, COL7]\n # df.columns = ['诊断文字', '人工转icd', '程序转icd', '描述', '标准转', '自定义转']\n\n writer = pd.ExcelWriter(filepath, engine='xlsxwriter')\n df.to_excel(writer, sheet_name='diagnosis', index=False)\n\n except Exception as e:\n print(e)\n finally:\n close(session)\n\n\ndef export2excelfromdiagnosisclass(filepath):\n try:\n session = connectDBgetSesion()\n\n results = session.query(DiagnosisNoRepeat.diagnosis_desc, DiagnosisNoRepeat.manualicd,\n DiagnosisNoRepeat.programicd,\n DiagnosisNoRepeat.alldesc, DiagnosisNoRepeat.standardicd, DiagnosisNoRepeat.customicd,\n DiagnosisNoRepeat.subtyle)\n df = pd.read_sql(sql=results.statement, con=results.session.bind)\n df.columns = ['诊断文字', '人工转icd', '程序转icd', '描述', '标准转', '自定义转', \"分类\"]\n\n writer = pd.ExcelWriter(filepath, engine='xlsxwriter')\n df.to_excel(writer, sheet_name='diagnosis', index=False)\n\n except Exception as e:\n print(e)\n finally:\n close(session)\n\n\ndef tableheaddiagnosis():\n # sql = \"SELECT diagnosis_desc,manualicd,programicd,standardicd,customicd FROM diagnosis ORDER BY id asc LIMIT 0,4\"\n try:\n session = connectDBgetSesion()\n dds = session.query(Diagnosis).order_by('id').offset(0).limit(4).all()\n #\n l = []\n for d in dds:\n # ['诊断文字', '人工转icd', '程序转icd', '描述', '标准转', '自定义转'])\n # 诊断文字\t原人工转ICD\t标准句转\t自定义词转\t标准描述\t分类\t人工确认\n l.append([d.diagnosis_desc, d.manualicd, d.standardicd, d.customicd, d.alldesc, d.subtyle, d.manualsure])\n\n return l\n except Exception as e:\n print(e)\n return []\n finally:\n close(session)\n\n\ndef tableDISTINCTdiagnosis():\n try:\n session = connectDBgetSesion()\n dds = session.query(DiagnosisNoRepeat.diagnosis_desc, DiagnosisNoRepeat.manualicd,\n DiagnosisNoRepeat.standardicd,\n DiagnosisNoRepeat.customicd, DiagnosisNoRepeat.alldesc, DiagnosisNoRepeat.subtyle,\n DiagnosisNoRepeat.manualsure).order_by(desc(DiagnosisNoRepeat.manualicd),\n desc(DiagnosisNoRepeat.standardicd)).offset(0).limit(\n 500).all()\n l = []\n for d in dds:\n l.append([d.diagnosis_desc, d.manualicd, d.standardicd, d.customicd, d.alldesc, d.subtyle, d.manualsure])\n\n return l\n except Exception as e:\n print(e)\n return []\n finally:\n close(session)\n\n\ndef getDISTINCTdiagnosis(page, matchstate):\n try:\n pagecount=1\n pagesize = 100\n p = int(page) - 1\n if p < 0:\n p = 0\n p = p * pagesize\n\n session = connectDBgetSesion()\n # dds = session.query(DiagnosisNoRepeat).order_by(desc(DiagnosisNoRepeat.manualicd),\n # desc(DiagnosisNoRepeat.standardicd)).offset(p).limit(50).all()\n\n if matchstate != None and matchstate == 'match':\n dds = session.query(DiagnosisNoRepeat.id, DiagnosisNoRepeat.diagnosis_desc, DiagnosisNoRepeat.manualicd,\n DiagnosisNoRepeat.standardicd, DiagnosisNoRepeat.customicd, DiagnosisNoRepeat.alldesc,\n DiagnosisNoRepeat.subtyle, DiagnosisNoRepeat.manualsure) \\\n .filter(and_(DiagnosisNoRepeat.alldesc != None, DiagnosisNoRepeat.alldesc != '')) \\\n .order_by(desc(DiagnosisNoRepeat.manualicd), desc(DiagnosisNoRepeat.standardicd)).offset(p).limit(\n pagesize).all()\n pagecount = int(session.query(DiagnosisNoRepeat.id).filter(and_(DiagnosisNoRepeat.alldesc != None, DiagnosisNoRepeat.alldesc != '')) \\\n .count())/pagesize\n\n else:\n dds = session.query(DiagnosisNoRepeat.id, DiagnosisNoRepeat.diagnosis_desc, DiagnosisNoRepeat.manualicd,\n DiagnosisNoRepeat.standardicd, DiagnosisNoRepeat.customicd, DiagnosisNoRepeat.alldesc,\n DiagnosisNoRepeat.subtyle, DiagnosisNoRepeat.manualsure) \\\n .filter(or_(DiagnosisNoRepeat.alldesc == None, DiagnosisNoRepeat.alldesc == '')) \\\n .order_by(desc(DiagnosisNoRepeat.manualicd), desc(DiagnosisNoRepeat.standardicd)).offset(p).limit(\n pagesize).all()\n pagecount = int(session.query(DiagnosisNoRepeat.id).filter(or_(DiagnosisNoRepeat.alldesc == None, DiagnosisNoRepeat.alldesc == '')) \\\n .count())/pagesize\n\n l = []\n for row in dds:\n row = row._asdict()\n l.append(row)\n # for d in dds:\n # l.append([d.diagnosis_desc, d.manualicd, d.standardicd, d.customicd, d.alldesc, d.subtyle, d.manualsure])\n\n return l,pagecount\n except Exception as e:\n print(e)\n return []\n finally:\n close(session)\n\n\ndef tabletaildiagnosis():\n pass\n\n\ndef matchlistandupdate():\n try:\n session = connectDBgetSesion()\n # getstandardicddict\n # sql = \"SELECT icd,word_desc FROM icd_desc ORDER BY LENGTH(word_desc) DESC\"\n standardicddict = session.query(Icd_desc.icd, Icd_desc.word_desc).order_by(\n desc(char_length(Icd_desc.word_desc))).all()\n\n # getcustomicddict\n # sql = \"SELECT icd,word_desc FROM custom_icd_desc ORDER BY LENGTH(word_desc) DESC\"\n customicddict = session.query(Custom_icd_desc.icd, Custom_icd_desc.word_desc).order_by(\n desc(char_length(Custom_icd_desc.word_desc))).all()\n\n # getthediagnosis\n # sql = \"SELECT id,diagnosis_desc FROM diagnosis\"\n thediagnosis = session.query(DiagnosisNoRepeat.id, DiagnosisNoRepeat.diagnosis_desc).all()\n thediagnosisquery = session.query(DiagnosisNoRepeat)\n standardic = []\n customicd = []\n\n dict = {\"可能\": \"A\", \"待排\": \"B\", \"疑似\": \"C\"}\n begin_time = time.time()\n # i=0\n for id, diagnosis in thediagnosis:\n # i+=1\n # print(id, diagnosis)\n if len(diagnosis) < 1:\n continue\n\n subtyle = str_change(diagnosis, dict, repl_mode=0, mode=0, cut_str=1, duplicate=0, final_result=1)\n # print('subtyle:' + subtyle)\n thediagnosisquery.filter(DiagnosisNoRepeat.id == id).update(\n {DiagnosisNoRepeat.subtyle: subtyle})\n\n for icd, word_desc in standardicddict:\n # print(word_desc)\n if len(diagnosis) < 1:\n break\n if str(diagnosis).__contains__(str(word_desc)):\n # standardic.append(word_desc)\n standardic.append(icd)\n diagnosis = str(diagnosis).replace(word_desc, '')\n continue\n for icd, word_desc in customicddict:\n # print(word_desc)\n if len(diagnosis) < 1:\n break\n if str(diagnosis).__contains__(str(word_desc)):\n # customicd.append(word_desc)\n customicd.append(icd)\n diagnosis = str(diagnosis).replace(word_desc, '')\n continue\n\n if standardic.__len__() > 0 or customicd.__len__() > 0:\n # sql = \"UPDATE diagnosisnorepeat SET standardicd=%s,customicd=%s WHERE id = %s\"\n # cursor.execute(sql, [','.join(standardic), ','.join(customicd), id])\n thediagnosisquery.filter(DiagnosisNoRepeat.id == id).update(\n {DiagnosisNoRepeat.standardicd: ','.join(standardic),\n DiagnosisNoRepeat.customicd: ','.join(customicd)})\n # print(standardic)\n # print(customicd)\n\n standardic = []\n customicd = []\n\n begin_time2 = time.time()\n # print('time:',(begin_time2-begin_time))\n # 0.017 time: 293.01399993896484 time: 282.0129997730255time: 281.6879999637604 time: 327.47899985313416time: 316.5099997520447\n\n except Exception as e:\n print(e)\n return None\n finally:\n close(session)\n setDiagnosissNoRepeatDesc()\n resetDiagnosis()\n\n\n# select 标准匹配 XXX条ICD码; 自定义规则匹配XXX条ICD码\ndef statisticit():\n try:\n session = connectDBgetSesion()\n # sql = \"SELECT COUNT(standardicd) from diagnosis WHERE LENGTH(standardicd)>1\"\n # sql2 = \"SELECT COUNT(customicd) from diagnosis WHERE LENGTH(customicd)>1\"\n COUNT_standardicd = session.query(DiagnosisNoRepeat.id).filter(and_(DiagnosisNoRepeat.standardicd != '', DiagnosisNoRepeat.standardicd != None)).count()\n COUNT_customicd = session.query(DiagnosisNoRepeat.id).filter(and_(DiagnosisNoRepeat.customicd != '', DiagnosisNoRepeat.customicd != None)).count()\n COUNT_distinct = session.query(DiagnosisNoRepeat.id).count()\n\n return COUNT_distinct,COUNT_standardicd, COUNT_customicd\n except Exception as e:\n print(e)\n return 0, 0\n finally:\n close(session)\n\n\ndef countdiagnosis():\n try:\n session = connectDBgetSesion()\n return session.query(Diagnosis).count()\n except Exception as e:\n print(e)\n return 0\n finally:\n close(session)\n\n\ndef searchICDfromDb(newicdword):\n try:\n session = connectDBgetSesion()\n # sql = \"SELECT * from custom_icd_desc where icd LIKE %s LIMIT 0,10 UNION \\\n # SELECT * from icd_desc where icd LIKE %s LIMIT 0,10\"\n rows1 = session.query(Icd_desc.icd, Icd_desc.word_desc).filter(\n Icd_desc.icd.like(\"%\" + newicdword + \"%\")).offset(0).limit(12).all()\n rows2 = session.query(Custom_icd_desc.icd, Custom_icd_desc.word_desc).filter(\n Custom_icd_desc.icd.like(\"%\" + newicdword + \"%\")).offset(0).limit(12).all()\n\n dict1 = {}\n for row in rows1:\n row = row._asdict()\n icd = row['icd']\n oldicdvalue = dict1.get(icd)\n if oldicdvalue == None:\n dict1[icd] = row['word_desc'] + \"  ,      \"\n else:\n dict1[icd] = oldicdvalue + row['word_desc'] + \"  ,      \"\n for row in rows2:\n row = row._asdict()\n icd = row['icd']\n oldicdvalue = dict1.get(icd)\n if oldicdvalue == None:\n dict1[icd] = row['word_desc'] + \"  ,      \"\n else:\n dict1[icd] = oldicdvalue + row['word_desc'] + \"  ,      \"\n # return json.dumps([dict(ix) for ix in rows], ensure_ascii=False)\n # return json.dumps(rows, ensure_ascii=False)\n return json.dumps(dict1, ensure_ascii=False)\n except Exception as e:\n print(e)\n dict1 = {}\n return json.dumps(dict1, ensure_ascii=False)\n finally:\n close(session)\n\n\n# 搜索所有的相关 词\ndef searchPerfwordfromDb(perfword):\n try:\n session = connectDBgetSesion()\n sql = \"SELECT icd,word_desc FROM icd_desc where word_desc like %s LIMIT 0,15 \\\n UNION SELECT icd,word_desc FROM custom_icd_desc where word_desc LIKE %s LIMIT 0,15\"\n rows1 = session.query(Icd_desc.icd, Icd_desc.word_desc).filter(\n Icd_desc.word_desc.like(\"%\" + perfword + \"%\")).offset(0).limit(15).all()\n rows2 = session.query(Custom_icd_desc.icd, Custom_icd_desc.word_desc).filter(\n Custom_icd_desc.word_desc.like(\"%\" + perfword + \"%\")).offset(0).limit(15).all()\n l = []\n for row in rows1:\n row = row._asdict()\n l.append(row)\n for row in rows2:\n row = row._asdict()\n l.append(row)\n\n return json.dumps(l, ensure_ascii=False)\n except Exception as e:\n print(e)\n return json.dumps([], ensure_ascii=False)\n finally:\n close(session)\n\n\n# 搜索所有的相关 词\n# 计算与reverse_icds 的id距离, 排序前15个为输出\ndef searchPerfwordfromDbNew(perfword, reverse_icds):\n try:\n # rlist = reverse_icds.strip(',').split(',')\n reverse_icds = reverse_icds.replace(\" \", \"\")\n reverse_icds = reverse_icds.replace(\"\\xa0\", \"\")\n rlist = reverse_icds.split(',')\n reverse_ids = [1]\n session = connectDBgetSesion()\n reverse = session.query(Icd_desc).filter(Icd_desc.icd.in_(rlist)).all()\n\n if reverse is None:\n pass\n else:\n for i in reverse:\n reverse_ids.append(i.id)\n\n print(reverse_ids)\n rows1 = session.query(Icd_desc).filter(Icd_desc.word_desc.like(\"%\" + perfword + \"%\")).all()\n\n theresult = []\n for id in reverse_ids:\n # print(\"nowid: \",id)\n for icdobj in rows1:\n icdobj.absscore = abs(icdobj.id - id)\n\n resort1 = sorted(rows1, key=lambda icdobj: icdobj.absscore, reverse=False)\n for i in range(15):\n if i >= len(resort1):\n break\n theresult.append(resort1[i])\n # print(resort1[i].id,resort1[i].absscore)\n\n theresult = sorted(theresult, key=lambda icdobj: icdobj.absscore, reverse=False)\n l = []\n for i in range(15):\n if i >= len(theresult):\n break\n kv = {\"icd\": theresult[i].icd, \"word_desc\": theresult[i].word_desc}\n l.append(kv)\n\n rows2 = session.query(Custom_icd_desc.icd, Custom_icd_desc.word_desc).filter(\n Custom_icd_desc.word_desc.like(\"%\" + perfword + \"%\")).offset(0).limit(15).all()\n for row in rows2:\n row = row._asdict()\n l.append(row)\n\n return json.dumps(l, ensure_ascii=False)\n except Exception as e:\n print(e)\n return json.dumps([], ensure_ascii=False)\n finally:\n close(session)\n\n\ndef setDiagnosissNoRepeatDesc():\n try:\n session = connectDBgetSesion()\n dnorepeat = session.query(DiagnosisNoRepeat).all()\n\n for d in dnorepeat:\n sids = d.standardicd\n cids = d.customicd\n sets = set()\n set2 = set()\n if sids is None:\n pass\n else:\n sid1ist = str(sids).split(',')\n sets = set(sid1ist)\n if cids is None:\n pass\n else:\n cidlist = str(cids).split(',')\n set2 = set(cidlist)\n\n sets = sets | set2\n print(sets)\n word_desc = ''\n for icd in sets:\n icd_desc = session.query(Icd_desc).filter(Icd_desc.icd == icd).first()\n if icd_desc is None:\n continue\n word_desc = word_desc + icd_desc.word_desc + ';'\n\n d.alldesc = word_desc\n d.programicd = ','.join(sets)\n if str(d.programicd).startswith(','):\n d.programicd = str(d.programicd).strip(',')\n\n except Exception as e:\n print(e)\n finally:\n close(session)\n\n\ndef resetDiagnosis():\n try:\n session = connectDBgetSesion()\n dnorepeat = session.query(DiagnosisNoRepeat).all()\n bigdiagnosis = session.query(Diagnosis)\n\n for d in dnorepeat:\n for dd in bigdiagnosis.filter(Diagnosis.diagnosis_desc == d.diagnosis_desc).all():\n dd.manualicd = d.manualicd\n dd.standardicd = d.standardicd\n dd.customicd = d.customicd\n dd.alldesc = d.alldesc\n dd.subtyle = d.subtyle\n # dd.programicd = d.programicd\n dd.manualsure = d.manualsure\n\n except Exception as e:\n print(e)\n finally:\n close(session)\n\n\n# 这方法有依赖性,需要icd列表,的id大小是与icd的类排序相应!\n# 这样做的目的,是icd直接 是以ID来作为 其分数, 而这个分类是有意义的!\ndef find_recommend_words(recommend_words, reverse_icds):\n try:\n session = connectDBgetSesion()\n # sql = \"SELECT * from custom_icd_desc where icd LIKE %s LIMIT 0,10 UNION \\\n # SELECT * from icd_desc where icd LIKE %s LIMIT 0,10\"\n reverse = session.query(Icd_desc).filter(Icd_desc.icd.in_(reverse_icds)).all()\n reverse_ids = []\n if reverse is None:\n pass\n else:\n for i in reverse:\n reverse_ids.append(i.id)\n\n recommend_words.sort(key=lambda x: len(x), reverse=True)\n print(reverse_ids, reverse_icds)\n print(recommend_words)\n relist = []\n for word in recommend_words:\n # step1 find a icd by word like\n rows1 = session.query(Icd_desc).filter(Icd_desc.word_desc.like(\"%\" + word + \"%\")).offset(0).limit(50).all()\n if rows1 is None:\n continue\n if len(rows1) < 1:\n continue\n # step2 find the nearby icd 的id! and compute the relate\n # 找出 距任意已翻译的点 里 最近的一点\n tmpmix = 300000\n tmpicdobj = rows1[0]\n tmpicdobj.word_inside = word\n\n for icdobj in rows1:\n for id in reverse_ids:\n if abs(icdobj.id - id) < tmpmix and abs(icdobj.id - id) != 0:\n # if abs(icdobj.id-id) < tmpmix :\n tmpmix = abs(icdobj.id - id)\n tmpicdobj = icdobj\n tmpicdobj.word_inside = word\n\n # print(tmpicdobj.id, tmpicdobj.icd, tmpicdobj.word_desc,word,tmpicdobj.word_inside)\n # 已包含icd,则排除 最后生成list 返回 !\n\n kv = {\"icd\": tmpicdobj.icd, \"word_desc\": tmpicdobj.word_desc, \"id\": tmpicdobj.id,\n \"word_inside\": tmpicdobj.word_inside}\n relist.append(kv)\n\n results = [obj for obj in relist if obj[\"id\"] not in reverse_ids]\n\n return results\n except Exception as e:\n print(e)\n finally:\n close(session)\n\n# resetDiagnosis()\n#\n# setDiagnosissNoRepeatDesc()\n# print(countdiagnosis())\n\n# export2excelfromdiagnosis('../temp/xlsx_file2.xlsx')\n# statisticit()\n# matchlistandupdate()\n\n# newCutWordTOdb('sdfsl','心心')\n# searchPerfwordfromDb('心')\n\n# -----\n# recommend_words = ['心脏瓣膜病', '老年', '钙化', '性', '主闭', '轻度', '二闭', '三闭', '重度', '性主闭']\n# reverse_icds = ['A01.000', 'I38.x01']\n# results = find_recommend_words(recommend_words, reverse_icds)\n# print(results)\n\n# reverse_icds = 'I38.x01 , A01.000 , '\n# reverse_icds = ['A01.000', 'I38.x01']\n# print(searchPerfwordfromDb(\"老年\"))\n# print(searchPerfwordfromDbNew(\"老年\",reverse_icds))\n","sub_path":"code/python/db/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":31007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"460421521","text":"# C - Welcome to AtCoder\n# https://atcoder.jp/contests/abc151/tasks/abc151_c\n\nn,m = map(int,input().split())\n\n# 2 5\n# 1 WA\n# 1 AC\n# 2 WA\n# 2 AC\n# 2 WA\n# 2 2x\n\n# 提出問題数の分だけ配列を作る\nac = [False] * n\nwa = [0] * n \n\n# ================\n# ac F T .....\n# wa 1 2 .....\n# ================\n\n# まずはテーブルを作成する\nfor i in range(m):\n p, s = input().split()\n p = int(p) - 1\n\n if s == \"AC\":\n # 正解したことのある問題か確認\n ac[p] = True\n else:\n if ac[p] == False:\n wa[p] += 1\n\nac_cnt = 0\nwa_cnt = 0\n\nfor i in range(n):\n # Tの数をカウント。\n if ac[i] == True:\n ac_cnt += 1\n wa_cnt += wa[i]\n\nprint(ac_cnt,wa_cnt)","sub_path":"151/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"355023738","text":"''' d =deque('ghi') ->deque tiene 3 elementos\nappend(x)\nAdd x to the right side of the deque.\n\nappendleft(x)popleft()\nAdd x to the left side of the deque.\n\nclear()\nRemove all elements from the deque leaving it with length 0.\n\ncopy()\nCreate a shallow copy of the deque.\n\ncount(x)\nCount the number of deque elements equal to x.\n\nindex(x[, start[, stop]])\nReturn the position of x in the deque (at or after index start and before index stop). Returns the first match or raises ValueError if not found.\n\n'''\n\n\ndef apilar(pila,elemento):\n pila.append(elemento)\n\ndef desapilar(pila):\n return pila.pop()\ndef cima(pila):\n return pila[-1]\ndef encolar(cola,elemento):\n cola.insert(0,elemento)\n\ndef desencolar (cola):\n return cola.pop\ndef primero(cola):\n return cola[-1]\n\ndef balanceado (cadena):\n p=[]\n for elem in cadena :\n if elem == \"(\":\n apilar(p,elem)\n elif elem ==\")\":\n desapilar(p)\n if len(p) == 0:\n return (\"Es balanceado\")\n else:\n return (\"No esta balanceado\")\n\nstring=\"((())\"\nprint(balanceado(string))\n\n\ndef preordenIN(operator):\n if operator == '(':\n return 0\n elif operator == '+' or operator == '-':\n return 1\n elif operator == '*' or operator == '/':\n return 2\n elif operator == '^':\n return 3\n\ndef preordenOut(operator):\n if operator == '(':\n return 5\n elif operator == '+' or operator == '-':\n return 1\n elif operator == '*' or operator == '/':\n return 2\n elif operator == '^':\n return 4\n\n\n\ndef postfija (lista):\n pf=[]\n pila=[]#operadores\n\n for elem in lista:\n if elem.isdigit():\n pf.append(elem)\n #apilar(pf,elem)\n else:\n if len(pila)==0:\n apilar(pila,elem)\n elif elem == \")\":\n while cima(pila)!=\"(\":\n pf.append(desapilar(pila))\n desapilar(pila)\n elif preordenIN(cima(pila)) < preordenOut(elem):\n apilar (pila,elem)\n else:\n while len(pila)!=0 and preordenIN(cima(pila)) >= preordenOut(elem):\n pf.append(desapilar(pila))\n apilar(pila,elem)\n while len(pila)!=0 :\n pf.append(desapilar(pila))\n return pf\n\n\n\nexpresion = '4 - 5 ^ ( 5 - 2 ) + 9 * 7 - 24 / ( 7 - 2 ) '\nlista = solve(expresion)\nprint(postfija(lista))\nlista2=postfija(lista)\ndef calc(a,b,o):\n if o == \"+\":\n return str(int(a) + int(b))\n elif o == \"-\":\n return str(int(a) - int(b))\n elif o == \"/\":\n return str(int(a) // int(b))\n if o == \"*\":\n return str(int(a) * int(b))\n if o == \"^\":\n return str(int(a) ** int(b))\ndef resultado (lista2):\n pila = []\n po = []\n for elem in lista2:\n if elem.isdigit():\n apilar(pila,elem)\n else:\n b=desapilar(pila)\n a=desapilar(pila)\n apilar(pila,calc(a,b,elem))\n return cima(pila)\ndef solve(expresion):\n l=expresion.split\n print(l)\n pf= postfija(l)\n print (pf)\n return resultado(pf)\nprint(solve(expresion))","sub_path":"Pilas.py","file_name":"Pilas.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"496606754","text":"from pyTsetlinMachineParallel.tm import MultiClassConvolutionalTsetlinMachine2D\n\n\ndef init(os, _clauses, _t, _s, _window_x, _window_y, _shape_x, _shape_y, _shape_z, _name, _machine_type, _data_dim,\n _dataset, app_start_date, _epoch, _boost, _weighted, _epoch_results):\n epoch_count = 0\n for i in range(_epoch):\n _epoch_results.append([])\n\n print(\"Creating result file in.. \", \"Results/\" + _name + \"/\" + _machine_type + \"/\" + _data_dim\n + _dataset + \"/\" + str(_window_x) + \"x\" + str(_window_y) + \"/\"\n + _data_dim + _dataset + \"_\" + app_start_date + \".csv\", \"\\n\\n\")\n os.makedirs(os.path.dirname(\"Results/\" + _name + \"/\" + _machine_type + \"/\" + _data_dim + _dataset + \"/\"\n + str(_window_x) + \"x\" + str(_window_y) + \"/\" + _data_dim + _dataset + \"_\"\n + app_start_date + \".csv\"), exist_ok=True)\n _results = open(\"Results/\" + _name + \"/\" + _machine_type + \"/\" + _data_dim + _dataset + \"/\"\n + str(_window_x) + \"x\" + str(_window_y) + \"/\" + _data_dim + _dataset + \"_\"\n + app_start_date + \".csv\", 'a')\n _results.write(\"MultiClassConvolutionalTsetlinMachine2D,Parallel,\")\n\n while epoch_count < _epoch:\n _results.write(\"Epoch\" + str(epoch_count + 1) + \",\")\n epoch_count += 1\n _results.write(\"\\n\")\n\n _results.write(\"Settings:\\nClauses:,%.1f\\nThreshold:,%.1f\\ns:,%.1f\\nboost:,%s\\nWindow_X:,%.1f\\n\"\n \"Window_Y:,%.1f\\nShape_X:,%.1f\\nShape_Y:,%.1f\\nShape_Z:,%.1f\\n\"\n % (_clauses, _t, _s, _boost, _window_x, _window_y, _shape_x, _shape_y, _shape_z))\n\n _results.close()\n\n print(\"Settings:\", \"\\n\")\n print(\"Clauses:\", _clauses)\n print(\"Threshold:\", _t)\n print(\"s:\", _s)\n print(\"boost:\", _boost)\n print(\"weighted clauses:\", _weighted)\n print(\"Window X\", _window_x)\n print(\"Window Y\", _window_y)\n print(\"Shape X\", _shape_x)\n print(\"Shape Y\", _shape_y)\n print(\"Shape Z\", _shape_z)\n print(\"\\n\")\n\n return _epoch_results\n\n\ndef load_data(train_data, test_data, _shape_x, _shape_y, _shape_z, _window_x, _window_y, _clauses, _t, _s, _boost,\n _weighted, _data_dim, data_name, _dataset, _app_start_date, _name, _machine_type, _numb):\n x_train = train_data[:, 0:-1].reshape(train_data.shape[0], _shape_x, _shape_y, _shape_z)\n y_train = train_data[:, -1]\n x_test = test_data[:, 0:-1].reshape(test_data.shape[0], _shape_x, _shape_y, _shape_z)\n y_test = test_data[:, -1]\n\n machine = MultiClassConvolutionalTsetlinMachine2D(_clauses, _t, _s, (_window_x, _window_y),\n boost_true_positive_feedback=_boost,\n weighted_clauses=_weighted)\n print(\"-------------------------------------------------------------------------------------------\")\n print(\"MultiClassConvolutionalTsetlinMachine2D using %s, Draw, %s, written to file %s%s_%s.csv \"\n \"(%.1f x %.1f x %.1f)\"\"\\n\"\n % (_data_dim, _dataset, data_name, _dataset, _app_start_date,\n _shape_x, _shape_y, _shape_z))\n print(\"Settings: Clauses: %.1f Threshold: %.1f S: %.1f Window_X: %.1f Window_Y: %.1f\\n\" % (\n _clauses, _t, _s, _window_x, _window_y))\n\n _results = open(\"Results/\" + _name + \"/\" + _machine_type + \"/\" + _data_dim + _dataset + \"/\"\n + str(_window_x) + \"x\" + str(_window_y) + \"/\"\n + _data_dim + _dataset + \"_\" + _app_start_date + \".csv\", 'a')\n _results.write(_data_dim + _dataset + _numb + \",\")\n _results.close()\n\n return x_train, y_train, x_test, y_test, machine\n","sub_path":"Classifier/CTM.py","file_name":"CTM.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"177442854","text":"import os\nimport io\nimport json\nimport pickle\n\nimport copper\nimport pandas as pd\n\n\ndef load(filepath):\n ''' Loads a pickled dataset\n\n Returns\n -------\n copper.Dataset\n '''\n if len(filepath.split('.')) == 1:\n filepath = filepath + '.dataset'\n\n if filepath.endswith('.dataset'):\n f = os.path.join(copper.project.data, filepath)\n pkl_file = open(f, 'rb')\n return pickle.load(pkl_file)\n\ndef save(dataset, name):\n ''' Saves a picke Dataset\n '''\n f = os.path.join(copper.project.data, name + '.dataset')\n output = open(f, 'wb')\n pickle.dump(dataset, output)\n output.close()\n\ndef export(data, name, format='csv'):\n ''' Exports a Dataset/DataFrame into text formats: csv, json\n '''\n if type(data) is copper.Dataset:\n df = data.frame\n else:\n df = data\n\n if format == 'csv':\n fpath = os.path.join(copper.project.exported, name + '.csv')\n df.to_csv(fpath, encoding='utf-8')\n elif format == 'json':\n fpath = os.path.join(copper.project.exported, name + '.json')\n with io.open(fpath, 'w', encoding='utf-8') as outfile:\n json.dumps(df_to_json(df), outfile)\n\ndef read_csv(file_path, **args):\n ''' Reads a csv file into a pandas DataFrame\n\n Parameters\n ----------\n same as pandas.read_csv\n\n Returns\n -------\n pandas.DataFrame\n '''\n file_path = os.path.join(copper.project.data, file_path)\n return pd.read_csv(file_path, **args)\n\n\n","sub_path":"copper/io/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"544666398","text":"\nfrom __future__ import division\n\nimport numpy as np\nimport random\n\ndef clamp(x, low, high):\n\tif x < low:\n\t\tx = low\n\tif x > high:\n\t\tx = high\n\treturn x\n\ndef dist(loc1, loc2):\n\tx1, y1 = loc1\n\tx2, y2 = loc2\n\treturn ((x1 - x2)**2 + (y1 - y2)**2)**0.5\n\nclass StaticTarget:\n\t'''\n\t2D environment bounded by [xlow, xhigh] x [ylow, yhigh]\n\tthere is one agent and one target, spawning randomly in the environment\n\ttarget is not moving\n\taction is 2D continuous, dx and dy, that moves the the agent correspondingly\n\tdx and dy are bounded by 0.1 in magnitude\n\treward is negative distance from agent to target\n\tmaximum number of iterations is 50 by default\n\t'''\n\n\tdef __init__(self, xlow, xhigh, ylow, yhigh, max_iter=50):\n\t\tself.xlow = xlow\n\t\tself.xhigh = xhigh\n\t\tself.ylow = ylow\n\t\tself.yhigh = yhigh\n\t\tself.max_iter = max_iter\n\n\tdef s(self):\n\t\treturn np.array([self.x, self.y, self.xT, self.yT]).astype('float32')\t\n\n\tdef reset(self):\n\t\tself.iter = 0\n\t\tself.x = random.random() * (self.xhigh - self.xlow) + self.xlow\n\t\tself.y = random.random() * (self.yhigh - self.ylow) + self.ylow\n\t\tself.xT = random.random() * (self.xhigh - self.xlow) + self.xlow\n\t\tself.yT = random.random() * (self.yhigh - self.ylow) + self.ylow\n\t\treturn self.s()\n\n\tdef step(self, a):\n\t\tdx, dy = a\n\t\tdx = clamp(dx, -0.1, 0.1)\n\t\tdy = clamp(dy, -0.1, 0.1)\n\t\tself.x = clamp(self.x + dx, self.xlow, self.xhigh)\n\t\tself.y = clamp(self.y + dy, self.ylow, self.yhigh)\n\t\tself.iter += 1\n\t\tr = - dist([self.x, self.y], [self.xT, self.yT])\n\t\tif self.iter == self.max_iter:\n\t\t\tdone = True\n\t\telse:\n\t\t\tdone = False\n\t\treturn self.s(), r, done\n\nclass WaypointTarget:\n\t'''\n\t2D environment bounded by [xlow, xhigh] x [ylow, yhigh]\n\n\tthere is a target that moves on a waypoint trajectory\n\tthe number of waypoints defaults to 5\n\teach waypoint is chosen randomly\n\tthe target will spawn at the first waypoint, and move at constant speed of 0.05\n\ttoward each of waypoint consecutively\n\n\tthere are two agents, a speaker and a mover\n\tthe speaker agent is outside of the \"playing field\", \n\tand can sense the location of the target at each time step\n\tthe mover agent needs to chase down the target, but does not know its location\n\n\taction is 2D continuous, dx and dy, that moves the the agent correspondingly\n\tdx and dy are bounded by 0.1 in magnitude\n\n\treward is negative distance from the mover agent to target, and is shared by two agents\n\tmaximum number of iterations is 100 by default\n\t'''\n\n\tdef __init__(self, xlow, xhigh, ylow, yhigh, n_waypoints=5, max_iter=100, xyT_mapper=None):\n\t\tself.xlow = xlow\n\t\tself.xhigh = xhigh\n\t\tself.ylow = ylow\n\t\tself.yhigh = yhigh\n\t\tself.max_iter = max_iter\n\t\tself.n_waypoints = 5\n\t\tself.xyT_mapper = xyT_mapper\n\n\t# def s(self):\n\t# \treturn np.array([self.x, self.y, self.xT, self.yT]).astype('float32')\t\n\n\tdef segment(self):\n\t\tself.cur_dist = self.cur_dist % self.total_dist\n\t\tcum_dist = 0\n\t\tfor i, d in enumerate(self.dists):\n\t\t\tcum_dist += d\n\t\t\tif cum_dist > self.cur_dist:\n\t\t\t\treturn i, self.cur_dist - (cum_dist - d)\n\t\tassert False\n\n\tdef target_loc(self):\n\t\tseg, rem_dist = self.segment()\n\t\tseg_s = self.wpts[seg]\n\t\tseg_t = self.wpts[(seg+1) % len(self.wpts)]\n\t\tseg_len = np.linalg.norm(seg_s - seg_t)\n\t\tassert rem_dist <= seg_len\n\t\tu = rem_dist / seg_len\n\t\t# print seg, rem_dist, u\n\t\txs, ys = seg_s\n\t\txt, yt = seg_t\n\t\txT = xs + (xt - xs) * u\n\t\tyT = ys + (yt - ys) * u\n\t\treturn xT, yT\n\n\tdef reset(self):\n\t\tself.iter = 0\n\t\tself.x = random.random() * (self.xhigh - self.xlow) + self.xlow\n\t\tself.y = random.random() * (self.yhigh - self.ylow) + self.ylow\n\t\twaypoints_x = np.random.random((self.n_waypoints, 1)) * (self.xhigh - self.xlow) + self.xlow\n\t\twaypoints_y = np.random.random((self.n_waypoints, 1)) * (self.yhigh - self.ylow) + self.ylow\n\t\tself.wpts = np.hstack((waypoints_x, waypoints_y))\n\t\tself.dists = [np.linalg.norm(b-a) for a, b in zip(self.wpts[1:], self.wpts[:-1])]\n\t\tself.dists.append(np.linalg.norm(self.wpts[-1] - self.wpts[0]))\n\t\tself.total_dist = sum(self.dists)\n\t\tself.cur_dist = random.random() * self.total_dist\n\t\txT, yT = self.target_loc()\n\t\tif self.xyT_mapper is not None:\n\t\t\txT, yT = self.xyT_mapper(xT, yT)\n\t\treturn np.array([self.x, self.y, xT, yT]).astype('float32')\n\n\tdef step(self, a):\n\t\tdx, dy = a\n\t\tdx = clamp(dx, -0.1, 0.1)\n\t\tdy = clamp(dy, -0.1, 0.1)\n\t\tself.x = clamp(self.x + dx, self.xlow, self.xhigh)\n\t\tself.y = clamp(self.y + dy, self.ylow, self.yhigh)\n\t\tself.iter += 1\n\t\tself.cur_dist += 0.05\n\t\txT, yT = self.target_loc()\n\t\tr = - dist([self.x, self.y], [xT, yT])\n\t\tif self.iter == self.max_iter:\n\t\t\tdone = True\n\t\telse:\n\t\t\tdone = False\n\t\tif self.xyT_mapper is not None:\n\t\t\txT, yT = self.xyT_mapper(xT, yT)\n\t\treturn np.array([self.x, self.y, xT, yT]).astype('float32'), r, done\n\n\t### test and visualization below ###\n\t# env = WaypointTarget(-1, 1, -1, 1)\n\t# x, y, xT, yT = env.reset()\n\t# xTs = [xT]\n\t# yTs = [yT]\n\t# xs = [x]\n\t# ys = [y]\n\t# done = False\n\t# while not done:\n\t# \ts, r, done = env.step([0.04, 0.04])\n\t# \tx, y, xT, yT = s\n\t# \txTs.append(xT)\n\t# \tyTs.append(yT)\n\t# \txs.append(x)\n\t# \tys.append(y)\n\t# import matplotlib.pyplot as plt\n\t# plt.plot(xTs, yTs, '.-')\n\t# plt.plot(xs, ys, '.-')\n\t# plt.axis([-1, 1, -1, 1])\n\t# plt.show()\n\nclass DirectedNavigation:\n\t'''\n\t2D navigation task\n\tthere are m potential targets, but only one is the true target. \n\tthe state returns an m x 2 matrix representing target locations, and \n\ta single index specifying the desired target. \n\tthe reward is calculated as the negative distance to the desired target. \n\tthis environment can be cast into a multi-agent problem by having one agent \n\t(speaker) getting the index and the other (mover) getting the location matrix. \n\t'''\n\tdef __init__(self, xlow, xhigh, ylow, yhigh, n_targets, max_iter=50):\n\t\tself.xlow = xlow\n\t\tself.xhigh = xhigh\n\t\tself.ylow = ylow\n\t\tself.yhigh = yhigh\n\t\tself.m = n_targets\n\t\tself.max_iter = max_iter\n\n\tdef s(self):\n\t\treturn self.selected, self.locations.astype('float32'), np.array([self.x, self.y]).astype('float32')\n\n\tdef reset(self):\n\t\tself.iter = 0\n\t\tself.selected = random.choice(range(self.m))\n\t\tself.xlocs = np.random.random(self.m) * (self.xhigh - self.xlow) + self.xlow\n\t\tself.ylocs = np.random.random(self.m) * (self.yhigh - self.ylow) + self.ylow\n\t\tself.locations = np.vstack((self.xlocs, self.ylocs)).T\n\t\tself.x = random.random() * (self.xhigh - self.xlow) + self.xlow\n\t\tself.y = random.random() * (self.yhigh - self.ylow) + self.ylow\n\t\treturn self.s()\n\n\tdef step(self, a):\n\t\tdx, dy = a\n\t\tdx = clamp(dx, -0.1, 0.1)\n\t\tdy = clamp(dy, -0.1, 0.1)\n\t\tself.x = clamp(self.x + dx, self.xlow, self.xhigh)\n\t\tself.y = clamp(self.y + dy, self.ylow, self.yhigh)\n\t\ttarget_loc = self.locations[self.selected]\n\t\tr = - dist([self.x, self.y], target_loc)\n\t\tself.iter += 1\n\t\tdone = False\n\t\tif self.iter == self.max_iter:\n\t\t\tdone = True\n\t\treturn self.s(), r, done\n","sub_path":"envs.py","file_name":"envs.py","file_ext":"py","file_size_in_byte":6775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"331664825","text":"import numpy as np\nimport pandas as pd\nimport neurokit2 as nk\n\nimport scipy.signal\n\n# =============================================================================\n# Signal\n# =============================================================================\n\n\ndef test_signal_binarize():\n\n signal = np.cos(np.linspace(start=0, stop=20, num=1000))\n binary = nk.signal_binarize(signal)\n assert len(binary) == 1000\n\n binary = nk.signal_binarize(list(signal))\n assert len(binary) == 1000\n\n\n\n\ndef test_signal_resample():\n\n signal = np.cos(np.linspace(start=0, stop=20, num=50))\n\n downsampled_interpolation = nk.signal_resample(signal, method=\"interpolation\", sampling_rate=1000, desired_sampling_rate=500)\n downsampled_numpy = nk.signal_resample(signal, method=\"numpy\", sampling_rate=1000, desired_sampling_rate=500)\n downsampled_pandas = nk.signal_resample(signal, method=\"pandas\", sampling_rate=1000, desired_sampling_rate=500)\n downsampled_fft = nk.signal_resample(signal, method=\"FFT\", sampling_rate=1000, desired_sampling_rate=500)\n downsampled_poly = nk.signal_resample(signal, method=\"poly\", sampling_rate=1000, desired_sampling_rate=500)\n\n # Upsample\n upsampled_interpolation = nk.signal_resample(downsampled_interpolation, method=\"interpolation\", sampling_rate=500, desired_sampling_rate=1000)\n upsampled_numpy = nk.signal_resample(downsampled_numpy, method=\"numpy\", sampling_rate=500, desired_sampling_rate=1000)\n upsampled_pandas = nk.signal_resample(downsampled_pandas, method=\"pandas\", sampling_rate=500, desired_sampling_rate=1000)\n upsampled_fft = nk.signal_resample(downsampled_fft, method=\"FFT\", sampling_rate=500, desired_sampling_rate=1000)\n upsampled_poly = nk.signal_resample(downsampled_poly, method=\"poly\", sampling_rate=500, desired_sampling_rate=1000)\n\n # Check\n rez = pd.DataFrame({\"Interpolation\": upsampled_interpolation - signal,\n \"Numpy\": upsampled_numpy - signal,\n \"Pandas\": upsampled_pandas - signal,\n \"FFT\": upsampled_fft - signal,\n \"Poly\": upsampled_poly - signal})\n assert np.allclose(np.mean(rez.mean()), 0.0001, atol=0.0001)\n\n\n\ndef test_signal_detrend():\n signal = np.cos(np.linspace(start=0, stop=10, num=1000)) # Low freq\n signal += np.cos(np.linspace(start=0, stop=100, num=1000)) # High freq\n signal += 3 # Add baseline\n\n rez_nk = nk.signal_detrend(signal, order=1)\n rez_scipy = scipy.signal.detrend(signal, type=\"linear\")\n assert np.allclose(np.mean(rez_nk - rez_scipy), 0, atol=0.000001)\n\n rez_nk = nk.signal_detrend(signal, order=0)\n rez_scipy = scipy.signal.detrend(signal, type=\"constant\")\n assert np.allclose(np.mean(rez_nk - rez_scipy), 0, atol=0.000001)\n\n\n\n\n\ndef test_signal_filter():\n\n signal = np.cos(np.linspace(start=0, stop=10, num=1000)) # Low freq\n signal += np.cos(np.linspace(start=0, stop=100, num=1000)) # High freq\n filtered = nk.signal_filter(signal, highcut=10)\n assert np.std(signal) > np.std(filtered)\n\n\n\ndef test_signal_interpolate():\n\n x_axis = np.linspace(start=10, stop=30, num=10)\n signal = np.cos(x_axis)\n\n interpolated = nk.signal_interpolate(signal, desired_length=1000)\n assert len(interpolated) == 1000\n\n new_x = np.linspace(start=0, stop=40, num=1000)\n interpolated = nk.signal_interpolate(signal,\n desired_length=1000,\n x_axis=x_axis,\n new_x=new_x)\n assert len(interpolated) == 1000\n assert interpolated[0] == signal[0]\n\n\ndef test_signal_findpeaks():\n\n signal1 = np.cos(np.linspace(start=0, stop=30, num=1000))\n peaks1, info1 = nk.signal_findpeaks(signal1)\n\n signal2 = np.concatenate([np.arange(0, 20, 0.1), np.arange(17, 30, 0.1), np.arange(30, 10, -0.1)])\n peaks2, info2 = nk.signal_findpeaks(signal2)\n assert len(peaks1) > len(peaks2)\n\n\ndef test_signal_merge():\n\n signal1 = np.cos(np.linspace(start=0, stop=10, num=100))\n signal2 = np.cos(np.linspace(start=0, stop=20, num=100))\n\n signal = nk.signal_merge(signal1, signal2, time1=[0, 10], time2=[-5, 5])\n assert len(signal) == 150\n assert signal[0] == signal2[0] + signal2[0]\n\n","sub_path":"tests/tests_signal.py","file_name":"tests_signal.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"409055002","text":"import time\nfrom ..基础接口 import 时间 as 北向时间\nfrom ..命令行接口 import 时间 as 南向时间\nfrom ..命令行接口 import 模式\nfrom ..命令行接口 import 命令\nclass C时间(模式.C同级模式, 南向时间.I时间配置):\n\tdef __init__(self, a):\n\t\t南向时间.I时间配置.__init__(self, a)\n\tdef fs日期时间(self, a日期时间):\n\t\tv时间 = 北向时间.f解析日期时间(a日期时间)\n\t\tv命令 = 命令.C命令(\"clock datetime\")\n\t\tv命令 += time.strftime(\"%H:%M:%S %Y-%m-%d\", v时间)\n\t\tself.m设备.f执行命令(v命令)\n\tdef fs时区(self, a时区):\n\t\tv时区 = 北向时间.f解析时区(a时区)\n\t\tv时区名, v符号, v时, v分 = 北向时间.f拆分时区(v时区)\n\t\tv命令 = 命令.C命令(\"clock timezone\")\n\t\tv命令 += v时区名\n\t\tv命令 += \"add\" if v符号 else \"minus\"\n\t\tv命令 += v时\n\t\tif v分:\n\t\t\tv命令 -= f\":{v分}\"\n\t\tself.m设备.f执行命令(v命令)","sub_path":"网络设备脚本/华为命令行/时间.py","file_name":"时间.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"306343038","text":"\"\"\"\nThis file defines any arbitrary global variables used in Materials Project\ndatabase building and in the website code, to ensure consistency between\ndifferent modules and packages.\n\"\"\"\nimport json\nimport requests\nfrom pydantic import BaseSettings, Field, root_validator\nfrom pydantic.types import Path\n\nDEFAULT_CONFIG_FILE_PATH = str(Path.home().joinpath(\".emmet.json\"))\n\n\nclass EmmetSettings(BaseSettings):\n \"\"\"\n Settings for the emmet- packages\n The default way to modify these is to modify ~/.emmet.json or set the environment variable\n EMMET_CONFIG_FILE to point to the json with emmet settings\n \"\"\"\n\n config_file: str = Field(\n DEFAULT_CONFIG_FILE_PATH, description=\"File to load alternative defaults from\"\n )\n\n LTOL: float = Field(\n 0.2, description=\"Fractional length tolerance for structure matching\"\n )\n STOL: float = Field(\n 0.3,\n description=\"Site tolerance for structure matching. Defined as the fraction of the\"\n \" average free length per atom = ( V / Nsites ) ** (1/3)\",\n )\n SYMPREC: float = Field(\n 0.1, description=\"Symmetry precision for spglib symmetry finding\"\n )\n ANGLE_TOL: float = Field(\n 5, description=\"Angle tolerance for structure matching in degrees.\"\n )\n\n class Config:\n env_prefix = \"emmet_\"\n extra = \"ignore\"\n\n @root_validator(pre=True)\n def load_default_settings(cls, values):\n \"\"\"\n Loads settings from a root file if available and uses that as defaults in\n place of built in defaults\n \"\"\"\n config_file_path: str = values.get(\"config_file\", DEFAULT_CONFIG_FILE_PATH)\n\n new_values = {}\n\n if config_file_path.startswith(\"http\"):\n new_values = requests.get(config_file_path).json()\n elif Path(config_file_path).exists():\n with open(config_file_path) as f:\n new_values = json.load(f)\n\n new_values.update(values)\n\n return new_values\n","sub_path":"emmet-core/emmet/core/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"246641330","text":"\n#https://yiyibooks.cn/xx/python_352/library/http.server.html\n#https://yiyibooks.cn/xx/python_352/library/socketserver.html#socketserver.TCPServer\n\nfrom http.server import HTTPServer,BaseHTTPRequestHandler,SimpleHTTPRequestHandler\n\nfrom http.client import HTTPResponse\nimport mimetypes\nimport os\n\nMEDIA_ROOT = \"/home/liulonghua/service\"\n\n\nclass HttpRequest(object):\n pass\n\n\nclass Handler(BaseHTTPRequestHandler):\n \"\"\"def handle(self):\n print(self.request[0])\n 调用handle_one_request()一次(如果启用持久连接,则多次)以处理传入的HTTP请求。你应该永远不需要覆盖它;而是实现适当的do_*()方法。\n \"\"\"\n def do_GET(self):\n #简单的静态服务器\n path = self.path\n self.send_response(200)\n mime = mimetypes.read_mime_types(path)\n self.send_header(\"Content-type\", mime)\n self.end_headers()\n\n dir_path = os.path.join(MEDIA_ROOT,path.strip(\"/\"))\n if os.path.isdir(dir_path):\n html = '' \\\n '' \\\n '' \\\n '' \\\n '' \\\n '%(dir_path)s' \\\n '%(detail)s' \\\n '' \\\n ''\n file_list = os.listdir(dir_path)\n p = [' %s
'%(path + '/' + one, one) for one in file_list]\n print('===',path)\n p = ''.join(p)\n html = html%{'dir_path': dir_path, 'detail': p}\n self.wfile.write(html.encode('utf-8'))\n else:\n try:\n with open(dir_path, \"rb\") as f:\n\n self.wfile.write(f.read())\n except:\n with open(\"404.html\",\"rb\") as f:\n\n self.wfile.write(f.read())\n\n def do_POST(self):\n l = self.headers.get(\"content-length\")\n\n print(self.rfile.read(int(l)))\n\n\nif __name__ == \"__main__\":\n port = 8080\n host = \"0.0.0.0\"\n server = HTTPServer((host,port),Handler)\n server.serve_forever()\n","sub_path":"http_server_test.py","file_name":"http_server_test.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"516881274","text":"######################################################################\n#\n# File: b2/parse_args.py\n#\n# Copyright 2018 Backblaze Inc. All Rights Reserved.\n#\n# License https://www.backblaze.com/using_b2_code.html\n#\n######################################################################\n\nimport logging\n\nimport six\n\nfrom .utils import repr_dict_deterministically\n\nlogger = logging.getLogger(__name__)\n\n\nclass Arguments(object):\n \"\"\"\n An object to stick attributes on.\n \"\"\"\n\n def __repr__(self):\n return '%s(%s)' % (\n self.__class__.__name__,\n repr_dict_deterministically(self.__dict__),\n )\n\n\ndef check_for_duplicate_args(args_dict):\n \"\"\"\n Checks that no argument name is listed in multiple places.\n\n Raises a ValueError if there is a problem.\n\n This args_dict has a problem because 'required' and 'optional'\n both contain 'a':\n\n {\n 'option_args': ['b', 'c'],\n 'required': ['a', 'd']\n 'optional': ['a', 'e']\n }\n \"\"\"\n categories = sorted(six.iterkeys(args_dict))\n for index_a, category_a in enumerate(categories):\n for category_b in categories[index_a + 1:]:\n names_a = args_dict[category_a]\n names_b = args_dict[category_b]\n for common_name in set(names_a) & set(names_b):\n raise ValueError(\n \"argument '%s' is in both '%s' an '%s'\" % (common_name, category_a, category_b)\n )\n\n\ndef parse_arg_list(\n arg_list, option_flags, option_args, list_args, optional_before, required, optional, arg_parser\n):\n \"\"\"\n Converts a list of string arguments to an Arguments object, with\n one attribute per parameter.\n\n The value of every parameter is set in the returned Arguments object,\n even for parameters not specified on the command line.\n\n Option Flags set boolean values that default to False. When the\n option is present on the command line, the value is set to True.\n\n Option Args have values provided on the command line. The default\n if not present is None.\n\n List Args act like Option Args, but can be specified more than\n once, and their values are collected into a list. Default is [].\n\n Required positional parameters must be present, and do not have\n a double-dash name preceding them.\n\n Optional positional parameters are just like required parameters,\n but don't have to be there and default to None.\n\n Arg Parser is a dict that maps from a parameter name to a function\n tha converts the string argument into the value needed by the\n program. These parameters can be Option Args, List Args, Required,\n or Optional.\n\n :param arg_list sys.argv[1:], or equivalent\n :param option_flags: Names of options that are boolean flags.\n :param option_args: Names of options that have values.\n :param list_args: Names of options whose values are collected into a list.\n :param optional_before: Names of option positional params that come before the required ones.\n :param required: Names of positional params that must be there.\n :param optional: Names of optional params.\n :param arg_parser: Map from param name to parser for values.\n :return: An Argument object, or None if there was any error parsing.\n \"\"\"\n\n # Sanity check the inputs.\n check_for_duplicate_args(\n {\n 'option_flags': option_flags,\n 'option_args': option_args,\n 'optional_before': optional_before,\n 'required': required,\n 'optional': optional\n }\n )\n\n # Create an object to hold the arguments.\n result = Arguments()\n\n # Set the default value for everything that has a default value.\n for name in option_flags:\n setattr(result, name, False)\n for name in option_args:\n setattr(result, name, None)\n for name in list_args:\n setattr(result, name, [])\n for name in optional:\n setattr(result, name, None)\n\n # Make a function for parsing argument values\n def parse_arg(name, arg_list):\n value = arg_list.pop(0)\n if name in arg_parser:\n value = arg_parser[name](value)\n return value\n\n # Parse the '--' options\n while len(arg_list) != 0 and arg_list[0].startswith('--'):\n option = arg_list.pop(0)[2:]\n if option in option_flags:\n logger.debug('option %s is properly recognized as OPTION_FLAGS', option)\n setattr(result, option, True)\n elif option in option_args:\n if len(arg_list) == 0:\n logger.debug(\n 'option %s is recognized as OPTION_ARGS and there are no more arguments on arg_list to parse',\n option\n )\n return None\n else:\n logger.debug('option %s is properly recognized as OPTION_ARGS', option)\n setattr(result, option, parse_arg(option, arg_list))\n elif option in list_args:\n if len(arg_list) == 0:\n logger.debug(\n 'option %s is recognized as LIST_ARGS and there are no more arguments on arg_list to parse',\n option\n )\n return None\n else:\n logger.debug('option %s is properly recognized as LIST_ARGS', option)\n getattr(result, option).append(parse_arg(option, arg_list))\n else:\n logger.error('option %s is of unknown type!', option)\n return None\n\n # Handle optional positional parameters that come first.\n # We assume that if there are optional parameters, the\n # ones that come before take precedence over the ones\n # that come after the required arguments.\n for arg_name in optional_before:\n if len(required) < len(arg_list):\n setattr(result, arg_name, parse_arg(arg_name, arg_list))\n else:\n setattr(result, arg_name, None)\n\n # Parse the positional parameters\n for arg_name in required:\n if len(arg_list) == 0:\n logger.debug('lack of required positional argument: %s', arg_name)\n return None\n setattr(result, arg_name, parse_arg(arg_name, arg_list))\n for arg_name in optional:\n if len(arg_list) != 0:\n setattr(result, arg_name, parse_arg(arg_name, arg_list))\n\n # Anything left is a problem\n if len(arg_list) != 0:\n logger.debug('option parser failed to consume this: %s', arg_list)\n return None\n\n # Return the Arguments object\n return result\n","sub_path":"b2/parse_args.py","file_name":"parse_args.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"476667282","text":"import time\r\nfrom pathlib import Path\r\n\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport scipy\r\nimport scipy.fftpack\r\nimport scipy.ndimage\r\n\r\n\r\ndef smooth_fourier(\r\n y, min_value=None, max_value=None, min_balance=None, max_balance=None\r\n):\r\n w = scipy.fftpack.rfft(y)\r\n spectrum = w ** 2\r\n\r\n cutoff_idx = np.full(spectrum.shape, False)\r\n\r\n if min_value is not None:\r\n cutoff_idx = np.logical_or(cutoff_idx, spectrum > min_value)\r\n if max_value is not None:\r\n cutoff_idx = np.logical_or(cutoff_idx, spectrum < max_value)\r\n if min_balance is not None:\r\n cutoff_idx = np.logical_or(\r\n cutoff_idx, spectrum > (spectrum.max() / min_balance)\r\n )\r\n if max_balance is not None:\r\n cutoff_idx = np.logical_or(\r\n cutoff_idx, spectrum < (spectrum.max() / max_balance)\r\n )\r\n\r\n w2 = w.copy()\r\n w2[cutoff_idx] = 0\r\n\r\n return scipy.fftpack.irfft(w2)\r\n\r\n\r\n# Simple Moving Average (SMA):\r\n# Source: https://docs.python.org/3/library/collections.html#deque-recipes\r\ndef moving_average(iterable, size=3):\r\n # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0\r\n # http://en.wikipedia.org/wiki/Moving_average\r\n from collections import deque\r\n from itertools import islice\r\n\r\n it = iter(iterable)\r\n d = deque(islice(it, size - 1))\r\n d.appendleft(0)\r\n s = sum(d)\r\n for elem in it:\r\n s += elem - d.popleft()\r\n d.append(elem)\r\n yield s / size\r\n\r\n\r\ndef smooth_moving_average(y, size=3, mode='symmetric'):\r\n return np.array(moving_average(np.pad(y, size // 2, mode=mode), size=size))\r\n\r\n\r\ndef smooth_mean(y, size=3, **kwargs):\r\n kernel = np.full((size, *y.shape[1:]), 1.0) / size\r\n return np.array(scipy.ndimage.filters.convolve(y, kernel, **kwargs))\r\n\r\n\r\nfilename = (\r\n Path('.')\r\n / 'experiments'\r\n / 'Experiment Output 20-01-2020'\r\n / 'Experiment 0 -- 17-00.csv'\r\n)\r\n\r\nfor chunk in pd.read_csv(filename, delimiter=',', chunksize=10000):\r\n fig, ax = plt.subplots()\r\n\r\n plt.plot(\r\n chunk['Elapsed time'],\r\n chunk['Bulk Temperature'],\r\n '.',\r\n label='Bulk Temperature',\r\n )\r\n plt.plot(\r\n chunk['Elapsed time'],\r\n chunk['Wire Temperature'],\r\n '.',\r\n label='Wire Temperature',\r\n )\r\n plt.grid(True)\r\n\r\n formatter = matplotlib.ticker.FuncFormatter(\r\n lambda x, pos: time.strftime('%M:%S', time.gmtime(x))\r\n )\r\n ax.xaxis.set_major_formatter(formatter)\r\n\r\n # plt.plot(chunk['Elapsed time'], smooth_fourier(chunk['Wire Temperature'], max_balance=10000), '-', label='FFT-Filtered Wire Temperature')\r\n size = 9\r\n plt.plot(\r\n chunk['Elapsed time'],\r\n smooth_mean(chunk['Wire Temperature'], size),\r\n '-',\r\n label=f'{size}-Mean-Filtered Wire Temperature',\r\n )\r\n\r\n plt.legend()\r\n plt.xlabel('Elapsed time [min:s]')\r\n plt.ylabel('Temperature [°C]')\r\n plt.savefig('images/foo.png')\r\n break\r\ndata = chunk\r\nprint(data)\r\n\r\nplt.plot(data['Elapsed time'], data['Wire Temperature'], 'r,')\r\nplt.grid(True)\r\nplt.title('Signal-Diagram')\r\nplt.xlabel('Sample')\r\nplt.ylabel('In-Phase')\r\nplt.savefig('foo2.png')\r\n","sub_path":"archive/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"175794303","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/10/27 17:05\n# @Author : 饭盆里\n# @File : test_add_contact_bybasepage.py\n# @Software: PyCharm\n# @desc :\n\nimport os\n\nFILE_PATH = \"/Users/a/Documents/2020study/all_study_practice/base/demo.txt\"\n\nif os.path.exists(FILE_PATH):\n with open(FILE_PATH, encoding=\"utf-8\", mode=\"w+\") as FILE_HANDLER:\n for i in range(50000,60000):\n s = 'fanfantest_10N_50_'+str(i)+'\\n'\n FILE_HANDLER.write(s)\n\n\n","sub_path":"base/test_write_file.py","file_name":"test_write_file.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"513731799","text":"#!/bin/python\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import defaultdict, Counter\n\n\n# Complete the freqQuery function below.\ndef freqQuery(queries):\n result = []\n curr_dict = defaultdict(int)\n count = Counter()\n for idx, val in queries:\n if idx == 1:\n # Insert entry in dict\n count[curr_dict[val]] -= 1\n curr_dict[val] += 1\n count[curr_dict[val]] += 1\n\n elif idx == 2:\n count[curr_dict[val]] -= 1\n curr_dict[val] -= 1 if curr_dict[val] > 0 else 0\n count[curr_dict[val]] += 1\n\n else:\n result.append(1) if count[val] else result.append(0)\n\n return result\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n q = int(raw_input().strip())\n\n queries = []\n\n for _ in xrange(q):\n queries.append(map(int, raw_input().rstrip().split()))\n\n ans = freqQuery(queries)\n\n fptr.write('\\n'.join(map(str, ans)))\n fptr.write('\\n')\n\n fptr.close()\n","sub_path":"Questions/Maps/Frequencies_queries.py","file_name":"Frequencies_queries.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"38125554","text":"from decimal import Decimal, getcontext\n\nfrom vector import Vector\n\ngetcontext().prec = 30\n\n\nclass Hyperplane(object):\n\n NO_NONZERO_ELTS_FOUND_MSG = 'No nonzero elements found'\n EITHER_DIM_OR_NORMAL_VEC_MUST_BE_PROVIDE_MSG = 'Either the dimension or the normal vector must be provided'\n\n def __init__(self, dimension=None, normal_vector=None, constant_term=None):\n if not dimension and not normal_vector:\n raise Exception(self.EITHER_DIM_OR_NORMAL_VEC_MUST_BE_PROVIDE_MSG)\n elif not normal_vector:\n self.dimension = dimension\n all_zeros = [0] * self.dimension\n normal_vector = Vector(all_zeros)\n else:\n self.dimension = normal_vector.dimension\n self.normal_vector = normal_vector\n\n if not constant_term:\n constant_term = 0\n self.constant_term = Decimal(constant_term)\n\n self.set_basepoint()\n\n def set_basepoint(self):\n try:\n n = self.normal_vector.coordinates\n c = self.constant_term\n basepoint_coords = [0] * self.dimension\n\n initial_index = self.first_nonzero_index(n)\n initial_coefficient = n[initial_index]\n\n basepoint_coords[initial_index] = Decimal(c) / initial_coefficient\n self.basepoint = Vector(basepoint_coords)\n\n except Exception as e:\n if str(e) == self.NO_NONZERO_ELTS_FOUND_MSG:\n self.basepoint = None\n else:\n raise e\n\n def __str__(self):\n\n num_decimal_places = 3\n\n def write_coefficient(coefficient, is_initial_term=False):\n coefficient = round(coefficient, num_decimal_places)\n if coefficient % 1 == 0:\n coefficient = int(coefficient)\n\n output = ''\n\n if coefficient < 0:\n output += '-'\n if coefficient > 0 and not is_initial_term:\n output += '+'\n\n if not is_initial_term:\n output += ' '\n\n if abs(coefficient) != 1:\n output += '{}'.format(abs(coefficient))\n\n return output\n\n n = self.normal_vector.coordinates\n\n try:\n initial_index = self.first_nonzero_index(n)\n terms = [write_coefficient(n[i], is_initial_term=(i == initial_index)) + 'x_{}'.format(i + 1)\n for i in range(self.dimension) if round(n[i], num_decimal_places) != 0]\n output = ' '.join(terms)\n\n except Exception as e:\n if str(e) == self.NO_NONZERO_ELTS_FOUND_MSG:\n output = '0'\n else:\n raise e\n\n constant = round(self.constant_term, num_decimal_places)\n if constant % 1 == 0:\n constant = int(constant)\n output += ' = {}'.format(constant)\n\n return output\n\n @staticmethod\n def first_nonzero_index(iterable):\n for k, item in enumerate(iterable):\n if not MyDecimal(item).is_near_zero():\n return k\n raise Exception(Hyperplane.NO_NONZERO_ELTS_FOUND_MSG)\n\n def is_paralle_to(self, p):\n return self.normal_vector.is_parallel_to(p.normal_vector)\n\n def __eq__(self, p):\n if not self.is_paralle_to(p):\n return False\n elif self.basepoint == None and p.basepoint == None and self.constant_term == p.constant_term:\n return True\n else:\n base_vector = self.basepoint - p.basepoint\n return base_vector.is_orthogonal_to(self.normal_vector)\n\n\nclass MyDecimal(Decimal):\n\n def is_near_zero(self, eps=1e-30):\n return abs(self) < eps\n\nif __name__ == '__main__':\n p1 = Hyperplane(Vector([-7.926, 8.625, -7.212]), -7.952)\n p2 = Hyperplane(Vector([-2.642, 2.875, -2.404]), -2.443)\n print(p2 == p1)\n print(p1.is_paralle_to(p2))\n","sub_path":"hyperplane.py","file_name":"hyperplane.py","file_ext":"py","file_size_in_byte":3841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"286555480","text":"def stdDevOfLengths(L):\n if len(L) == 0:\n return 'NaN'\n totLength = 0.0\n quanity = 0.0\n for l in L:\n totLength += len(l)\n mean = float(totLength / len(L))\n for l in L:\n quanity += (len(l) - mean)**2\n return (quanity / len(L))**.5, mean\n\ndef stdDev(L):\n mean = float(sum(L) / len(L))\n quanity = 0.0\n \n for n in L:\n quanity += (n - mean)**2\n return (quanity / len(L))**.5, mean\n \n \ndef coeffVar(L):\n stDev, mean = stdDev(L)\n \n return stDev/mean","sub_path":"python/mit/6.00.2/ps2/lecture4.py","file_name":"lecture4.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"24003956","text":"#!/usr/bin/python\r\nfrom configparser import ConfigParser\r\nimport psycopg2\r\nimport requests\r\nimport json\r\n\r\nconn = None\r\n\r\n\r\ndef config(filename='database.ini', section='postgresql'):\r\n # create a parser\r\n parser = ConfigParser()\r\n # read config file\r\n parser.read(filename)\r\n\r\n # get section, default to postgresql\r\n db = {}\r\n if parser.has_section(section):\r\n params = parser.items(section)\r\n for param in params:\r\n db[param[0]] = param[1]\r\n else:\r\n raise Exception(\r\n 'Section {0} not found in the {1} file'.format(section, filename))\r\n\r\n return db\r\n\r\n\r\ndef connect():\r\n global conn\r\n \"\"\" Connect to the PostgreSQL database server \"\"\"\r\n # conn = None\r\n try:\r\n # read connection parameters\r\n params = config()\r\n\r\n # connect to the PostgreSQL server\r\n print('Connecting to the PostgreSQL database...')\r\n conn = psycopg2.connect(**params)\r\n # create a cursor\r\n # cur = conn.cursor()\r\n\r\n # execute a statement\r\n # print('PostgreSQL database version:')\r\n # cur.execute('SELECT version()')\r\n\r\n # display the PostgreSQL database server version\r\n # db_version = cur.fetchone()\r\n # print(db_version)\r\n\r\n # close the communication with the PostgreSQL\r\n # cur.close()\r\n except (Exception, psycopg2.DatabaseError) as error:\r\n print(error)\r\n finally:\r\n if conn is not None:\r\n pass\r\n # conn.close()\r\n # print('Database connection closed.')\r\n\r\n\r\ndef raise_complain(against_user_id, details, created_by, parking_lot_id=None, parking_space_id=None):\r\n global conn\r\n \"\"\" insert a new vendor into the vendors table \"\"\"\r\n sql = \"\"\"INSERT INTO public.parking_complain(\r\n\tagainst_user_id, parking_lot_id, parking_space_id, details, created_by)\r\n\tVALUES ( %s, %s, %s, %s, %s)\r\n returning id\"\"\"\r\n # conn = None\r\n if conn is None:\r\n # read database configuration\r\n params = config()\r\n # connect to the PostgreSQL database\r\n conn = psycopg2.connect(**params)\r\n\r\n insert_id = None\r\n try:\r\n # create a new cursor\r\n cur = conn.cursor()\r\n # execute the INSERT statement\r\n cur.execute(sql, (against_user_id, parking_lot_id,\r\n parking_space_id, details, created_by))\r\n # get the generated id back\r\n insert_id = cur.fetchone()[0]\r\n # commit the changes to the database\r\n conn.commit()\r\n # close communication with the database\r\n cur.close()\r\n\r\n send_push_noti(against_user_id)\r\n\r\n except (Exception, psycopg2.DatabaseError) as error:\r\n print(\"error\", error)\r\n return error\r\n finally:\r\n pass\r\n # if conn is not None:\r\n # conn.close()\r\n\r\n return insert_id\r\n\r\n\r\ndef send_push_noti(user_id):\r\n global conn\r\n sql = \"\"\"SELECT noti_token FROM public.\"user\" where id=%s\"\"\"\r\n if conn is None:\r\n conn = connect()\r\n\r\n insert_id = None\r\n try:\r\n # create a new cursor\r\n cur = conn.cursor()\r\n # execute the INSERT statement\r\n cur.execute(sql, (user_id,))\r\n # get the generated id back\r\n rows = cur.fetchall()\r\n print(\"The number of parts: \", cur.rowcount)\r\n\r\n token = None\r\n for row in rows:\r\n print(row[0])\r\n token = row[0]\r\n if token is not None:\r\n request_fire_base(token)\r\n cur.close()\r\n # commit the changes to the database\r\n conn.commit()\r\n # close communication with the database\r\n # except (Exception, psycopg2.DatabaseError) as error:\r\n except (psycopg2.DatabaseError) as error:\r\n print(\"error\", error)\r\n return error\r\n finally:\r\n pass\r\n # if conn is not None:\r\n # conn.close()\r\n\r\n return insert_id\r\n\r\n\r\ndef save_register_noti(user_id, token):\r\n global conn\r\n sql = \"\"\"UPDATE public.\"user\"\r\n\tSET noti_token=%s\r\n\tWHERE firebase_id=%s\r\n returning id\"\"\"\r\n if conn is None:\r\n connect()\r\n\r\n insert_id = None\r\n try:\r\n # create a new cursor\r\n cur = conn.cursor()\r\n # execute the INSERT statement\r\n cur.execute(sql, (token, user_id))\r\n # get the generated id back\r\n insert_id = cur.fetchone()[0]\r\n # commit the changes to the database\r\n conn.commit()\r\n # close communication with the database\r\n cur.close()\r\n except (Exception, psycopg2.DatabaseError) as error:\r\n print(\"error\", error)\r\n return error\r\n finally:\r\n pass\r\n # if conn is not None:\r\n # conn.close()\r\n\r\n return insert_id\r\n\r\ndef request_fire_base(token):\r\n url = \"https://fcm.googleapis.com/fcm/send\"\r\n payload = json.dumps({\r\n \"notification\": {\r\n \"title\": \"Parkign Issue\",\r\n \"body\": \"It's seems your car is double parked, kindly park properly\",\r\n \"click_action\": \"http://localhost:4200/defaultLayout/scanCar\"\r\n },\r\n \"to\": token\r\n })\r\n headers = {\r\n 'Authorization': \"key=AAAAWe_xG2k:APA91bGK8imO-seV6g8vB6kiUNqsffRs7M-3u68k_ViCp8CLL5Ko0tKCOfHuZUFTBOMkaaW4opX8G1w6j1STvP1G1KqEMGy9J-3sr9RFO3ZQCEJRy65ycva2p7XmSb-rFT_iY3SAGPSR\",\r\n 'Content-Type': \"application/json\",\r\n 'cache-control': \"no-cache\"\r\n }\r\n\r\n response = requests.request(\"POST\", url, data=payload, headers=headers)\r\n print(response.text)\r\n if response.status_code != 200:\r\n return False\r\n return True\r\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":5575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"458842820","text":"from collections import deque\n\nDEFAULT_SERIALIZED_TREE = [1,2,3,4,None]\n\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Tree(object):\n def __init__(self):\n self.root = None\n\ndef init_tree(serialized_tree=DEFAULT_SERIALIZED_TREE):\n tree = Tree()\n nodes = deque([TreeNode(val), None][val is None] for val in serialized_tree)\n q = deque([nodes.popleft()])\n tree.root = q[0]\n while q:\n cur = q.popleft()\n cur.left = nodes.popleft() if nodes else None\n cur.right = nodes.popleft() if nodes else None\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n\n return tree.root\n\ninit_tree()\n","sub_path":"src/util/tree_questions.py","file_name":"tree_questions.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"474503784","text":"\n# coding: utf-8\n\n# [Sberbank Russian Housing Market](https://www.kaggle.com/c/sberbank-russian-housing-market)\n\n# In[ ]:\n\nfrom ds_utils.imports import *\n\n\n# In[14]:\n\nfrom secrets import KAGGLE_USER, KAGGLE_PW\n\n\n# In[3]:\n\ncompetition_name = 'sberbank-russian-housing-market'\n\n\n# In[15]:\n\nmodel_description = 'xgb_naive'\n\n\n# In[16]:\n\ntrain = pd.read_csv('data/train.csv', parse_dates=['timestamp'])\ntest = pd.read_csv('data/test.csv', parse_dates=['timestamp'])\nmacro = pd.read_csv('data/macro.csv', parse_dates=['timestamp'])\n\n\n# In[17]:\n\ny_train = train.price_doc.values\n\n\n# In[18]:\n\ntrain.dtypes\n\n\n# In[ ]:\n\ndf_submit = pd.DataFrame({'id': id_test, 'price_doc': y_pred})\n\n\n# In[ ]:\n\nsubmit_file = 'results/submit_%s.csv' % model_description\ndf_submit.to_csv(submit_file, index=False)\n\n\n# In[ ]:\n\nget_ipython().system('kg config -g -u $KAGGLE_USER -p $KAGGLE_PW -c $competition_name')\nget_ipython().system('kg submit $submit_file -u $KAGGLE_USER -p $KAGGLE_PW -m $model_description')\n\n","sub_path":"sberbank-russian-housing-market/model_v0.py","file_name":"model_v0.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"215423144","text":"import sys\nsys.stdin = open('4837.txt', 'r')\n\nT = int(input())\nfor tc in range(1, T+1):\n N, K = map(int, input().split())\n #print(tc, N, K)\n\n A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n Al = len(A)\n final_list = []\n count = 0\n for i in range(1< None:\n self.parent.con.commit()\n self.parent.init_data_base()\n self.parent.show()\n super().closeEvent(a0)\n\n\nclass Main(QMainWindow, Ui_MainWindow):\n def __init__(self):\n self.con = sqlite3.connect(\"../data/coffee.sqlite\")\n self.child = None\n self.headers = None\n super().__init__()\n self.setupUi(self)\n # uic.loadUi(\"../UI/main_ui.ui\", self)\n self.initUI()\n self.init_data_base()\n\n def initUI(self):\n self.setWindowTitle(\"CoffeeBook\")\n self.add_action.triggered.connect(self.add_unit)\n self.tableWidget.cellDoubleClicked.connect(self.change_unit)\n\n def init_data_base(self):\n cur = self.con.cursor()\n result = cur.execute(\"\"\"SELECT * FROM coffee\"\"\").fetchall()\n self.headers = [x for x, *_ in cur.description]\n self.tableWidget.setColumnCount(len(self.headers))\n self.tableWidget.setHorizontalHeaderLabels(self.headers)\n self.tableWidget.setRowCount(len(result))\n for i, row in enumerate(result):\n for j, elem in enumerate(row):\n self.tableWidget.setItem(i, j, QTableWidgetItem(str(elem)))\n self.tableWidget.resizeColumnsToContents()\n\n def add_unit(self):\n self.hide()\n self.child = AddEditCoffeeForm(parent=self)\n self.child.show()\n\n def change_unit(self, row):\n unit_id = self.tableWidget.item(row, 0).text()\n self.hide()\n self.child = AddEditCoffeeForm(unit_id=unit_id, unit_row=row, parent=self)\n self.child.show()\n\n def delete_unit(self, unit_id):\n cur = self.con.cursor()\n cur.execute(f\"\"\"DELETE FROM coffee WHERE ID={unit_id}\"\"\")\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n ex = Main()\n ex.show()\n sys.exit(app.exec())\n","sub_path":"release/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"310680805","text":"from flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.dialects.postgresql import UUID\nimport uuid\n\ndb = SQLAlchemy()\n\nclass Ticket(db.Model):\n __tablename__ = 'ticket'\n\n id = db.Column(UUID(as_uuid=True), primary_key=True, nullable=False, default=lambda: str(uuid.uuid4()))\n name = db.Column(db.String(length=100), nullable=False)\n status = db.Column(db.Integer, nullable=False, server_default='0')\n url = db.Column(db.String(length=100), nullable=True)\n\n def __repr__(self):\n return f\"Ticket: name={self.name}, status={self.status}, url={self.url}\"\n\n #get string representation of status\n @property\n def get_status(self):\n all_statuses = {'0': 'Reported', '1': 'In Progress', '2': 'In Review', '3': 'Resolved'}\n return all_statuses[str(self.status)]\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"97482721","text":"\"\"\" \n\"\"\"\n\nimport os\nimport wget\nimport torch\nimport pandas as pd\n\nfrom torch.utils.data import TensorDataset, random_split\nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler, DistributedSampler\n\nfrom dataset import Dataset, InputExample, InputFeatures\nfrom processors import DataProcessor\nfrom utils import check_folder\n\n\n\nclass SentenceClassificationDataset(Dataset):\n \"\"\"Class for sentence classification dataset fetching and formatting.\"\"\"\n\n def __init__(self, task_name, dataset_name, dataset_dir=None, url=None):\n super(SentenceClassificationDataset, self).__init__(task_name, dataset_name, dataset_dir, url)\n\n def _fetch_dataset(self):\n \"\"\"Fetch sentence classification dataset.\"\"\"\n if not os.path.exists(self.dataset_dir):\n check_folder(self.dataset_dir)\n if self.dataset_name=='cola':\n self.url = self.url if self.url else 'https://nyu-mll.github.io/CoLA/cola_public_1.1.zip'\n try:\n local_path = os.path.join(self.dataset_dir, 'cola.zip')\n wget.download(self.url, local_path)\n # Unzip the dataset (if we haven't already)\n os.system(\"unzip {} -d {}\".format(local_path, self.dataset_dir))\n os.system(\"mv {} {}\".format(os.path.join(self.dataset_dir, 'cola_public/raw/in_domain_dev.tsv'),\n os.path.join(self.dataset_dir, 'dev.tsv')))\n os.system(\"mv {} {}\".format(os.path.join(self.dataset_dir, 'cola_public/raw/in_domain_train.tsv'),\n os.path.join(self.dataset_dir, 'train.tsv')))\n os.system(\"mv {} {}\".format(os.path.join(self.dataset_dir, 'cola_public/raw/out_of_domain_dev.tsv'),\n os.path.join(self.dataset_dir, 'test.tsv')))\n #os.system(\"rm {}\".format(local_path))\n #os.system(\"rm -r {}\".format(os.path.join(self.dataset_dir, 'cola_public')))\n except Exception:\n raise FileNotFoundError(\"Invalid URL.\")\n if self.dataset_name=='sst-2':\n self.url = self.url if self.url else 'https://github.com/clairett/pytorch-sentiment-classification/raw/master/data/SST2/'\n try:\n for _file in ['train.tsv', 'dev.tsv', 'test.tsv']:\n local_path = self.dataset_dir if self.dataset_dir else \"./{}\".format(self.dataset_name)\n wget.download(os.path.join(self.url, _file), local_path)\n except Exception:\n raise FileNotFoundError(\"Invalid URL.\")\n \n def process_dataset(self, set_type):\n if self.dataset_name=='cola':\n self.process_cola(set_type)\n elif self.dataset_name=='sst-2':\n self.process_sst2(set_type)\n\n def process_cola(self, set_type):\n \"\"\"Process CoLA dataset.\n The result is an iterator of tuples (sentence, label).\"\"\"\n _file = set_type + '.tsv'\n path_to_data = os.path.join(self.dataset_dir, _file)\n df = pd.read_csv(path_to_data, \n delimiter='\\t', \n header=None, \n names=['sentence_source', 'label', 'label_notes', 'sentence'])\n sentences = df.sentence.values\n labels = df.label.values\n data = zip(sentences, labels)\n if set_type=='train':\n self.train = list(data).copy()\n elif set_type=='test':\n self.test = list(data).copy()\n elif set_type=='dev':\n self.dev = list(data).copy()\n \n def process_sst2(self, set_type):\n \"\"\"Process SST-2 dataset.\n The result is an iterator of tuples (sentence, label).\"\"\"\n _file = set_type + '.tsv'\n path_to_data = os.path.join(self.dataset_dir, _file)\n df = pd.read_csv(path_to_data, \n delimiter='\\t', \n header=None, \n names=['sentence', 'label'])\n sentences = df.sentence.values\n labels = df.label.values\n data = zip(sentences, labels)\n if set_type=='train':\n self.train = list(data).copy()\n elif set_type=='test':\n self.test = list(data).copy()\n elif set_type=='dev':\n self.dev = list(data).copy()\n \n def get_labels(self):\n \"\"\" Returns possible labels for the task.\n \"\"\"\n if not self.train:\n raise AttributeError(\"You need to process dataset before retrieving labels.\")\n df = pd.DataFrame(self.train, columns =['sentence', 'labels'])\n labels = list(df.labels.unique())\n return sorted(labels)\n\n\nclass SentenceClassificationProcessor(DataProcessor):\n \"\"\"Processor for the CoNLL-2003 data set.\"\"\"\n\n def get_train_examples(self, dataset_object):\n \"\"\"See base class.\"\"\"\n return self._create_examples(dataset_object.train, \"train\")\n\n def get_dev_examples(self, dataset_object):\n \"\"\"See base class.\"\"\"\n return self._create_examples(dataset_object.dev, \"dev\")\n\n def get_test_examples(self, dataset_object):\n \"\"\"See base class.\"\"\"\n return self._create_examples(dataset_object.test, \"test\")\n\n def _create_examples(self, lines, set_type):\n \"\"\"Returns list of InputExample objects.\"\"\"\n examples = []\n for i, (sentence, label) in enumerate(lines):\n guid = \"%s-%s\" % (set_type, i)\n text_a = sentence\n text_b = None\n label = label\n examples.append(InputExample(guid=guid,text_a=text_a,text_b=text_b,label=label))\n return examples\n \n def convert_examples_to_features(self, examples, label_list, max_seq_length, tokenizer):\n \"\"\"Loads a data file into a list of `InputBatch`s.\n - input_ids: ids of ntokens + padding.\n e.g.: [103, 1023, 6423, 896, 102, 0, 0]\n - attention_mask: mask, 1 for tokens and 0 for padding.\n e.g.: [1, 1, 1, 1, 1, 0, 0]\n - token_type_ids: vector of 0.\n e.g.:[0, 0, 0, 0, 0, 0, 0]\n - label_ids: ids of the labels (there is 1 label for each word\n piece) + 0-padding\n e.g.: [1, 4, 4, 5, 2, 0, 0]\n \"\"\"\n features = []\n label_map = {label : i for i, label in enumerate(label_list,1)}\n\n for example in examples:\n encoded_dict = tokenizer.encode_plus(\n example.text_a, # Sentence to encode.\n add_special_tokens = True, # Add '[CLS]' and '[SEP]'\n max_length = max_seq_length, # Pad & truncate all sentences.\n pad_to_max_length = True,\n return_attention_mask = True, # Construct attn. masks.\n return_tensors = 'pt' # Return pytorch tensors.\n ) \n features.append(InputFeatures(input_ids=encoded_dict['input_ids'],\n attention_mask=encoded_dict['attention_mask'],\n token_type_ids=encoded_dict['token_type_ids'],\n label_ids=torch.tensor(example.label).unsqueeze(0)\n )\n )\n return features\n \n def get_data_loader(self, features, batch_size, local_rank, set_type):\n \"\"\"See base class.\"\"\"\n input_ids = torch.cat([f.input_ids for f in features], dim=0)\n attention_mask = torch.cat([f.attention_mask for f in features], dim=0)\n token_type_ids = torch.cat([f.token_type_ids for f in features], dim=0)\n label_ids = torch.cat([f.label_ids for f in features], dim=0)\n data = TensorDataset(input_ids, attention_mask, token_type_ids, label_ids)\n if set_type=='train':\n if local_rank == -1:\n sampler = RandomSampler(data)\n else:\n sampler = DistributedSampler(data)\n else:\n sampler = SequentialSampler(data)\n dataloader = DataLoader(data, sampler=sampler, batch_size=batch_size)\n return dataloader","sub_path":"ROBERTA/sentence_classification.py","file_name":"sentence_classification.py","file_ext":"py","file_size_in_byte":8379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"173921509","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport os\r\nimport tensorflow as tf\r\nimport random\r\nfrom tensorflow.python.keras.utils import data_utils\r\nfrom Config import Config\r\nimport imageio\r\nimport cv2\r\nfrom PIL import Image\r\n\r\n\r\n\r\nclass DataGenerator(tf.data.Dataset):\r\n \r\n def _generator(num_samples, size = (224,224), SAMPLE_DIR = \"Database/cars_train\" , FG_DIR=\"Database/VW/tmp3\", MASK_DIR = \"Database/VW_Masks2\", BG_DIR=\"Database/Backgrounds\"):\r\n \r\n data_augmentation = tf.keras.Sequential([\r\n tf.keras.layers.experimental.preprocessing.RandomZoom(-0.8, -0.5),\r\n tf.keras.layers.experimental.preprocessing.RandomRotation(0.5),\r\n tf.keras.layers.experimental.preprocessing.RandomContrast(0.5)\r\n ])\r\n\r\n #it's custom arumnted tf's layer to diversyfied db. in color dimension\r\n color_augmentation = tf.keras.Sequential([\r\n RandomColorDistortion(), # colour distoriton \r\n tf.keras.layers.experimental.preprocessing.RandomContrast(0.5) #contrast distortion \r\n ])\r\n FG_DIR = FG_DIR.decode(\"utf-8\")\r\n fg_list = os.listdir(FG_DIR)[:-1]\r\n fg_img = [tf.expand_dims(imageio.imread(os.path.join(FG_DIR, i)),0) for i in fg_list] \r\n fg_size = len(fg_list)\r\n \r\n MASK_DIR = MASK_DIR.decode(\"utf-8\")\r\n mask_img = [np.repeat(imageio.imread(os.path.join(MASK_DIR, i))[:, :, np.newaxis], 3, axis=2) for i in fg_list]\r\n \r\n BG_DIR = BG_DIR.decode(\"utf-8\")\r\n bg_list = os.listdir(BG_DIR)[:-1]\r\n bg_img = [tf.expand_dims(imageio.imread(os.path.join(BG_DIR, i)),0) for i in bg_list] \r\n bg_size = len(bg_list)\r\n \r\n SAMPLE_DIR = SAMPLE_DIR.decode(\"utf-8\")\r\n sample_list = os.listdir(SAMPLE_DIR)[:50]\r\n sample_img = [tf.expand_dims(imageio.imread(os.path.join(SAMPLE_DIR, i)),0) for i in sample_list] \r\n sample_size = len(sample_list)\r\n img_shape = size + (3,)\r\n\r\n for sample_idx in range(num_samples):\r\n class_index = random.randint(0,1) \r\n if class_index:\r\n \r\n fg_index = random.randint(0, fg_size-1)\r\n foreground = fg_img[fg_index] \r\n #foreground = data_augmentation(background, training = True)\r\n foreground = color_augmentation(foreground, training = True).numpy()[0,:,:,:]\r\n \r\n bg_index = random.randint(0, bg_size - 1)\r\n background = bg_img[bg_index]\r\n \r\n #background = tf.expand_dims(background, 0)\r\n background = data_augmentation(background, training = True)\r\n background = color_augmentation(background, training = True) \r\n background = background.numpy()[0,:,:,:]\r\n\r\n mask = mask_img[fg_index]\r\n \r\n foreground = np.multiply(mask, foreground)\r\n background = np.multiply(1 - mask, background)\r\n\r\n img = np.add(foreground, background)\r\n img = tf.expand_dims(img, 0)\r\n img = data_augmentation(img, training=True).numpy()[0,:,:,:]\r\n \r\n else: \r\n img_index = random.randint(0, sample_size-1)\r\n img = sample_img[img_index] \r\n #img = tf.expand_dims(img, 0)\r\n img = data_augmentation(img, training = True)\r\n img = color_augmentation(img, training = True).numpy()[0,:,:,:]\r\n \r\n\r\n yield (img, class_index,)\r\n \r\n def __new__(cls,num_samples, img_size, samle_dir, fg_dir, mask_dir, bg_dir):\r\n img_shape = img_size + (3, )\r\n \r\n return tf.data.Dataset.from_generator(\r\n cls._generator,\r\n output_shapes = (img_shape, ()),\r\n output_types = (tf.float32, tf.int32),\r\n args=(\r\n num_samples, \r\n img_size, \r\n samle_dir, \r\n fg_dir, \r\n mask_dir, \r\n bg_dir\r\n )\r\n )\r\n\r\nclass RandomColorDistortion(tf.keras.layers.Layer):\r\n def __init__(self, contrast_range=[0.5, 1.5], \r\n brightness_delta=[-0.5, 0.5], **kwargs):\r\n super(RandomColorDistortion, self).__init__(**kwargs)\r\n self.contrast_range = contrast_range\r\n self.brightness_delta = brightness_delta\r\n \r\n def call(self, images, training=None):\r\n if not training:\r\n return images\r\n \r\n contrast = np.random.uniform(\r\n self.contrast_range[0], self.contrast_range[1])\r\n brightness = np.random.uniform(\r\n self.brightness_delta[0], self.brightness_delta[1])\r\n images = tf.image.adjust_contrast(images, contrast)\r\n images = tf.image.adjust_brightness(images, brightness)\r\n\r\n return images\r\n\"\"\"\r\n \r\n \r\n \r\n\r\n\r\nclass DataGenerator(data_utils.Sequence):\r\n\r\n def __init__(self, sample_dir, fg_dir, mask_dir, bg_dir, output_size =None, shuffle=False, batch_size=32):\r\n\r\n #self.df = pd.read_csv(csv_file)\r\n super(DataGenerator, self).__init__()\r\n self.sample_dir = sample_dir\r\n self.sample_list = os.listdir(sample_dir)[:-1]\r\n self.sample_size = len(self.sample_list)\r\n\r\n self.fg_dir = fg_dir \r\n self.fg_list = os.listdir(fg_dir)[:-1]\r\n self.fg_size = len(self.fg_list)\r\n\r\n self.mask_dir = mask_dir \r\n self.mask_list = os.listdir(mask_dir)[:-1]\r\n\r\n self.bg_dir = bg_dir\r\n self.bg_list = os.listdir(bg_dir)[:-1]\r\n self.bg_size = len(self.bg_list)\r\n\r\n if output_size == None: \r\n self.output_size = (224,224)\r\n else: \r\n self.output_size = output_size\r\n\r\n self.shuffle = shuffle\r\n self.batch_size = batch_size\r\n\r\n # define augmanted tf's layer to diversyfied our dataset\r\n #This layer performs random zooming, rotation, and contrast distortion\r\n self.training_augmentation = tf.keras.Sequential([\r\n tf.keras.layers.experimental.preprocessing.RandomZoom(-0.2, -0.2),\r\n tf.keras.layers.experimental.preprocessing.RandomRotation(0.1),\r\n tf.keras.layers.experimental.preprocessing.RandomContrast(0.5),\r\n tf.keras.layers.experimental.preprocessing.RandomFlip('horizontal'),\r\n\r\n ])\r\n\r\n #it's custom arumnted tf's layer to diversyfied db. in color dimension\r\n self.color_augmentation = tf.keras.Sequential([\r\n RandomColorDistortion(), # colour distoriton \r\n tf.keras.layers.experimental.preprocessing.RandomContrast(0.25) #contrast distortion \r\n ])\r\n\r\n self.on_epoch_end()\r\n\r\n def on_epoch_end(self):\r\n self.sample_indices = np.arange(len(self.sample_list))\r\n self.fg_indices = np.arange(len(self.fg_list))\r\n self.bg_indices = np.arange(len(self.bg_list))\r\n\r\n if self.shuffle:\r\n np.random.shuffle(self.sample_indices)\r\n np.random.shuffle(self.fg_indices)\r\n np.random.shuffle(self.bg_indices)\r\n\r\n #tf.keras.backend.clear_session()\r\n\r\n def __len__(self):\r\n return int(self.fg_size*10 / self.batch_size)\r\n\r\n def augment_image(self, img_path):\r\n img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)\r\n img = tf.expand_dims(img, 0)\r\n img = self.training_augmentation(img, training = True).numpy()[0,:,:,:]\r\n return img\r\n\r\n def blend_image_mask_bg(self, img_path, mask_path, bg_path):\r\n\r\n foreground = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)\r\n foreground = tf.expand_dims(foreground, 0)\r\n foreground = self.color_augmentation(foreground, training = True).numpy()[0,:,:,:]\r\n\r\n background = cv2.imread(bg_path, cv2.IMREAD_UNCHANGED)\r\n background = tf.expand_dims(background, 0)\r\n background = self.training_augmentation(background, training = True)\r\n background = self.color_augmentation(background, training = True).numpy()[0,:,:,:]\r\n\r\n mask = cv2.imread(mask_path)\r\n\r\n foreground = np.multiply(mask, foreground)\r\n background = np.multiply(1 - mask, background)\r\n\r\n img_blend = np.add(foreground, background)\r\n #img_blend = tf.expand_dims(img_blend, 0)\r\n #img_blend = self.training_augmentation(img_blend, training = True)\r\n\r\n return img_blend\r\n\r\n\r\n def __data_generation(self):\r\n\r\n #'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)\r\n # Initialization\r\n X = np.empty((self.batch_size, *self.output_size, 3))\r\n y = np.empty((self.batch_size), dtype=int)\r\n\r\n # Generate data\r\n for i in range(self.batch_size):\r\n\r\n class_index = random.randint(0,1) \r\n if class_index:\r\n fg_index = random.randint(0, self.fg_size-1)\r\n fg_name = os.path.join(self.fg_dir, self.fg_list[fg_index])\r\n\r\n mask_name = os.path.join(self.mask_dir, self.fg_list[fg_index].split('.')[0] +\"_mask.jpg\")\r\n\r\n bg_index = random.randint(0, self.bg_size - 1)\r\n bg_name = os.path.join(self.bg_dir, self.bg_list[bg_index])\r\n\r\n img = self.blend_image_mask_bg(fg_name, mask_name, bg_name)\r\n else: \r\n img_index = random.randint(0, self.sample_size -1)\r\n img_name =os.path.join(self.sample_dir, self.sample_list[img_index])\r\n img = self.augment_image(img_name)\r\n\r\n X[i,] = img\r\n y[i] = class_index\r\n\r\n #return tf.convert_to_tensor(X), tf.convert_to_tensor(y, dtype=np.int32)\r\n return X, tf.convert_to_tensor(y, dtype=np.int32)\r\n #return X, keras.utils.to_categorical(y, num_classes=self.n_classes)\r\n\r\n def __getitem__(self, index):\r\n ## Initializing Batch\r\n # that one in the shape is just for a one channel images\r\n # if you want to use colored images you might want to set that to 3\r\n 'Generate one batch of data'\r\n # Generate indexes of the batch\r\n\r\n X, y = self.__data_generation()\r\n\r\n return (X,y)\r\n\"\"\"\r\n\r\n\r\n","sub_path":"DatabaseGenerator.py","file_name":"DatabaseGenerator.py","file_ext":"py","file_size_in_byte":10213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"583401302","text":"# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved.\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport torchvision\nimport math\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\ndef attention(query, key, value, mask=None, dropout=None):\n \"Compute 'Scaled Dot Product Attention'\"\n d_k = query.size(-1)\n scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)\n # print('scores', scores)\n if mask is not None:\n scores = scores.masked_fill(mask == 0, -1e9)\n scores.retain_grad()\n p_attn = F.softmax(scores, dim=-1)\n if dropout is not None:\n p_attn = dropout(p_attn)\n res = torch.matmul(p_attn, value)\n return res, p_attn\n\n\nQ = torch.tensor(\n [[[1.0, 1.0, 2.0, 0.0, 5.0], [-1.0, 2.0, 2.0, 0.0, 5.0]]], requires_grad=True\n)\n\nmask = torch.tensor([[[1, 1], [1, 1]]])\n\nres, p_attn = attention(Q, Q, Q, mask)\n\nprint(\"res\", res)\nprint()\nprint(\"p_attn\", p_attn)\np_attn.retain_grad()\nres.backward(torch.tensor([[[1.0, 1.0, 2.0, 0.0, 5.0], [-1.0, 2.0, 2.0, 0.0, 5.0]]]))\n\nprint(Q.grad)\n","sub_path":"training/src/tests/tests/python/self-attention.py","file_name":"self-attention.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"557139638","text":"import sys\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom surfaceintegral import surfaceintegral\nfrom call_rseq import rseq\nfrom makepotential import makepotential\nfrom basis import Basis\nfrom integrate import integrate\nfrom scipy import interpolate\nfrom scipy.integrate import tplquad,trapz\nfrom scipy.integrate import simps,cumtrapz\nfrom mayavi import mlab\nfrom scipy.interpolate import RegularGridInterpolator\nfrom scipy.special import sph_harm\nfrom make_V_radial_new import make_V_radial_new\n\nEPSVAL = 1.e-20\n\ndef main():\n # make environment\n pot_region = np.array((2/np.sqrt(3),2/np.sqrt(3),2/np.sqrt(3)))\n bound_rad = pot_region / 2\n radius = np.sqrt(pot_region[0] **2 + pot_region[1] **2 + pot_region[2] **2 )\n region = (radius,radius,radius)\n nr = 201\n gridpx = 200 \n gridpy = 200 \n gridpz = 200 \n x,y,z = grid(gridpx,gridpy,gridpz,region)\n xx, yy, zz = np.meshgrid(x,y,z)\n\n #make mesh\n\n #linear mesh\n #r =np.linspace(0.0001,region,nr)\n\n #log mesh\n a = np.log(2) / (nr - 1) \n b = radius / (np.e**(a * ( nr - 1)) - 1)\n rofi = np.array([b * (np.e**(a * i) - 1) for i in range(nr)])\n\n # make potential\n V = makepotential(xx,yy,zz,pot_region,pottype=\"cubic\",potbottom=-1,potshow_f=False)\n\n # surface integral\n V_radial = surfaceintegral(x,y,z,rofi,V,method=\"lebedev_py\",potshow_f=False)\n\n V_radial_new = make_V_radial_new(V_radial,rofi,pot_region,bound_rad,pot_show_f=False)\n vofi = np.array (V_radial_new) \n\n # make basis\n \n node_open = 1\n node_close = 4\n LMAX = 8\n\n all_basis = []\n\n for lvalsh in range (LMAX):\n l_basis = []\n # for open channel\n val = 1.\n slo = 0.\n for node in range(node_open):\n basis = Basis(nr)\n emin = -10.\n emax = 1000.\n basis.make_basis(a,b,emin,emax,lvalsh,node,nr,rofi,slo,vofi,val)\n l_basis.append(basis)\n\n # for close channel\n val = 0.\n slo = -1.\n for node in range(node_close):\n basis = Basis(nr)\n emin = -10.\n emax = 1000.\n basis.make_basis(a,b,emin,emax,lvalsh,node,nr,rofi,slo,vofi,val)\n l_basis.append(basis)\n\n all_basis.append(l_basis)\n\n with open (\"wavefunc.dat\", mode = \"w\") as fw_w :\n fw_w.write(\"#r, l, node, open or close = \") \n for l_basis in all_basis:\n for nyu_basis in l_basis:\n fw_w.write(str(nyu_basis.l))\n fw_w.write(str(nyu_basis.node))\n if nyu_basis.open:\n fw_w.write(\"open\")\n else:\n fw_w.write(\"close\")\n fw_w.write(\" \")\n fw_w.write(\"\\n\")\n\n for i in range(nr):\n fw_w.write(\"{:>13.8f}\".format(rofi[i]))\n for l_basis in all_basis:\n for nyu_basis in l_basis:\n fw_w.write(\"{:>13.8f}\".format(nyu_basis.g[i]))\n fw_w.write(\"\\n\")\n\n hsmat = np.zeros((LMAX,LMAX,node_open + node_close,node_open + node_close),dtype = np.float64)\n lmat = np.zeros((LMAX,LMAX,node_open + node_close,node_open + node_close), dtype = np.float64)\n qmat = np.zeros((LMAX,LMAX,node_open + node_close,node_open + node_close), dtype = np.float64)\n\n for l1 in range (LMAX):\n for l2 in range (LMAX):\n if l1 != l2 :\n continue\n for n1 in range (node_open + node_close):\n for n2 in range (node_open + node_close):\n if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2:\n print(\"error: L is differnt\")\n sys.exit()\n hsmat[l1][l2][n1][n2] = integrate(all_basis[l1][n1].g[:nr] * all_basis[l2][n2].g[:nr],rofi,nr) * all_basis[l1][n1].e\n lmat[l1][l2][n1][n2] = all_basis[l1][n1].val * all_basis[l2][n2].slo\n qmat[l1][l2][n1][n2] = all_basis[l1][n1].val * all_basis[l2][n2].val\n print (\"\\nhsmat\")\n print (hsmat)\n print (\"\\nlmat\")\n print (lmat)\n print (\"\\nqmat\")\n print (qmat)\n\n\n #make not spherical potential\n my_radial_interfunc = interpolate.interp1d(rofi, V_radial_new)\n\n V_ang = np.where(np.sqrt(xx * xx + yy * yy + zz * zz) < rofi[-1] , V - my_radial_interfunc(np.sqrt(xx * xx + yy * yy + zz * zz)),0. )\n \"\"\"\n for i in range(gridpx):\n for j in range(gridpy):\n for k in range(gridpz):\n print(V_ang[i][j][k],end=\" \")\n print(\"\")\n print(\"\\n\")\n sys.exit()\n \"\"\"\n\n #WARING!!!!!!!!!!!!!!!!!!!!!!\n \"\"\"\n Fujikata rewrote ~/.local/lib/python3.6/site-packages/scipy/interpolate/interpolate.py line 690~702\n To avoid exit with error \"A value in x_new is below the interpolation range.\"\n \"\"\"\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n \"\"\"\n with open (\"V_ang.dat\",mode = \"w\") as fw_a:\n for i in range(len(V_ang)):\n fw_a.write(\"{:>13.8f}\".format(xx[50][i][50]))\n fw_a.write(\"{:>13.8f}\\n\".format(V_ang[i][50][50]))\n \"\"\"\n\n #mayavi.mlab.plot3d(xx,yy,V_ang)\n# mlab.contour3d(V_ang,color = (1,1,1),opacity = 0.1)\n# obj = mlab.volume_slice(V_ang)\n# mlab.show()\n\n fw_grid = open(\"umat_grid_all.dat\",mode = \"w\")\n for ngrid in range(5,50):\n fw_grid_2 = open(\"umat_grid\"+str(ngrid)+\".dat\",mode=\"w\")\n fw_grid.write(str(ngrid)+\" \") \n t1 = time.time()\n \n umat = np.zeros((node_open + node_close,node_open + node_close,LMAX,LMAX,2 * LMAX + 1,2 * LMAX + 1), dtype = np.complex64)\n # umat_t = np.zeros((LMAX,LMAX,2 * LMAX + 1,2 * LMAX + 1,node_open + node_close,node_open + node_close), dtype = np.complex64)\n \n #my_V_ang_inter_func = RegularGridInterpolator((x, y, z), V_ang)\n \n igridpx = ngrid\n igridpy = ngrid \n igridpz = ngrid \n \n ix,iy,iz = grid(igridpx,igridpy,igridpz,pot_region)\n ixx,iyy,izz = np.meshgrid(ix,iy,iz)\n \n #V_ang_i = my_V_ang_inter_func((ixx,iyy,izz))\n V_ang_i = np.zeros((igridpx,igridpy,igridpz))\n V_ang_i = -1. - my_radial_interfunc(np.sqrt(ixx * ixx + iyy * iyy + izz * izz))\n\n \n #mlab.points3d(V_ang_i,scale_factor=0.4)\n # mlab.contour3d(V_ang_i,color = (1,1,1),opacity = 0.1)\n # obj = mlab.volume_slice(V_ang_i)\n #mlab.show()\n \n dis = np.sqrt(ixx **2 + iyy **2 + izz **2)\n dis2 = ixx **2 + iyy **2 + izz **2\n theta = np.where( dis != 0., np.arccos(izz / dis), 0.)\n phi = np.where( iyy**2 + ixx **2 != 0 , np.where(iyy >= 0, np.arccos(ixx / np.sqrt(ixx **2 + iyy **2)), np.pi + np.arccos(ixx / np.sqrt(ixx **2 + iyy **2))), 0.)\n # region_t = np.where(dis < rofi[-1],1,0)\n sph_harm_mat = np.zeros((LMAX,2 * LMAX + 1, igridpx,igridpy,igridpz),dtype = np.complex64)\n for l1 in range (LMAX):\n for m1 in range (-l1,l1 + 1):\n sph_harm_mat[l1][m1] = np.where(dis != 0., sph_harm(m1,l1,phi,theta),0.)\n g_ln_mat = np.zeros((node_open + node_close,LMAX,igridpx,igridpy,igridpz),dtype = np.float64)\n for n1 in range (node_open + node_close):\n for l1 in range (LMAX):\n my_radial_g_inter_func = interpolate.interp1d(rofi,all_basis[l1][n1].g[:nr])\n g_ln_mat[n1][l1] = my_radial_g_inter_func(np.sqrt(ixx **2 + iyy **2 + izz **2))\n \n for n1 in range (node_open + node_close):\n for n2 in range (node_open + node_close):\n for l1 in range (LMAX):\n for l2 in range (LMAX):\n if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2:\n print(\"error: L is differnt\")\n sys.exit()\n # to avoid nan in region where it can not interpolate ie: dis > rofi\n g_V_g = np.where(dis < rofi[-1], g_ln_mat[n1][l1] * V_ang_i * g_ln_mat[n2][l2], 0.)\n for m1 in range (-l1,l1+1):\n for m2 in range (-l2,l2+1):\n #print(\"n1 = {} n2 = {} l1 = {} l2 = {} m1 = {} m2 = {}\".format(n1,n2,l1,l2,m1,m2))\n #umat[n1][n2][l1][l2][m1][m2] = np.sum(np.where( dis2 != 0., sph_harm_mat[l1][m1].conjugate() * g_V_g * sph_harm_mat[l2][m2] / dis2, 0.)) * (2 * pot_region[0] * 2 * pot_region[1] * 2 * pot_region[2]) / (igridpx * igridpy * igridpz)\n umat[n1][n2][l1][l2][m1][m2] = trapz(trapz(trapz(np.where(dis2 != 0. ,sph_harm_mat[l1][m1].conjugate() * g_V_g * sph_harm_mat[l2][m2] / dis2,0),x=iz,axis=2),x=iy,axis=1),x=ix,axis=0)\n #umat[n1][n2][l1][l2][m1][m2] = simps(simps(simps(np.where(dis2 != 0. ,sph_harm_mat[l1][m1].conjugate() * g_V_g * sph_harm_mat[l2][m2] / dis2,0),x=iz,axis=2),x=iy,axis=1),x=ix,axis=0)\n #umat[n1][n2][l1][l2][m1][m2] = simps(simps(simps(np.where(dis2 != 0. ,sph_harm_mat[l1][m1].conjugate() * g_V_g * sph_harm_mat[l2][m2] / dis2,0),x=iz,axis=2,even=\"first\"),x=iy,axis=1,even=\"first\"),x=ix,axis=0,even=\"first\")\n fw_grid.write(\"{:>13.8f}\".format(umat[n1][n2][l1][l2][m1][m2].real))\n\n count = 0\n for l1 in range (LMAX):\n for l2 in range (LMAX):\n for m1 in range (-l1,l1+1):\n for m2 in range (-l2,l2+1):\n for n1 in range (node_open + node_close):\n for n2 in range (node_open + node_close):\n fw_grid_2.write(str(count))\n fw_grid_2.write(\"{:>15.8f}{:>15.8f}\\n\".format(umat[n1][n2][l1][l2][m1][m2].real,umat[n1][n2][l1][l2][m1][m2].imag))\n count += 1\n \n t2 = time.time()\n fw_grid.write(\"\\n\")\n print(\"grid = \", ngrid, \"time = \",t2 - t1)\n fw_grid.close()\n\n\ndef grid (nx,ny,nz,region):\n x = np.linspace(-region[0],region[0],nx)\n y = np.linspace(-region[1],region[1],ny)\n z = np.linspace(-region[2],region[2],nz)\n return x,y,z\n\n\ndef fitting(r,V,d):\n w = np.polyfit(r,V,d)\n print(w)\n xs = np.linspace(r[0],r[-1],300)\n ys = np.polyval(w,xs)\n return xs,ys\n \nif __name__ ==\"__main__\":\n main()\n","sub_path":"Potential/Code/Previous/gridloop20191127.py","file_name":"gridloop20191127.py","file_ext":"py","file_size_in_byte":10349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"532535489","text":"from os import path\n\nfrom flask import Flask, render_template, jsonify, request\nfrom flask_migrate import Migrate\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bootstrap import Bootstrap\n\n\n# Текущая директория\nbasedir = path.abspath(path.dirname(__file__))\n\n# Flask приложение\napp = Flask(__name__)\n# Обновление конфигурации\napp.config.update(\n dict(\n SECRET_KEY='powerful-secretkey',\n WTF_CSRF_SECRET_KEY='a-csrf-secret-key',\n SQLALCHEMY_TRACK_MODIFICATIONS=False,\n SQLALCHEMY_DATABASE_URI='sqlite:///' + path.join(basedir, 'app.db')\n )\n)\n\n# База данных\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n# Bootstrap\nbootstrap = Bootstrap(app)\n\n\n# Модель базы данных\nclass Temperature(db.Model):\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n value = db.Column(db.Integer, nullable=False)\n datetime = db.Column(db.DateTime, nullable=False)\n\n # Получение n последних данных\n @staticmethod\n def get_last_values(n):\n return Temperature.query.order_by(Temperature.datetime.desc())[:n]\n\n\n# Путь для графика в реальном времени\n@app.route('/')\n@app.route('/index')\n@app.route('/realtime')\ndef index():\n values = Temperature.get_last_values(30)\n return render_template('chart.html', values=values)\n\n\n# Путь для графика истории\n@app.route('/history')\ndef history():\n values = Temperature.get_last_values(30)\n return render_template('chart.html', values=values)\n\n\n# Путь для добавления данных в базу данных\n@app.route('/add_data', methods=['POST'])\ndef add_data():\n data = request.json\n t = Temperature(value=data[\"value\"], datetime=data[\"datetime\"])\n db.session.add(t)\n db.session.commit()\n return jsonify({})\n\n\nif __name__ == \"__main__\":\n # Создание базы данных\n db.create_all()\n # Запуск сервера\n app.run()\n","sub_path":"server/flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"482845192","text":"import sys, os\nmyPath = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, myPath + '/../')\n\nfrom torch.optim import Adam\nimport torch\ndevice = torch.device(\"cuda:0\")\nimport matplotlib.pyplot as plt\n\nfrom models.rbm import RBM, RBMClassifier\nfrom dpipe.mnist import smallMnist, Mnist\nimport matplotlib.pyplot as plt\n\ndef modeler():\n data = Mnist()\n model = RBM()\n\n ks = [3,1,4,2,6,4,2,7,2,6,8,11,15,2,13,1,2,6,7,4,6]\n for k in ks:\n model.k = k\n model.CDk(data)\n\ndef recon():\n x = torch.load(\"weights/rbm/test.pt\")\n model = RBM()\n\n fig, ax = plt.subplots(nrows=1, ncols=2)\n x_new = x.clone()\n ax[0].imshow(x.view(28,28).numpy())\n \n x_new = model.reconstruction(x_new.cuda())\n\n ax[1].imshow(x_new.view(28,28).detach().cpu().numpy())\n plt.show()\n\n\ndef recons():\n data = Mnist()\n data.MODE = \"test\"\n model = RBM()\n\n fig, ax = plt.subplots(nrows=2, ncols=10)\n\n c = 0\n for i in range(0,100,10):\n x = data[i+2][0].t()[0]*255\n\n x = x.view(784,1)\n \n mask = (torch.rand(x.shape).cuda() > 0.2).float()\n x = x * mask\n x_new = x.clone()\n ax[0][c].imshow(x.view(28,28).detach().cpu().numpy())\n \n for i in range(6):\n x_new = model.reconstruction(x_new)\n\n x = x_new.view(28,28).detach().cpu().numpy()\n ax[1][c].imshow(x)\n c+=1\n \n plt.show()\n\ndef classify():\n data = Mnist()\n rbm = RBM()\n\n model = RBMClassifier(rbm).to(device)\n loss_fn = torch.nn.CrossEntropyLoss(reduction='mean')\n\n optimizer = Adam(model.classifier.parameters(),lr=0.0001,weight_decay=0.00001)\n\n for e in range(100):\n tots = 0\n for i,(x,y) in enumerate(data):\n if torch.Size([784,0]) == x.shape:\n break\n \n out = model(x)\n optimizer.zero_grad()\n loss = loss_fn(out,y.long())\n tots+=loss.item()\n loss.backward()\n\n optimizer.step()\n\n if i%50 ==0:\n print(e,i,tots/(i+1))\n\n torch.save(model.state_dict(),\"weights/rbm/rbmclass.pth\")\n\ndef test():\n data = Mnist()\n data.MODE = \"test\"\n rbm = RBM()\n\n model = RBMClassifier(rbm).to(device)\n model.load_state_dict(torch.load(\"weights/rbm/rbmclass.pth\"))\n sm = torch.nn.Softmax()\n\n x,y = data[0]\n\n out = model(x)\n\n val, ind = out.max(1)\n\ndef analyze():\n w = torch.load(\"weights/rbm/W100s.pt\").cpu()\n\n fig, ax = plt.subplots(nrows=10, ncols=10)\n\n plt.axis('off')\n i=0\n for row in ax:\n for col in row:\n col.imshow(w[i].view(28,28))\n col.set_axis_off()\n i+=1\n \n plt.show()\n\ndef analyze2():\n w = torch.load(\"weights/rbm/W16.pt\").cpu()\n\n fig, ax = plt.subplots(nrows=4, ncols=4)\n\n plt.axis('off')\n i=0\n for row in ax:\n for col in row:\n col.imshow(w[i].view(28,28))\n col.set_axis_off()\n i+=1\n \n plt.show()\n\n\n\n\nif __name__ == \"__main__\":\n analyze()\n","sub_path":"exp/rbm.py","file_name":"rbm.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"603157199","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/python\n#__author__= \"PengZhang\"\n\nimport os\nimport sys\nimport argparse\nimport time\n\nusage = \"NL流程整理加工,输入vcf文件,整理两次获得新的突变的阀值\\n\"\n\nparser = argparse.ArgumentParser(description=usage)\nparser.add_argument(\"-n\", \"--name\", help = \"输入文件夹名字\", required = True)\nparser.add_argument(\"-i\", \"--input\", help = \"输入文件夹的路径\", required = True)\nparser.add_argument(\"-o\", \"--output\", help = \"输出的文件夹路径\", required = True)\nargs = vars(parser.parse_args())\n\nargs['input'] = os.path.abspath(args['input'])\n\nif args['output'] and not os.path.exists(args['output']):\n\tos.mkdir(args['output'])\n\n##读取文件夹中的所有文件\nfilelist = os.listdir(args['input'])\n##工作环境设定,建立另外两个文件夹\nout_file_path = args['output'] + '/' +args['name']\nif not os.path.exists(out_file_path):\n\tos.mkdir(out_file_path)\n##第一步转为蛋白质序列的文件,第二步替换之后的结果\nout_file_path_NL_v1 = args['output'] + '/' +args['name'] + '/workspace_v1'\nout_file_path_NL_v2 = args['output'] + '/' +args['name'] + '/workspace_v2'\nout_file_path_put = args['output'] + '/' +args['name'] + '/other_file'\n\nif not os.path.exists(out_file_path_NL_v1):\n\tos.mkdir(out_file_path_NL_v1)\nif not os.path.exists(out_file_path_NL_v2):\n\tos.mkdir(out_file_path_NL_v2)\nif not os.path.exists(out_file_path_put):\n\tos.mkdir(out_file_path_put)\n\nfor name in filelist:\n\tname_two = args['input'] + '/' + name\n\t#print('Rscript /work/home/zhangp/workspace/20170718/code/NL_v2.RNL_v2.R %s %s' %(name_two, out_file_path_NL_v1))\n\tos.system('Rscript /work/home/zhangp/workspace/20170718/code/NL_v2.R %s %s' %(name_two, out_file_path_NL_v1))\n\nprint('STEP_FIRST_END')\n\n##增加第二步,先复制一个数据样子,放在workspace_v2中,然后读每行数据,跟新一个文件,让外部程序解析;\n\n##step1workspace_v1中的文件\n\nfilelist_v2 = os.listdir(out_file_path_NL_v1)\n\nfor name in filelist_v2:\n\tnew_file = out_file_path_NL_v1 + '/' + name\n\tnew_file_v2 = out_file_path_NL_v2 + '/' + name\n\tzp = 1.1\n\twith open(new_file_v2, 'w') as tmp_v2:\n\t\ttmp_v2.write('first_data\\tsecond_data\\n')\n\t\ttmp_v2.write('%s\\t%s\\n' %(zp,zp))\n\tfor s in open(new_file).readlines():\n\t\ts = s.strip().split('\\t')\n\t\tif not s:\n\t\t\tcontinue\n\t\tif s[3] != 'fs':\n\t\t\tone = s\n\t\t\tother_path_file = out_file_path_put + '/output.txt' \n\t\t\twith open(other_path_file, 'w') as tmp:\n\t\t\t\ttmp.write('>' + one[2] + '\\n')\n\t\t\t\ttmp.write(one[4] + '\\n')\n\t\t\tother_path_app_v1 = out_file_path_put + '/app_v1.txt'\n\t\t\tos.system('/work/home/zhangp/workspace/20170714/code_v4/netchop-3.1/Linux_x86_64/bin/netChop %s -tdir ./ > %s' %(other_path_file, other_path_app_v1))\n\t\t\tos.system('Rscript /work/home/zhangp/workspace/20170718/code/NL_v4.R %s %s' %(other_path_app_v1, out_file_path_put))\n\t\t\tapp_v2_path = out_file_path_put + '/1.txt'\n\t\t\tapp_v2_path_out = out_file_path_put + '/2.txt'\n\t\t\tos.system('/work/home/zhangp/workspace/20170714/code_v2/netMHCpan-3.0/Linux_x86_64/bin/netMHCpan %s > %s' %(app_v2_path, app_v2_path_out))\n\t\t\tos.system('Rscript /work/home/zhangp/workspace/20170718/code/NL_v3.R %s %s' %(app_v2_path_out, new_file_v2))\n\tprint(name)\n","sub_path":"NAB计算方法/NL_sum_v3.py","file_name":"NL_sum_v3.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"205137035","text":"from datetime import datetime, date, timedelta\nimport datetime\nfrom pprint import pprint\nimport json\n\ntoday = datetime.datetime.now()\n\ni = 1\ndata = {}\ndata1 = {}\n\nwhile(i < 1000):\n\n datelst = []\n\n today = today + datetime.timedelta(days=1)\n\n day = today.strftime(\"%Y-%m-%d\")\n\n data1[day] = day\n\n i += 1\n\ndata[\"calendar\"] = data1\n\n# pprint(data)\n\nwith open('calendar.json', 'w') as jsonfile:\n json.dump(data, jsonfile, ensure_ascii=False)\n\nprint(\"JSON completed\")","sub_path":"user/calendarJSON.py","file_name":"calendarJSON.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"624225928","text":"import os\nimport sys\npath = os.path.split(sys.argv[0])[0]\nsys.path.append(\n\t\t\t'\\\\'.join(path.split('\\\\')[:-1]))\n\nfrom analyzer.expression import exp\nfrom analyzer.data import regex\nfrom optimizer.optimizer import code_optimizer\nimport re\n\n\ndata = regex\nERR_RE_MSG = 'Error: invalid regular expression'\n\nclass Regex:\n\t\n\t'''Holds all the regular expression inside data.py file\n\t and find all the matches with the passed code then\n\t passes each match to the optimizer individually'''\n\n\t#reads the regular expressions from data.py and \n\t#create object for each regex\n\n\t_data = [\n\t\texp(re, data[re][0], data[re][1], data[re][2])\n\t\tfor re in data\n\t] #exp(name, type, pattern, description)\n\t_numberOfRegex = len(_data) #Count the overall number of the regular expressions\n\tfixed_code = '' #Holds the optimized code\n\n\tdef __len__(self): #returns number of regular expressions \n\t\treturn Regex._numberOfRegex \n\n\t@staticmethod\n\tdef read_code(file):\n\t\t'''Read file content and return it inside a variable'''\n\t\t\n\t\twith open(file) as f:\n\t\t\tcontent = f.read()\n\n\t\treturn content\n\n\t@staticmethod\n\tdef compile_regex(regex):\n\t\t''' Compiles the passed regular expression and test if it's valid\n\t\t\t,if so, it returns the compiled regex, otherwise it prints out\n\t\t\tan error message, but never stop, the reason behind that is to\n\t\t\tcheck the other regular expressions. '''\n\t\t\n\t\ttry:\n\t\t\tpattern = re.compile(regex.pattern, re.VERBOSE)\n\t\texcept:\n\t\t\tprint(f'{ERR_RE_MSG}\\nName:{regex.name}\\nType:{regex.type}')\n\t\telse:\n\t\t \treturn pattern\n\n\t@staticmethod\n\tdef find_matches(pattern, name):\n\t\t\"\"\"Find matches the pass the matches to code_optimizer\n\t\t class.\"\"\"\n\t\tmatches = pattern.finditer(Regex.fixed_code)\n\t\tRegex.fixed_code = code_optimizer.optimize(matches, name, Regex.fixed_code)\n\n\t@staticmethod\n\tdef output_code():\n\t\twith open('optimizedCode.py', 'w') as output:\n\t\t\toutput.write(Regex.fixed_code)\n\n\t@staticmethod\n\tdef check_regex(code):\n\t\t'''Run over all the regular expression inside _data and check\n\t\t there validity, then passes the expression to find_matches()\n\t\t modular if any there's any match.'''\n\t\tRegex.fixed_code = code\n\t\tfor regex in Regex._data:\n\t\t\tpattern = Regex.compile_regex(regex)\n\t\t\tif(not pattern.search(code)): continue\n\t\t\telse:\n\t\t\t\tRegex.find_matches(pattern, regex.name)\n\n\t\tRegex.output_code()\n\n\t\t\n\n\t@staticmethod\n\tdef main(code_file):\n\t\t'''The analyzing starter porcess'''\n\t\t\n\t\tcode = Regex.read_code(code_file)\n\t\t\n\t\tRegex.check_regex(code)\n\ndef run_analyzer(code_file):\n\tRegex.main(code_file)\n\nif __name__ == '__main__':\n\tsys.exit()\n\n","sub_path":"wizardpy/analyzer/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"281554892","text":"import numpy as np\nfrom tensorflow.keras.optimizers import Adam\nfrom matplotlib import pyplot as plt\n\n\ndef train_with_adam(network, learning_rate, x_train, y_train, bs, n_ep, x_test, y_test):\n # Compiling the layers and setting loss & optimizer function\n network.compile(loss='binary_crossentropy',\n optimizer=Adam(lr=learning_rate),\n metrics=['binary_accuracy'])\n # Trains the model\n hist = network.fit(x_train, y_train,\n batch_size=bs, epochs=n_ep,\n validation_data=(x_test, y_test)) # Validation data is training data shuffleddef plotting(hist):\n plt.figure(figsize=(4, 4))\n plt.title(\"Learning curve\")\n plt.plot(hist.history[\"loss\"], label=\"loss\")\n plt.plot(hist.history[\"val_loss\"], label=\"val_loss\")\n plt.plot(np.argmin(hist.history[\"val_loss\"]),\n np.min(hist.history[\"val_loss\"]),\n marker=\"x\", color=\"r\", label=\"best model\")\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Loss Value\")\n plt.legend()\n plt.show()\n\n","sub_path":"functions/old_functions/train_with_adam.py","file_name":"train_with_adam.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"641178432","text":"'''\nCreated on Aug 4, 2016\n\n@author: safrant\n'''\nfrom argparse import ArgumentParser\n\nENDPOINT = []\nPROXY = []\nGRAPHNCI = []\nGRAPHGO = []\n\nSERVICEHOST=\"http://sparql-evs-dev.nci.nih.gov/sparql\"\n\nif __name__ == '__main__':\n parser = ArgumentParser(\n prog=\"checkEndpoint\",\n description=\"Federated Query test.\")\n \n args = parser.parse_args()\n \n ","sub_path":"SPARQL_Test/src/federated.py","file_name":"federated.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"629444629","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n#\n# These tests will most probably fail for you, as they rely on a specific service being up and you\n# having a RSA private key that is not on the repository. # TODO: try to make them self-sustainable\n\n# Before running these tests, you need urls to point to a properly functioning\n# SessionManager microservice. Either substitute here the domain in the urls \n# or set sessionManager to be resolved in your /etc/hosts file to the proper domain\n\nimport hashlib\nimport json\nimport unittest\nimport logging\n\nfrom lib.SMHandler import SMHandler\nfrom lib.Tools import sha256_fingerprint\nfrom lib.dto.SessionMngrResponse import SessionMngrCode, SessionMngrResponse\nfrom lib.httpsig.HttpSig import HttpError\nfrom lib.httpsig.HttpSigClient import HttpSigClient\n\n\nclass HttpSigTest(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n super(HttpSigTest, self).__init__(*args, **kwargs)\n # logging.basicConfig(level=logging.DEBUG)\n # requests_log = logging.getLogger(\"requests.packages.urllib3\")\n # requests_log.setLevel(logging.DEBUG)\n # requests_log.propagate = True\n self.init_tests()\n\n def init_tests(self):\n pass\n\n def test_calculate_fingerprint(self):\n # TODO generate a new test key\n key = 'data/httpsig_key.pem'\n fingerprint = '58f20aef58f63c28d95a57e5e7dd3e6971122ce35b5448acf36818874a0b2c0c'\n trusted_keys = ['MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJBbbirvao04+n3R0rvX2Mbq+J' +\n 'JyEl06K6hWf4MarVi6YTuJWWQb3D0mkWLATBchAntTsQsj+TH8VLkVIP3YWuOeT9' +\n '49AmfGQ1lM5FTzYmyh5wl6n1v/k7CGKqkm/WLRZD94HJE+FDhJ+ERy4/nF54n6ex' +\n 'Z1Fd4eevfzE1QqNJSQIDAQAB']\n c = HttpSigClient(key, trusted_keys)\n self.assertEqual(c.key_id, fingerprint)\n self.assertEqual(sha256_fingerprint(c.trusted_keys[0]), fingerprint)\n\n def test_https_calls(self):\n key = 'data/httpsig_key.pem'\n fingerprint = '58f20aef58f63c28d95a57e5e7dd3e6971122ce35b5448acf36818874a0b2c0c'\n key = 'data/httpsig_key_esmo.pem'\n trusted_keys = {'58f20aef58f63c28d95a57e5e7dd3e6971122ce35b5448acf36818874a0b2c0c':\n 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJBbbirvao04+n3R0rvX2Mbq+J' +\n 'JyEl06K6hWf4MarVi6YTuJWWQb3D0mkWLATBchAntTsQsj+TH8VLkVIP3YWuOeT9' +\n '49AmfGQ1lM5FTzYmyh5wl6n1v/k7CGKqkm/WLRZD94HJE+FDhJ+ERy4/nF54n6ex' +\n 'Z1Fd4eevfzE1QqNJSQIDAQAB'}\n c = HttpSigClient(key, trusted_keys)\n\n c.debug(True)\n c.validateResponse(False)\n\n res = c.postForm(\"http://sessionManager:8090/sm/startSession\")\n res = json.loads(res.text)\n sessionId = res['sessionData']['sessionId']\n self.assertIsNotNone(sessionId)\n self.assertNotEqual(sessionId, \"\")\n\n body = {\n 'sessionId': sessionId,\n 'variableName': 'testvar',\n 'dataObject': 'testvalue',\n }\n res = c.postJson('http://sessionManager:8090/sm/updateSessionData', body)\n smres = SessionMngrResponse()\n smres.json_unmarshall(res.text)\n self.assertNotEqual(smres.code, SessionMngrCode.ERROR)\n\n try:\n res = c.get(\"http://sessionManager:8090/sm/endSession?sessionId=\" + sessionId)\n except HttpError as err:\n self.assertEqual(True, False)\n\n\n# TODO: use below examples to mock HTTP calls here, in SMtests, CMtests and api tests\n'''\n\nThis is how you can do it (you can run this file as-is):\n\nimport requests\nimport unittest\nfrom unittest import mock\n\n# This is the class we want to test\nclass MyGreatClass:\n def fetch_json(self, url):\n response = requests.get(url)\n return response.json()\n\n# This method will be used by the mock to replace requests.get\ndef mocked_requests_get(*args, **kwargs):\n class MockResponse:\n def __init__(self, json_data, status_code):\n self.json_data = json_data\n self.status_code = status_code\n\n def json(self):\n return self.json_data\n\n if args[0] == 'http://someurl.com/test.json':\n return MockResponse({\"key1\": \"value1\"}, 200)\n elif args[0] == 'http://someotherurl.com/anothertest.json':\n return MockResponse({\"key2\": \"value2\"}, 200)\n\n return MockResponse(None, 404)\n\n# Our test case class\nclass MyGreatClassTestCase(unittest.TestCase):\n\n # We patch 'requests.get' with our own method. The mock object is passed in to our test case method.\n @mock.patch('requests.get', side_effect=mocked_requests_get)\n def test_fetch(self, mock_get):\n # Assert requests.get calls\n mgc = MyGreatClass()\n json_data = mgc.fetch_json('http://someurl.com/test.json')\n self.assertEqual(json_data, {\"key1\": \"value1\"})\n json_data = mgc.fetch_json('http://someotherurl.com/anothertest.json')\n self.assertEqual(json_data, {\"key2\": \"value2\"})\n json_data = mgc.fetch_json('http://nonexistenturl.com/cantfindme.json')\n self.assertIsNone(json_data)\n\n # We can even assert that our mocked method was called with the right parameters\n self.assertIn(mock.call('http://someurl.com/test.json'), mock_get.call_args_list)\n self.assertIn(mock.call('http://someotherurl.com/anothertest.json'), mock_get.call_args_list)\n\n self.assertEqual(len(mock_get.call_args_list), 3)\n\nif __name__ == '__main__':\n unittest.main()\n\n\nImportant Note: If your MyGreatClass class lives in a different package, say my.great.package, you have to mock my.great.package.requests.get instead of just 'request.get'. In that case your test case would look like this:\n\nimport unittest\nfrom unittest import mock\nfrom my.great.package import MyGreatClass\n\n# This method will be used by the mock to replace requests.get\ndef mocked_requests_get(*args, **kwargs):\n # Same as above\n\n\nclass MyGreatClassTestCase(unittest.TestCase):\n\n # Now we must patch 'my.great.package.requests.get'\n @mock.patch('my.great.package.requests.get', side_effect=mocked_requests_get)\n def test_fetch(self, mock_get):\n # Same as above\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n'''","sub_path":"test/HttpSigClient.py","file_name":"HttpSigClient.py","file_ext":"py","file_size_in_byte":6238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"107140172","text":"\n#python libraries\nfrom types import ListType, TupleType, IntType\nfrom socket import timeout\n\n# nps libraries\nfrom networkedpowersupply import NetworkedPowerSupply\nfrom errors import FaucetteError\n\n#apetools\nfrom apetools.baseclass import BaseClass\nfrom apetools.commons import errors\n\nAffectorError = errors.AffectorError\nConfigurationError = errors.ConfigurationError\n\n\nclass NaxxxError(AffectorError):\n \"\"\"\n A NaxxxError is raised if there is a problem with the Naxxx\n \"\"\"\n pass\n\n\nclass Naxxx(BaseClass):\n \"\"\"\n An adapter to the nps to reduce the interface.\n \n \"\"\"\n def __init__(self, hostname, clear=False, retries=5):\n \"\"\"\n :param:\n - `hostname` : IP address of the Elexol device.\n - `clear` : Bool indicating whether or not NPS will disable all plugs at start\n - `retries` : Number of times to retry if communication with Elexol fails.\n \"\"\" \n super(Naxxx, self).__init__()\n self.hostname = hostname\n self.clear = clear\n self.retries = retries\n self._naxxx = None\n return\n\n @property\n def naxxx(self):\n \"\"\"\n :rtype: NetworkedPowerSupply\n :return: Controller for the networked power supply\n \"\"\"\n if self._naxxx is None:\n self._naxxx = NetworkedPowerSupply(IP=self.hostname,\n clear=self.clear,\n retry=self.retries)\n self.logger.debug(\"Created {0}\".format(self._naxxx))\n return self._naxxx\n\n def _clean_outlets(self, outlets):\n \"\"\"\n The option to pass in a single castable object allows the caller\n to pass in a generic parameters object.\n \n :param:\n\n - `outlets`: List, Tuple, or something castable to an int\n \n :return: list of integers\n \"\"\"\n if type(outlets) not in (ListType, TupleType):\n try:\n outlets = [int(outlets)]\n except ValueError as error:\n self.logger.error(error)\n raise FaucetteError(\"Invalid Identifier: {0}\".format(outlets))\n else:\n try:\n outlets = [int(outlet) for outlet in outlets]\n except (ValueError, TypeError) as error:\n self.logger.error(error)\n raise FaucetteError(\"Unable to turn on {0}\".format(outlets))\n assert all((type(outlet) is IntType for outlet in outlets))\n return outlets\n\n def run(self, outlets):\n \"\"\"\n For each id in outlets, turn on the given outlet\n Turns off all outlets not in outlets.\n\n :param:\n\n - `outlets`: ID of power switch to turn on. Or list of ID's.\n\n :raise:\n\n - `NaxxxError`: If connection (socket) times-out.\n - `FaucetteError`: If there is a problem with the outlet identifiers.\n\n :postcondition: Only switches in `outlets` are on.\n \"\"\"\n self.logger.info(\"Turning on Power Outlet(s): {0}\".format(outlets))\n outlets = self._clean_outlets(outlets)\n try:\n self.naxxx.turn_on_switches(outlets, turn_others_off=True)\n except (TypeError, timeout) as error:\n self.logger.error(error)\n raise NaxxxError(\"Unable to connect to the Naxxx - check your LAN connection.\")\n return\n\n def __call__(self, parameters):\n \"\"\"\n turns on parameters.naxxx.identifier (this is backwards, maybe I'll fix it)\n \"\"\"\n self.run(parameters.naxxx.parameters.identifier)\n return parameters.naxxx.parameters.switch\n# end class NAXXX\n","sub_path":"apetools/affectors/elexol/naxxx.py","file_name":"naxxx.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"638310844","text":"# coding: utf-8\n\nfrom CScanPoc.thirdparty import requests\nfrom CScanPoc import ABPoc, ABVuln, VulnLevel, VulnType\n\n\nclass Vuln(ABVuln):\n vuln_id = 'WordPress_0100_L' # 平台漏洞编号\n name = 'Wordpress插件Single Personal Message SQL注入' # 漏洞名称\n level = VulnLevel.HIGH # 漏洞危害级别\n type = VulnType.INJECTION # 漏洞类型\n disclosure_date = '2016-12-09' # 漏洞公布时间\n desc = '''\n WordPress是一个基于PHP和MySQL的免费开源内容管理系统(CMS)。功能包括插件架构和模板系统。它与博客最相关,但支持其他类型的网络内容,包括更传统的邮件列表和论坛,媒体画廊和在线商店。截至2018年4月,超过6000万个网站使用,包括前1000万个网站的30.6%,WordPress是最受欢迎的网站管理系统正在使用中。WordPress也被用于其他应用领域,如普适显示系统(PDS)。\n Wordpress插件Single Personal Message的admin.php页面的message参数存在SQL注入漏洞。由于程序未能充分过滤用户提交的输入,攻击者可以通过该漏洞控制应用程序,访问或修改数据,或利用底层数据库中潜在的漏洞。\n ''' # 漏洞描述\n ref = 'http://www.cnvd.org.cn/flaw/show/CNVD-2016-12076'\n cnvd_id = 'CNVD-2016-12076' # cnvd漏洞编号\n cve_id = 'CVE-2017-1002026' # cve编号\n product = 'WordPress' # 漏洞组件名称\n product_version = 'WordPress Single Personal Message 1.0.3' # 漏洞应用版本\n\n\nclass Poc(ABPoc):\n poc_id = 'c99ef374-efee-425f-8962-1b58269f8537' # 平台 POC 编号\n author = '国光' # POC编写者\n create_date = '2018-08-01' # POC创建时间\n\n def __init__(self):\n super(Poc, self).__init__(Vuln())\n self.option_schema = {\n 'properties': {\n 'base_path': {\n 'type': 'string',\n 'description': '部署路径',\n 'default': '',\n '$default_ref': {\n 'property': 'deploy_path'\n }\n },\n 'cookie': {\n 'type': 'string',\n 'description': '登录cookie',\n 'default': '',\n }\n }\n }\n\n def verify(self):\n self.target = self.target.rstrip(\n '/') + '/' + (self.get_option('base_path').lstrip('/'))\n try:\n self.output.info('开始对 {target} 进行 {vuln} 的扫描'.format(\n target=self.target, vuln=self.vuln))\n arg = '{target}'.format(target=self.target)\n payload = \"/wp-admin/admin.php?page=simple-personal-message-outbox&action=view&message=0%20UNION%20SELECT%201,2.3,md5(233),5,6slug,7,8,9,10,11,12%20FROM%20wp_terms%20WHERE%20term_id=1\"\n\n vul_url = arg + payload\n headers = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Cookie': self.get_option('cookie')\n }\n response = requests.get(vul_url, headers=headers)\n self.output.info(\"正在执行SQL注入测试语句\")\n if response.status_code == 200 and 'e165421110ba03099a1c0393373c5b43' in response.text:\n self.output.report(self.vuln, '发现{target}存在{name}漏洞'.format(\n target=self.target, name=self.vuln.name))\n except Exception as e:\n self.output.info('执行异常{}'.format(e))\n\n def exploit(self):\n self.verify()\n\n\nif __name__ == '__main__':\n Poc().run()\n","sub_path":"pocs/cms/WordPress/WordPress_0100_L.py","file_name":"WordPress_0100_L.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"494861582","text":"# Copyright (c) 2021 The University of Manchester\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nSet a job from the queue to \"Error\" status.\n\nAuthentication parameters can be found in the config files on the server.\n\"\"\"\nimport argparse\nimport requests\n\nNMPI_URL = \"https://nmpi.hbpneuromorphic.eu/api/v2/queue/{}\"\nNMPI_LOG_URL = \"https://nmpi.hbpneuromorphic.eu/api/v2/log/{}\"\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"job\", help=\"The Job ID\")\nparser.add_argument(\"username\", help=\"The username to authenticate with\")\nparser.add_argument(\"token\", help=\"The token to authenticate with\")\n\nargs = parser.parse_args()\nheaders = {\n \"Authorization\": \"ApiKey {}:{}\".format(args.username, args.token),\n \"Content-Type\": \"application/json\"\n}\n\njob_url = NMPI_URL.format(args.job)\nresponse = requests.get(job_url, headers=headers)\njob = response.json()\nprint(job)\n\njob[\"status\"] = \"submitted\"\nput_response = requests.put(job_url, json=job, headers=headers)\nprint(\"Job update response:\", put_response)\n","sub_path":"nmpi/set_job_submitted.py","file_name":"set_job_submitted.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"586040743","text":"import os\r\nimport tensorflow as tf\r\nfrom model import *\r\nfrom datas import *\r\n\r\n\r\n\r\ndef start_train():\r\n m = model(True)\r\n d = datas()\r\n loss = m.loss()\r\n train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)\r\n init = tf.initialize_all_variables()\r\n\r\n\r\n sess = tf.Session()\r\n saver = tf.train.Saver() \r\n sess.run(init)\r\n\r\n try:\r\n\t saver.restore(sess, \"./mod/m.ckpt\")\r\n\t print(\"load model\")\r\n except:\r\n\t print(\"no model\")\r\n\r\n for i in range(100000):\r\n batch_xs, batch_ys = d.getbatch()\r\n sess.run(train_step, feed_dict={m.input: batch_xs, m.label: batch_ys})\r\n\r\n if i % 100 ==0:\r\n loss_value = sess.run(loss, feed_dict={m.input: batch_xs, m.label: batch_ys})\r\n y_value = sess.run(m.output, feed_dict={m.input: batch_xs, m.label: batch_ys})\r\n #print(y_value)\r\n print(\"loss %f\" % loss_value)\r\n print(\"save model epoch %d \" % i)\r\n saver.save(sess, (\"./mod/m.ckpt\"))\r\n\r\n\r\nif __name__ == '__main__':\r\n start_train()","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"560195707","text":"# -*- coding: utf-8 -*-\nimport random\nimport math\nimport numpy as np\nfrom collections import deque\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom keras.models import model_from_json\nfrom keras.models import load_model\nimport h5py\nimport time\nimport game\nimport util\nimport models\nfrom pystockfish import *\n\n###############################################################################\n# Training\n###############################################################################\n\nif __name__ == \"__main__\":\n '''\n Modes\n - if with_teacher is set to True, then train with teacher\n '''\n with_teacher = True\n episodes_per_student = 25\n EPISODES = 250\n student_action_size = 1856\n start_episode = 0\n teacher_agent = models.TeacherAgent()\n student_agent = models.StudentAgent()\n teacher_agent.load('save/teacher.h5')\n #student_agent.load('save/with_random_25.h5')\n batch_size = 8\n scores_list = []\n matched_list = []\n rounds_list = []\n mat_diff_list = []\n\n # Creating a list of all possible actions of student agent on the chessboard\n possible_actions = util.get_possible_actions(student_action_size)\n\n for e in range(EPISODES):\n if e % 25 == 0: # 10 games per student\n if with_teacher:\n filename = 'save/with_teacher_' + str(int((e / 25 + 1) * 25)) + '.h5'\n else:\n filename = 'save/without_teacher_' + str(int((e / 25 + 1) * 25)) + '.h5'\n student_agent.load(filename)\n print('testing {}: {}'.format(filename, str(int((e / 25 + 1) * 25))))\n start_time = time.time()\n print_game = (e + 1) % 25 == 0\n check_mated_yet = False\n print (\"episode: \", e)\n deep = Engine(depth=20) # Initialize Stockfish\n final_score = 0 # Initialize final score for the game\n done = False\n pos = game.Position(util.initial, 0, (True,True), (True,True), 0, 0)\n searcher = game.Searcher()\n moves_list = []\n round = 0\n matched = 0\n while True:\n round += 1\n if print_game:\n game.print_pos(pos)\n state = util.toBit(pos)\n before_output_list = deep.bestmove()['info'].split(\" \")\n if 'mate' in before_output_list:\n if util.inCheck(pos, True):\n print(\"You lost, but you're getting there little one\")\n else:\n print(\"Huh. Stalemate. \")\n end_time = time.time()\n duration = end_time - start_time\n print(\"episode: {}/{}, number of rounds: {}, score: {}, e: {:.2}, time : {}\"\n .format(e, EPISODES, round, final_score / float(round), student_agent.epsilon, duration / 60.0))\n scores_list.append(final_score / float(round))\n matched_list.append(float(matched) / float(round))\n rounds_list.append(round)\n mat_diff = util.get_material_difference(pos)\n mat_diff_list.append(mat_diff)\n done = True\n #game.print_pos(pos)\n break\n else:\n score_before_model_move = (-1)*int(before_output_list[9]) # changed from 9\n\n # get possible valid moves of student\n possibly_valid_moves = [m for m in pos.gen_moves(False)]\n possibly_valid_move_indices = [possible_actions.index(gm) for gm in possibly_valid_moves]\n\n '''Begin check for check code'''\n valid_move_indices = []\n for index in possibly_valid_move_indices:\n newPos = pos.getNewState(possible_actions[index])\n if not util.inCheck(newPos, True):\n valid_move_indices.append(index)\n if len(valid_move_indices) == 0:\n if util.inCheck(pos, True):\n print(\"You lost, but you're getting there little one\")\n else:\n print(\"Huh. Stalemate. \")\n end_time = time.time()\n duration = end_time - start_time\n print(\"episode: {}/{}, number of rounds: {}, score: {}, e: {:.2}, time : {}\"\n .format(e, EPISODES, round, final_score / float(round), student_agent.epsilon, duration / 60.0))\n scores_list.append(final_score / float(round))\n matched_list.append(float(matched) / float(round))\n rounds_list.append(round)\n mat_diff = util.get_material_difference(pos)\n mat_diff_list.append(mat_diff)\n done = True\n #game.print_pos(pos)\n break\n ''' End check for check code'''\n\n dqn_move_index = student_agent.act(state, valid_move_indices)\n output = deep.bestmove()\n best_move = (util.convert_to_nums(output['move'][0:2]),util.convert_to_nums(output['move'][2:]))\n if best_move[0] == None or best_move[1] == None:\n matched += 0\n else:\n best_move_index = possible_actions.index(best_move)\n if dqn_move_index == best_move_index:\n matched += 1\n\n # STUDENT ACTUALLY ACTS #\n dqn_move = possible_actions[dqn_move_index]\n # flip move\n flipped_dqn_move = util.flip_move(dqn_move)\n pos = pos.move(dqn_move, True) ## used to be new_dqn_move\n # update stockfish based on DQN action\n dqn_move_stockfish = game.render(119-flipped_dqn_move[0]) + game.render(119-flipped_dqn_move[1]) ## used to be dqn_move\n moves_list.append(dqn_move_stockfish)\n deep.setposition(moves_list)\n\n\n # compute score of board after student agent makes action\n after_output = deep.bestmove()\n after_output_list = after_output['info'].split(\" \")\n if 'mate' in after_output_list:\n if util.inCheck(pos, True):\n print(\"You lost, but you're getting there little one\")\n else:\n print(\"Huh. Stalemate. \")\n end_time = time.time()\n duration = end_time - start_time\n print(\"episode: {}/{}, number of rounds: {}, score: {}, e: {:.2}, time : {}\"\n .format(e, EPISODES, round, final_score / float(round), student_agent.epsilon, duration / 60.0))\n scores_list.append(final_score / float(round))\n matched_list.append(float(matched) / float(round))\n rounds_list.append(round)\n mat_diff = util.get_material_difference(pos)\n mat_diff_list.append(mat_diff)\n done = True\n break\n else:\n score_after_model_move = (-1)*int(after_output['info'].split(\" \")[9]) # changed from 9\n\n # Q-Learning\n pos.rotate()\n reward = score_after_model_move - score_before_model_move\n final_score += reward\n\n if print_game:\n game.print_pos(pos.rotate())\n else:\n pos.rotate()\n\n # ''' Teacher Q-learning '''\n\n '''Begin check for check code'''\n possibly_valid_moves = [m for m in pos.gen_moves(True)]\n possibly_valid_move_indices = [possible_actions.index(gm) for gm in possibly_valid_moves]\n valid_move_indices = []\n for index in possibly_valid_move_indices:\n newPos = pos.getNewState(possible_actions[index])\n if not util.inCheck(newPos, True):\n valid_move_indices.append(index)\n if len(valid_move_indices) == 0:\n if util.inCheck(pos, True):\n print(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n print(\"Hahaha! We won.\")\n print(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\n else:\n print(\"Hahaha! Stalemate. \")\n end_time = time.time()\n duration = end_time - start_time\n print(\"episode: {}/{}, number of rounds: {}, score: {}, e: {:.2}, time : {}\"\n .format(e, EPISODES, round, final_score / float(round), student_agent.epsilon, duration / 60.0))\n scores_list.append(final_score / float(round))\n print(\"scores list\")\n print (scores_list)\n matched_list.append(float(matched) / float(round))\n print(\"number of matches list\")\n print (matched_list)\n print(\"number of rounds list\")\n rounds_list.append(round)\n print(rounds_list)\n print(\"material differences list\")\n mat_diff = util.get_material_difference(pos)\n mat_diff_list.append(mat_diff)\n print(mat_diff_list)\n done = True\n #game.print_pos(pos)\n break\n\n ''' End check for check code'''\n\n ''' if there is a problem in the future with valid moves, it might be because sunfish moves into check '''\n\n # Opponent takes an action\n opponent_move, score = searcher.search(pos, secs=2)\n opponent_move_stockfish = game.render(119-opponent_move[0]) + game.render(119-opponent_move[1])\n pos = pos.move(opponent_move, False)\n moves_list.append(opponent_move_stockfish)\n deep.setposition(moves_list)\n","sub_path":"environment/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":9663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"214919693","text":"import numpy as np\nfrom matplotlib import pyplot as plt\n\n#routine to calculate the sine coefficients for a thin strip from x=0 to x=a held at potential V0\n\na=5.0\nx=np.linspace(0,a,1000)\nz=np.linspace(0,0.5*a,2000)\npot=0*x\nV0=1.5\n\nkmax=500\nckvec=np.zeros(kmax)\npotmat=0\nsigma=0.0\nfor k in range(1,kmax,2):\n ck=4.0*V0/k/np.pi\n ckvec[k]=ck\n pot=pot+ck*np.sin(np.pi*k*x/a)\n potmat=potmat+np.outer(ck*np.sin(x*np.pi*k/a),np.exp(-z*np.pi*k/a))\n sigma=sigma+np.sin(x*np.pi*k/a)*ck*k*np.pi/a\n\nplt.ion()\n\nplt.figure(1)\nplt.clf()\nplt.plot(x,pot)\n\nplt.figure(2)\nplt.clf()\nplt.imshow(potmat,extent=[0,z.max(),0,x.max()],aspect='auto')\nplt.colorbar()\n\n","sub_path":"lecture_12/2d_strip.py","file_name":"2d_strip.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"235553147","text":"from collections import deque\n\n\ndef solution(bridge_length, weight, truck_weights):\n answer = 0\n truck_weights = deque(truck_weights) # 대기 중인 트럭\n on_bridge = deque([0] * bridge_length) # 건너는 트럭\n total_weights = 0 # 도로 위 트럭 무게\n\n while on_bridge: # 다리에 트럭이 없을 때까지 진행\n answer += 1\n total_weights -= on_bridge.popleft()\n\n if truck_weights: # 대기 중인 트럭이 있으면\n if total_weights + truck_weights[0] <= weight: # 견디는 무게보다 작다면\n going_truck = truck_weights.popleft()\n on_bridge.append(going_truck) # 트럭 출발\n total_weights += going_truck # 도로 위 트럭 무게 증가\n\n else: # 견디는 무게보다 크면 다리를 통과 못하니 0 추가\n on_bridge.append(0)\n\n return answer","sub_path":"Programmers/Level2/다리를 지나는 트럭/solving.py","file_name":"solving.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"50818961","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport codecs\nfrom setuptools import setup\n\nimport versioneer\n\n\ndef read(fname):\n file_path = os.path.join(os.path.dirname(__file__), fname)\n return codecs.open(file_path, encoding='utf-8').read()\n\n\nsetup(\n name='pytest-nbsmoke',\n version=versioneer.get_version(),\n author='pytest-nbsmoke contributors',\n license='BSD-3',\n url='https://github.com/pyviz/nbsmoke',\n description='Deprecated: now nbsmoke (see https://github.com/pyviz/nbsmoke).',\n long_description=read('README.txt'),\n py_modules=['pytest_nbsmoke'],\n install_requires=['pytest>=3.1.1',\n 'jupyter_client',\n 'ipykernel',\n 'nbformat',\n 'nbconvert',\n 'pyflakes'],\n classifiers=[\n 'Development Status :: 7 - Inactive',\n ],\n entry_points={\n 'pytest11': [\n 'nbsmoke = pytest_nbsmoke',\n ],\n },\n)\n","sub_path":"pypi_install_script/pytest-nbsmoke-0.1.7.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"515032565","text":"#importamos un modulo\r\nimport random\r\n#definimos una variable float con un valor\r\nnumero1=float(6.9)\r\n#usamos una funcion\r\ndef miFuncion():\r\n #convertimos a float el numero random\r\n numero2=float(random.randrange(1,10))\r\n mensaje=\"La suma de {} y {} es {}\"\r\n print(mensaje.format(numero1,numero2,numero1+numero2))\r\n\r\n#ejecutamos la funcion del codigo\r\nmiFuncion()\r\n","sub_path":"Aleatorio.py","file_name":"Aleatorio.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"333182853","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 19 13:34:25 2018\n\n@author: yordan\n\"\"\"\nimport numpy as np\nimport pickle\nimport pandas as pd\nfrom netcdftime import utime\nimport netCDF4 as nc\n\ndef ciclo_diurno_anual(matriz, fechas, len_lat, len_lon):\n\t#matriz : matriz de numpy de 3 dimensiones donde cada capa corresponde a una fecha en el vector de pandas \"fechas\"\n\t#fechas : objeto de pandas con las fechas que corresponden a cada una de las capas en matríz\n\t#len_lat: integer cantidad de pixeles en direccion meridional\n\t#len_lon: integer cantidad de pixeles en direccion zonal\n\n\t#return: devuelve diccionario con ciclo diuno para cada mes\n\tDict_ciclo = {}\n\tfor i, mes in enumerate(['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic']):\n\t\tfor j, hora in enumerate(['0', '6', '12', '18']):\n\t\t\tpos = np.where((fechas.month == i+1 ) & (fechas.hour == int(hora)))[0]\n\t\t\tM = np.zeros((len(pos), len_lat, len_lon))\n\n\t\t\tfor k, l in enumerate(pos):\n\t\t\t\tM[k] = matriz[l]\n\n\t\t\tmedia = np.mean(M, axis=0)\n\n\t\t\tDict_ciclo.update({mes+'_'+hora:media})\n\n\treturn Dict_ciclo\n\n\"Se leen datos de viento a resolución de 0.25 grados\"\narchivo = nc.Dataset('/home/yordan/YORDAN/UNAL/TRABAJO_DE_GRADO/DATOS_Y_CODIGOS/DATOS/UyV_1979_2016_res025.nc')\nlat = archivo.variables['latitude'][:]; lon = archivo.variables['longitude'][:]-360\n\n\"Fechas\"\ntime = archivo['time'][:]\ncdftime = utime('hours since 1900-01-01 00:00:0.0', calendar='gregorian')\nfechas = [cdftime.num2date(x) for x in time]\nDATES = pd.DatetimeIndex(fechas)[:]\n\n\"Viento\"\nv = archivo['v10'][:] # Para quedar con las mismas fechas del archivo U y V, 6 horas, 10 m, 1979-2016.nc, con el que se hizo\nu = archivo['u10'][:] # Para quedar con las mismas fechas del archivo U y V, 6 horas, 10 m, 1979-2016.nc, con el que se hizo\nwnd = np.sqrt(v*v+u*u)\n\n\"Se calcula ciclo anual de ciclo diurno\"\nCICLO_WND = ciclo_diurno_anual(wnd, DATES, len(lat), len(lon))\nCICLO_U = ciclo_diurno_anual(u, DATES, len(lat), len(lon))\nCICLO_V = ciclo_diurno_anual(v, DATES, len(lat), len(lon))\n\npunto_bin = open('/home/yordan/YORDAN/UNAL/TESIS_MAESTRIA/13_expo_2018/ciclo_diurno_anual_wind_025_6h.bin','wb')\npickle.dump(CICLO_WND, punto_bin)\npunto_bin = open('/home/yordan/YORDAN/UNAL/TESIS_MAESTRIA/13_expo_2018/ciclo_diurno_anual_wind_025_6h.bin','wb')\npickle.dump(CICLO_WND, punto_bin)\n\npunto_bin = open('/home/yordan/YORDAN/UNAL/TESIS_MAESTRIA/13_expo_2018/ciclo_diurno_anual_U_025_6h.bin','wb')\npickle.dump(CICLO_U, punto_bin)\npunto_bin = open('/home/yordan/YORDAN/UNAL/TESIS_MAESTRIA/13_expo_2018/ciclo_diurno_anual_U_025_6h.bin','wb')\npickle.dump(CICLO_U, punto_bin)\n\npunto_bin = open('/home/yordan/YORDAN/UNAL/TESIS_MAESTRIA/13_expo_2018/ciclo_diurno_anual_V_025_6h.bin','wb')\npickle.dump(CICLO_V, punto_bin)\npunto_bin = open('/home/yordan/YORDAN/UNAL/TESIS_MAESTRIA/13_expo_2018/ciclo_diurno_anual_V_025_6h.bin','wb')\npickle.dump(CICLO_V, punto_bin)\n","sub_path":"13_expo_2018/ciclo_diurno_anual_wind_025_6h.py","file_name":"ciclo_diurno_anual_wind_025_6h.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"469702558","text":"# -*- coding: utf-8 -*-\n#############################################################################\n# OpenERP, Open Source Management Solution #\n# Copyright (C) 2013 ed.winTG, www.syscod.com #\n# #\n# This program is free software: you can redistribute it and/or modify #\n# it under the terms of the GNU General Public License as published by #\n# the Free Software Foundation, either version 3 of the License, or #\n# (at your option) any later version. #\n# #\n# This program is distributed in the hope that it will be useful, #\n# but WITHOUT ANY WARRANTY; without even the implied warranty of #\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #\n# GNU General Public License for more details. #\n# #\n# You should have received a copy of the GNU General Public License #\n# along with this program. If not, see . #\n#############################################################################\n\n\n\nimport logging\nfrom osv import fields, osv\nimport netsvc, tools\nimport time\nfrom tools.translate import _\n\n_logger = logging.getLogger(__name__)\n\n\n\nclass ecua_ndd(osv.osv):\n _name = 'ecua.ndd'\n _inherits={'documentos.complementarios':'document_id'}\n _description='Debit Notes'\n\n def check_ref(self, cr, uid, ids):\n partner_obj = self.pool.get('res.partner')\n for data in self.browse(cr, uid, ids):\n return partner_obj.check_ced(data.ruc).get('valid', False)\n \n def _default_company(self, cr, uid, context=None):\n user = self.pool.get('res.users').browse(cr, uid, uid, context=context)\n return user.company_id and user.company_id.id or False\n\n _columns = {\n 'document_id': fields.many2one('documentos.complementarios','Document',ondelete='cascade'),\n 'ndd_line_ids':fields.one2many('ecua.ndd_line','ecua_ndd_id','Lineas N. Debito'), \n 'ndd_concept':fields.selection([\n ('error','Error de Facturacion'),\n ('interes','Intereses'),\n ('flete','Gastos por fletes'),\n ('banco','Gastos bancarios')],'Concepto', select=True),\n }\n\n _defaults = {'company_id':_default_company,\n 'denominacion': 'Debit Note',\n 'is_ndd': lambda *a: 1, \n 'state': 'draft',\n }\n \n def onChange_comprobante(self, cr, uid, ids, comprobante_id, context=None):\n values={}\n comprobant=self.pool.get('account.invoice').browse(cr, uid,comprobante_id, context)\n values['customer_name']=comprobant.partner_id.name\n values['customer_ruc']=comprobant.partner_id.ref\n if comprobant.period_id:\n values['ejercicio_fiscal']=comprobant.period_id.fiscalyear_id.name\n #phone para el telefono\n address=\"\";\n if(comprobant.partner_id.street):\n address=comprobant.partner_id.street\n if (comprobant.partner_id.street2):\n address=address+\" & \"+comprobant.partner_id.street2 \n if(comprobant.partner_id.city):\n address=address+\" - \"+comprobant.partner_id.city \n values['customer_dir']=address\n return {'value': values}\n \n def onchange_data(self, cr, uid, ids, doc_number, shop_id=None, date=None, context=None):\n if context is None: context = {}\n shops_domain_ids = []\n domain = {}\n values={} \n warning = {}\n if not doc_number and not shop_id:\n return {}\n if not doc_number:\n warning = {\n 'title': _('Warning!!!'),\n 'message': _('Document must have a printer point selected to validate number!!!'),\n }\n return {'warning': warning}\n printer_obj = self.pool.get('sri.printer.point')\n doc_obj=self.pool.get('sri.type.document')\n auth_obj = self.pool.get('sri.authorization')\n shop_obj = self.pool.get('sale.shop')\n curr_user = self.pool.get('res.users').browse(cr, uid, uid, context)\n curr_shop = shop_id and shop_obj.browse(cr, uid, shop_id, context) or None\n journal_id = curr_shop.sales_journal_id and curr_shop.sales_journal_id.id or None\n name_document = 'credit_note'\n name_field = 'doc_number'\n values['journal_id'] = journal_id\n printer = None\n if curr_user.printer_default_id:\n printer = curr_user.printer_default_id\n if not printer:\n for shop in curr_user.shop_ids:\n for printer_id in shop.printer_point_ids:\n printer = printer_id\n break\n if printer:\n values['shop_id'] = printer.shop_id.id\n values['printer_id'] = printer.id\n printer_id=printer.id\n \n #import pdb\n #pdb.set_trace() \n \n if curr_shop:\n if doc_number and printer_id:\n shops_domain_ids.append(curr_shop.id)\n auth = self.pool.get('sri.authorization').check_if_seq_exist(cr, uid, name_document, doc_number, printer_id , date, context)\n authorization = auth and auth_obj.browse(cr, uid, auth['authorization'], context) or None\n values['num_atoriza'] = authorization.number \n values['shop_id'] = curr_shop.id\n values['autoriza_date_emision'] = authorization.start_date\n values['autoriza_date_expire'] = authorization.expiration_date \n else:\n curr_user.printer_default_id and curr_user.printer_default_id.shop_id and shops_domain_ids.append(curr_user.printer_default_id.shop_id.id)\n for shop_allowed in curr_user.shop_ids:\n shops_domain_ids.append(shop_allowed.id)\n auth_line_id = doc_obj.search(cr, uid, [('name','=',name_document), ('printer_id','=',printer_id), ('state','=',True)])\n if auth_line_id:\n auth_line = doc_obj.browse(cr, uid, auth_line_id[0],context)\n values['num_atoriza'] = auth_line.sri_authorization_id.number\n values['autoriza_date_emision'] = auth_line.sri_authorization_id.start_date\n values['autoriza_date_expire'] = auth_line.sri_authorization_id.expiration_date\n next_number = doc_obj.get_next_value_secuence(cr, uid, name_document, False, printer_id, 'ecua.ndd', name_field, context)\n values[name_field] = next_number#'001-001-000000005'\n values['fecha_emision'] = time.strftime('%Y-%m-%d')\n else:\n if printer_id and curr_shop:\n printer = printer_obj.browse(cr, uid, printer_id, context)\n warning = {\n 'title': _(\"There's not any authorization for generate documents for data input: Agency %s Printer Point %s\") % (curr_shop.number, printer.name)\n }\n domain['shop_id'] = [('id','in', shops_domain_ids)]\n return {'value': values, 'domain':domain, 'warning': warning}\n \n def default_get(self, cr, uid, fields_list, context=None):\n if context is None:\n context = {}\n doc_obj=self.pool.get('sri.type.document')\n values={}\n if not values:\n values={}\n curr_user = self.pool.get('res.users').browse(cr, uid, uid, context)\n values['ruc'] = curr_user.company_id.ruc\n #ADDRESS COMPANY\n address=\"\";\n if(curr_user.company_id.street):\n address=curr_user.company_id.street\n if (curr_user.company_id.street2):\n address=address+\" & \"+curr_user.company_id.street2 \n if(curr_user.company_id.city):\n address=address+\" - \"+curr_user.company_id.city \n values[\"dir_matriz\"]=address\n values[\"company_id\"]=curr_user.company_id.id\n #Hay que primero agregar un campo direccion en sales.shop...o tienda para poder sacar este campo\n values[\"dir_sucursal\"]=address \n values[\"nom_comercial\"]=curr_user.company_id.name\n #Hay que primero agregar este campo en res.company, para poder sacar este campo\n values[\"razon_social\"]=curr_user.company_id.name \n printer = None\n if curr_user.printer_default_id:\n printer = curr_user.printer_default_id\n if not printer:\n for shop in curr_user.shop_ids:\n for printer_id in shop.printer_point_ids:\n printer = printer_id\n break\n if printer:\n values['shop_id'] = printer.shop_id.id\n values['printer_id'] = printer.id\n if ('doc_number') in fields_list:\n auth_line_id = doc_obj.search(cr, uid, [('name','=','debit_note'), ('printer_id','=',printer.id), ('state','=',True)])\n if auth_line_id:\n auth_line = doc_obj.browse(cr, uid, auth_line_id[0],context)\n values['num_atoriza'] = auth_line.sri_authorization_id.number\n values['autoriza_date_emision'] = auth_line.sri_authorization_id.start_date\n values['autoriza_date_expire'] = auth_line.sri_authorization_id.expiration_date\n values['doc_number'] = doc_obj.get_next_value_secuence(cr, uid, 'debit_note', False, printer.id, 'ecua.ndd', 'doc_number', context)\n values['fecha_emision'] = time.strftime('%Y-%m-%d')\n values['denominacion']='Nota de debito'\n return values\n \n \n\n def do_payment(self, cr, uid, ids, data, context=None):\n import pdb\n if context is None:\n context = {}\n move_pool = self.pool.get('account.move')\n move_line_pool = self.pool.get('account.move.line')\n journal_pool = self.pool.get('account.journal')\n period_pool = self.pool.get('account.period')\n timenow = time.strftime('%Y-%m-%d')\n for slip in self.browse(cr, uid, ids, context=context):\n journal_id = slip.journal_id.id\n move_line_ids = []\n debit_sum = 0.0\n credit_sum = 0.0\n journal = journal_pool.browse(cr, uid, journal_id, context=context)\n if not slip.period_id:\n search_periods = period_pool.find(cr, uid, slip.date_to, context=context)\n period_id = search_periods[0]\n else:\n period_id = slip.period_id.id\n\n #default_partner_id = slip.employee_id.address_home_id.id\n #name = _('Payslip of %s') % (slip.partner_id.name) #employee_id\n name = ('Nota de Debito por %s') % (slip.ndd_concept)\n move = {\n 'narration': name,\n 'date': timenow,\n 'ref': slip.doc_number,\n 'journal_id': slip.journal_id.id,\n 'period_id': period_id,\n }\n for line in slip.ndd_line_ids:\n amt_tax = 0.0\n amt = slip.valor_total and -line.valor_modifica or line.valor_modifica\n amtd = 0.0\n # partner_id = line.salary_rule_id.register_id.partner_id and line.salary_rule_id.register_id.partner_id.id or default_partner_id\n partner_id = slip.partner_id.id\n #debit_account_id = line.salary_rule_id.account_debit.id\n #credit_account_id = line.salary_rule_id.account_credit.id\n debit_account_id = slip.num_comprob_venta.account_id.id\n credit_account_id = slip.journal_id.default_debit_account_id.id\n import pdb\n pdb.set_trace()\n for tax in line.invoice_line_tax_id:\n amt_tax = tax.amount * amt\n tax_credit_line = (0, 0, {\n 'name': line.motivo_modifica,\n 'date': timenow,\n 'partner_id': slip.partner_id.id,\n 'account_id': tax.account_paid_id.id,\n #'account_id': debit_account_id,\n 'journal_id': slip.journal_id.id,\n 'period_id': period_id,\n 'debit': amt_tax < 0.0 and -amt_tax or 0.0,\n 'credit': amt_tax > 0.0 and amt_tax or 0.0,\n #'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_id.id or False,\n 'tax_code_id': tax.tax_code_id.id or False,\n #'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False,\n 'tax_amount': -amt_tax or 0.0,\n #'tax_amount': line.salary_rule_id.account_tax_id and amt or 0.0,\n })\n move_line_ids.append(tax_credit_line) \n credit_sum += tax_credit_line[2]['credit'] - tax_credit_line[2]['debit']\n \n if credit_account_id:\n\n credit_line = (0, 0, {\n #'name': line.name,\n 'name': line.motivo_modifica,\n 'date': timenow,\n 'partner_id': slip.partner_id.id,\n 'account_id': credit_account_id,\n 'journal_id': slip.journal_id.id,\n 'period_id': period_id,\n 'debit': amt < 0.0 and -amt or 0.0,\n 'credit': amt > 0.0 and amt or 0.0,\n #'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_id.id or False,\n #'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False, \n #'tax_amount': line.salary_rule_id.account_tax_id and amt or 0.0,\n })\n move_line_ids.append(credit_line)\n credit_sum += credit_line[2]['credit'] - credit_line[2]['debit']\n if debit_account_id:\n amtd = credit_sum \n debit_line = (0, 0, {\n #'name': line.name,\n 'name': line.motivo_modifica,\n 'date': timenow,\n 'partner_id': slip.partner_id.id,\n 'account_id': debit_account_id,\n 'journal_id': slip.journal_id.id,\n 'period_id': period_id,\n 'debit': amtd > 0.0 and amtd or 0.0,\n 'credit': amtd < 0.0 and -amtd or 0.0,\n #'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_id.id or False,\n #'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False,\n #'tax_amount': line.salary_rule_id.account_tax_id and amt or 0.0,\n })\n move_line_ids.append(debit_line)\n debit_sum += debit_line[2]['debit'] - debit_line[2]['credit']\n if debit_sum > credit_sum:\n acc_id = slip.journal_id.default_credit_account_id.id\n if not acc_id:\n raise osv.except_osv(_('Configuration Error!'),_('The Expense Journal \"%s\" has not properly configured the Credit Account!')%(slip.journal_id.name))\n adjust_credit = (0, 0, {\n 'name': _('Adjustment Entry'),\n 'date': timenow,\n 'partner_id': False,\n 'account_id': acc_id,\n 'journal_id': slip.journal_id.id,\n 'period_id': period_id,\n 'debit': 0.0,\n 'credit': debit_sum - credit_sum,\n })\n move_line_ids.append(adjust_credit)\n\n elif debit_sum < credit_sum:\n acc_id = slip.journal_id.default_debit_account_id.id\n if not acc_id:\n raise osv.except_osv(_('Configuration Error!'),_('The Expense Journal \"%s\" has not properly configured the Debit Account!')%(slip.journal_id.name))\n adjust_debit = (0, 0, {\n 'name': _('Adjustment Entry'),\n 'date': timenow,\n 'partner_id': False,\n 'account_id': acc_id,\n 'journal_id': slip.journal_id.id,\n 'period_id': period_id,\n 'debit': credit_sum - debit_sum,\n 'credit': 0.0,\n })\n move_line_ids.append(adjust_debit)\n move.update({'line_id': move_line_ids})\n move_id = move_pool.create(cr, uid, move, context=context)\n self.write(cr, uid, [slip.id], {'move_id': move_id, 'period_id' : period_id}, context=context)\n if slip.journal_id.entry_posted: \n move_pool.post(cr, uid, [move_id], context=context) #omitir estado borrador\n self.write(cr, uid, ids, {'state':'posted'})\n return False\n\n def cancel_payment(self, cr, uid, ids, data, context=None):\n reconcile_pool = self.pool.get('account.move.reconcile')\n move_pool = self.pool.get('account.move')\n for voucher in self.browse(cr, uid, ids, context=context):\n recs = []\n for line in voucher.move_ids:\n if line.reconcile_id:\n recs += [line.reconcile_id.id]\n if line.reconcile_partial_id:\n recs += [line.reconcile_partial_id.id]\n\n reconcile_pool.unlink(cr, uid, recs)\n\n if voucher.move_id:\n move_pool.button_cancel(cr, uid, [voucher.move_id.id])\n move_pool.unlink(cr, uid, [voucher.move_id.id])\n res = {\n 'state':'cancel',\n 'move_id':False,\n }\n self.write(cr, uid, ids, res)\n return True\n \n def action_cancel_draft(self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {'state':'draft'})\n return True\n\necua_ndd()\n\nclass ecua_ndd_line(osv.osv):\n _name = 'ecua.ndd_line' \n _description = 'Lineas de la Nota de debito'\n _columns = {\n 'name':fields.char('Nombre', size=64, readonly=False),\n 'ecua_ndd_id':fields.many2one('ecua.ndd','Nota'),\n 'motivo_modifica':fields.char('Motivo', size=64,required=True),\n 'valor_modifica':fields.float('Valor a modificar', required=True),\n 'invoice_line_tax_id': fields.many2many('account.tax', 'account_invoice_line_tax_nd', 'invoice_line_id', 'tax_id', 'Taxes'),\n 'iva12':fields.integer('IVA', readonly=True),\n 'iva0':fields.integer('IVA', readonly=True),\n 'valor_total':fields.float('Valor total'), \n }\n \n def onchange_impuestos_ids(self, cr, uid, ids, comprobante_id, context=None):\n return True\n \n \n def calcula_ndd(self, cr, uid, ids, comprobante_id, context=None):\n return True\n \necua_ndd_line()\n","sub_path":"ec_rect/ndd.py","file_name":"ndd.py","file_ext":"py","file_size_in_byte":19559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"402987943","text":"# -*- coding: utf-8 -*\n\nimport requests\nimport re\nimport time\nimport getpass\nfrom rk import RClient\n\n'''\n定义全局cookies,所有网络请求返回的cookies都放在这里\n'''\nall_cookies = {}\n#获取若快图像识别客户端\nrc = RClient('ljc1998', 'ljc19980217.', '117226', 'abf23a6f920644d9b8db7908b773f16a')\n\n'''\n定义需要用到的URL\n'''\nurl = {\n 'yiban_login': 'https://www.yiban.cn/login/', # get,登录页面\n 'yiban_do_login': 'https://www.yiban.cn/login/doLoginAjax/', # post,请求登录\n 'yiban_index': 'https://www.yiban.cn/', # get,易班首页\n 'yiban_app_base': 'https://q.yiban.cn/app/index/appid/', # get,易班app页面,后面需加应用id\n 'yiban_signup_get': 'https://q.yiban.cn/signup/getSignupAjax/', # post,查询讲座状态\n 'yiban_signup_insert': 'https://q.yiban.cn/signup/insertBoxAjax/', # post,抢讲座入口\n 'yiban_captcha_get':'https://www.yiban.cn/captcha/index/' #get,获取登录的验证码\n}\n\n'''\n工具函数,用于将网络请求返回的cookies与全局cookies合并,返回全局cookies\n'''\n\n\ndef merge_cookies(resp):\n cookies = requests.utils.dict_from_cookiejar(resp.cookies)\n all_cookies.update(cookies)\n return all_cookies\n\n\n'''\n工具函数,用于按正则表达式从网络请求返回的内容查找匹配字符串,返回匹配到的第一个字符串\n'''\n\n\ndef find_str(resp, pattern):\n p = re.compile(pattern)\n try:\n resoult = p.findall(resp.text)[0]\n except:\n return \"\"\n return resoult\n\n\n'''\n工具函数,用于获取访问指定url返回的时间\n'''\n\n\ndef get_time_from_url(u):\n r = requests.post(u)\n date = r.headers['Date']\n time_tmp = time.strptime(date[5:25], \"%d %b %Y %H:%M:%S\")\n time_float = time.mktime(time_tmp) + 8 * 60 * 60\n return time_float\n\n\n'''\n工具函数,用于获取指定response的时间戳\n'''\ndef get_time_from_response(r):\n date = r.headers['Date']\n time_tmp = time.strptime(date[5:25], \"%d %b %Y %H:%M:%S\")\n time_float = time.mktime(time_tmp) + 8 * 60 * 60\n return time_float\n\n\n'''\n工具函数,将单位为秒的时间转换成xx天xx时xx分xx秒格式\n'''\n\n\ndef transform_time(old_time):\n flag = \"\"\n if (old_time < 0):\n old_time = abs(old_time)\n flag = \"-\"\n days = int(old_time / (60 * 60 * 24))\n hours = int(old_time % (60 * 60 * 24) / (60 * 60))\n minutes = int(old_time % (60 * 60) / 60)\n seconds = int(old_time % 60)\n new_time = flag + str(days) + \"天\" + str(hours) + \"时\" + str(minutes) + \"分\" + str(seconds) + \"秒\"\n return new_time\n\n\n'''\n工具函数,获取验证码图片,返回验证码图片字节流\n'''\ndef get_captcha_img():\n r = requests.get(\n url=url[\"yiban_captcha_get\"],\n cookies=all_cookies\n )\n return r.content\n\n\n'''\n工具函数,识别验证码\n'''\ndef read_captcha_img(values,img):\n r = rc.rk_create(img, 4010)\n p1 = re.compile(r'\"Result\":\"(.{1})\",\"Id\"')\n p2 = re.compile(r'\"Id\":\"(.*)\"}')\n try:\n code = p1.findall(r)[0]\n img_id = p2.findall(r)[0]\n except:\n code = \"0\"\n img_id = \"0\"\n values[\"img_id\"] = img_id\n return code\n\n\n'''\n通过键盘给变量赋值\n'''\n\n\ndef input_to_values(values):\n print(\"请按提示输入信息:\\n\")\n print(\"appid获取方法:\\n1.在易班手机APP进入抢讲座页面->点击右上角的选项按钮->点击底部弹出的复制链接按钮\")\n print(\"2.将复制内容粘贴到任意文本编辑框得到一个类似'https://q.yiban.cn/app/index/appid/325512'的链接\")\n print(\"3.其中'appid/'后紧跟的数字(这里是'325512')就是该讲座对应的appid\\n\")\n values[\"appid\"] = input(\"appid:\")\n values[\"account\"] = input(\"账号(手机号码):\")\n values[\"password\"] = getpass.getpass('密码:')\n values[\"info\"] = []\n values[\"info\"].append(input(\"学院:\"))\n values[\"info\"].append(input(\"班级:\"))\n values[\"info\"].append(input(\"性别:\"))\n values[\"info\"].append(input(\"学号:\"))\n values[\"info\"].append(input(\"电话:\"))\n flag = input(\"请检查你输入的信息,确认请输入y,重输请输入其他任意字符:\")\n if flag == 'y' or flag == 'Y':\n return 0\n else:\n input_to_values(values)\n\n\n'''\n登录易班\n'''\n\n\ndef login_yiban(values):\n r1 = requests.get(url=url[\"yiban_login\"])\n merge_cookies(r1)\n data_keys_time = find_str(r1, r\"data-keys-time='([\\d]+.*)'\")\n headers_do = {\"X-Requested-With\": \"XMLHttpRequest\"}\n r2 = requests.post(\n url=url[\"yiban_do_login\"],\n data={\"account\": values[\"account\"], \"password\": values[\"password\"], \"keysTime\": data_keys_time},\n cookies=all_cookies,\n headers=headers_do\n )\n merge_cookies(r2)\n\n if all_cookies.__contains__(\"YB_SSID\") and all_cookies.__contains__(\"yiban_user_token\"):\n print(\"登录成功!\")\n else:\n # 密码错误\n if find_str(r2, r'\"code\":\"(\\d+)\",\"message\"') == \"415\" or find_str(r2, r'\"code\":(\\d+),\"message\"') == \"415\":\n print(\"账号或密码错误!\")\n exit(1)\n elif find_str(r2, r'\"code\":\"(\\d+)\",\"message\"') == \"422\" or find_str(r2, r'\"code\":(\\d+),\"message\"') == \"422\":\n print(\"该账户不存在!\")\n exit(1)\n # 需要验证码\n elif find_str(r2, r'\"code\":\"(\\d+)\",\"message\"') == \"711\" or find_str(r2, r'\"code\":(\\d+),\"message\"') == \"711\":\n print(\"需要验证码!\\n正在识别并输入验证码~~~\")\n captcha_img = get_captcha_img()\n captcha_code = read_captcha_img(values,captcha_img)\n r2 = requests.post(\n url=url[\"yiban_do_login\"],\n data={\"account\": values[\"account\"], \"password\": values[\"password\"],\"captcha\":captcha_code ,\"keysTime\": data_keys_time},\n cookies=all_cookies,\n headers=headers_do\n )\n merge_cookies(r2)\n # 密码错误\n if find_str(r2, r'\"code\":\"(\\d+)\",\"message\"') == \"415\" or find_str(r2, r'\"code\":(\\d+),\"message\"') == \"415\":\n print(\"账号或密码错误!\")\n exit(1)\n elif find_str(r2, r'\"code\":\"(\\d+)\",\"message\"') == \"422\" or find_str(r2, r'\"code\":(\\d+),\"message\"') == \"422\":\n print(\"该账户不存在!\")\n exit(1)\n # 图片验证码错误\n if find_str(r2, r'\"code\":\"(\\d+)\",\"message\"') == \"201\" or find_str(r2, r'\"code\":(\\d+),\"message\"') == \"201\":\n print(\"验证码错误,正在重新输入验证码(最多尝试3次)~~~\")\n # 接下来重新获取页面,重新获识别验证证码,重新登录,循环3次,除非登陆成功\n for i in range(3):\n r1 = requests.get(\n url=url[\"yiban_login\"],\n cookies=all_cookies\n )\n merge_cookies(r1)\n data_keys_time = find_str(r1, r\"data-keys-time='([\\d]+.*)'\")\n headers_do = {\"X-Requested-With\": \"XMLHttpRequest\"}\n captcha_img = get_captcha_img()\n captcha_code = read_captcha_img(values,captcha_img)\n r2 = requests.post(\n url=url[\"yiban_do_login\"],\n data={\"account\": values[\"account\"], \"password\": values[\"password\"],\"captcha\":captcha_code , \"keysTime\": data_keys_time},\n cookies=all_cookies,\n headers=headers_do\n )\n merge_cookies(r2)\n # 密码错误\n if find_str(r2, r'\"code\":\"(\\d+)\",\"message\"') == \"415\" or find_str(r2, r'\"code\":(\\d+),\"message\"') == \"415\":\n print(\"账号或密码错误!\")\n exit(1)\n elif find_str(r2, r'\"code\":\"(\\d+)\",\"message\"') == \"422\" or find_str(r2, r'\"code\":(\\d+),\"message\"') == \"422\":\n print(\"该账户不存在!\")\n exit(1)\n if all_cookies.__contains__(\"YB_SSID\") and all_cookies.__contains__(\"yiban_user_token\"):\n print(\"再次输入验证码后登录成功!\")\n break\n elif all_cookies.__contains__(\"yiban_user_token\"):\n print(\"验证码正确,登陆成功!\")\n if not all_cookies.__contains__(\"yiban_user_token\"):\n print(\"登录失败!\")\n exit(1)\n r3 = requests.get(url=url[\"yiban_index\"], cookies=all_cookies)\n merge_cookies(r3)\n\n\n'''\n请求讲座页面\n'''\n\n\ndef into_enroll_page(values):\n r = requests.get(url=url[\"yiban_app_base\"] + values[\"appid\"], cookies=all_cookies)\n merge_cookies(r)\n title = find_str(r, r\"(.*)\")\n if (\"警告\" in title) or (\"呵呵\" in title):\n print(\"appid错误!\")\n exit(1)\n else:\n print(\"请求讲座页面成功!\")\n enroll_code = find_str(r, r'\"code\":\"(enroll-[\\d]+)\"')\n values[\"enroll_code\"] = enroll_code\n return 0\n\n\n'''\n请求讲座信息\n'''\n\n\ndef get_enroll_info(values):\n t1 = time.time()\n r = requests.post(\n url=url[\"yiban_signup_get\"],\n data={\"App_id\": values[\"appid\"], \"code\": values[\"enroll_code\"]},\n cookies=all_cookies\n )\n merge_cookies(r)\n\n # 记录flag\n flag = find_str(r, r'\"flag\":\"(.*)\",\"questionList\"')\n values[\"enroll_flag\"] = flag\n start_time = find_str(r, r'\"startTime\":\"(.*)\",\"endTime\"')\n values[\"start_time\"] = start_time\n # 计算距离讲座开始报名时间\n start_time_tmp = time.strptime(start_time, \"%Y-%m-%d %H:%M\")\n start_time_float = time.mktime(start_time_tmp)\n values[\"start_time_float\"] = start_time_float\n yiban_time = r.headers[\"Date\"]\n yiban_time_tmp = time.strptime(yiban_time[5:25], \"%d %b %Y %H:%M:%S\")\n yiban_time_float = time.mktime(yiban_time_tmp) + 8 * 60 * 60\n interval_time = start_time_float - yiban_time_float\n values[\"interval_time\"] = interval_time\n enroll_id = find_str(r, r'\"id\":\"(\\d+)\"')\n values[\"enroll_id\"] = enroll_id\n t2 = time.time()\n # 计算网络延迟时间\n values[\"net_delay_time\"] = t2 - t1\n return 0\n\n\n'''\n抢讲座\n'''\n\n\ndef grab_enroll(values):\n values[\"success\"] = 0\n start_time = values[\"start_time\"]\n start_time_tmp = time.strptime(start_time, \"%Y-%m-%d %H:%M\")\n start_time_float = time.mktime(start_time_tmp)\n while get_time_from_url(url[\"yiban_signup_get\"]) < start_time_float:\n continue\n print(\"延迟7秒再抢~~~\")\n time.sleep(7)\n r = requests.post(\n url=url[\"yiban_signup_insert\"],\n data={\"App_id\": values[\"appid\"], \"id\": values[\"enroll_id\"], \"flag\": values[\"enroll_flag\"],\n \"answers[]\": values[\"info\"]},\n cookies=all_cookies\n )\n merge_cookies(r)\n\n t_start = values[\"start_time_float\"]\n t_done = get_time_from_response(r)\n # 计算报名开始到报名完成的时间\n values[\"take_time\"] = t_done - t_start\n if find_str(r, r'\"code\":\"(\\d+)\",\"message\"') == \"200\" or find_str(r, r'\"code\":(\\d+),\"message\"') == \"200\":\n values[\"success\"] = 1\n return 0\n else:\n return 1\n","sub_path":"qjz_v1.0/tools1.py","file_name":"tools1.py","file_ext":"py","file_size_in_byte":11204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"511625502","text":"from flask import render_template\nfrom flask_security import login_required, roles_accepted\n\nimport assets\nfrom controllers import shops\nfrom controllers import stats\nfrom webapp.dashboard_stats import dashboard_stats\nfrom webapp.helpers import Paginator, get_page_arg\nfrom webapp.helpers import catch_errors\nfrom webapp.shop_dashboard.routes import verify_shop_owner\n\nSHOP_PRODUCT_ORDERS_ITEMS_PER_PAGE = 5\nSHOP_REVIEWS_PER_PAGE = 5\n\n\n@dashboard_stats.route('/shops//stats/product-reviews')\n@login_required\n@roles_accepted(assets.Roles.SHOP_OWNER_ROLE)\n@catch_errors()\ndef product_reviews_table(shop_id):\n shop = verify_shop_owner(shop_id)\n page = get_page_arg()\n product_orders_reviews = stats.gather_order_reviews_by_product(shop)\n product_orders_reviews = Paginator(items=product_orders_reviews,\n items_per_page=SHOP_PRODUCT_ORDERS_ITEMS_PER_PAGE).get_page(page=page)\n return render_template(\"product_reviews_orders_table.html\", product_orders_reviews=product_orders_reviews)\n\n\n@dashboard_stats.route('/shops//products//reviews')\n@login_required\n@roles_accepted(assets.Roles.SHOP_OWNER_ROLE)\n@catch_errors()\ndef shop_product_reviews(shop_id, product_id):\n verify_shop_owner(shop_id)\n page = get_page_arg()\n product_reviews = shops.get_reviews_by_product(shop_id, product_id)\n reviews = product_reviews['reviews']\n product_reviews['reviews'] = Paginator(items=reviews, items_per_page=SHOP_REVIEWS_PER_PAGE).get_page(page=page)\n return render_template(\"reviews_list.html\", product_reviews=product_reviews)\n","sub_path":"webapp/dashboard_reviews/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"479763106","text":"from collections import defaultdict\n\n\ndef delete_nth(order, max_e):\n counter = defaultdict(int)\n result = []\n\n for number in order:\n if counter[number] < max_e:\n counter[number] += 1\n result.append(number)\n\n return result\n","sub_path":"kyu6/find_the_missing_letter.py","file_name":"find_the_missing_letter.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"62016694","text":"from datetime import date\nimport json\nfrom typing import List\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\n\n\nclass GoogleApi:\n SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']\n creds = None\n\n def __init__(self, token: json = None, config: json = None) -> None:\n if token is not None:\n self.creds = Credentials.from_authorized_user_info(\n token, self.SCOPES)\n\n self.config = config\n\n def get_events(self, from_date: date = None, to_date: date = None\n ) -> List[any]:\n \"\"\"Возвращает список событий из календаря за указанный\n интервал времени\n\n Args:\n from_date (date, optional): Дата, начиная с которой\n производится фильтрация.\n to_date (date, optional): Дата, заканчивая которой\n производится фильтрация.\n\n Returns:\n List[any]: Список событий из календаря\n \"\"\"\n service = self.build_service()\n events_result = service.events().list(\n calendarId='primary',\n timeMin=from_date, timeMax=to_date\n ).execute()\n events = events_result.get('items', [])\n\n return events\n\n def build_service(self):\n return build('calendar', 'v3', credentials=self.creds)\n\n def get_or_refresh_token(self):\n creds = self.creds\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n elif self.config:\n flow = InstalledAppFlow.from_client_config(\n self.config, self.SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n print(creds.to_json())\n","sub_path":"src/api/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"96497970","text":"import unittest\nimport io\nfrom copy import deepcopy\n\nfrom continuation import Continuation, Stack\nfrom interpret import *\n\nfrom aftype import StackObject\nfrom af_types import Type, TypeSignature, \\\n make_atom, TAtom\n\nTBool = Type(\"Bool\")\nTInt = Type(\"Int\")\n\n\nclass TestExecution(unittest.TestCase):\n\n def setUp(self) -> None:\n self.stack = Stack()\n self.cont = Continuation(self.stack)\n self.save_types = deepcopy(Type.types)\n self.save_ctors = deepcopy(Type.ctors)\n\n def tearDown(self) -> None:\n Type.types = deepcopy(self.save_types)\n Type.ctors = deepcopy(self.save_ctors)\n\n def execute(self, code) -> Any:\n self.cont.execute(interpret(self.cont, io.StringIO(code)))\n return self.cont.stack.tos().value\n\n def test_compile_double(self) -> None:\n code = \"\"\"\n debug on\n double : Int -> Int;\n dup + .\n\n 2 int double\n \"\"\"\n assert self.execute(code) == 4\n\n def test_compile_double_literal(self) -> None:\n code = \"\"\"\n double : Int -> Int;\n 2 int * .\n\n 2 int double\n \"\"\"\n assert self.execute(code) == 4\n\n def test_compile_combo(self) -> None:\n code = \"\"\"\n is_equal : Any Any -> Bool;\n == .\n\n double : Int -> Int;\n dup +.\n\n combo : Int Int -> Bool;\n double\n swap\n double\n is_equal.\n\n 8 int 8 int combo\n 4 int 2 int combo\n \"\"\"\n\n assert self.execute(code) == False\n assert self.cont.stack.depth() == 2\n self.cont.stack.pop()\n assert self.cont.stack.depth() == 1\n assert self.cont.stack.tos().value == True\n\n def test_compile_double_drop(self) -> None:\n code = \"\"\"\n double : Int -> Int ;\n 2 int *.\n 5 int double\n \"\"\"\n assert self.execute(code) == 10\n\n def test_compile_no_input_no_output(self) -> None:\n code = \"\"\"\n noinputnooutput : -> ;\n stack .\n \"\"\"\n stack = Stack()\n cont = Continuation(stack)\n cont = cont.execute(interpret(cont, io.StringIO(code)))\n\n op, found = Type.op(\"noinputnooutput\", cont ) #, \"Test\")\n\n assert found\n assert op.sig == TypeSignature([],[])\n\n op, found = Type.op(\"not found\", cont)\n assert not found\n\n def test_compile_multi_input_multi_output(self) -> None:\n code = \"\"\"\n multiinput : Bool Int Int Int -> Int ;\n + == == .\n False bool 1 int 1 int 1 int\n \"\"\"\n stack = Stack()\n cont = Continuation(stack)\n cont = cont.execute(interpret(cont, io.StringIO(code)))\n\n op, found = Type.op(\"multiinput\", cont ) #, \"Test\")\n\n assert found\n assert op.sig == TypeSignature([StackObject(stype=TBool),StackObject(stype=TInt),StackObject(stype=TInt),StackObject(stype=TInt)],\n [StackObject(stype=TInt)])\n\n op, found = Type.op(\"not found\", cont)\n assert not found\n\n ","sub_path":"src/tests/test_execute_code.py","file_name":"test_execute_code.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"651385798","text":"import json\nfrom datetime import timedelta\n\nimport airflow\nfrom airflow import DAG\nfrom airflow.operators.http_operator import SimpleHttpOperator\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.sensors.http_sensor import HttpSensor\n\ndefault_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'start_date': airflow.utils.dates.days_ago(2),\n 'email': ['airflow@example.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n}\n\ndag = DAG('example_http_operator2', default_args=default_args)\n\ndag.doc_md = __doc__\n\nt1 = BashOperator(\n task_id='also_run_this',\n bash_command='wget hadoop-master:8088',\n dag=dag,\n)\n\nt1\n","sub_path":"local-executor/dags/httpd.py","file_name":"httpd.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"255719030","text":"from openpyxl import load_workbook\nfrom openpyxl import Workbook\nfrom datetime import datetime\nimport os\n\n\nCURRENT_YEAR = datetime.now().strftime(\"%Y\")\nCURRENT_MONTH = datetime.now().strftime(\"%B\")\n\n\nclass ExcelHandler(object):\n def __init__(self, file, name_index=3, type_index=4):\n self.type_index = type_index\n self.name_index = name_index\n\n self.wb = load_workbook(file)\n self.ws = self.wb.active\n self._ensure_header_row()\n\n correct_year = input(\"Is this the correct year for these records? - {}\\n[Y/N] \".format(CURRENT_YEAR))\n self.year = CURRENT_YEAR if correct_year.lower() in [\"yes\", \"y\"] else input(\"Please enter correct year:\\n\")\n self._ensure_year_dir()\n\n correct_month = input(\"Is this the correct month for these records? - {}\\n[Y/N] \".format(CURRENT_MONTH))\n self.month = CURRENT_MONTH if correct_month.lower() in [\"yes\", \"y\"] else input(\"Please enter correct month:\\n\")\n self.month_dir = \"{}/{}\".format(self.year, self.month)\n self._ensure_month_dir()\n\n def _ensure_header_row(self):\n self.header_row = self.ws.rows.__next__()\n assert (self.header_row[self.type_index].value.lower() == \"type\"), \\\n \"Unable to confirm header row. Please ensure it's at the top of the source spreadsheet.\"\n\n def _ensure_year_dir(self):\n if not os.path.exists(self.year):\n os.makedirs(self.year)\n\n def _ensure_month_dir(self):\n if not os.path.exists(self.month_dir):\n os.makedirs(self.month_dir)\n\n def has_row_type(self, row, exp_type):\n row_type = row[self.type_index].value\n return True if row_type == exp_type else False\n\n def has_row_type_and_name(self, row, exp_type, *exp_name):\n row_type = row[self.type_index].value\n row_name = row[self.name_index].value\n return row_type == exp_type and any(row_name == expected for expected in exp_name)\n\n def collect_rows(self, filter_fn, *filter_fn_args):\n rows = []\n for row in self.ws.iter_rows():\n if filter_fn(row, *filter_fn_args):\n rows.append(row)\n continue\n return rows\n\n def collect_by_type(self, row_type):\n return self.collect_rows(self.has_row_type, row_type)\n\n def write_to_new_worksheet(self, sheet_name, rows):\n rows.insert(0, self.header_row)\n sheet_name = sheet_name + \" ({}).xlsx\".format(self.month)\n new_wb = Workbook()\n new_ws = new_wb.active\n for row in rows:\n new_ws.append(cell.value for cell in row)\n new_wb.save(\"{}/{}\".format(self.month_dir, sheet_name))\n\n\nif __name__ == \"__main__\":\n source_file = input('Enter source file name, e.g. \"Oct 17 Full Download\" (no quotes): ')\n\n if not source_file.endswith(\".xlsx\"):\n source_file = source_file + \".xlsx\"\n\n if not (os.path.isfile(source_file)):\n print(\"Could not find file '{}'. Make sure it's spelled correctly and lives inside \"\n \"your bt-blazin-finances folder.\".format(source_file))\n exit(1)\n\n handler = ExcelHandler(source_file)\n\n eby_auc_rows = handler.collect_by_type(\"eBay Auction Payment\")\n exp_pmt_rows = handler.collect_by_type(\"Express Checkout Payment\")\n gen_pmt_rows = handler.collect_by_type(\"General Payment\")\n mb_pmt_rows = handler.collect_by_type(\"Mobile Payment\")\n pp_rows = handler.collect_by_type(\"General PayPal Debit Transaction\")\n pstg_pmt_rows = handler.collect_by_type(\"Postage Payment\")\n refund_rows = handler.collect_by_type(\"Payment Refund\")\n web_pmt_rows = handler.collect_by_type(\"Website Payment\")\n bill_usr_ebay_rows = handler.collect_rows(handler.has_row_type_and_name,\n \"PreApproved Payment Bill User Payment\",\n \"eBay Inc.\",\n \"eBay Inc Shipping\")\n bill_usr_other_rows = handler.collect_rows(handler.has_row_type_and_name,\n \"PreApproved Payment Bill User Payment\",\n \"Dropbox\",\n \"Netflix.com\")\n money_rows = mb_pmt_rows + pp_rows + bill_usr_other_rows + gen_pmt_rows + exp_pmt_rows + eby_auc_rows\n\n handler.write_to_new_worksheet(\"Bulk\", web_pmt_rows)\n handler.write_to_new_worksheet(\"Costs\", pstg_pmt_rows + refund_rows + bill_usr_ebay_rows)\n handler.write_to_new_worksheet(\"eBay Sales Records\", eby_auc_rows)\n handler.write_to_new_worksheet(\"Money\", money_rows)\n\n","sub_path":"local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"580158445","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2020/2/7 10:56\r\n# @Author : 番茄炒鸡蛋\r\nimport requests\r\nimport pandas as pd\r\nimport numpy as np\r\nimport os\r\nfrom statsmodels.tsa.seasonal import seasonal_decompose\r\nfrom statsmodels.tsa.arima_model import ARIMA\r\nfrom sklearn.metrics import mean_absolute_error # 平方绝对误差\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtWidgets import QMainWindow,QMessageBox\r\nfrom PyQt5.QtGui import QPixmap\r\nfrom PyQt5 import QtCore, QtWidgets\r\nfrom PyQt5.QtWidgets import QApplication, QVBoxLayout, QSizePolicy, QWidget\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\r\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\r\nfrom pylab import *\r\n'''\r\n↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓\r\n界面代码\r\n'''\r\n#coordinate conversion\r\nclass Ui_Form_conversion(object):\r\n def setupUi(self, Form_conversion):\r\n Form_conversion.setObjectName(\"Form_conversion\")\r\n Form_conversion.setEnabled(True)\r\n Form_conversion.resize(387, 373)\r\n self.groupBox = QtWidgets.QGroupBox(Form_conversion)\r\n self.groupBox.setGeometry(QtCore.QRect(20, 270, 251, 81))\r\n self.groupBox.setObjectName(\"groupBox\")\r\n self.layoutWidget = QtWidgets.QWidget(self.groupBox)\r\n self.layoutWidget.setGeometry(QtCore.QRect(20, 20, 211, 48))\r\n self.layoutWidget.setObjectName(\"layoutWidget\")\r\n self.gridLayout_2 = QtWidgets.QGridLayout(self.layoutWidget)\r\n self.gridLayout_2.setContentsMargins(0, 0, 0, 0)\r\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\r\n self.lineEdit_ccoordinate = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.lineEdit_ccoordinate.setObjectName(\"lineEdit_ccoordinate\")\r\n self.gridLayout_2.addWidget(self.lineEdit_ccoordinate, 0, 1, 1, 1)\r\n self.label_5 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_5.setObjectName(\"label_5\")\r\n self.gridLayout_2.addWidget(self.label_5, 0, 0, 1, 1)\r\n self.groupBox_3 = QtWidgets.QGroupBox(Form_conversion)\r\n self.groupBox_3.setGeometry(QtCore.QRect(20, 10, 341, 171))\r\n self.groupBox_3.setObjectName(\"groupBox_3\")\r\n self.layoutWidget1 = QtWidgets.QWidget(self.groupBox_3)\r\n self.layoutWidget1.setGeometry(QtCore.QRect(10, 20, 219, 22))\r\n self.layoutWidget1.setObjectName(\"layoutWidget1\")\r\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget1)\r\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\r\n self.label = QtWidgets.QLabel(self.layoutWidget1)\r\n self.label.setObjectName(\"label\")\r\n self.horizontalLayout.addWidget(self.label)\r\n self.lineEdit_key = QtWidgets.QLineEdit(self.layoutWidget1)\r\n self.lineEdit_key.setText(\"\")\r\n self.lineEdit_key.setObjectName(\"lineEdit_key\")\r\n self.horizontalLayout.addWidget(self.lineEdit_key)\r\n self.groupBox_2 = QtWidgets.QGroupBox(self.groupBox_3)\r\n self.groupBox_2.setGeometry(QtCore.QRect(10, 50, 241, 111))\r\n self.groupBox_2.setObjectName(\"groupBox_2\")\r\n self.layoutWidget2 = QtWidgets.QWidget(self.groupBox_2)\r\n self.layoutWidget2.setGeometry(QtCore.QRect(11, 21, 221, 81))\r\n self.layoutWidget2.setObjectName(\"layoutWidget2\")\r\n self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget2)\r\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\r\n self.gridLayout.setObjectName(\"gridLayout\")\r\n self.lineEdit_ocoordinate = QtWidgets.QLineEdit(self.layoutWidget2)\r\n self.lineEdit_ocoordinate.setObjectName(\"lineEdit_ocoordinate\")\r\n self.gridLayout.addWidget(self.lineEdit_ocoordinate, 0, 1, 1, 2)\r\n self.label_2 = QtWidgets.QLabel(self.layoutWidget2)\r\n self.label_2.setObjectName(\"label_2\")\r\n self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1)\r\n self.label_4 = QtWidgets.QLabel(self.layoutWidget2)\r\n self.label_4.setObjectName(\"label_4\")\r\n self.gridLayout.addWidget(self.label_4, 1, 0, 1, 1)\r\n self.comboBox_coordinatetype = QtWidgets.QComboBox(self.layoutWidget2)\r\n self.comboBox_coordinatetype.setObjectName(\"comboBox_coordinatetype\")\r\n self.comboBox_coordinatetype.addItem(\"\")\r\n self.comboBox_coordinatetype.addItem(\"\")\r\n self.comboBox_coordinatetype.addItem(\"\")\r\n self.gridLayout.addWidget(self.comboBox_coordinatetype, 1, 1, 1, 1)\r\n self.groupBox_4 = QtWidgets.QGroupBox(Form_conversion)\r\n self.groupBox_4.setGeometry(QtCore.QRect(20, 200, 121, 51))\r\n self.groupBox_4.setObjectName(\"groupBox_4\")\r\n self.pushButton_conversion = QtWidgets.QPushButton(self.groupBox_4)\r\n self.pushButton_conversion.setGeometry(QtCore.QRect(20, 20, 75, 23))\r\n self.pushButton_conversion.setObjectName(\"pushButton_conversion\")\r\n self.retranslateUi(Form_conversion)\r\n self.pushButton_conversion.clicked.connect(Form_conversion.conversion)\r\n QtCore.QMetaObject.connectSlotsByName(Form_conversion)\r\n def retranslateUi(self, Form_conversion):\r\n _translate = QtCore.QCoreApplication.translate\r\n Form_conversion.setWindowTitle(_translate(\"Form_conversion\", \"坐标转换\"))\r\n self.groupBox.setTitle(_translate(\"Form_conversion\", \"输出模块\"))\r\n self.label_5.setText(_translate(\"Form_conversion\", \"经纬度:\"))\r\n self.groupBox_3.setTitle(_translate(\"Form_conversion\", \"输入模块\"))\r\n self.label.setText(_translate(\"Form_conversion\", \"密钥(key):\"))\r\n self.groupBox_2.setTitle(_translate(\"Form_conversion\", \"原坐标\"))\r\n self.label_2.setText(_translate(\"Form_conversion\", \"经纬度:\"))\r\n self.label_4.setText(_translate(\"Form_conversion\", \"坐标系类型:\"))\r\n self.comboBox_coordinatetype.setItemText(0, _translate(\"Form_conversion\", \"gps\"))\r\n self.comboBox_coordinatetype.setItemText(1, _translate(\"Form_conversion\", \"baidu\"))\r\n self.comboBox_coordinatetype.setItemText(2, _translate(\"Form_conversion\", \"mapbar\"))\r\n self.groupBox_4.setTitle(_translate(\"Form_conversion\", \"执行模块\"))\r\n self.pushButton_conversion.setText(_translate(\"Form_conversion\", \"转换\"))\r\n#dataprocessing\r\nclass Ui_Form_dataprocessing(object):\r\n def setupUi(self, Form_dataprocessing):\r\n Form_dataprocessing.setObjectName(\"Form_dataprocessing\")\r\n Form_dataprocessing.setEnabled(True)\r\n Form_dataprocessing.resize(619, 277)\r\n self.groupBox = QtWidgets.QGroupBox(Form_dataprocessing)\r\n self.groupBox.setGeometry(QtCore.QRect(10, 20, 291, 171))\r\n self.groupBox.setObjectName(\"groupBox\")\r\n self.label_4 = QtWidgets.QLabel(self.groupBox)\r\n self.label_4.setGeometry(QtCore.QRect(30, 60, 54, 12))\r\n self.label_4.setObjectName(\"label_4\")\r\n self.lineEdit_starttime = QtWidgets.QLineEdit(self.groupBox)\r\n self.lineEdit_starttime.setGeometry(QtCore.QRect(120, 60, 131, 20))\r\n self.lineEdit_starttime.setObjectName(\"lineEdit_starttime\")\r\n self.label_3 = QtWidgets.QLabel(self.groupBox)\r\n self.label_3.setGeometry(QtCore.QRect(31, 31, 60, 16))\r\n self.label_3.setObjectName(\"label_3\")\r\n self.comboBox_crawltime4 = QtWidgets.QComboBox(self.groupBox)\r\n self.comboBox_crawltime4.setGeometry(QtCore.QRect(121, 31, 62, 20))\r\n self.comboBox_crawltime4.setObjectName(\"comboBox_crawltime4\")\r\n self.comboBox_crawltime4.addItem(\"\")\r\n self.comboBox_crawltime4.addItem(\"\")\r\n self.comboBox_crawltime4.addItem(\"\")\r\n self.comboBox_crawltime4.addItem(\"\")\r\n self.comboBox_crawltime4.addItem(\"\")\r\n self.comboBox_crawltime4.addItem(\"\")\r\n self.comboBox_crawltime4.addItem(\"\")\r\n self.comboBox_crawltime4.addItem(\"\")\r\n self.comboBox_crawltime4.addItem(\"\")\r\n self.label = QtWidgets.QLabel(self.groupBox)\r\n self.label.setGeometry(QtCore.QRect(30, 100, 60, 16))\r\n self.label.setObjectName(\"label\")\r\n self.comboBox_targettype = QtWidgets.QComboBox(self.groupBox)\r\n self.comboBox_targettype.setGeometry(QtCore.QRect(120, 100, 146, 20))\r\n self.comboBox_targettype.setObjectName(\"comboBox_targettype\")\r\n self.comboBox_targettype.addItem(\"\")\r\n self.comboBox_targettype.addItem(\"\")\r\n self.comboBox_targettype.addItem(\"\")\r\n self.label_2 = QtWidgets.QLabel(self.groupBox)\r\n self.label_2.setGeometry(QtCore.QRect(30, 135, 84, 16))\r\n self.label_2.setObjectName(\"label_2\")\r\n self.lineEdit_targetroad = QtWidgets.QLineEdit(self.groupBox)\r\n self.lineEdit_targetroad.setGeometry(QtCore.QRect(120, 135, 133, 20))\r\n self.lineEdit_targetroad.setObjectName(\"lineEdit_targetroad\")\r\n self.groupBox_2 = QtWidgets.QGroupBox(Form_dataprocessing)\r\n self.groupBox_2.setGeometry(QtCore.QRect(80, 200, 120, 71))\r\n self.groupBox_2.setObjectName(\"groupBox_2\")\r\n self.pushButton = QtWidgets.QPushButton(self.groupBox_2)\r\n self.pushButton.setGeometry(QtCore.QRect(20, 30, 75, 23))\r\n self.pushButton.setObjectName(\"pushButton\")\r\n self.groupBox_3 = QtWidgets.QGroupBox(Form_dataprocessing)\r\n self.groupBox_3.setGeometry(QtCore.QRect(310, 10, 291, 261))\r\n self.groupBox_3.setObjectName(\"groupBox_3\")\r\n self.textEdit_progressbar1 = QtWidgets.QTextEdit(self.groupBox_3)\r\n self.textEdit_progressbar1.setGeometry(QtCore.QRect(20, 60, 251, 71))\r\n self.textEdit_progressbar1.setObjectName(\"textEdit_progressbar1\")\r\n self.textEdit_progressbar2 = QtWidgets.QTextEdit(self.groupBox_3)\r\n self.textEdit_progressbar2.setGeometry(QtCore.QRect(20, 170, 251, 71))\r\n self.textEdit_progressbar2.setObjectName(\"textEdit_progressbar2\")\r\n self.widget = QtWidgets.QWidget(self.groupBox_3)\r\n self.widget.setGeometry(QtCore.QRect(20, 30, 251, 22))\r\n self.widget.setObjectName(\"widget\")\r\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)\r\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\r\n self.label_5 = QtWidgets.QLabel(self.widget)\r\n self.label_5.setObjectName(\"label_5\")\r\n self.horizontalLayout.addWidget(self.label_5)\r\n self.progressBar_dataprocessing1 = QtWidgets.QProgressBar(self.widget)\r\n self.progressBar_dataprocessing1.setProperty(\"value\", 0)\r\n self.progressBar_dataprocessing1.setObjectName(\"progressBar_dataprocessing1\")\r\n self.horizontalLayout.addWidget(self.progressBar_dataprocessing1)\r\n self.widget1 = QtWidgets.QWidget(self.groupBox_3)\r\n self.widget1.setGeometry(QtCore.QRect(20, 140, 251, 22))\r\n self.widget1.setObjectName(\"widget1\")\r\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.widget1)\r\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\r\n self.label_6 = QtWidgets.QLabel(self.widget1)\r\n self.label_6.setObjectName(\"label_6\")\r\n self.horizontalLayout_2.addWidget(self.label_6)\r\n self.progressBar_dataprocessing2 = QtWidgets.QProgressBar(self.widget1)\r\n self.progressBar_dataprocessing2.setProperty(\"value\", 0)\r\n self.progressBar_dataprocessing2.setObjectName(\"progressBar_dataprocessing2\")\r\n self.horizontalLayout_2.addWidget(self.progressBar_dataprocessing2)\r\n self.retranslateUi(Form_dataprocessing)\r\n self.pushButton.clicked.connect(Form_dataprocessing.dataprocessing)\r\n QtCore.QMetaObject.connectSlotsByName(Form_dataprocessing)\r\n def retranslateUi(self, Form_dataprocessing):\r\n _translate = QtCore.QCoreApplication.translate\r\n Form_dataprocessing.setWindowTitle(_translate(\"Form_dataprocessing\", \"数据处理\"))\r\n self.groupBox.setTitle(_translate(\"Form_dataprocessing\", \"输入模块\"))\r\n self.label_4.setText(_translate(\"Form_dataprocessing\", \"开始时间:\"))\r\n self.lineEdit_starttime.setText(_translate(\"Form_dataprocessing\", \"2019-12-21\"))\r\n self.label_3.setText(_translate(\"Form_dataprocessing\", \"爬取时间:\"))\r\n self.comboBox_crawltime4.setItemText(0, _translate(\"Form_dataprocessing\", \"1小时\"))\r\n self.comboBox_crawltime4.setItemText(1, _translate(\"Form_dataprocessing\", \"17小时\"))\r\n self.comboBox_crawltime4.setItemText(2, _translate(\"Form_dataprocessing\", \"1天\"))\r\n self.comboBox_crawltime4.setItemText(3, _translate(\"Form_dataprocessing\", \"1周\"))\r\n self.comboBox_crawltime4.setItemText(4, _translate(\"Form_dataprocessing\", \"3周\"))\r\n self.comboBox_crawltime4.setItemText(5, _translate(\"Form_dataprocessing\", \"1个月\"))\r\n self.comboBox_crawltime4.setItemText(6, _translate(\"Form_dataprocessing\", \"半年\"))\r\n self.comboBox_crawltime4.setItemText(7, _translate(\"Form_dataprocessing\", \"1年\"))\r\n self.comboBox_crawltime4.setItemText(8, _translate(\"Form_dataprocessing\", \"2年\"))\r\n self.label.setText(_translate(\"Form_dataprocessing\", \"数据类型:\"))\r\n self.comboBox_targettype.setItemText(0, _translate(\"Form_dataprocessing\", \"长方形爬虫数据结果\"))\r\n self.comboBox_targettype.setItemText(1, _translate(\"Form_dataprocessing\", \"正方形爬虫数据结果\"))\r\n self.comboBox_targettype.setItemText(2, _translate(\"Form_dataprocessing\", \"指定线路爬虫数据结果\"))\r\n self.label_2.setText(_translate(\"Form_dataprocessing\", \"指定目标路段:\"))\r\n self.groupBox_2.setTitle(_translate(\"Form_dataprocessing\", \"执行模块\"))\r\n self.pushButton.setText(_translate(\"Form_dataprocessing\", \"运行\"))\r\n self.groupBox_3.setTitle(_translate(\"Form_dataprocessing\", \"运行过程可视化\"))\r\n self.label_5.setText(_translate(\"Form_dataprocessing\", \"提取指定路段:\"))\r\n self.label_6.setText(_translate(\"Form_dataprocessing\", \"形成时间序列:\"))\r\n#images\r\nclass Ui_Form_images(object):\r\n def setupUi(self, Form_images):\r\n Form_images.setObjectName(\"Form_images\")\r\n Form_images.resize(690, 512)\r\n self.tabWidget = QtWidgets.QTabWidget(Form_images)\r\n self.tabWidget.setGeometry(QtCore.QRect(-4, -1, 691, 511))\r\n self.tabWidget.setObjectName(\"tabWidget\")\r\n self.tab_rectangle = QtWidgets.QWidget()\r\n self.tab_rectangle.setObjectName(\"tab_rectangle\")\r\n self.label_rectangle = QtWidgets.QLabel(self.tab_rectangle)\r\n self.label_rectangle.setGeometry(QtCore.QRect(10, 10, 671, 471))\r\n self.label_rectangle.setText(\"\")\r\n self.label_rectangle.setObjectName(\"label_rectangle\")\r\n self.textBrowser_2 = QtWidgets.QTextBrowser(self.tab_rectangle)\r\n self.textBrowser_2.setGeometry(QtCore.QRect(510, 100, 171, 71))\r\n self.textBrowser_2.setObjectName(\"textBrowser_2\")\r\n self.tabWidget.addTab(self.tab_rectangle, \"\")\r\n self.tab_square = QtWidgets.QWidget()\r\n self.tab_square.setObjectName(\"tab_square\")\r\n self.label_square = QtWidgets.QLabel(self.tab_square)\r\n self.label_square.setGeometry(QtCore.QRect(10, 0, 671, 471))\r\n self.label_square.setText(\"\")\r\n self.label_square.setObjectName(\"label_square\")\r\n self.textBrowser = QtWidgets.QTextBrowser(self.tab_square)\r\n self.textBrowser.setGeometry(QtCore.QRect(510, 120, 171, 71))\r\n self.textBrowser.setObjectName(\"textBrowser\")\r\n self.tabWidget.addTab(self.tab_square, \"\")\r\n self.tab_road = QtWidgets.QWidget()\r\n self.tab_road.setObjectName(\"tab_road\")\r\n self.label_road = QtWidgets.QLabel(self.tab_road)\r\n self.label_road.setGeometry(QtCore.QRect(10, 10, 671, 471))\r\n self.label_road.setText(\"\")\r\n self.label_road.setObjectName(\"label_road\")\r\n self.label = QtWidgets.QLabel(self.tab_road)\r\n self.label.setGeometry(QtCore.QRect(30, 10, 381, 16))\r\n self.label.setObjectName(\"label\")\r\n self.tabWidget.addTab(self.tab_road, \"\")\r\n\r\n self.retranslateUi(Form_images)\r\n self.tabWidget.setCurrentIndex(0)\r\n QtCore.QMetaObject.connectSlotsByName(Form_images)\r\n\r\n def retranslateUi(self, Form_images):\r\n _translate = QtCore.QCoreApplication.translate\r\n Form_images.setWindowTitle(_translate(\"Form_images\", \"查看详情——区域形式\"))\r\n self.textBrowser_2.setHtml(_translate(\"Form_images\", \"\\n\"\r\n\"\\n\"\r\n\"

由于矩形对角线不能超过10公里,所以通过拼接矩形的方法,扩大爬取数据范围,长方形示例如下图方形框内的数据。

\\n\"\r\n\"


\"))\r\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_rectangle), _translate(\"Form_images\", \"长方形\"))\r\n self.textBrowser.setHtml(_translate(\"Form_images\", \"\\n\"\r\n\"\\n\"\r\n\"

由于矩形对角线不能超过10公里,所以通过拼接矩形的方法,扩大爬取数据范围,正方形示例如下图方形框内的数据。

\\n\"\r\n\"


\"))\r\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_square), _translate(\"Form_images\", \"正方形\"))\r\n self.label.setText(_translate(\"Form_images\", \"指定线路的示例如下图的红色路段:\"))\r\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_road), _translate(\"Form_images\", \"指定线路\"))\r\n#mainwindow\r\nclass Ui_MainWindow(object):\r\n def setupUi(self, MainWindow):\r\n MainWindow.setObjectName(\"MainWindow\")\r\n MainWindow.resize(493, 397)\r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.groupBox = QtWidgets.QGroupBox(self.centralwidget)\r\n self.groupBox.setGeometry(QtCore.QRect(30, 30, 261, 111))\r\n self.groupBox.setObjectName(\"groupBox\")\r\n self.label_gdgw = QtWidgets.QLabel(self.groupBox)\r\n self.label_gdgw.setGeometry(QtCore.QRect(11, 21, 168, 16))\r\n self.label_gdgw.setObjectName(\"label_gdgw\")\r\n self.label_gdcoordinate = QtWidgets.QLabel(self.groupBox)\r\n self.label_gdcoordinate.setGeometry(QtCore.QRect(11, 53, 120, 16))\r\n self.label_gdcoordinate.setObjectName(\"label_gdcoordinate\")\r\n self.label_xingzheng = QtWidgets.QLabel(self.groupBox)\r\n self.label_xingzheng.setGeometry(QtCore.QRect(11, 84, 120, 16))\r\n self.label_xingzheng.setObjectName(\"label_xingzheng\")\r\n self.pushButton_coordinateconversion = QtWidgets.QPushButton(self.groupBox)\r\n self.pushButton_coordinateconversion.setGeometry(QtCore.QRect(140, 80, 111, 23))\r\n self.pushButton_coordinateconversion.setObjectName(\"pushButton_coordinateconversion\")\r\n self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)\r\n self.groupBox_2.setGeometry(QtCore.QRect(40, 170, 241, 141))\r\n self.groupBox_2.setObjectName(\"groupBox_2\")\r\n self.layoutWidget = QtWidgets.QWidget(self.groupBox_2)\r\n self.layoutWidget.setGeometry(QtCore.QRect(20, 30, 91, 101))\r\n self.layoutWidget.setObjectName(\"layoutWidget\")\r\n self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget)\r\n self.verticalLayout.setContentsMargins(0, 0, 0, 0)\r\n self.verticalLayout.setObjectName(\"verticalLayout\")\r\n self.pushButton_rectangle = QtWidgets.QPushButton(self.layoutWidget)\r\n self.pushButton_rectangle.setObjectName(\"pushButton_rectangle\")\r\n self.verticalLayout.addWidget(self.pushButton_rectangle)\r\n self.pushButton_square = QtWidgets.QPushButton(self.layoutWidget)\r\n self.pushButton_square.setObjectName(\"pushButton_square\")\r\n self.verticalLayout.addWidget(self.pushButton_square)\r\n self.pushButton_road = QtWidgets.QPushButton(self.layoutWidget)\r\n self.pushButton_road.setObjectName(\"pushButton_road\")\r\n self.verticalLayout.addWidget(self.pushButton_road)\r\n self.pushButton_images = QtWidgets.QPushButton(self.groupBox_2)\r\n self.pushButton_images.setGeometry(QtCore.QRect(140, 60, 75, 23))\r\n self.pushButton_images.setObjectName(\"pushButton_images\")\r\n self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget)\r\n self.groupBox_3.setGeometry(QtCore.QRect(310, 40, 141, 61))\r\n self.groupBox_3.setObjectName(\"groupBox_3\")\r\n self.pushButton_dataprocessing = QtWidgets.QPushButton(self.groupBox_3)\r\n self.pushButton_dataprocessing.setGeometry(QtCore.QRect(30, 20, 75, 23))\r\n self.pushButton_dataprocessing.setObjectName(\"pushButton_dataprocessing\")\r\n self.groupBox_4 = QtWidgets.QGroupBox(self.centralwidget)\r\n self.groupBox_4.setGeometry(QtCore.QRect(310, 160, 141, 61))\r\n self.groupBox_4.setObjectName(\"groupBox_4\")\r\n self.pushButton_predict = QtWidgets.QPushButton(self.groupBox_4)\r\n self.pushButton_predict.setGeometry(QtCore.QRect(30, 20, 75, 23))\r\n self.pushButton_predict.setObjectName(\"pushButton_predict\")\r\n self.line = QtWidgets.QFrame(self.centralwidget)\r\n self.line.setGeometry(QtCore.QRect(290, 20, 20, 321))\r\n self.line.setFrameShape(QtWidgets.QFrame.VLine)\r\n self.line.setFrameShadow(QtWidgets.QFrame.Sunken)\r\n self.line.setObjectName(\"line\")\r\n self.line_2 = QtWidgets.QFrame(self.centralwidget)\r\n self.line_2.setGeometry(QtCore.QRect(20, 150, 281, 16))\r\n self.line_2.setFrameShape(QtWidgets.QFrame.HLine)\r\n self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)\r\n self.line_2.setObjectName(\"line_2\")\r\n self.line_3 = QtWidgets.QFrame(self.centralwidget)\r\n self.line_3.setGeometry(QtCore.QRect(20, 330, 451, 16))\r\n self.line_3.setFrameShape(QtWidgets.QFrame.HLine)\r\n self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken)\r\n self.line_3.setObjectName(\"line_3\")\r\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton.setGeometry(QtCore.QRect(340, 280, 75, 23))\r\n self.pushButton.setObjectName(\"pushButton\")\r\n self.line_4 = QtWidgets.QFrame(self.centralwidget)\r\n self.line_4.setGeometry(QtCore.QRect(460, 20, 20, 321))\r\n self.line_4.setFrameShape(QtWidgets.QFrame.VLine)\r\n self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken)\r\n self.line_4.setObjectName(\"line_4\")\r\n self.line_5 = QtWidgets.QFrame(self.centralwidget)\r\n self.line_5.setGeometry(QtCore.QRect(300, 110, 171, 20))\r\n self.line_5.setFrameShape(QtWidgets.QFrame.HLine)\r\n self.line_5.setFrameShadow(QtWidgets.QFrame.Sunken)\r\n self.line_5.setObjectName(\"line_5\")\r\n self.line_6 = QtWidgets.QFrame(self.centralwidget)\r\n self.line_6.setGeometry(QtCore.QRect(300, 240, 171, 20))\r\n self.line_6.setFrameShape(QtWidgets.QFrame.HLine)\r\n self.line_6.setFrameShadow(QtWidgets.QFrame.Sunken)\r\n self.line_6.setObjectName(\"line_6\")\r\n self.line_7 = QtWidgets.QFrame(self.centralwidget)\r\n self.line_7.setGeometry(QtCore.QRect(10, 20, 20, 321))\r\n self.line_7.setFrameShape(QtWidgets.QFrame.VLine)\r\n self.line_7.setFrameShadow(QtWidgets.QFrame.Sunken)\r\n self.line_7.setObjectName(\"line_7\")\r\n self.line_8 = QtWidgets.QFrame(self.centralwidget)\r\n self.line_8.setGeometry(QtCore.QRect(20, 10, 451, 16))\r\n self.line_8.setFrameShape(QtWidgets.QFrame.HLine)\r\n self.line_8.setFrameShadow(QtWidgets.QFrame.Sunken)\r\n self.line_8.setObjectName(\"line_8\")\r\n MainWindow.setCentralWidget(self.centralwidget)\r\n self.menubar = QtWidgets.QMenuBar(MainWindow)\r\n self.menubar.setGeometry(QtCore.QRect(0, 0, 493, 23))\r\n self.menubar.setObjectName(\"menubar\")\r\n MainWindow.setMenuBar(self.menubar)\r\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n MainWindow.setStatusBar(self.statusbar)\r\n\r\n self.label_gdgw.setOpenExternalLinks(True)\r\n self.label_gdcoordinate.setOpenExternalLinks(True)\r\n self.label_xingzheng.setOpenExternalLinks(True)\r\n\r\n\r\n self.retranslateUi(MainWindow)\r\n self.pushButton_coordinateconversion.clicked.connect(MainWindow.coordinatechange)\r\n self.pushButton_rectangle.clicked.connect(MainWindow.rectangleclick)\r\n self.pushButton_square.clicked.connect(MainWindow.squareclick)\r\n self.pushButton_road.clicked.connect(MainWindow.roadclick)\r\n self.pushButton_images.clicked.connect(MainWindow.imageclick)\r\n self.pushButton_dataprocessing.clicked.connect(MainWindow.dataprocessing)\r\n self.pushButton_predict.clicked.connect(MainWindow.predict)\r\n self.pushButton.clicked.connect(MainWindow.close)\r\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\r\n\r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"主窗口——陈国强作品\"))\r\n self.groupBox.setTitle(_translate(\"MainWindow\", \"模块1:模块2相关参数参考资料\"))\r\n self.label_gdgw.setText(_translate(\"MainWindow\", \"高德地图交通态势开发指南官网\"))\r\n self.label_gdcoordinate.setText(_translate(\"MainWindow\", \"高德地图拾取坐标系统\"))\r\n self.label_xingzheng.setText(_translate(\"MainWindow\", \"行政区域坐标拾取系统\"))\r\n self.pushButton_coordinateconversion.setText(_translate(\"MainWindow\", \"坐标转换\"))\r\n self.groupBox_2.setTitle(_translate(\"MainWindow\", \"模块2:自动生成爬虫代码\"))\r\n self.pushButton_rectangle.setText(_translate(\"MainWindow\", \"长方形区域\"))\r\n self.pushButton_square.setText(_translate(\"MainWindow\", \"正方形区域\"))\r\n self.pushButton_road.setText(_translate(\"MainWindow\", \"指定路线\"))\r\n self.pushButton_images.setText(_translate(\"MainWindow\", \"查看详情\"))\r\n self.groupBox_3.setTitle(_translate(\"MainWindow\", \"模块3:数据处理\"))\r\n self.pushButton_dataprocessing.setText(_translate(\"MainWindow\", \"数据处理\"))\r\n self.groupBox_4.setTitle(_translate(\"MainWindow\", \"模块4:数据预测\"))\r\n self.pushButton_predict.setText(_translate(\"MainWindow\", \"数据预测\"))\r\n self.pushButton.setText(_translate(\"MainWindow\", \"关闭\"))\r\n#predict\r\nclass Ui_Form_predict(object):\r\n def setupUi(self, Form_predict):\r\n Form_predict.setObjectName(\"Form_predict\")\r\n Form_predict.resize(1226, 615)\r\n self.scrollArea = QtWidgets.QScrollArea(Form_predict)\r\n self.scrollArea.setGeometry(QtCore.QRect(10, 10, 1181, 591))\r\n self.scrollArea.setWidgetResizable(True)\r\n self.scrollArea.setObjectName(\"scrollArea\")\r\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\r\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, -466, 1162, 1701))\r\n self.scrollAreaWidgetContents.setMinimumSize(QtCore.QSize(700, 1701))\r\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\r\n self.label = QtWidgets.QLabel(self.scrollAreaWidgetContents)\r\n self.label.setGeometry(QtCore.QRect(860, 90, 261, 16))\r\n self.label.setObjectName(\"label\")\r\n self.groupBox_correlation = QtWidgets.QGroupBox(self.scrollAreaWidgetContents)\r\n self.groupBox_correlation.setGeometry(QtCore.QRect(10, 40, 801, 531))\r\n self.groupBox_correlation.setObjectName(\"groupBox_correlation\")\r\n self.matplotlibwidget_correlation = MatplotlibWidget(self.groupBox_correlation)\r\n self.matplotlibwidget_correlation.setGeometry(QtCore.QRect(10, 20, 771, 471))\r\n self.matplotlibwidget_correlation.setObjectName(\"matplotlibwidget_correlation\")\r\n self.pushButton_correlation = QtWidgets.QPushButton(self.groupBox_correlation)\r\n self.pushButton_correlation.setGeometry(QtCore.QRect(360, 500, 81, 23))\r\n self.pushButton_correlation.setObjectName(\"pushButton_correlation\")\r\n self.groupBox_arima = QtWidgets.QGroupBox(self.scrollAreaWidgetContents)\r\n self.groupBox_arima.setGeometry(QtCore.QRect(10, 590, 801, 531))\r\n self.groupBox_arima.setObjectName(\"groupBox_arima\")\r\n self.matplotlibwidget_arimapre = MatplotlibWidget(self.groupBox_arima)\r\n self.matplotlibwidget_arimapre.setGeometry(QtCore.QRect(10, 20, 771, 471))\r\n self.matplotlibwidget_arimapre.setObjectName(\"matplotlibwidget_arimapre\")\r\n self.pushButton_arimapre = QtWidgets.QPushButton(self.groupBox_arima)\r\n self.pushButton_arimapre.setGeometry(QtCore.QRect(360, 500, 81, 23))\r\n self.pushButton_arimapre.setObjectName(\"pushButton_arimapre\")\r\n self.pushButton_arimapre.raise_()\r\n self.matplotlibwidget_arimapre.raise_()\r\n self.textEdit_arima = QtWidgets.QTextEdit(self.scrollAreaWidgetContents)\r\n self.textEdit_arima.setGeometry(QtCore.QRect(830, 800, 321, 201))\r\n self.textEdit_arima.setObjectName(\"textEdit_arima\")\r\n self.groupBox = QtWidgets.QGroupBox(self.scrollAreaWidgetContents)\r\n self.groupBox.setGeometry(QtCore.QRect(840, 160, 291, 111))\r\n self.groupBox.setObjectName(\"groupBox\")\r\n self.layoutWidget = QtWidgets.QWidget(self.groupBox)\r\n self.layoutWidget.setGeometry(QtCore.QRect(20, 30, 241, 22))\r\n self.layoutWidget.setObjectName(\"layoutWidget\")\r\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget)\r\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\r\n self.label_2 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_2.setObjectName(\"label_2\")\r\n self.horizontalLayout.addWidget(self.label_2)\r\n self.comboBox_datavolume = QtWidgets.QComboBox(self.layoutWidget)\r\n self.comboBox_datavolume.setObjectName(\"comboBox_datavolume\")\r\n self.comboBox_datavolume.addItem(\"\")\r\n self.comboBox_datavolume.addItem(\"\")\r\n self.comboBox_datavolume.addItem(\"\")\r\n self.horizontalLayout.addWidget(self.comboBox_datavolume)\r\n self.layoutWidget1 = QtWidgets.QWidget(self.groupBox)\r\n self.layoutWidget1.setGeometry(QtCore.QRect(20, 70, 261, 22))\r\n self.layoutWidget1.setObjectName(\"layoutWidget1\")\r\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget1)\r\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\r\n self.label_4 = QtWidgets.QLabel(self.layoutWidget1)\r\n self.label_4.setObjectName(\"label_4\")\r\n self.horizontalLayout_2.addWidget(self.label_4)\r\n self.lineEdit_targetroad = QtWidgets.QLineEdit(self.layoutWidget1)\r\n self.lineEdit_targetroad.setObjectName(\"lineEdit_targetroad\")\r\n self.horizontalLayout_2.addWidget(self.lineEdit_targetroad)\r\n self.progressBar_arima = QtWidgets.QProgressBar(self.scrollAreaWidgetContents)\r\n self.progressBar_arima.setGeometry(QtCore.QRect(900, 740, 211, 23))\r\n self.progressBar_arima.setProperty(\"value\", 0)\r\n self.progressBar_arima.setObjectName(\"progressBar_arima\")\r\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\r\n\r\n self.retranslateUi(Form_predict)\r\n self.pushButton_correlation.clicked.connect(Form_predict.correlation)\r\n self.pushButton_arimapre.clicked.connect(Form_predict.arimaclick)\r\n QtCore.QMetaObject.connectSlotsByName(Form_predict)\r\n\r\n def retranslateUi(self, Form_predict):\r\n _translate = QtCore.QCoreApplication.translate\r\n Form_predict.setWindowTitle(_translate(\"Form_predict\", \"数据预测\"))\r\n self.label.setText(_translate(\"Form_predict\", \"注意:数据预测功能的实现需要1周以上的数据量\"))\r\n self.groupBox_correlation.setTitle(_translate(\"Form_predict\", \"工作日、休息日相关性可视化\"))\r\n self.pushButton_correlation.setText(_translate(\"Form_predict\", \"相关性可视化\"))\r\n self.groupBox_arima.setTitle(_translate(\"Form_predict\", \"ARIMA预测\"))\r\n self.pushButton_arimapre.setText(_translate(\"Form_predict\", \"预测\"))\r\n self.textEdit_arima.setHtml(_translate(\"Form_predict\", \"\\n\"\r\n\"\\n\"\r\n\"

预测过程:

\"))\r\n self.groupBox.setTitle(_translate(\"Form_predict\", \"数据输入\"))\r\n self.label_2.setText(_translate(\"Form_predict\", \"数据量:\"))\r\n self.comboBox_datavolume.setItemText(0, _translate(\"Form_predict\", \"1周\"))\r\n self.comboBox_datavolume.setItemText(1, _translate(\"Form_predict\", \"3周\"))\r\n self.comboBox_datavolume.setItemText(2, _translate(\"Form_predict\", \"1个月\"))\r\n self.label_4.setText(_translate(\"Form_predict\", \"指定目标路段:\"))\r\n#rectangle createcode\r\nclass Ui_Form_rectangle(object):\r\n def setupUi(self, Form_rectangle):\r\n Form_rectangle.setObjectName(\"Form_rectangle\")\r\n Form_rectangle.resize(311, 225)\r\n self.button_code = QtWidgets.QPushButton(Form_rectangle)\r\n self.button_code.setGeometry(QtCore.QRect(120, 180, 75, 23))\r\n self.button_code.setObjectName(\"button_code\")\r\n self.layoutWidget_2 = QtWidgets.QWidget(Form_rectangle)\r\n self.layoutWidget_2.setGeometry(QtCore.QRect(60, 20, 181, 22))\r\n self.layoutWidget_2.setObjectName(\"layoutWidget_2\")\r\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget_2)\r\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\r\n self.label_2 = QtWidgets.QLabel(self.layoutWidget_2)\r\n self.label_2.setObjectName(\"label_2\")\r\n self.horizontalLayout_2.addWidget(self.label_2)\r\n self.comboBox_crawltime1 = QtWidgets.QComboBox(self.layoutWidget_2)\r\n self.comboBox_crawltime1.setObjectName(\"comboBox_crawltime1\")\r\n self.comboBox_crawltime1.addItem(\"\")\r\n self.comboBox_crawltime1.addItem(\"\")\r\n self.comboBox_crawltime1.addItem(\"\")\r\n self.comboBox_crawltime1.addItem(\"\")\r\n self.comboBox_crawltime1.addItem(\"\")\r\n self.comboBox_crawltime1.addItem(\"\")\r\n self.comboBox_crawltime1.addItem(\"\")\r\n self.comboBox_crawltime1.addItem(\"\")\r\n self.comboBox_crawltime1.addItem(\"\")\r\n self.horizontalLayout_2.addWidget(self.comboBox_crawltime1)\r\n self.layoutWidget = QtWidgets.QWidget(Form_rectangle)\r\n self.layoutWidget.setGeometry(QtCore.QRect(40, 60, 231, 101))\r\n self.layoutWidget.setObjectName(\"layoutWidget\")\r\n self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget)\r\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\r\n self.gridLayout.setObjectName(\"gridLayout\")\r\n self.label_baselat = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_baselat.setObjectName(\"label_baselat\")\r\n self.gridLayout.addWidget(self.label_baselat, 2, 0, 1, 1)\r\n self.label_key = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_key.setObjectName(\"label_key\")\r\n self.gridLayout.addWidget(self.label_key, 0, 0, 1, 1)\r\n self.lineEdit_baselat = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.lineEdit_baselat.setObjectName(\"lineEdit_baselat\")\r\n self.gridLayout.addWidget(self.lineEdit_baselat, 2, 1, 1, 1)\r\n self.lineEdit_key = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.lineEdit_key.setObjectName(\"lineEdit_key\")\r\n self.gridLayout.addWidget(self.lineEdit_key, 0, 1, 1, 1)\r\n self.label_baselng = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_baselng.setObjectName(\"label_baselng\")\r\n self.gridLayout.addWidget(self.label_baselng, 1, 0, 1, 1)\r\n self.lineEdit_baselng = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.lineEdit_baselng.setObjectName(\"lineEdit_baselng\")\r\n self.gridLayout.addWidget(self.lineEdit_baselng, 1, 1, 1, 1)\r\n\r\n self.retranslateUi(Form_rectangle)\r\n self.button_code.clicked.connect(Form_rectangle.createcode)\r\n QtCore.QMetaObject.connectSlotsByName(Form_rectangle)\r\n\r\n def retranslateUi(self, Form_rectangle):\r\n _translate = QtCore.QCoreApplication.translate\r\n Form_rectangle.setWindowTitle(_translate(\"Form_rectangle\", \"矩形代码生成\"))\r\n self.button_code.setText(_translate(\"Form_rectangle\", \"生成代码\"))\r\n self.label_2.setText(_translate(\"Form_rectangle\", \"爬取时间:\"))\r\n self.comboBox_crawltime1.setItemText(0, _translate(\"Form_rectangle\", \"1小时\"))\r\n self.comboBox_crawltime1.setItemText(1, _translate(\"Form_rectangle\", \"17小时\"))\r\n self.comboBox_crawltime1.setItemText(2, _translate(\"Form_rectangle\", \"1天\"))\r\n self.comboBox_crawltime1.setItemText(3, _translate(\"Form_rectangle\", \"1周\"))\r\n self.comboBox_crawltime1.setItemText(4, _translate(\"Form_rectangle\", \"3周\"))\r\n self.comboBox_crawltime1.setItemText(5, _translate(\"Form_rectangle\", \"1个月\"))\r\n self.comboBox_crawltime1.setItemText(6, _translate(\"Form_rectangle\", \"半年\"))\r\n self.comboBox_crawltime1.setItemText(7, _translate(\"Form_rectangle\", \"1年\"))\r\n self.comboBox_crawltime1.setItemText(8, _translate(\"Form_rectangle\", \"2年\"))\r\n self.label_baselat.setText(_translate(\"Form_rectangle\", \"纬度:\"))\r\n self.label_key.setText(_translate(\"Form_rectangle\", \"密钥:\"))\r\n self.label_baselng.setText(_translate(\"Form_rectangle\", \"经度:\"))\r\n#road createcode\r\nclass Ui_Form_road(object):\r\n def setupUi(self, Form_road):\r\n Form_road.setObjectName(\"Form_road\")\r\n Form_road.resize(270, 243)\r\n self.button_code = QtWidgets.QPushButton(Form_road)\r\n self.button_code.setGeometry(QtCore.QRect(90, 210, 75, 23))\r\n self.button_code.setObjectName(\"button_code\")\r\n self.layoutWidget = QtWidgets.QWidget(Form_road)\r\n self.layoutWidget.setGeometry(QtCore.QRect(20, 60, 241, 131))\r\n self.layoutWidget.setObjectName(\"layoutWidget\")\r\n self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget)\r\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\r\n self.gridLayout.setObjectName(\"gridLayout\")\r\n self.label_key = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_key.setObjectName(\"label_key\")\r\n self.gridLayout.addWidget(self.label_key, 0, 0, 1, 1)\r\n self.lineEdit_key = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.lineEdit_key.setObjectName(\"lineEdit_key\")\r\n self.gridLayout.addWidget(self.lineEdit_key, 0, 1, 1, 1)\r\n self.label_cityname = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_cityname.setObjectName(\"label_cityname\")\r\n self.gridLayout.addWidget(self.label_cityname, 1, 0, 1, 1)\r\n self.lineEdit_cityname = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.lineEdit_cityname.setObjectName(\"lineEdit_cityname\")\r\n self.gridLayout.addWidget(self.lineEdit_cityname, 1, 1, 1, 1)\r\n self.label_roadname = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_roadname.setObjectName(\"label_roadname\")\r\n self.gridLayout.addWidget(self.label_roadname, 2, 0, 1, 1)\r\n self.lineEdit_roadname = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.lineEdit_roadname.setObjectName(\"lineEdit_roadname\")\r\n self.gridLayout.addWidget(self.lineEdit_roadname, 2, 1, 1, 1)\r\n self.layoutWidget_2 = QtWidgets.QWidget(Form_road)\r\n self.layoutWidget_2.setGeometry(QtCore.QRect(50, 20, 181, 22))\r\n self.layoutWidget_2.setObjectName(\"layoutWidget_2\")\r\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget_2)\r\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\r\n self.label = QtWidgets.QLabel(self.layoutWidget_2)\r\n self.label.setObjectName(\"label\")\r\n self.horizontalLayout.addWidget(self.label)\r\n self.comboBox_crawltime3 = QtWidgets.QComboBox(self.layoutWidget_2)\r\n self.comboBox_crawltime3.setObjectName(\"comboBox_crawltime3\")\r\n self.comboBox_crawltime3.addItem(\"\")\r\n self.comboBox_crawltime3.addItem(\"\")\r\n self.comboBox_crawltime3.addItem(\"\")\r\n self.comboBox_crawltime3.addItem(\"\")\r\n self.comboBox_crawltime3.addItem(\"\")\r\n self.comboBox_crawltime3.addItem(\"\")\r\n self.comboBox_crawltime3.addItem(\"\")\r\n self.comboBox_crawltime3.addItem(\"\")\r\n self.comboBox_crawltime3.addItem(\"\")\r\n self.horizontalLayout.addWidget(self.comboBox_crawltime3)\r\n\r\n self.retranslateUi(Form_road)\r\n self.button_code.clicked.connect(Form_road.createcode)\r\n QtCore.QMetaObject.connectSlotsByName(Form_road)\r\n\r\n def retranslateUi(self, Form_road):\r\n _translate = QtCore.QCoreApplication.translate\r\n Form_road.setWindowTitle(_translate(\"Form_road\", \"指定线路代码生成\"))\r\n self.button_code.setText(_translate(\"Form_road\", \"生成代码\"))\r\n self.label_key.setText(_translate(\"Form_road\", \"密钥:\"))\r\n self.label_cityname.setText(_translate(\"Form_road\", \"城市:\"))\r\n self.label_roadname.setText(_translate(\"Form_road\", \"路段名称:\"))\r\n self.label.setText(_translate(\"Form_road\", \"爬取时间:\"))\r\n self.comboBox_crawltime3.setItemText(0, _translate(\"Form_road\", \"1小时\"))\r\n self.comboBox_crawltime3.setItemText(1, _translate(\"Form_road\", \"17小时\"))\r\n self.comboBox_crawltime3.setItemText(2, _translate(\"Form_road\", \"1天\"))\r\n self.comboBox_crawltime3.setItemText(3, _translate(\"Form_road\", \"1周\"))\r\n self.comboBox_crawltime3.setItemText(4, _translate(\"Form_road\", \"3周\"))\r\n self.comboBox_crawltime3.setItemText(5, _translate(\"Form_road\", \"1个月\"))\r\n self.comboBox_crawltime3.setItemText(6, _translate(\"Form_road\", \"半年\"))\r\n self.comboBox_crawltime3.setItemText(7, _translate(\"Form_road\", \"1年\"))\r\n self.comboBox_crawltime3.setItemText(8, _translate(\"Form_road\", \"2年\"))\r\n#square createcode\r\nclass Ui_Form_square(object):\r\n def setupUi(self, Form_square):\r\n Form_square.setObjectName(\"Form_square\")\r\n Form_square.resize(311, 258)\r\n self.button_code = QtWidgets.QPushButton(Form_square)\r\n self.button_code.setGeometry(QtCore.QRect(110, 210, 75, 23))\r\n self.button_code.setObjectName(\"button_code\")\r\n self.layoutWidget_2 = QtWidgets.QWidget(Form_square)\r\n self.layoutWidget_2.setGeometry(QtCore.QRect(60, 20, 181, 22))\r\n self.layoutWidget_2.setObjectName(\"layoutWidget_2\")\r\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget_2)\r\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\r\n self.label_2 = QtWidgets.QLabel(self.layoutWidget_2)\r\n self.label_2.setObjectName(\"label_2\")\r\n self.horizontalLayout_2.addWidget(self.label_2)\r\n self.comboBox_crawltime2 = QtWidgets.QComboBox(self.layoutWidget_2)\r\n self.comboBox_crawltime2.setObjectName(\"comboBox_crawltime2\")\r\n self.comboBox_crawltime2.addItem(\"\")\r\n self.comboBox_crawltime2.addItem(\"\")\r\n self.comboBox_crawltime2.addItem(\"\")\r\n self.comboBox_crawltime2.addItem(\"\")\r\n self.comboBox_crawltime2.addItem(\"\")\r\n self.comboBox_crawltime2.addItem(\"\")\r\n self.comboBox_crawltime2.addItem(\"\")\r\n self.comboBox_crawltime2.addItem(\"\")\r\n self.comboBox_crawltime2.addItem(\"\")\r\n self.horizontalLayout_2.addWidget(self.comboBox_crawltime2)\r\n self.layoutWidget = QtWidgets.QWidget(Form_square)\r\n self.layoutWidget.setGeometry(QtCore.QRect(40, 70, 231, 101))\r\n self.layoutWidget.setObjectName(\"layoutWidget\")\r\n self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget)\r\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\r\n self.gridLayout.setObjectName(\"gridLayout\")\r\n self.label_baselat = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_baselat.setObjectName(\"label_baselat\")\r\n self.gridLayout.addWidget(self.label_baselat, 2, 0, 1, 1)\r\n self.label_key = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_key.setObjectName(\"label_key\")\r\n self.gridLayout.addWidget(self.label_key, 0, 0, 1, 1)\r\n self.lineEdit_baselat = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.lineEdit_baselat.setObjectName(\"lineEdit_baselat\")\r\n self.gridLayout.addWidget(self.lineEdit_baselat, 2, 1, 1, 1)\r\n self.lineEdit_key = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.lineEdit_key.setObjectName(\"lineEdit_key\")\r\n self.gridLayout.addWidget(self.lineEdit_key, 0, 1, 1, 1)\r\n self.label_baselng = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_baselng.setObjectName(\"label_baselng\")\r\n self.gridLayout.addWidget(self.label_baselng, 1, 0, 1, 1)\r\n self.lineEdit_baselng = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.lineEdit_baselng.setObjectName(\"lineEdit_baselng\")\r\n self.gridLayout.addWidget(self.lineEdit_baselng, 1, 1, 1, 1)\r\n\r\n self.retranslateUi(Form_square)\r\n self.button_code.clicked.connect(Form_square.createcode)\r\n QtCore.QMetaObject.connectSlotsByName(Form_square)\r\n\r\n def retranslateUi(self, Form_square):\r\n _translate = QtCore.QCoreApplication.translate\r\n Form_square.setWindowTitle(_translate(\"Form_square\", \"正方形代码生成\"))\r\n self.button_code.setText(_translate(\"Form_square\", \"生成代码\"))\r\n self.label_2.setText(_translate(\"Form_square\", \"爬取时间:\"))\r\n self.comboBox_crawltime2.setItemText(0, _translate(\"Form_square\", \"1小时\"))\r\n self.comboBox_crawltime2.setItemText(1, _translate(\"Form_square\", \"17小时\"))\r\n self.comboBox_crawltime2.setItemText(2, _translate(\"Form_square\", \"1天\"))\r\n self.comboBox_crawltime2.setItemText(3, _translate(\"Form_square\", \"1周\"))\r\n self.comboBox_crawltime2.setItemText(4, _translate(\"Form_square\", \"3周\"))\r\n self.comboBox_crawltime2.setItemText(5, _translate(\"Form_square\", \"1个月\"))\r\n self.comboBox_crawltime2.setItemText(6, _translate(\"Form_square\", \"半年\"))\r\n self.comboBox_crawltime2.setItemText(7, _translate(\"Form_square\", \"1年\"))\r\n self.comboBox_crawltime2.setItemText(8, _translate(\"Form_square\", \"2年\"))\r\n self.label_baselat.setText(_translate(\"Form_square\", \"纬度:\"))\r\n self.label_key.setText(_translate(\"Form_square\", \"密钥:\"))\r\n self.label_baselng.setText(_translate(\"Form_square\", \"经度:\"))\r\n#dialog information 已删除,用QMessage替换\r\n#如果想使用户体验感再好一点,可以选择将information放在“数据处理结尾处”和“arima预测结尾处,正在绘图”,未考虑运行速度,本代码未加入\r\n#matplotlib widget\r\nclass MyMplCanvas(FigureCanvas):\r\n def __init__(self,parent=None,width=6,height=5,dpi=100):\r\n #设置中文显示\r\n plt.rcParams['font.family']=['SimHei']#用来正常显示中文标签\r\n plt.rcParams['axes.unicode_minus']=False#用来正常显示负号\r\n #新建一个绘图对象\r\n self.fig=Figure(figsize=(width,height),dpi=dpi)\r\n #建立一个子图,如果要建立复合图,可以在这里修改\r\n self.axes=self.fig.add_subplot(111)\r\n FigureCanvas.__init__(self,self.fig)\r\n self.setParent(parent)\r\n\r\n '''定义FigureCanvas的尺寸策略,意思是设置FigureCanvas,使之尽可能向外填充空间'''\r\n FigureCanvas.setSizePolicy(self,\r\n QSizePolicy.Expanding,\r\n QSizePolicy.Expanding)\r\n FigureCanvas.updateGeometry(self)\r\n '''绘制静态图,可以在这里定义自己的绘图逻辑'''\r\n\r\n def start_correlation_plot(self,weekdayline,weekendline):\r\n self.axes.plot(weekdayline, label=r'工作日', linestyle='-') # 有无u都无所谓#\r\n self.axes.plot(weekendline, label=r'休息日', linestyle='--') # 有无u都无所谓\r\n self.axes.set_xlabel('时间', fontproperties='SimHei', fontsize=10)\r\n self.axes.set_ylabel('车速', fontproperties='SimHei', fontsize=10)\r\n self.axes.set_title(r'休息日、工作日平均速度相关性可视化比较', fontproperties='SimHei', fontsize=12)\r\n self.axes.grid(True) # 加入栅栏,缓和曲线,网格\r\n self.axes.legend(loc='best')\r\n\r\n def start_arima_plot(self,pred_arima,test,MAE_arima):\r\n self.axes.plot(pred_arima,label='预测值', linestyle='-')\r\n self.axes.plot(test,label='实际值', linestyle='--')\r\n self.axes.set_xlabel('时间', fontproperties='SimHei', fontsize=10)\r\n self.axes.set_ylabel('车速', fontproperties='SimHei', fontsize=10)\r\n self.axes.set_title('ARIMA模型预测结果的MAE: %.4f' % MAE_arima, fontproperties='SimHei', fontsize=12)\r\n self.axes.grid(True) # 加入栅栏,缓和曲线,网格\r\n self.axes.legend(loc='best')\r\n\r\n def start_ann_plot(self,pred_ann,test,MAE_ann):\r\n self.axes.plot(pred_ann,label='预测值', linestyle='-')\r\n self.axes.plot(test,label='实际值', linestyle='--')\r\n self.axes.set_xlabel('时间', fontproperties='SimHei', fontsize=10)\r\n self.axes.set_ylabel('车速', fontproperties='SimHei', fontsize=10)\r\n self.axes.set_title('简单神经网络预测结果的MAE: %.4f' % MAE_ann, fontproperties='SimHei', fontsize=12)\r\n self.axes.grid(True) # 加入栅栏,缓和曲线,网格\r\n self.axes.legend(loc='best')\r\nclass MatplotlibWidget(QWidget):\r\n def __init__(self, parent=None):\r\n super(MatplotlibWidget, self).__init__(parent)\r\n self.initUi()\r\n\r\n def initUi(self):\r\n self.layout=QVBoxLayout(self)\r\n self.mpl=MyMplCanvas(self,width=6,height=5,dpi=100)\r\n '''下面两个绘图函数放在if name中和initUi中要过是一样的,区别在于:放在if name中不ui。show,但放在initUi,需要ui.show(),考虑简便性,将其放在initUi中'''\r\n #self.mpl.start_correlation_plot()# 测试静态图效果\r\n self.mpl_ntb=NavigationToolbar(self.mpl,self)#添加完整的工具栏\r\n\r\n self.layout.addWidget(self.mpl)\r\n self.layout.addWidget(self.mpl_ntb)\r\n'''\r\n↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓\r\n逻辑代码\r\n'''\r\nclass MainWindow(QMainWindow,Ui_MainWindow):\r\n def __init__(self):\r\n super(MainWindow, self).__init__()\r\n self.setupUi(self)\r\n self.child_conversion = ChildForm_conversion()\r\n self.child_rectangle = ChildForm_rectangle()\r\n self.child_square = ChildForm_square()\r\n self.child_road = ChildForm_road()\r\n self.child_images = ChildForm_images()\r\n self.child_dataprocessing = ChildForm_dataprocessing()\r\n self.child_predict = ChildForm_predict()\r\n def coordinatechange(self):\r\n self.child_conversion.show()\r\n def rectangleclick(self):\r\n self.child_rectangle.show()\r\n def squareclick(self):\r\n self.child_square.show()\r\n def roadclick(self):\r\n self.child_road.show()\r\n def imageclick(self):\r\n self.child_images.show()\r\n def dataprocessing(self):\r\n self.child_dataprocessing.show()\r\n def predict(self):\r\n self.child_predict.show()\r\n\r\nclass ChildForm_conversion(QWidget,Ui_Form_conversion):\r\n def __init__(self):\r\n super(ChildForm_conversion, self).__init__()\r\n self.setupUi(self)\r\n\r\n def conversion(self):\r\n key = self.lineEdit_key.text()\r\n ocoordinate=self.lineEdit_ocoordinate.text()\r\n coordinatetype=self.comboBox_coordinatetype.currentText()\r\n\r\n rep = requests.get('http://restapi.amap.com/v3/assistant/coordinate/convert?key=' + key + '&locations=' + ocoordinate + '&coordsys=' + coordinatetype)\r\n rep.encoding = 'utf-8'\r\n print(rep.json())\r\n\r\n locations = rep.json()['locations']\r\n locations=eval(locations)#将str变为tuple,便于分出“逗号”前后的经纬度\r\n location1=round(locations[0],6)#让坐标保留至小数点后6位\r\n location2=round(locations[1],6)\r\n locations=str(location1) + ',' +str(location2)\r\n self.lineEdit_ccoordinate.setText(locations)\r\n QMessageBox.information(self,\"提示\",\"转换完成!\",QMessageBox.Yes | QMessageBox.No)\r\n\r\nclass ChildForm_rectangle(QWidget,Ui_Form_rectangle):\r\n def __init__(self):\r\n super(ChildForm_rectangle, self).__init__()\r\n self.setupUi(self)\r\n\r\n def changetext(self,a1,a2,a3,a4,b1,b2,b3,b4):\r\n with open('crawl_rectangle.py', 'r', encoding='utf-8') as f1:\r\n lines = [] # 创建了一个空列表,里面没有元素\r\n for line in f1.readlines():\r\n if line != '\\n':\r\n lines.append(line)\r\n f1.close()\r\n with open('crawl_rectangle.py', 'w', encoding='utf-8') as f2:\r\n for line in lines:\r\n if a1 in line:\r\n line = b1\r\n f2.write('%s\\n' % line)\r\n elif a2 in line:\r\n line=b2\r\n f2.write('%s\\n' % line)\r\n elif a3 in line:\r\n line=b3\r\n f2.write('%s\\n' % line)\r\n elif a4 in line:\r\n line=b4\r\n f2.write('%s\\n' % line)\r\n else:\r\n f2.write('%s' % line)\r\n f2.close()\r\n\r\n def transcrawltime(self,yhxz):\r\n if yhxz == '1小时':\r\n pqsj = '12'\r\n elif yhxz == '17小时':\r\n pqsj = '204'\r\n elif yhxz == '1天':\r\n pqsj = '288'\r\n elif yhxz == '1周':\r\n pqsj = '2016'\r\n elif yhxz == '3周':\r\n pqsj = '6048'\r\n elif yhxz == '1个月':\r\n pqsj = '8640'\r\n elif yhxz == '半年':\r\n pqsj = '51840'\r\n elif yhxz == '1年':\r\n pqsj = '103680'\r\n elif yhxz == '2年':\r\n pqsj = '207360'\r\n return pqsj\r\n\r\n def createcode(self):\r\n yhxz = self.comboBox_crawltime1.currentText()\r\n pqsj = self.transcrawltime(yhxz)\r\n key = \"'\" + self.lineEdit_key.text() + \"'\"\r\n baselng = self.lineEdit_baselng.text()#与圆形和指定线路不通,baselng和baselat不是用于拼接URL的,不能是字符串形式\r\n baselat = self.lineEdit_baselat.text()\r\n self.changetext(\"pqsj=''\",\"key = ''\", \"baselng = ''\", \"baselat = ''\",\"pqsj=\" + pqsj, \" key=\" + key, \" baselng=\" + baselng,\" baselat =\" + baselat)\r\n\r\n QMessageBox.information(self,\"提示\",\"操作完成!!\",QMessageBox.Yes | QMessageBox.No)\r\n\r\nclass ChildForm_square(QWidget,Ui_Form_square):\r\n def __init__(self):\r\n super(ChildForm_square, self).__init__()\r\n self.setupUi(self)\r\n\r\n def changetext(self,a1,a2,a3,a4,b1,b2,b3,b4):\r\n with open('crawl_square.py', 'r', encoding='utf-8') as f1:\r\n lines = [] # 创建了一个空列表,里面没有元素\r\n for line in f1.readlines():\r\n if line != '\\n':\r\n lines.append(line)\r\n f1.close()\r\n with open('crawl_square.py', 'w', encoding='utf-8') as f2:\r\n for line in lines:\r\n if a1 in line:\r\n line = b1\r\n f2.write('%s\\n' % line)\r\n elif a2 in line:\r\n line=b2\r\n f2.write('%s\\n' % line)\r\n elif a3 in line:\r\n line=b3\r\n f2.write('%s\\n' % line)\r\n elif a4 in line:\r\n line=b4\r\n f2.write('%s\\n' % line)\r\n else:\r\n f2.write('%s' % line)\r\n f2.close()\r\n def transcrawltime(self,yhxz):\r\n if yhxz == '1小时':\r\n pqsj = '12'\r\n elif yhxz == '17小时':\r\n pqsj = '204'\r\n elif yhxz == '1天':\r\n pqsj = '288'\r\n elif yhxz == '1周':\r\n pqsj = '2016'\r\n elif yhxz == '3周':\r\n pqsj = '6048'\r\n elif yhxz == '1个月':\r\n pqsj = '8640'\r\n elif yhxz == '半年':\r\n pqsj = '51840'\r\n elif yhxz == '1年':\r\n pqsj = '103680'\r\n elif yhxz == '2年':\r\n pqsj = '207360'\r\n return pqsj\r\n\r\n\r\n def createcode(self):\r\n yhxz = self.comboBox_crawltime2.currentText()\r\n pqsj = self.transcrawltime(yhxz)\r\n key = \"'\" + self.lineEdit_key.text() + \"'\"\r\n baselng = self.lineEdit_baselng.text()#与圆形和指定线路不通,baselng和baselat不是用于拼接URL的,不能是字符串形式\r\n baselat = self.lineEdit_baselat.text()\r\n self.changetext(\"pqsj=''\",\"key = ''\", \"baselng = ''\", \"baselat = ''\",\"pqsj=\" + pqsj, \"key=\" + key, \"baselng=\" + baselng,\"baselat =\" + baselat)\r\n QMessageBox.information(self,\"提示\",\"操作完成!!\",QMessageBox.Yes | QMessageBox.No)\r\n\r\nclass ChildForm_road(QWidget,Ui_Form_road):\r\n def __init__(self):\r\n super(ChildForm_road, self).__init__()\r\n self.setupUi(self)\r\n\r\n def changetext(self,a1,a2,a3,a4,b1,b2,b3,b4):\r\n with open('crawl_road.py', 'r', encoding='utf-8') as f1:\r\n lines = [] # 创建了一个空列表,里面没有元素\r\n for line in f1.readlines():\r\n if line != '\\n':\r\n lines.append(line)\r\n f1.close()\r\n with open('crawl_road.py', 'w', encoding='utf-8') as f2:\r\n for line in lines:\r\n if a1 in line:\r\n line = b1\r\n f2.write('%s\\n' % line)\r\n elif a2 in line:\r\n line=b2\r\n f2.write('%s\\n' % line)\r\n elif a3 in line:\r\n line=b3\r\n f2.write('%s\\n' % line)\r\n elif a4 in line:\r\n line=b4\r\n f2.write('%s\\n' % line)\r\n else:\r\n f2.write('%s' % line)\r\n f2.close()\r\n def transcrawltime(self,yhxz):\r\n if yhxz == '1小时':\r\n pqsj = '12'\r\n elif yhxz == '17小时':\r\n pqsj = '204'\r\n elif yhxz == '1天':\r\n pqsj = '288'\r\n elif yhxz == '1周':\r\n pqsj = '2016'\r\n elif yhxz == '3周':\r\n pqsj = '6048'\r\n elif yhxz == '1个月':\r\n pqsj = '8640'\r\n elif yhxz == '半年':\r\n pqsj = '51840'\r\n elif yhxz == '1年':\r\n pqsj = '103680'\r\n elif yhxz == '2年':\r\n pqsj = '207360'\r\n return pqsj\r\n\r\n def createcode(self):\r\n yhxz = self.comboBox_crawltime3.currentText()\r\n pqsj = self.transcrawltime(yhxz)\r\n key=\"'\" + self.lineEdit_key.text() + \"'\"\r\n cityname=\"'\" + self.lineEdit_cityname.text()+ \"'\"\r\n roadname=\"'\" + self.lineEdit_roadname.text()+ \"'\"\r\n self.changetext(\"pqsj=''\",\"key = ''\",\"cityname = ''\",\"roadName = ''\",\"pqsj=\" + pqsj,\" key=\" + key,\" cityname=\" + cityname,\" roadName =\" + roadname)\r\n QMessageBox.information(self,\"提示\",\"操作完成!!\",QMessageBox.Yes | QMessageBox.No)\r\n\r\nclass ChildForm_images(QWidget,Ui_Form_images):\r\n def __init__(self):\r\n super(ChildForm_images, self).__init__()\r\n self.setupUi(self)\r\n self.label_rectangle.setPixmap( QPixmap(\"./images/rectangle.jpg\"))\r\n self.label_square.setPixmap( QPixmap(\"./images/square.jpg\"))\r\n self.label_road.setPixmap( QPixmap(\"./images/road.jpg\"))\r\n\r\nclass Runthread_dataprocessing(QThread):\r\n signal_pb1_dataprocessing = pyqtSignal('PyQt_PyObject')\r\n signal_pb2_dataprocessing = pyqtSignal('PyQt_PyObject')\r\n signal_textedit1_dataprocessing = pyqtSignal('PyQt_PyObject')\r\n signal_textedit2_dataprocessing = pyqtSignal('PyQt_PyObject')\r\n def __init__(self,crawl_time,target_type,target_road,start_time):\r\n super(Runthread_dataprocessing, self).__init__()\r\n\r\n self.crawl_time = crawl_time\r\n self.target_type = target_type\r\n self.target_road = target_road\r\n self.start_time = start_time\r\n def run(self):\r\n crawl_time = self.crawl_time\r\n target_type = self.target_type\r\n target_road = self.target_road\r\n start_time = self.start_time\r\n #pb_update = 0\r\n\r\n try:\r\n os.mkdir('./提取' + target_road + '数据/')\r\n os.mkdir('路段平均速度')#创建文件夹'提取目标路段'和'路段平均速度'\r\n except:\r\n pass\r\n # '选择指定路段数据'range(crawl_time个文件)\r\n for i in range(crawl_time):\r\n try:\r\n inputfile = './' + target_type + '/' + str(i) + '.csv' # './长方形爬虫数据结果/' +\r\n data = pd.read_csv(inputfile) # './指定线路爬虫数据结果/' +\r\n lists = list(data['路名'])\r\n data.index = lists\r\n x = data.loc[target_road]\r\n x = x.drop(columns=['Unnamed: 0'])\r\n x.to_csv('./提取' + target_road + '数据/' + str(i) + '.csv', mode='a', encoding='utf-8-sig')\r\n str1 = '完成' + str(i) + '.csv文件的数据处理'\r\n self.signal_textedit1_dataprocessing.emit(str1)\r\n pb_update = (i / (crawl_time-1)) * 100\r\n self.signal_pb1_dataprocessing.emit(pb_update)\r\n\r\n except:\r\n pass\r\n\r\n # '路段平均速度'(仅1个csv时间序列文件)\r\n Timestamp = pd.date_range(start_time, periods=crawl_time, freq='5T')\r\n Timestamp = pd.DataFrame(Timestamp, columns=['Timestamp'])\r\n pieces = []\r\n\r\n for i in range(crawl_time):\r\n frame = pd.read_csv('./提取' + target_road + '数据/' + str(i) + '.csv')\r\n means = frame['车速'].groupby([frame['路名']]).mean() # 求平均值\r\n speed = means.loc[target_road]#有无这一步无所谓\r\n sj = i\r\n data = pd.DataFrame({'时间': Timestamp.loc[sj], '车速': speed}) # 将data数据变为dataframe类型\r\n pieces.append(data)\r\n str2 = '完成' + str(i) + '.csv文件的数据处理'\r\n self.signal_textedit2_dataprocessing.emit(str2)\r\n pb_update = (i / (crawl_time-1)) * 100\r\n self.signal_pb2_dataprocessing.emit(pb_update)\r\n speed_rmnl3 = pd.concat(pieces, ignore_index=True)\r\n speed_rmnl3.to_csv('./路段平均速度/' + target_road + '.csv', mode='a', encoding='utf-8-sig')\r\n\r\nclass ChildForm_dataprocessing(QWidget,Ui_Form_dataprocessing):\r\n def __init__(self):\r\n super(ChildForm_dataprocessing, self).__init__()\r\n self.setupUi(self)\r\n\r\n def transcrawltime(self,yhxz):\r\n if yhxz == '1小时':\r\n crawl_time = 12\r\n elif yhxz == '17小时':\r\n crawl_time = 204\r\n elif yhxz == '1天':\r\n crawl_time = 288\r\n elif yhxz == '1周':\r\n crawl_time = 2016\r\n elif yhxz == '3周':\r\n crawl_time = 6048\r\n elif yhxz == '1个月':\r\n crawl_time = 8640\r\n elif yhxz == '半年':\r\n crawl_time = 51840\r\n elif yhxz == '1年':\r\n crawl_time = 103680\r\n elif yhxz == '2年':\r\n crawl_time = 207360\r\n return crawl_time\r\n\r\n def dataprocessing(self):\r\n QMessageBox.information(self,\"提示\",\"正在运行,耗时较长...\",QMessageBox.Yes | QMessageBox.No)\r\n yhxz = self.comboBox_crawltime4.currentText()\r\n crawl_time = self.transcrawltime(yhxz)\r\n target_type = self.comboBox_targettype.currentText()\r\n target_road = self.lineEdit_targetroad.text()\r\n start_time = self.lineEdit_starttime.text()\r\n # 创建线程\r\n self.thread = Runthread_dataprocessing(crawl_time,target_type,target_road,start_time)\r\n # 连接信号\r\n self.thread.signal_pb1_dataprocessing.connect(self.updatePB1)\r\n self.thread.signal_pb2_dataprocessing.connect(self.updatePB2)\r\n self.thread.signal_textedit1_dataprocessing.connect(self.updateText1)\r\n self.thread.signal_textedit2_dataprocessing.connect(self.updateText2)\r\n # 开始线程\r\n self.thread.start()\r\n\r\n def updatePB1(self, pb_update):\r\n self.progressBar_dataprocessing1.setValue(pb_update)\r\n def updatePB2(self, pb_update):\r\n self.progressBar_dataprocessing2.setValue(pb_update)\r\n def updateText1(self, text):\r\n self.textEdit_progressbar1.append(text)\r\n self.textEdit_progressbar1.moveCursor(self.textEdit_progressbar1.textCursor().End)\r\n def updateText2(self, text):\r\n self.textEdit_progressbar2.append(text)\r\n self.textEdit_progressbar2.moveCursor(self.textEdit_progressbar2.textCursor().End)\r\n\r\nclass Runthread_predict(QThread):\r\n signal_pb_predict = pyqtSignal('PyQt_PyObject')\r\n signal_textedit_predict = pyqtSignal('PyQt_PyObject')\r\n signal_plot = pyqtSignal('PyQt_PyObject')\r\n def __init__(self,test,trend,seasonal,residual):\r\n super(Runthread_predict, self).__init__()\r\n self.test = test\r\n self.trend = trend\r\n self.seasonal = seasonal\r\n self.residual = residual\r\n def run(self):\r\n test = self.test\r\n trend = self.trend\r\n seasonal = self.seasonal\r\n residual = self.residual\r\n\r\n MAE_arima = 1000.999999\r\n for p in range(6):\r\n for q in range(6):\r\n trend_model = ARIMA(trend, order=(p, 2, q)).fit(disp=-1, method='css')\r\n n = 288\r\n pred_time_index = pd.date_range(start=trend.index[-1], periods=n + 1, freq='5min')[1:]\r\n trend_pred = trend_model.forecast(n)[0] # add_season()\r\n train_season = seasonal\r\n train_residual = residual\r\n values = []\r\n for i, t in enumerate(pred_time_index):\r\n trend_part = trend_pred[i]\r\n # 相同时间的数据均值\r\n season_part = train_season[train_season.index.time == t.time()].mean()\r\n residual_part = train_residual[train_residual.index.time == t.time()].mean()\r\n # 趋势+周期+误差界限\r\n predict = trend_part + season_part + residual_part\r\n values.append(predict)\r\n final_pred = pd.Series(values, index=pred_time_index, name='predict')\r\n # 将trend预测趋势弄出来\r\n # 评估_________均方根误差rmse,画图对比和真实值的差距\r\n pred = final_pred\r\n MAE_arima_test = mean_absolute_error(test, pred)\r\n if MAE_arima > MAE_arima_test:\r\n MAE_arima = MAE_arima_test\r\n p_min = p\r\n q_min = q\r\n str1 = 'p = ' + str(p) + ',q = ' + str(q) + ',MAE = ' + str(MAE_arima_test) + ',MAE↓↓'\r\n self.signal_textedit_predict.emit(str1)\r\n else:\r\n str11 = 'p = ' + str(p) + ',q = ' + str(q) + ',MAE = ' + str(MAE_arima_test) + ',p,q值不变'\r\n self.signal_textedit_predict.emit(str11)\r\n\r\n pb_update = ((p*6+(q+1)) / 36) * 100\r\n self.signal_pb_predict.emit(pb_update)\r\n\r\n str2 = '①@@@@:使MAE最小的p,q取值为:p = ' + str(p_min) + ',q = ' + str(q_min) + ',MAE_min = ' + str(MAE_arima)\r\n self.signal_textedit_predict.emit(str2)\r\n str3 = '②****:最终确定的ARIMA模型为(' + str(p_min) + ',' + '2' + ',' + str(q_min) + ')'\r\n self.signal_textedit_predict.emit(str3)\r\n\r\n trend_model = ARIMA(trend, order=(p_min, 2, q_min)).fit(disp=-1, method='css')\r\n n = 288\r\n pred_time_index = pd.date_range(start=trend.index[-1], periods=n + 1, freq='5min')[1:]\r\n trend_pred = trend_model.forecast(n)[0] # add_season()\r\n train_season = seasonal\r\n train_residual = residual\r\n values = []\r\n trend_pred_values = [] # 趋势\r\n for i, t in enumerate(pred_time_index):\r\n trend_part = trend_pred[i]\r\n # 相同时间的数据均值\r\n season_part = train_season[train_season.index.time == t.time()].mean()\r\n residual_part = train_residual[train_residual.index.time == t.time()].mean()\r\n # 趋势+周期+误差界限\r\n predict = trend_part + season_part + residual_part\r\n values.append(predict)\r\n final_pred = pd.Series(values, index=pred_time_index, name='predict')\r\n # 评估_________均方根误差rmse,画图对比和真实值的差距\r\n pred = final_pred\r\n\r\n dp_output = {\r\n \"pred\": pred,\r\n \"MAE_arima\": MAE_arima,\r\n \"test\": test\r\n }\r\n self.signal_plot.emit(dp_output)\r\n\r\nclass ChildForm_predict(QWidget,Ui_Form_predict):\r\n def __init__(self):\r\n super(ChildForm_predict, self).__init__()\r\n self.setupUi(self)\r\n\r\n #设置对应的图像不可见\r\n self.matplotlibwidget_correlation.setVisible(False)\r\n self.matplotlibwidget_arimapre.setVisible(False)\r\n self.textEdit_arima.setVisible(False)\r\n\r\n def transvolume(self,datavolume):\r\n if datavolume == '1周':\r\n divide_time = 1728 #留出1天时间作为测试集\r\n ann_time = 1440 #留出1天 + 1天时间作为测试集\r\n elif datavolume == '3周':\r\n divide_time = 5760 #留出1天时间作为测试集\r\n ann_time = 5472 #留出1天 + 1天时间作为测试集\r\n elif datavolume == '1个月':\r\n divide_time = 8352 #留出1天时间作为测试集\r\n ann_time = 8064 #留出1天 + 1天时间作为测试集\r\n else:\r\n print('没有选择数据划分量')\r\n return divide_time,ann_time\r\n def correlation_conpute(self):\r\n datavolume = self.comboBox_datavolume.currentText()\r\n divide_time,ann_time = self.transvolume(datavolume)\r\n self.target_road = self.lineEdit_targetroad.text()\r\n self.speed_rmnl3 = pd.read_csv('./路段平均速度/' + self.target_road + '.csv')\r\n self.speed_rmnl3['Timestamp'] = pd.to_datetime(self.speed_rmnl3['时间'],format='%Y-%m-%d %H:%M') # 必须用到这一步,不然再后面的seasonal(分解周期)步骤中会出不了结果,卡起,不知道为什么,咱也没地方问啊,加上就对了\r\n self.speed_rmnl3.index = self.speed_rmnl3['Timestamp']\r\n self.speed_rmnl3 = self.speed_rmnl3['车速']\r\n self.train = self.speed_rmnl3[0:divide_time]\r\n\r\n weekend = np.where(self.train.index.weekday < 5, 'Weekday', 'Weekend')\r\n by_time = self.train.groupby([weekend, self.train.index.time]).mean() # weekend(5472)/by_time(576————包含weekend的288一天和weekday的288一天)\r\n weekdayline = by_time.ix['Weekday']\r\n weekendline = by_time.ix['Weekend']\r\n return weekdayline,weekendline\r\n def correlation(self):\r\n weekdayline,weekendline = self.correlation_conpute()\r\n self.matplotlibwidget_correlation.setVisible(True)\r\n self.matplotlibwidget_correlation.mpl.start_correlation_plot(weekdayline,weekendline)\r\n QMessageBox.information(self,\"提示\",\"操作完成\",QMessageBox.Yes | QMessageBox.No)\r\n def arimaclick(self):\r\n QMessageBox.information(self,\"提示\",\"请稍等,后台正在处理...\",QMessageBox.Yes | QMessageBox.No)\r\n #划分训练集、测试集\r\n target_road = self.lineEdit_targetroad.text()\r\n speed_rmnl3 = pd.read_csv('./路段平均速度/' + target_road + '.csv')\r\n speed_rmnl3['Timestamp'] = pd.to_datetime(speed_rmnl3['时间'],format='%Y-%m-%d %H:%M') # 必须用到这一步,不然再后面的seasonal(分解周期)步骤中会出不了结果,卡起,不知道为什么,咱也没地方问啊,加上就对了\r\n speed_rmnl3.index = speed_rmnl3['Timestamp']\r\n speed_rmnl3 = speed_rmnl3['车速']\r\n datavolume = self.comboBox_datavolume.currentText()\r\n divide_time,ann_time = self.transvolume(datavolume)\r\n train = speed_rmnl3[0:divide_time ]\r\n test = speed_rmnl3[divide_time:]\r\n ts = train\r\n decomposition = seasonal_decompose(ts, freq=288, two_sided=False) # 将288个数据作为一个周期\r\n trend =decomposition.trend\r\n seasonal = decomposition.seasonal\r\n residual = decomposition.resid\r\n residual.dropna(inplace=True)\r\n trend.dropna(inplace=True)\r\n\r\n self.thread = Runthread_predict(test,trend,seasonal,residual)\r\n # 连接信号\r\n self.thread.signal_pb_predict.connect(self.updatePB)\r\n self.thread.signal_textedit_predict.connect(self.updateText)\r\n #QMessageBox.information(self,\"提示\",\"请稍等,正在绘图...\",QMessageBox.Yes | QMessageBox.No)\r\n self.thread.signal_plot.connect(self.updatePlot)\r\n # 开始线程\r\n self.thread.start()\r\n def updatePB(self, pb_update):\r\n self.progressBar_arima.setValue(pb_update)\r\n def updateText(self, text):\r\n self.textEdit_arima.setVisible(True)\r\n self.textEdit_arima.append(text)\r\n self.textEdit_arima.moveCursor(self.textEdit_arima.textCursor().End)\r\n def updatePlot(self, dp_output):\r\n self.pred_arima = dp_output[\"pred\"]\r\n self.MAE_arima = dp_output[\"MAE_arima\"]\r\n self.test = dp_output[\"test\"]\r\n pred_arima = self.pred_arima\r\n MAE_arima = self.MAE_arima\r\n test = self.test\r\n self.matplotlibwidget_arimapre.setVisible(True)\r\n self.matplotlibwidget_arimapre.mpl.start_arima_plot(pred_arima,test,MAE_arima)\r\n QMessageBox.information(self,\"提示\",\"绘图完成\",QMessageBox.Yes | QMessageBox.No)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = QApplication(sys.argv)\r\n mainwin = MainWindow()\r\n mainwin.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"毕业设计2.py","file_name":"毕业设计2.py","file_ext":"py","file_size_in_byte":76454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"37612578","text":"import os\nfrom dotenv import load_dotenv, find_dotenv\nfrom pathlib import *\nfrom datetime import timedelta\n\nload_dotenv(find_dotenv())\nenv_path = Path('.') / '.env'\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.getenv('SECRET_KEY')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = [\"*\", ]\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.sites',\n 'useraccount',\n 'rest_framework',\n 'corsheaders',\n 'pytest',\n 'storages',\n 'django_short_url',\n 'sociallogin',\n 'rest_framework_simplejwt',\n 'rest_framework_swagger',\n 'django_inlinecss',\n 'django_celery_beat',\n 'django_elasticsearch_dsl',\n 'django_elasticsearch_dsl_drf',\n 'notes',\n\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n\n 'allauth.socialaccount.providers.github',\n 'allauth.socialaccount.providers.google',\n 'allauth.socialaccount.providers.facebook',\n 'allauth.socialaccount.providers.twitter',\n 'fundoomiddleware',\n\n]\n\nCELERY_ACCEPT_CONTENT = ['application/json']\nCELERY_TASK_SERIALIZER = 'json'\nCELERY_RESULT_SERIALIZER = 'json'\nCELERY_RESULT_BACKEND = 'rpc://'\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n\nSITE_ID = 1\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_LOGOUT_ON_GET = True\n\nELASTICSEARCH_DSL = {\n 'default': {\n 'hosts': 'localhost:9200'\n },\n}\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.BrokenLinkEmailsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n # 'fundoomiddleware.middleware.CheckLabelMiddleware',\n\n]\n\nCORS_ORIGIN_ALLOW_ALL = True\n\nROOT_URLCONF = 'fundoonote.urls'\n\nSWAGGER_SETTINGS = {\n 'SECURITY_DEFINITIONS': {\n 'api_key': {\n 'type': 'apiKey',\n 'in': 'header',\n 'name': 'Authorization'\n }\n },\n}\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')]\n ,\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'fundoonote.wsgi.application'\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'USER': 'myprojectuser', # Username:\n 'NAME': 'myproject',\n 'PASSWORD': 'Hello123#',\n 'HOST': '127.0.0.1', # Database host address\n 'PORT': '3306',\n # 'TEST': {\n # 'NAME': 'test_myproject',\n # },\n\n }\n}\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:6379/1\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n }\n }\n}\nSESSION_ENGINE = \"django.contrib.sessions.backends.cache\"\nSESSION_CACHE_ALIAS = \"default\"\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nREST_FRAMEWORK = {\n\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.SessionAuthentication',\n 'rest_framework.authentication.TokenAuthentication',\n 'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication',\n ),\n # 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',\n \"DEFAULT_SCHEMA_CLASS\": \"rest_framework.schemas.AutoSchema\"\n\n}\n\nSIMPLE_JWT = {\n 'ACCESS_TOKEN_LIFETIME': timedelta(days=1000),\n 'REFRESH_TOKEN_LIFETIME': timedelta(days=400),\n 'ROTATE_REFRESH_TOKENS': False,\n 'BLACKLIST_AFTER_ROTATION': True,\n\n 'ALGORITHM': 'HS256',\n 'SIGNING_KEY': SECRET_KEY,\n 'VERIFYING_KEY': None,\n 'AUDIENCE': None,\n 'ISSUER': None,\n\n 'AUTH_HEADER_TYPES': ('Bearer',),\n 'USER_ID_FIELD': 'id',\n 'USER_ID_CLAIM': 'user_id',\n\n 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),\n 'TOKEN_TYPE_CLAIM': 'token_type',\n\n 'JTI_CLAIM': 'jti',\n\n 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',\n 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),\n 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),\n}\nLOGIN_REDIRECT_URL = '/'\nEMAIL_USE_TLS = True\nEMAIL_HOST = os.getenv('EMAIL_HOST')\nEMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER')\nEMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD')\nEMAIL_PORT = 587\n\nDEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\n\nSTATIC_URL = '/static/account/Css/'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\n\nSHORT_API_KEY = os.getenv(\"SHORT_API_KEY\")\nAWS_STORAGE_BUCKET_NAME = os.getenv(\"AWS_UPLOAD_BUCKET\")\nAWS_ACCESS_KEY_ID = os.getenv(\"AWS_UPLOAD_ACCESS_KEY_ID\")\nAWS_SECRET_ACCESS_KEY = os.getenv(\"AWS_UPLOAD_SECRET_KEY\")\nAWS_DEFAULT_ACL = None\nAWS_S3_FILE_OVERWRITE = False\n\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nSOCIAL_AUTH_GITHUB_KEY = os.getenv('SOCIAL_AUTH_GITHUB_KEY ')\nSOCIAL_AUTH_GITHUB_SECRET = os.getenv('SOCIAL_AUTH_GITHUB_SECRET')\n\nSOCIAL_AUTH_GOOGLE_KEY = os.getenv('SOCIAL_AUTH_GOOGLE_KEY ')\nSOCIAL_AUTH_GOOGLE_SECRET = os.getenv('SOCIAL_AUTH_GOOGLE_SECRET')\n\nSOCIAL_AUTH_FACEBOOK_KEY = os.getenv('SOCIAL_AUTH_FACEBOOK_KEY ')\nSOCIAL_AUTH_FACEBOOK_SECRET = os.getenv('SOCIAL_AUTH_FACEBOOK_SECRET')\n\nSOCIAL_AUTH_TWITTER_KEY = os.getenv('SOCIAL_AUTH_TWITTER_KEY')\nSOCIAL_AUTH_TWITTER_SECRET = os.getenv('SOCIAL_AUTH_TWITTER_SECRET')\n\nnote_url = os.getenv('note_url')\nnote_create_url = os.getenv('note_create_url')\nget_note_url = os.getenv('get_note_url')\nlabel_url = os.getenv('label_url')\nlabel_create_url = os.getenv('label_create_url')\nreminder_url = os.getenv('reminder_url')\ntrash_notes_url = os.getenv('trash_notes_url')\narchive_notes_url = os.getenv('archive_notes_url')\nsend_mail_url = os.getenv('send_mail_url')\n\nlogin_url = os.getenv('login_url')\nregister_url = os.getenv('register_url')\npassword_reset_url = os.getenv('password_reset_url')\npassword_forgot_url = os.getenv('password_forgot_url')\ndetails_url = os.getenv('details_url')\n","sub_path":"fundoonote/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"176218643","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom atten import Atten\n\n\n\nclass FGA(nn.Module):\n def __init__(self, vocab_size, word_embed_dim, hidden_ques_dim, hidden_ans_dim,\n hidden_hist_dim, hidden_cap_dim, hidden_img_dim):\n '''\n Factor Graph Attention\n :param vocab_size: vocabulary size\n :param word_embed_dim\n :param hidden_ques_dim:\n :param hidden_ans_dim:\n :param hidden_hist_dim:\n :param img_features_dim:\n '''\n super(FGA, self).__init__()\n\n print(\"Init FGA with vocab size %s, word embed %s, hidden ques %s, hidden ans %s,\"\n \" hidden hist %s, hidden cap %s, hidden img %s\" % (vocab_size, word_embed_dim,\n hidden_ques_dim,\n hidden_ans_dim,\n hidden_hist_dim,\n hidden_cap_dim,\n hidden_img_dim))\n self.hidden_ques_dim = hidden_ques_dim\n self.hidden_ans_dim = hidden_ans_dim\n self.hidden_cap_dim = hidden_cap_dim\n self.hidden_img_dim = hidden_img_dim\n self.hidden_hist_dim = hidden_hist_dim\n\n # Vocab of History LSTMs is one more as we are keeping a stop id (the last id)\n self.word_embedddings = nn.Embedding(vocab_size+1+1, word_embed_dim, padding_idx=0)\n\n self.lstm_ques = nn.LSTM(word_embed_dim, self.hidden_ques_dim, batch_first=True)\n self.lstm_ans = nn.LSTM(word_embed_dim, self.hidden_ans_dim, batch_first=True)\n\n self.lstm_hist_ques = nn.LSTM(word_embed_dim, self.hidden_hist_dim, batch_first=True)\n self.lstm_hist_ans = nn.LSTM(word_embed_dim, self.hidden_hist_dim, batch_first=True)\n\n self.lstm_hist_cap = nn.LSTM(word_embed_dim, self.hidden_cap_dim, batch_first=True)\n\n\n self.qahistnet = nn.Sequential(\n nn.Linear(self.hidden_hist_dim*2, self.hidden_hist_dim),\n nn.ReLU(inplace=True)\n )\n\n self.concat_dim = self.hidden_ques_dim + self.hidden_ans_dim + \\\n self.hidden_ans_dim + self.hidden_img_dim + \\\n self.hidden_cap_dim + self.hidden_hist_dim*9\n\n self.simnet = nn.Sequential(\n nn.Linear(self.concat_dim, (self.concat_dim)//2, bias=False),\n nn.BatchNorm1d((self.concat_dim) // 2),\n nn.ReLU(inplace=True),\n nn.Linear((self.concat_dim)//2, (self.concat_dim)//4, bias=False),\n nn.BatchNorm1d((self.concat_dim) // 4),\n nn.ReLU(inplace=True),\n nn.Dropout(0.5),\n nn.Linear((self.concat_dim)//4, 1)\n )\n\n # To share weights, provide list of tuples: (idx, list of connected utils)\n # Note, for efficiency, the shared utils (i.e., history, are connected to ans and question only.\n # connecting shared factors is not supported (!)\n sharing_factor_weights = {4: (9, [0, 1]),\n 5: (9, [0, 1])}\n\n self.mul_atten = Atten(util_e=[self.hidden_ans_dim, # Answer modal\n self.hidden_ques_dim, # Question modal\n self.hidden_cap_dim, # Caption modal\n self.hidden_img_dim, # Image modal\n self.hidden_hist_dim, # Question-history modal\n self.hidden_hist_dim # Answer-history modal\n ],\n sharing_factor_weights=sharing_factor_weights,\n sizes=[100, # 100 Answers\n 21, # Question length\n 41, # Caption length\n 37, # 36 Image regions\n 21, # History-Question length\n 21 # History-Answer length\n ] # The spatial dim used for pairwise normalization (use force for adaptive)\n , prior_flag=True,\n pairwise_flag=True)\n\n\n\n def forward(self, input_ques, input_ans, input_hist_ques, input_hist_ans, input_hist_cap,\n input_ques_length, input_ans_length, input_cap_length, i_e):\n \"\"\"\n\n :param input_ques:\n :param input_ans:\n :param input_hist_ques:\n :param input_hist_ans:\n :param input_hist_cap:\n :param input_ques_length:\n :param input_ans_length:\n :param input_cap_length:\n :param i_e:\n :return:\n \"\"\"\n\n\n n_options = input_ans.size()[1]\n batch_size = input_ques.size()[0]\n\n\n\n nqa_per_dial, nwords_per_qa = input_hist_ques.size()[1], input_hist_ques.size()[2]\n nwords_per_cap = input_hist_cap.size()[1]\n max_length_input_ans = input_ans.size()[-1]\n\n assert batch_size == input_hist_ques.size()[0] == input_hist_ans.size()[0] == input_ques.size()[0] == \\\n input_ans.size()[0] == input_hist_cap.size()[0]\n assert nqa_per_dial == input_hist_ques.size()[1] == input_hist_ans.size()[1]\n assert nwords_per_qa == input_hist_ques.size()[2] == input_hist_ans.size()[2]\n\n q_we = self.word_embedddings(input_ques)\n a_we = self.word_embedddings(input_ans.view(-1, max_length_input_ans))\n hq_we = self.word_embedddings(input_hist_ques.view(-1, nwords_per_qa))\n ha_we = self.word_embedddings(input_hist_ans.view(-1, nwords_per_qa))\n c_we = self.word_embedddings(input_hist_cap.view(-1, nwords_per_cap))\n\n\n\n '''\n q_we = batch x 20 x embed_ques_dim\n a_we = 100*batch x 20 x embed_ans_dim\n hq_we = batch*nqa_per_dial, nwords_per_qa, embed_hist_dim\n ha_we = batch*nqa_per_dial, nwords_per_qa, embed_hist_dim\n c_we = batch*ncap_per_dial, nwords_per_cap, embed_hist_dim\n '''\n self.lstm_ques.flatten_parameters()\n self.lstm_ans.flatten_parameters()\n self.lstm_hist_ques.flatten_parameters()\n self.lstm_hist_ans.flatten_parameters()\n self.lstm_hist_cap.flatten_parameters()\n\n\n i_feat = i_e\n\n q_seq, self.hidden_ques = self.lstm_ques(q_we)\n a_seq, self.hidden_ans = self.lstm_ans(a_we)\n hq_seq, self.hidden_hist_ques = self.lstm_hist_ques(hq_we)\n ha_seq, self.hidden_hist_ans = self.lstm_hist_ans(ha_we)\n cap_seq, self.hidden_cap = self.lstm_hist_cap(c_we)\n\n\n '''\n length is used for attention prior\n '''\n q_len = input_ques_length.data - 1\n c_len = input_cap_length.data.view(-1) - 1\n\n\n ans_index = torch.arange(0, n_options * batch_size).long().cuda()\n ans_len = input_ans_length.data.view(-1) - 1\n ans_seq = a_seq[ans_index, ans_len, :]\n ans_seq = ans_seq.view(batch_size, n_options, self.hidden_ans_dim)\n\n batch_index = torch.arange(0, batch_size).long().cuda()\n q_prior = torch.zeros(batch_size, q_seq.size(1)).cuda()\n q_prior[batch_index, q_len] = 100\n c_prior = torch.zeros(batch_size, cap_seq.size(1)).cuda()\n c_prior[batch_index, c_len] = 100\n ans_prior = torch.ones(batch_size, ans_seq.size(1)).cuda()\n img_prior = torch.ones(batch_size, i_feat.size(1)).cuda()\n\n (ans_atten, ques_atten, cap_atten, img_atten, hq_atten, ha_atten) = \\\n self.mul_atten([ans_seq, q_seq, cap_seq, i_feat, hq_seq, ha_seq],\n priors=[ans_prior, q_prior, c_prior, img_prior, None, None])\n\n '''\n expand to answers based\n '''\n ques_atten = torch.unsqueeze(ques_atten, 1).expand(batch_size,\n n_options,\n self.hidden_ques_dim)\n cap_atten = torch.unsqueeze(cap_atten, 1).expand(batch_size,\n n_options,\n self.hidden_cap_dim)\n img_atten = torch.unsqueeze(img_atten, 1).expand(batch_size, n_options,\n self.hidden_img_dim)\n ans_atten = torch.unsqueeze(ans_atten, 1).expand(batch_size, n_options,\n self.hidden_ans_dim)\n\n\n '''\n combine history\n '''\n\n input_qahistnet = torch.cat((hq_atten, ha_atten), 1)\n # input_qahistnet: (nqa_per_dial*batch x 2*hidden_hist_dim)\n output_qahistnet = self.qahistnet(input_qahistnet)\n # output_qahistnet: (nqa_per_dial*batch x hidden_hist_dim)\n output_qahistnet = output_qahistnet.view(batch_size,\n nqa_per_dial * self.hidden_hist_dim)\n # output_qahistnet: (batch x nqa_per_dial*hidden_hist_dim)\n output_qahistnet = torch.unsqueeze(output_qahistnet, 1)\\\n .expand(batch_size,\n n_options,\n nqa_per_dial * self.hidden_hist_dim)\n\n input_qa = torch.cat((ans_seq, ques_atten, ans_atten, img_atten,\n output_qahistnet, cap_atten), 2) # Concatenate last dimension\n\n input_qa = input_qa.view(batch_size * n_options, self.concat_dim)\n\n out_scores = self.simnet(input_qa)\n\n out_scores = out_scores.squeeze(dim=1)\n out_scores = out_scores.view(batch_size, n_options)\n\n return out_scores","sub_path":"fga_model.py","file_name":"fga_model.py","file_ext":"py","file_size_in_byte":9746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"202029843","text":"import math\n\nimport numpy as np\n\nfrom auxiliary_functions import calculate_distance, get_motion_vector_as_numpy_array, center_of_mass\n\n\ndef get_details_about_ray(ray_points, current_position, ray_segment,is_up_is_minus):\n mass_center = center_of_mass(ray_points)\n to_mass_center_ray = get_motion_vector_as_numpy_array(current_position, mass_center)\n ray_motion_vector = get_motion_vector_as_numpy_array(ray_segment[0], ray_segment[1])\n angle = get_angle(to_mass_center_ray, ray_motion_vector)\n mass_center_radius = calculate_distance(mass_center, ray_segment[0]) / 2\n avg_height = get_average_height_around_central_mass(ray_points, mass_center, mass_center_radius)\n is_avg_lower = current_position.z > avg_height if is_up_is_minus else current_position.z < avg_height\n print(\"is_avg_lower:\"+str(is_avg_lower))\n print(\"angle:\"+str(angle))\n is_wall = angle > 30 and not is_avg_lower\n points = get_distance_to_points_dictionary(ray_points, current_position)\n keys = points.keys()\n order_keys = sorted(keys) if len(keys) > 1 else keys\n checkpoint = points[order_keys[0]] if is_wall else points[order_keys[-1]]\n return is_wall, checkpoint\n\n\ndef get_average_height_around_central_mass(ray_points, mass_center, mass_center_radius):\n avg = 0\n amount_of_close_points = 0\n for point in ray_points:\n if calculate_distance(mass_center, point) < mass_center_radius:\n avg += point.z\n amount_of_close_points += 1\n return avg / amount_of_close_points\n\n\ndef get_distance_to_points_dictionary(frame_ray_points, current_position):\n points = {}\n for point in frame_ray_points:\n points[calculate_distance(point, current_position)] = point\n return points\n\n\ndef get_angle(vector_1, vector_2):\n try:\n unit_vector_1 = vector_1 / np.linalg.norm(vector_1)\n unit_vector_2 = vector_2 / np.linalg.norm(vector_2)\n dot_product = np.dot(unit_vector_1, unit_vector_2)\n angle = int(math.degrees(np.arccos(dot_product)))\n if angle > 90:\n angle = 180 - angle\n return angle\n except Exception as e:\n print(e.args[0] + \"vector_1:\" + str(vector_1[0]) + \",\" + str(vector_1[1]) + \"\\nvector 2:\" + str(\n vector_2[0]) + \",\" + str(vector_2[1]))\n return 90\n\n\n\"\"\"path = \"/home/livne/PycharmProjects/drone_project/dani\"\ndirs = os.listdir(path)\n\nfor i in range(1,4):\n wall_path = path + \"/scan_\" + i + \"/scan_\" + i + \"_frames/wall_frames\"\n wall_dirs = os.listdir(wall_path)\n for file in dirs:\n if file == '*.csv':\n print file\"\"\"\n","sub_path":"Autonomous-navigation/collision_detector.py","file_name":"collision_detector.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"173145381","text":"\"\"\"\nParses Power, CPU, Memory and other resource usage results and plots them for a single experiment\n\"\"\"\n\nimport os\nimport re\nfrom datetime import datetime\nfrom datetime import timedelta\nimport random\nimport matplotlib.pyplot as plt\nimport json\nimport traceback as tc\nimport numpy as np\nimport run_experiments\n\n\n# Experiment setup class\nclass ExperimentSetup:\n def __init__(self, setup_file_path):\n # Parse experimental setup from setup file\n json_dict = json.load(open(setup_file_path, \"r\"))\n self.all_spark_nodes = json_dict[\"AllSparkNodes\"]\n self.designated_driver_node = json_dict[\"SparkDriverNode\"]\n self.power_meter_nodes_in_order = json_dict[\"PowerMeterNodesInOrder\"]\n self.input_size_gb = json_dict[\"InputSizeGb\"]\n self.link_bandwidth_mbps = float(json_dict[\"LinkBandwidthMbps\"])\n self.experiment_start_time = datetime.strptime(json_dict[\"ExperimentStartTime\"], \"%Y-%m-%d %H:%M:%S\")\n self.spark_job_start_time = datetime.strptime(json_dict[\"SparkJobStartTime\"], \"%Y-%m-%d %H:%M:%S\")\n self.spark_job_end_time = datetime.strptime(json_dict[\"SparkJobEndTime\"], \"%Y-%m-%d %H:%M:%S\")\n \n self.experiment_group = str(json_dict[\"ExperimentGroup\"])\n self.experiment_group_desc = json_dict.get(\"ExperimentGroupDesc\", \"No description\")\n self.scala_class_name = json_dict.get(\"ScalaClassName\", None)\n self.input_cached_in_hdfs = json_dict.get(\"InputHdfsCached\", None)\n self.plot_friendly_name = json_dict.get(\"PlotFriendlyName\", None)\n self.record_size_bytes = json_dict.get(\"RecordSizeByes\", None)\n self.final_partition_count = json_dict.get(\"FinalPartitionCount\", None)\n\n\n# Results base folder\nresults_base_dir = run_experiments.local_results_folder\nsetup_details_file_name = \"setup_details.txt\"\ncpu_readings_file_name = \"cpu.sar\"\nmem_readings_file_name = \"memory.sar\"\nnet_readings_file_name = \"network.sar\"\ndiskio_readings_file_name = \"diskio.sar\"\nmemaccess_readings_file_name = \"memaccess.csv\"\npower_readings_file_name = \"power_readings.txt\"\nspark_log_file_name = 'spark.log'\nspark_full_log_file_name = \"spark-detailed.log\"\n\n\n# Regex patterns. https://regex101.com/\n# First line of every SAR file to get date\nfirst_line_regex = r'^Linux.+\\s+([0-9]+[/-][0-9]+[/-][0-9]+)\\s+'\n# Example: <06:38:09 PM all 3.78 0.00 2.52 0.50 0.00 93.20>\ncpu_all_cores_regex = r'^([0-9]+:[0-9]+:[0-9]+ [AP]M)\\s+(all)\\s+([0-9]+\\.[0-9]+)\\s+([0-9]+\\.[0-9]+)\\s+([0-9]+\\.[0-9]+)\\s+([0-9]+\\.[0-9]+)\\s+([0-9]+\\.[0-9]+)\\s+([0-9]+\\.[0-9]+)$'\n# Example: <06:38:09 PM lo 12.00 12.00 2.13 2.13 0.00 0.00 0.00 0.00>\nnetwork_regex = r'^([0-9]+:[0-9]+:[0-9]+ [AP]M)\\s+([a-z0-9]+)\\s+([0-9]+\\.[0-9]+)\\s+([0-9]+\\.[0-9]+)\\s+([0-9]+\\.[0-9]+)\\s+([0-9]+\\.[0-9]+)\\s+'\n# Example: <06:38:09 PM 779700 15647244 95.25 65368 7407236 15733700 47.40 9560972 5486404 1292>\nmemory_regex = r'^([0-9]+:[0-9]+:[0-9]+ [AP]M)\\s+([0-9]+[\\.]?[0-9]+)\\s+([0-9]+[\\.]?[0-9]+)\\s+([0-9]+[\\.]?[0-9]+)\\s+([0-9]+[\\.]?[0-9]+)\\s+([0-9]+[\\.]?[0-9]+)\\s+([0-9]+[\\.]?[0-9]+)\\s+'\n# Example: <06:38:09 PM 21.00 21.00 0.00 2416.00 0.00>\nio_regex = r'^([0-9]+:[0-9]+:[0-9]+ [AP]M)\\s+([0-9]+[\\.]?[0-9]+)\\s+([0-9]+[\\.]?[0-9]+)\\s+([0-9]+[\\.]?[0-9]+)\\s+([0-9]+[\\.]?[0-9]+)\\s+([0-9]+[\\.]?[0-9]+)$'\n# Example: <1541731089.0383,112.50,95.172,98.975,97.549>\npower_regex = r'^([0-9]+[\\.]?[0-9]+),([0-9]+[\\.]?[0-9]+),([0-9]+[\\.]?[0-9]+),([0-9]+[\\.]?[0-9]+),([0-9]+[\\.]?[0-9]+)'\n# Spark log start executor\nspark_stage_and_task_log_regex = r'^([0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+).+stage ([0-9]+\\.[0-9]+).+(b09-[0-9]+).+executor ([0-9]+)'\nspark_stage_and_task_log_regex_2 = r'^([0-9]+\\/[0-9]+\\/[0-9]+ [0-9]+:[0-9]+:[0-9]+).+stage ([0-9]+\\.[0-9]+).+(b09-[0-9]+).+executor ([0-9]+)'\n# Spark log any line\nspark_log_generic_log_regex = r'^([0-9]+-[0-9]+-[0-9]+\\ [0-9]+:[0-9]+:[0-9]+) .+$'\n\n\n# Parses date from the first line in SAR output file. SAR outputs different formats at different times for some\n# reason. Returns date string in a uniform format, no matter which format SAR outputs in.\ndef parse_date_from_sar_file(first_line_in_file):\n matches = re.match(first_line_regex, first_line_in_file)\n date_string_match = matches.group(1)\n # e.g., 11/08/2018 or 2018-11-08\n try:\n date_string = datetime.strptime(date_string_match, '%m/%d/%Y').strftime('%m/%d/%Y')\n except ValueError:\n # Try parsing other format\n date_string = datetime.strptime(date_string_match, '%Y-%m-%d').strftime('%m/%d/%Y')\n return date_string\n\n\n# Collects all results from SAR and Powermeter, parses for required info and merges results onto single timeline.\ndef parse_results(results_dir_path, experiment_setup, output_readings_file_name, output_readings_to_file=False):\n # Final results\n all_readings = []\n\n # Parse SAR readings for each node\n for node_name in experiment_setup.all_spark_nodes:\n node_results_dir = os.path.join(results_dir_path, node_name)\n\n # Parse CPU results\n cpu_full_path = os.path.join(node_results_dir, cpu_readings_file_name)\n\n with open(cpu_full_path, \"r\") as lines:\n first_line = True\n date_part = None\n previous_reading_time_part = None\n for line in lines:\n if first_line:\n date_string = parse_date_from_sar_file(first_line_in_file=line)\n date_part = datetime.strptime(date_string, '%m/%d/%Y')\n first_line = False\n\n matches = re.match(cpu_all_cores_regex, line)\n if matches:\n time_string = matches.group(1)\n\n # Add a day when experiment runs past midnight, when the hour of the first reading is smaller than the one before.\n time_part = datetime.strptime(time_string, '%I:%M:%S %p')\n if previous_reading_time_part is not None and previous_reading_time_part.hour > time_part.hour:\n date_part = date_part + timedelta(days=1)\n previous_reading_time_part = time_part\n\n timestamp = date_part.replace(hour=time_part.hour, minute=time_part.minute, second=time_part.second)\n cpu_user_usage = float(matches.group(3))\n cpu_system_usage = float(matches.group(5))\n\n all_readings.append([timestamp, node_name, \"cpu_user_usage\", cpu_user_usage])\n all_readings.append([timestamp, node_name, \"cpu_system_usage\", cpu_system_usage])\n all_readings.append([timestamp, node_name, \"cpu_total_usage\", cpu_user_usage + cpu_system_usage])\n\n # Parse network usage\n net_full_path = os.path.join(node_results_dir, net_readings_file_name)\n\n with open(net_full_path, \"r\") as lines:\n first_line = True\n date_part = None\n previous_reading_time_part = None\n cum_net_tx_MB = 0\n cum_net_rx_MB = 0\n\n for line in lines:\n if first_line:\n date_string = parse_date_from_sar_file(first_line_in_file=line)\n date_part = datetime.strptime(date_string, '%m/%d/%Y')\n first_line = False\n\n matches = re.match(network_regex, line)\n if matches:\n time_string = matches.group(1)\n\n # Add a day when experiment runs past midnight, when the hour of the first reading is smaller than the one before.\n time_part = datetime.strptime(time_string, '%I:%M:%S %p')\n if previous_reading_time_part is not None and previous_reading_time_part.hour > time_part.hour:\n date_part = date_part + timedelta(days=1)\n previous_reading_time_part = time_part\n\n timestamp = date_part.replace(hour=time_part.hour, minute=time_part.minute, second=time_part.second)\n net_interface = matches.group(2)\n net_in_KBps = float(matches.group(5))\n net_out_KBps = float(matches.group(6))\n\n # Taking only enp59s0 interface for now.\n if net_interface == \"enp59s0\": # \"lo\"\n all_readings.append([timestamp, node_name, \"net_in_Mbps\", net_in_KBps * 8 / 1000])\n all_readings.append([timestamp, node_name, \"net_out_Mbps\", net_out_KBps * 8 / 1000])\n all_readings.append([timestamp, node_name, \"net_total_Mbps\", (net_in_KBps + net_out_KBps) * 8/ 1000])\n cum_net_rx_MB += net_in_KBps / 1000\n cum_net_tx_MB += net_out_KBps / 1000\n\n # Parse memory usage\n mem_full_path = os.path.join(node_results_dir, mem_readings_file_name)\n\n with open(mem_full_path, \"r\") as lines:\n first_line = True\n date_part = None\n previous_reading_time_part = None\n for line in lines:\n if first_line:\n date_string = parse_date_from_sar_file(first_line_in_file=line)\n date_part = datetime.strptime(date_string, '%m/%d/%Y')\n first_line = False\n\n matches = re.match(memory_regex, line)\n if matches:\n time_string = matches.group(1)\n\n # Add a day when experiment runs past midnight, when the hour of the first reading is smaller than the one before.\n time_part = datetime.strptime(time_string, '%I:%M:%S %p')\n if previous_reading_time_part is not None and previous_reading_time_part.hour > time_part.hour:\n date_part = date_part + timedelta(days=1)\n previous_reading_time_part = time_part\n\n timestamp = date_part.replace(hour=time_part.hour, minute=time_part.minute, second=time_part.second)\n mem_usage_percent = float(matches.group(5))\n\n all_readings.append([timestamp, node_name, \"mem_usage_percent\", mem_usage_percent])\n\n # Parse disk IO usage (Disk IO may not exist for some experiments, so skip it if it does not exist)\n diskio_full_path = os.path.join(node_results_dir, diskio_readings_file_name)\n if os.path.exists(diskio_full_path):\n with open(diskio_full_path, \"r\") as lines:\n first_line = True\n date_part = None\n previous_reading_time_part = None\n for line in lines:\n if first_line:\n date_string = parse_date_from_sar_file(first_line_in_file=line)\n date_part = datetime.strptime(date_string, '%m/%d/%Y')\n first_line = False\n\n matches = re.match(io_regex, line)\n if matches:\n time_string = matches.group(1)\n\n # Add a day when experiment runs past midnight, when the hour of the first reading is smaller than the one before.\n time_part = datetime.strptime(time_string, '%I:%M:%S %p')\n if previous_reading_time_part is not None and previous_reading_time_part.hour > time_part.hour:\n date_part = date_part + timedelta(days=1)\n previous_reading_time_part = time_part\n\n timestamp = date_part.replace(hour=time_part.hour, minute=time_part.minute, second=time_part.second)\n disk_rps = float(matches.group(3))\n disk_wps = float(matches.group(4))\n disk_brps = float(matches.group(5))\n disk_bwps = float(matches.group(6))\n\n all_readings.append([timestamp, node_name, \"disk_reads_ps\", disk_rps])\n all_readings.append([timestamp, node_name, \"disk_writes_ps\", disk_wps])\n all_readings.append([timestamp, node_name, \"disk_total_ps\", disk_rps + disk_wps])\n all_readings.append([timestamp, node_name, \"disk_breads_ps\", disk_brps])\n all_readings.append([timestamp, node_name, \"disk_bwrites_ps\", disk_bwps])\n all_readings.append([timestamp, node_name, \"disk_btotal_ps\", disk_brps + disk_bwps])\n all_readings.append([timestamp, node_name, \"disk_MBreads_ps\", disk_brps * 512 / (1024 * 1024)])\n all_readings.append([timestamp, node_name, \"disk_MBwrites_ps\", disk_bwps * 512 / (1024 * 1024)])\n all_readings.append([timestamp, node_name, \"disk_MBtotal_ps\", (disk_brps + disk_bwps) * 512 / (1024 * 1024)])\n\n # Parse power measurements and attribute them to each node connected to power meter\n designated_driver_results_path = os.path.join(results_dir_path, experiment_setup.designated_driver_node)\n power_full_path = os.path.join(designated_driver_results_path, power_readings_file_name)\n\n if os.path.exists(power_full_path):\n with open(power_full_path, \"r\") as lines:\n for line in lines:\n matches = re.match(power_regex, line)\n if matches:\n timestamp = datetime.fromtimestamp(float(matches.group(1)))\n\n i = 0\n for node_name in experiment_setup.power_meter_nodes_in_order:\n power_watts = float(matches.group(i + 2))\n all_readings.append([timestamp.replace(microsecond=0), node_name, \"power_watts\", power_watts])\n i += 1\n\n # Parse spark log\n spark_log_full_path = os.path.join(designated_driver_results_path, spark_log_file_name)\n task_counter = dict.fromkeys(experiment_setup.all_spark_nodes, 0)\n\n if os.path.exists(spark_log_full_path):\n with open(spark_log_full_path, \"r\") as lines:\n for line in lines:\n matches = re.match(spark_stage_and_task_log_regex_2, line)\n if matches:\n time_string = matches.group(1)\n timestamp = datetime.strptime(time_string, '%y/%m/%d %H:%M:%S')\n # timestamp = datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S')\n stage = float(matches.group(2))\n node_name = matches.group(3)\n\n # If only results from subset of the nodes are available (rare case)\n if node_name not in experiment_setup.all_spark_nodes:\n continue\n\n if \"Starting task\" in line:\n task_counter[node_name] += 1\n else:\n task_counter[node_name] -= 1\n\n all_readings.append([timestamp, node_name, \"spark_stage\", stage])\n all_readings.append([timestamp, node_name, \"spark_tasks\", task_counter[node_name]])\n\n # Add max and min timestamps for spark tasks with 0 to get the same time range in plots.\n time_stamps = list(map(lambda r: r[0], all_readings))\n min_time = min(time_stamps)\n max_time = max(time_stamps)\n for node_name in experiment_setup.all_spark_nodes:\n all_readings.append([min_time, node_name, \"spark_tasks\", 0])\n all_readings.append([max_time, node_name, \"spark_tasks\", 0])\n\n # Output to file\n if output_readings_to_file:\n output_full_path = os.path.join(results_dir_path, output_readings_file_name)\n\n with open(output_full_path, \"w\") as f:\n for r in all_readings:\n f.write(\"{0}, {1}, {2}\\n\".format(r[0], r[1], r[2]))\n\n return all_readings\n\n\n# Generates one plot for resource usages per node\ndef plot_all_for_one_node(plots_dir_full_path, all_readings, experiment_id, experiment_setup, node_name):\n\n # Filter all readings for node\n all_readings = list(filter(lambda r: r[1] == node_name, all_readings))\n\n fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1)\n fig.set_size_inches(w=10,h=10)\n fig.suptitle(\"Experiment ID: {0}\\nSpark sort on {1}GB input, Link bandwidth: {2}Mbps, Role: {3}\".format(\n experiment_id, experiment_setup.input_size_gb, experiment_setup.link_bandwidth_mbps,\n \"Driver\" if node_name == experiment_setup.designated_driver_node else \"Executor\"))\n\n # render subplots\n render_subplot_by_label(ax1, all_readings,\n filter_label='power_watts',\n x_label='Time (Sec)',\n y_label='Power (units?)',\n plot_label='Power')\n render_subplot_by_label(ax2, all_readings,\n filter_label='cpu_total_usage',\n x_label='Time (Sec)',\n y_label='CPU usage % (all cores)',\n plot_label='CPU')\n render_subplot_by_label(ax3, all_readings,\n filter_label='mem_usage_percent',\n x_label='Time (Sec)',\n y_label='Memory used %',\n plot_label='Memory')\n render_subplot_by_label(ax4, all_readings,\n filter_label='net_in_Mbps',\n x_label='Time (Sec)',\n y_label='Network Mbps',\n plot_label='In')\n render_subplot_by_label(ax4, all_readings,\n filter_label='net_out_Mbps',\n x_label='Time (Sec)',\n y_label='Network Mbps',\n plot_label='Out')\n render_subplot_by_label(ax5, all_readings,\n filter_label='disk_MBreads_ps',\n x_label='Time (Sec)',\n y_label='Disk MB/sec',\n plot_label='Reads')\n render_subplot_by_label(ax5, all_readings,\n filter_label='disk_MBwrites_ps',\n x_label='Time (in secs)',\n y_label='Disk MB/sec',\n plot_label='Writes')\n render_subplot_by_label(ax6.twinx(), all_readings,\n filter_label='spark_stage',\n x_label='Time (in secs)',\n y_label='',\n plot_label='Spark stage',\n plot_color='red')\n render_subplot_by_label(ax6, all_readings,\n filter_label='spark_tasks',\n x_label='Time (in secs)',\n y_label='',\n plot_label='Number of spark tasks')\n\n # Save the file, should be done before show()\n output_plot_file_name = \"plot_{0}_{1}.png\".format(experiment_setup.input_size_gb, node_name)\n output_full_path = os.path.join(plots_dir_full_path, output_plot_file_name)\n plt.savefig(output_full_path)\n # plt.show()\n plt.close()\n\n\n# Generates one plot for custom-selected resources\ndef plot_custom_for_one_node(plots_dir_full_path, all_readings, experiment_id, experiment_setup, node_name):\n\n # Filter all readings for node\n all_readings = list(filter(lambda r: r[1] == node_name, all_readings))\n\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1)\n fig.set_size_inches(w=10,h=10)\n fig.suptitle(\"Experiment ID: {0}\\nSpark sort on {1}GB input, Link bandwidth: {2}Mbps, Role: {3}\".format(\n experiment_id, experiment_setup.input_size_gb, experiment_setup.link_bandwidth_mbps,\n \"Driver\" if node_name == experiment_setup.designated_driver_node else \"Executor\"))\n\n # render subplots\n render_subplot_by_label(ax1, all_readings,\n filter_label='cpu_total_usage',\n x_label='',\n y_label='CPU usage % (all cores)',\n plot_label='CPU')\n render_subplot_by_label(ax2, all_readings,\n filter_label='net_in_Mbps',\n x_label='',\n y_label='Network Mbps',\n plot_label='In')\n render_subplot_by_label(ax2, all_readings,\n filter_label='net_out_Mbps',\n x_label='',\n y_label='Network Mbps',\n plot_label='Out')\n render_subplot_by_label(ax3.twinx(), all_readings,\n filter_label='spark_stage',\n x_label='Time (in secs)',\n y_label='',\n plot_label='Spark stage',\n plot_color='red')\n render_subplot_by_label(ax3, all_readings,\n filter_label='spark_tasks',\n x_label='Time (in secs)',\n y_label='',\n plot_label='Number of spark tasks')\n\n # Save the file, should be done before show()\n output_plot_file_name = \"plot_custom_{0}_{1}.png\".format(experiment_setup.input_size_gb, node_name)\n output_full_path = os.path.join(plots_dir_full_path, output_plot_file_name)\n plt.savefig(output_full_path)\n # plt.show()\n plt.close()\n\n\n\n# Generates one plot for resource usages on one node\ndef plot_all_for_one_label(plots_dir_full_path, all_readings, experiment_id, experiment_setup, label_name):\n\n # Filter all readings for node\n all_readings = list(filter(lambda r: r[2] == label_name, all_readings))\n\n fig, ax = plt.subplots(1, 1)\n # fig.set_size_inches(w=20,h=10)\n fig.suptitle(\"Spark sort for {1}GB, {2} Mbps ({0})\".format(\n experiment_id, experiment_setup.input_size_gb, experiment_setup.link_bandwidth_mbps, label_name))\n\n # render subplots\n for node_name in experiment_setup.all_spark_nodes:\n render_subplot_by_node(ax, all_readings,\n filter_node=node_name,\n x_label='Time (Sec)',\n y_label=label_name,\n plot_label=node_name)\n\n # Save the file, should be done before show()\n output_plot_file_name = \"plot_{0}_{1}.png\".format(experiment_setup.input_size_gb, label_name)\n output_full_path = os.path.join(plots_dir_full_path, output_plot_file_name)\n plt.savefig(output_full_path)\n # plt.show()\n plt.close()\n\n\ndef plot_cdf_for_one_label(plots_dir_full_path, all_readings, experiment_id, experiment_setup, label_name):\n \n # Filter all readings from the exact duration of spark job and for the label \n all_readings = [r for r in all_readings if r[2] == label_name and \n (experiment_setup.spark_job_start_time < r[0] < experiment_setup.spark_job_end_time)]\n\n fig, ax = plt.subplots(1, 1)\n fig.set_size_inches(w=10,h=10)\n # plt.clf()\n # plt.rcParams.update({'font.size': 20})\n fig.suptitle(\"Experiment ID: {0}\\nSpark sort on {1}GB input, Link bandwidth: {2}Mbps, Label: {3}\".format(\n experiment_id, experiment_setup.input_size_gb, experiment_setup.link_bandwidth_mbps, label_name))\n\n # render cdf subplots\n render_cdf_subplot_by_node(ax, all_readings,\n # filter_node=node_name,\n x_label=label_name,\n y_label='CDF')\n # plt.show()\n\n # Save the file, should be done before show()\n output_plot_file_name = \"plot_cdf_{0}_{1}.png\".format(experiment_setup.input_size_gb, label_name)\n output_full_path = os.path.join(plots_dir_full_path, output_plot_file_name)\n plt.savefig(output_full_path)\n # plt.show()\n plt.close()\n\n\n# Filters a subset of readings from all readings based on the filter label and plots it on provided axes\ndef render_subplot_by_label(ax, all_readings, filter_label, x_label, y_label, plot_label=None, plot_color=None):\n min_time_stamp = min(map(lambda r: r[0], all_readings)) if all_readings.__len__() != 0 else datetime.min\n filtered_readings = list(filter(lambda r: r[2] == filter_label, all_readings))\n ax.set_xlabel(x_label)\n ax.set_ylabel(y_label)\n time_series = list(map(lambda r: r[0], filtered_readings))\n x = []\n if time_series.__len__() != 0:\n x = [(t - min_time_stamp).total_seconds() for t in time_series]\n y = list(map(lambda r: r[3], filtered_readings))\n ax.plot(x, y, label=plot_label, color=plot_color)\n ax.legend()\n\n\n# Filters a subset of readings from all readings based on the filter label and plots it on provided axes\ndef render_subplot_by_node(ax, all_readings, filter_node, x_label, y_label, plot_label=None):\n min_time_stamp = min(map(lambda r: r[0], all_readings)) if all_readings.__len__() != 0 else datetime.min\n filtered_readings = list(filter(lambda r: r[1] == filter_node, all_readings))\n ax.set_xlabel(x_label)\n ax.set_ylabel(y_label)\n time_series = list(map(lambda r: r[0], filtered_readings))\n x = []\n if time_series.__len__() != 0:\n x = [(t - min_time_stamp).total_seconds() for t in time_series]\n y = list(map(lambda r: r[3], filtered_readings))\n ax.plot(x, y, label=plot_label)\n ax.legend()\n\n\n# Generates cdf for a list \ndef gen_cdf_curve(np_array, num_bin):\n array = np.sort(np_array)\n h, edges = np.histogram(array, density=True, bins=num_bin)\n h = np.cumsum(h)/np.cumsum(h).max()\n x = edges.repeat(2)[:-1]\n y = np.zeros_like(x)\n y[1:] = h.repeat(2)\n return x, y\n\n\n# Generates cumulative sum curve for a list\ndef gen_cumsum_curve(np_array, num_bin):\n array = np.sort(np_array)\n h, edges = np.histogram(array, bins=num_bin)\n h = np.cumsum(h)\n x = edges.repeat(2)[:-1]\n y = np.zeros_like(x)\n y[1:] = h.repeat(2)\n return x, y\n\n\ndef time_series_to_int_list(time_series):\n min_time_stamp = min(time_series)\n return [int((t - min_time_stamp).total_seconds()) for t in time_series]\n\n\n# Filters a subset of readings from all readings based on the filter label and plots it on provided axes\ndef render_cdf_subplot_by_node(ax, all_readings, x_label, y_label, plot_label=None):\n ax.set_xlabel(x_label)\n ax.set_ylabel(y_label)\n all_values = [ r[3] for r in all_readings ]\n x,y = gen_cdf_curve(all_values, 100)\n if plot_label is not None:\n ax.plot(x, y, label=plot_label)\n ax.legend()\n else:\n ax.plot(x, y)\n\n\n# Parse results and generate plots for one experiment, and returns full path to the output folder\ndef parse_and_plot_results(experiment_id):\n results_dir_name = experiment_id\n results_dir_path = os.path.join(results_base_dir, results_dir_name)\n setup_file_path = os.path.join(results_dir_path, setup_details_file_name)\n experiment_setup = ExperimentSetup(setup_file_path)\n\n # Assign a random run id for this parse run and use it for generated outputs\n random_parse_run_id = random.randint(1, 1001)\n plots_dir_name = \"plots_{0}\".format(random_parse_run_id)\n output_readings_file_name = \"all_readings_{0}.txt\".format(random_parse_run_id)\n\n # Collect readings from all results files\n all_readings = parse_results(results_dir_path, experiment_setup, output_readings_file_name,\n output_readings_to_file=False)\n\n # Generate plots for each node\n plots_dir_full_path = os.path.join(results_dir_path, plots_dir_name)\n if not os.path.exists(plots_dir_full_path):\n os.mkdir(plots_dir_full_path)\n\n for node_name in experiment_setup.all_spark_nodes:\n plot_all_for_one_node(plots_dir_full_path, all_readings, experiment_id, experiment_setup, node_name)\n pass\n\n for node_name in experiment_setup.all_spark_nodes:\n plot_custom_for_one_node(plots_dir_full_path, all_readings, experiment_id, experiment_setup, node_name)\n pass\n\n for label_name in ['power_watts', 'cpu_total_usage', 'mem_usage_percent', 'net_in_Mbps', 'net_out_Mbps',\n 'disk_MBreads_ps', 'disk_MBwrites_ps', 'spark_tasks']:\n plot_all_for_one_label(plots_dir_full_path, all_readings, experiment_id, experiment_setup, label_name)\n pass\n\n for label_name in ['net_out_Mbps']:\n plot_cdf_for_one_label(plots_dir_full_path, all_readings, experiment_id, experiment_setup, label_name)\n\n return plots_dir_full_path\n\n\n# Filter experiments to generate plots\ndef filter_experiments_to_consider():\n start_time = datetime.strptime('2019-05-07 18:00:00', '%Y-%m-%d %H:%M:%S')\n end_time = datetime.now()\n\n # All experiments after start_time that doesn't already have plots_ folder.\n experiments_to_consider = []\n all_experiments = [os.path.join(results_base_dir, item) for item in os.listdir(results_base_dir)\n if item.startswith(\"Exp-\")\n and os.path.isdir(os.path.join(results_base_dir, item))\n and not [subdir for subdir in os.listdir(os.path.join(results_base_dir, item)) if subdir.startswith(\"plots_\")]]\n\n for experiment_dir_path in all_experiments:\n experiment_id = os.path.basename(experiment_dir_path)\n experiment_time = datetime.fromtimestamp(os.path.getctime(experiment_dir_path))\n if start_time < experiment_time < end_time:\n experiments_to_consider.append(experiment_id)\n pass\n\n # experiments_to_consider.append(\"Exp-2019-01-30-18-21-58\")\n\n return experiments_to_consider\n\n\nif __name__ == \"__main__\":\n # all_experiments = [\"Sting-Exp-2018-12-19-23-43-24\"]\n all_experiments = filter_experiments_to_consider()\n for experiment_id in all_experiments:\n try:\n print(\"Parsing experiment \" + experiment_id)\n parse_and_plot_results(experiment_id)\n except Exception as e:\n tc.print_exc(e)\n pass\n","sub_path":"v2/spark/plot_one_experiment.py","file_name":"plot_one_experiment.py","file_ext":"py","file_size_in_byte":29333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"308749032","text":"import random\n\n__author__ = 'caoyu'\nimport numpy as np\na = random.randrange(3)\nif a == 1:\n print (\"Hei An Liao Li\")\nelif a ==2:\n print (\"Chinese food\")\nelse:\n print(\"Han Bao King\")\n\n\n","sub_path":"eat_what.py","file_name":"eat_what.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"166402436","text":"from cpbox.tool import functocli\nfrom cpbox.tool import template\nfrom cpbox.tool import dockerutil\nfrom cpbox.app.devops import DevOpsApp\n\n\nAPP_NAME = 'digital-currency-alarm'\n\n\nclass App(DevOpsApp):\n\n def __init__(self):\n DevOpsApp.__init__(self, APP_NAME)\n\n def install_dependencies(self):\n cmd = 'npm install'\n self.shell_run(cmd)\n\n cmd = 'npm install -g supervisor@0.12.0 typescript@3.9.3'\n self.shell_run(cmd)\n\n def run(self):\n cmd = 'npm run server'\n self.shell_run(cmd)\n\n\nif __name__ == '__main__':\n functocli.run_app(App)\n","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"95803541","text":"import sys\nsys.path.append('form-filling')\nfrom form_constructor import form_constructor\nimport unittest\nimport json\n\nclass TestFormConstruction(unittest.TestCase):\n\n def setUp(self):\n with open('tests/resources/dummy_example.json', 'r') as f:\n data = ''\n for line in f:\n data += line\n self.data = json.loads(data)\n\n def test_basic_example(self):\n output = form_constructor(self.data)\n self.assertEqual(len(output), 10)\n\n def test_child_supplement_even(self):\n data = self.data\n data['childInfo'] = data['childInfo'] * 10\n output = form_constructor(data)\n self.assertEqual(len(output), 13)\n\n def test_child_supplement_odd(self):\n data = self.data\n data['childInfo'] = data['childInfo'] * 9\n output = form_constructor(data)\n self.assertEqual(len(output), 13)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"backend/tests/form_construction_test.py","file_name":"form_construction_test.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"447123553","text":"\"\"\"\n/***************************************************\n * s-Sense CCS811 by itbrainpower.net python library v0.3 / 20200218\n * CCS811 TVOC/eCO2 sensors are manufactured by AMS\n *\n * This CCS811 CO2 and tVOC class - based on test software (Beerware license) provided by Nathan Seidle from SparkFun Electronics. \n * Thank you Nathan! Great job! \n * We've ported Nathan's functions into python, add some variables, functions and functionalities.\n *\n * This library it's compatible with:\n *\t\ts-Sense CCS811 I2C sensor breakout [PN: SS-CCS811#I2C, SKU: ITBP-6004], info https://itbrainpower.net/sensors/CCS811-CO2-TVOC-I2C-sensor-breakout \n *\t\ts-Sense CCS811 + HDC2010 I2C sensor breakout [PN: SS-HDC2010+CCS811#I2C, SKU: ITBP-6006], info https://itbrainpower.net/sensors/CCS811-HDC2010-CO2-TVOC-TEMPERATURE-HUMIDITY-I2C-sensor-breakout\n *\t\tall Raspberry PI, using Python 2.7\n * \n * \n * \n * CCS811 definitions are placed in ccs811_param.py\n *\n * New CCS811 sensors requires at 48-burn in. Once burned in a sensor requires 20 minutes of run in before readings are considered good.\n * READ CCS811 documentation! https://itbrainpower.net/downloadables/CCS811_DS000459_5-00.pdf\n * \n * You are legaly entitled to use this SOFTWARE ONLY IN CONJUNCTION WITH s-Sense CCS811 I2C sensors DEVICES USAGE. Modifications, derivates and redistribution \n * of this software must include unmodified this COPYRIGHT NOTICE. You can redistribute this SOFTWARE and/or modify it under the terms \n * of this COPYRIGHT NOTICE. Any other usage may be permited only after written notice of Dragos Iosub / R&D Software Solutions srl.\n * \n * This SOFTWARE is distributed is provide \"AS IS\" in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY \n * or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * \n * itbrainpower.net invests significant time in design phase of our IoT products and in associated software and support resources.\n * Support us by purchasing our environmental and air quality sensors from here https://itbrainpower.net/order#s-Sense\n *\n * This library is dependent on python-smbus2\n * https://pypi.org/project/smbus2/\n * https://buildmedia.readthedocs.org/media/pdf/smbus2/latest/smbus2.pdf\n *\n * Dragos Iosub, Bucharest 2020.\n * https://itbrainpower.net\n */\n\"\"\"\n\nimport smbus2 as smbus\n\nimport RPi.GPIO as GPIO\nfrom time import sleep\n\nfrom ccs811_param import *\n\n\nCO2 = 0\ntVOC = 0\n\nHWRST = True #hardware RESET pin defined\nSleepWake = True #SLEEP/WAKE pin defined\n\n\ndef ccs811GPIOInit():\n global CCS811_RESET_PIN\n global CCS811_WAKE_PIN\n global HWRST\n global SleepWake\n\n GPIO.setmode(GPIO.BOARD)\n GPIO.setwarnings(False)\n #GPIO.cleanup()\n print (\"init CCS811 control GPIOs\")\n\n try:\n GPIO.setup(CCS811_RESET_PIN, GPIO.IN)\n except:\n HWRST = False\n print (\"no RESET PIN defined\")\n\n try:\n GPIO.setup(CCS811_WAKE_PIN, GPIO.OUT, initial=GPIO.LOW)\n GPIO.output(CCS811_WAKE_PIN,GPIO.LOW)\n except:\n SleepWake = False\n print (\"no sleep wake control PIN defined\")\n\n sleep(0.2)\n \n\ndef ccs811SWReset():\n global CO2\n global tVOC\n\n CO2 = 0\n tVOC = 0\n \n ccs811NWriteRegisters(CCS811_SW_RESET, [0x11, 0xE5, 0x72, 0x8A])\n sleep(0.5)\n \n\ndef ccs811HWReset():\n global HWRST \n global CO2\n global tVOC\n\n CO2 = 0\n tVOC = 0\n\n if HWRST == False:\n print( \"no RESET PIN defined\")\n return\n\n GPIO.setup(CCS811_RESET_PIN, GPIO.OUT, initial=GPIO.LOW)\n GPIO.output(CCS811_RESET_PIN,GPIO.LOW) #RESET\n sleep(0.2)\n GPIO.setup(CCS811_RESET_PIN, GPIO.IN) #release RESET line\n sleep(0.5)\n return\n\ndef ccs811Sleep():\n global SleepWake\n if(SleepWake == False):\n return\n GPIO.setup(CCS811_WAKE_PIN, GPIO.IN)\n\ndef ccs811Wake():\n global SleepWake\n if(SleepWake == False):\n return\n GPIO.setup(CCS811_WAKE_PIN, GPIO.OUT, initial=GPIO.LOW)\n GPIO.output(CCS811_WAKE_PIN,GPIO.LOW)\n\n\ndef ccs811ReadNRegisters(address, length):\n global bus\n global CCS811_I2C_ADDRESS\n contents = bus.read_i2c_block_data(CCS811_I2C_ADDRESS, address, length)\n return contents\n\n\ndef ccs811ReadRegister(address):\n global bus\n global CCS811_I2C_ADDRESS\n\n contents = bus.read_i2c_block_data(CCS811_I2C_ADDRESS, address, 1)\n return contents[0]\n\ndef ccs811NWriteRegisters(address, data):\n global bus\n global CCS811_I2C_ADDRESS\n bus.write_i2c_block_data(CCS811_I2C_ADDRESS, address, data)\n\ndef ccs811WriteRegister(address, data):\n global bus\n global CCS811_I2C_ADDRESS\n\n bus.write_byte_data(CCS811_I2C_ADDRESS, address, data)\n\n\n#Displays the type of error\n#Calling this causes reading the contents of the ERROR register\n#This should clear the ERROR_ID register\ndef ccs811PrintError():\n error = ccs811ReadRegister(CCS811_ERROR_ID)\n if (error & 1 << 5):\n print(\"Error: HeaterSupply \")\n if (error & 1 << 4):\n print(\"Error: HeaterFault \")\n if (error & 1 << 3):\n print(\"Error: MaxResistance \")\n if (error & 1 << 2):\n print(\"Error: MeasModeInvalid \")\n if (error & 1 << 1):\n print(\"Error: ReadRegInvalid\")\n if (error & 1 << 0):\n print(\"Error: MsgInvalid \")\n\ndef ccs811CheckForError():\n value = ccs811ReadRegister(CCS811_STATUS)\n #print \"STATUS register : 0x%02x \" %value\n return value & 1 << 0\n\n#Mode 0 = Idle\n#Mode 1 = read every 1s\n#Mode 2 = every 10s\n#Mode 3 = every 60s\n#Mode 4 = RAW mode\ndef ccs811SetDriveMode(mode):\n if (mode > 4): #error correction\n mode = 4\n\n setting = ccs811ReadRegister(CCS811_MEAS_MODE) #Read what's currently there\n setting &= ~(0b00000111 << 4) #Clear DRIVE_MODE bits\n setting = setting | (mode << 4) #Mask in mode\n ccs811WriteRegister(CCS811_MEAS_MODE, setting)\n\n\ndef ccs811AppValid():\n #print \"AppValid to be done\"\n value = ccs811ReadRegister(CCS811_STATUS)\n return (value & 1 << 4)\n\n\n\n#Enable the nINT signal\ndef ccs811EnableInterrupts():\n setting = ccs811ReadRegister(CCS811_MEAS_MODE) #Read what's currently there\n setting |= setting | (1 << 3) #Set INTERRUPT bit\n ccs811WriteRegister(CCS811_MEAS_MODE, setting)\n\n#Enable the nINT signal\ndef ccs811DisableInterrupts():\n setting = ccs811ReadRegister(CCS811_MEAS_MODE) #Read what's currently there\n setting &= ~(1 << 3) & 0xFF #Clear INTERRUPT bit\n ccs811WriteRegister(CCS811_MEAS_MODE, setting)\n\n\n\n#Updates the total voltatile organic compounds (TVOC) in parts per billion (PPB)\n#and the CO2 value\ndef ccs811ReadAlgorithmResults():\n global CO2\n global tVOC\n\n contents = ccs811ReadNRegisters(CCS811_ALG_RESULT_DATA, 4)\n\n co2MSB = contents[0]\n co2LSB = contents[1]\n tvocMSB = contents[2]\n tvocLSB = contents[3]\n\n CO2 = (co2MSB << 8) | co2LSB\n tVOC = (tvocMSB << 8) | tvocLSB\n\n\n#Checks to see if DATA_READ flag is set in the status register\ndef ccs811DataAvailable():\n value = ccs811ReadRegister(CCS811_STATUS)\n return (value & 1 << 3)\n\n\ndef ccs811CheckDataAndUpdate():\n if(ccs811DataAvailable()):\n ccs811ReadAlgorithmResults() #update the global tVOC and CO2 variables\n return True\n else:\n return False\n\n \n\n\ndef ccs811GetBaseline():\n global bus\n\n contents = ccs811ReadNRegisters(CCS811_BASELINE, 2)\n baselineMSB = contents[0]\n baselineLSB = contents[1]\n\n #print \"baselineMSB: 0x%02x \" %baselineMSB\n #print \"baselineLSB: 0x%02x \" %baselineLSB\n\n baseline = (baselineMSB << 8) | baselineLSB\n return baseline\n\n\n \ndef ccs811Begin(driveMode):\n global HWRST\n global SleepWake\n\n ccs811GPIOInit()\n\n if(HWRST != False):\n ccs811HWReset()\n else:\n print (\"sofware reset\")\n ccs811SWReset()\n \n ccs811Wake()\n\n contents = ccs811ReadRegister(CCS811_HW_ID) #Hardware ID should be 0x81\n print (\"CCS811_HW_ID : 0x%02x \" )\n \n\n if (contents != 0x81): #\"CCS811 not found. Please check wiring.\"\n print (\"CCS811 not found. Please check wiring.\")\n #return -1\n else:\n print (\"CCS811 found.\")\n \n if (ccs811CheckForError() == True):\n print (\"Error at startup\")\n ccs811PrintError()\n #return -2\n else:\n print (\"Clean startup\")\n\n \n if (ccs811AppValid() == False):\n print (\"Error: App not valid.\")\n #return -3\n else:\n print (\"App valid\")\n\n bus.write_byte(CCS811_I2C_ADDRESS, CCS811_APP_START)\n\n\n if (ccs811CheckForError() == True):\n print(\"Error at AppStart\")\n ccs811PrintError()\n #return -4\n else:\n print (\"Clean AppStart\")\n\n ccs811DisableInterrupts()\n\n ccs811SetDriveMode(driveMode) # Mode 0/1/2/3/4==> Idle/1sec/10sec/60sec/RAW\t\tITBP add\n \n\n #sleep(0.5)\n\n if (ccs811CheckForError() == True):\n print (\"Error at SetDriveMode\")\n ccs811PrintError()\n #return -5\n else:\n print (\"Clean SetDriveMode\")\n\n result = ccs811GetBaseline()\n print (\"baseline for this sensor: 0x%02x \" %result)\n return 0 \n\n\ndef ccs811SetEnvironmentalData(relativeHumidity, temperature): \n rH = int(relativeHumidity * 1000)\n temp = int(temperature * 1000)\n\n if ((rH % 1000) / 100) > 7:\n envData0 = (rH / 1000 + 1) << 1\n else:\n envData0 = (rH / 1000) << 1\n \n envData1 = 0 #CCS811 only supports increments of 0.5 so bits 7-0 will always be zero\n\n if ((((rH % 1000) / 100) > 2) and (((rH % 1000) / 100) < 8)):\n envData0 = envData0 | 1 #Set 9th bit of fractional to indicate 0.5%\n\n temp = temp + 25000 #Add the 25C offset\n\n #Split value into 7-bit integer and 9-bit fractional\n if ((temp % 1000) / 100) > 7:\n envData2 = (temp / 1000 + 1) << 1\n else:\n envData2 = (temp / 1000) << 1\n\n envData3 = 0\n\n if (((temp % 1000) / 100) > 2 and (((temp % 1000) / 100) < 8)):\n envData2 |= envData2 | 1 #Set 9th bit of fractional to indicate 0.5C\n \n\n envData = [envData0, envData1, envData2, envData3]\n\n #bus.write_i2c_block_data(CCS811_I2C_ADDRESS, CCS811_ENV_DATA, envData)\n ccs811NWriteRegisters(CCS811_ENV_DATA, envData)\n\n\ndef ccs811GetCO2():\n global CO2\n return CO2\n\ndef ccs811GetTVOC():\n global tVOC\n return tVOC\n\n\n\n# Initialize I2C (SMBus)\ntry:\n configContents = ccs811ReadRegister(CCS811_HW_ID)\n print (\"I2C alredy loaded\")\nexcept:\n bus = smbus.SMBus(channel)\n\n","sub_path":"c02/ccs811_simple/ccs811.py","file_name":"ccs811.py","file_ext":"py","file_size_in_byte":11815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"178939553","text":"import socket\nimport struct\nimport time\n# import numpy\nimport math\nk = 32\ns = 32\nWORKER1_IP=\"10.0.0.1\"\nWORKER2_IP=\"10.0.0.2\"\nWORKER3_IP=\"10.0.0.3\"\nWORKER4_IP=\"10.0.0.4\"\nWORKER5_IP=\"10.0.0.5\"\nSERVER_IP=\"10.0.0.6\"\nN=40\ninterval=1/N\nSML_PORT=8888\n\n# u=(32,32)\n# U=numpy.zeros(u)\n# print(U)\nwork_data = \"work_data\"\nu_data =\"u_data\"\n#定义数据包类\nclass p:\n def __init__(self):\n self.idx = 0\n self.off = 0\n self.vector = []\n# 生成socket对象\nss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nss.bind((WORKER1_IP,SML_PORT))\n# 链接要链接的ip和port(端口)\nsent_addr=(\"10.0.0.6\",SML_PORT)\n# 读取梯度值\nf1 = open(work_data, \"r\")\nf2 = open(u_data, \"w\")\nsent_data = f1.read()\nsent_data = sent_data.split()\nsent_data = list(map(float, sent_data)) # 把数据转换成浮点数\n# p.off=0\n# 发送数据\nfor i in range(1, s+1):\n p.idx = i\n p.off = k * i-k\n if p.off + k <= len(sent_data):\n sent_vector = sent_data[p.off:p.off + k]\n idx_field = struct.pack(\">i\", p.idx)\n off_field = struct.pack(\"i\", p.off)\n sent_packet = idx_field + off_field\n for ii in range(len(sent_vector)):\n sent_vector[ii] = int(sent_vector[ii] * 2 ** 28)\n sent_packet += struct.pack(\"i\", sent_vector[ii])\n print(sent_packet)\n ss.sendto(sent_packet, sent_addr)\n print(\"yes\")\n time.sleep(interval)\n # print(vector)\n else:\n idx_field = struct.pack(\">i\", p.idx)\n off_field = struct.pack(\"i\", p.off)\n sent_packet = idx_field + off_field\n sent_vector = sent_data[p.off:]\n for iii in range(len(sent_vector)):\n sent_vector[iii] = int(sent_vector[iii] * 2 ** 28)\n sent_packet += struct.pack(\"i\", sent_vector[iii])\n # print(vector)\n print(p.off)\ncounter=0\nprint(\"recieve data:\")\nwhile True:\n # 接收数据\n #print(counter)\n recv_packet,recv_addr=ss.recvfrom(1024)\n counter=counter+1\n recv_data=[]\n p.idx=int(struct.unpack(\">i\",recv_packet[0:4])[0])\n for d in range(4,len(recv_packet),4):\n recv_data.append(struct.unpack(\"i\",recv_packet[d:d+4])[0])\n #print(recv_data)\n #p.idx=int(recv_data[0])\n p.off=int(recv_data[0])\n print(\"idx={0},offset={1}\".format(p.idx,p.off))\n recv_vector=recv_data[1:]\n for i in range(len(recv_vector)):\n recv_vector[i]=float(recv_vector[i]/(2**28))\n # f2.write(str(recv_vector[i])+' ')\n print(recv_vector)\n sent_data[p.off:p.off+k]=recv_vector\n p.off += k*s\n #time.sleep(interval)\n if p.offi\", p.idx)\n off_field = struct.pack(\"i\", p.off)\n sent_packet = idx_field + off_field\n for ii in range(len(sent_vector)):\n sent_vector[ii] = int(sent_vector[ii] * 2 ** 28)\n sent_packet += struct.pack(\"i\", sent_vector[ii])\n print(\"sent again:\")\n print(sent_packet)\n ss.sendto(sent_packet, sent_addr)\n time.sleep(interval)\n elif p.off len(sent_data):\n idx_field = struct.pack(\">i\", p.idx)\n off_field = struct.pack(\"i\", p.off)\n sent_packet = idx_field + off_field\n sent_vector = sent_data[p.off:]\n for iii in range(len(sent_vector)):\n sent_vector[iii] = int(sent_vector[iii] * 2 ** 28)\n sent_packet += struct.pack(\"i\", sent_vector[iii])\n ss.sendto(sent_packet, sent_addr)\n if counter == math.ceil(len(sent_data)/k):\n #if counter == math.ceil(len(sent_data)/k) or p.off==131040:\n print(\"done!\")\n break\n\nfor list_men in sent_data:\n # off=0\n # for i in range(k):\n f2.write(str(list_men)+ \" \")\n # off=k*i\nf2.flush()\nf1.close()\nf2.close()\n\n # p.off = p.off + k\nss.close()\nprint('Connection is broken')\n","sub_path":"contrast/5/p4/worker1/worker1.py","file_name":"worker1.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"347009718","text":"#Hello\ndef hello(x):\n if x == 0:\n return\n else:\n print('Hello World!')\n hello(x-1)\n\nhello(4)\n\n# Summ\ndef factorial(x):\n if x == 0:\n return 1\n else:\n return x * factorial(x - 1)\n\n\nprint(factorial(4)) #24\n\n\ndef factorial(x):\n if x == 0:\n return 1\n else:\n return x * factorial(x-1)\n\nprint(factorial(6)) #720\n\n\n#Fibonacci\ndef fibo(x):\n if x == 0:\n return 0\n elif x == 1:\n return 1\n else:\n return fibo(x - 1) + fibo(x - 2)\n\n\nprint(fibo(7)) #13","sub_path":"ADV-IT/Recursion.py","file_name":"Recursion.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"64261924","text":"import front.frontend as f\nimport back.backend as b\nimport utils.args as a\n\n# Front end: UI, user event\n# Back end: ...\n\n\nclass App:\n def __init__(self, front_end=None, back_end=None, args=None):\n self.front_end = front_end\n self.back_end = back_end\n self.args = args\n self.running = False\n\n def prepare(self):\n self.front_end.prepare() # input the utils into the back\n self.back_end.prepare() # input the utils into the front\n\n def run(self):\n self.running = True\n while self.running:\n self.set_fps(80)\n self.render()\n self.events()\n\n def events(self):\n events = self.front_end.get_events()\n if events['quit']:\n self.quit()\n elif 'f' in events['key-down'] and (events['mods'] & 64 != 0 or events['mods'] & 128 != 0):\n self.front_end.ui.toggle_fullscreen()\n else:\n command = self.back_end.process_events(events)\n if command == 'quit':\n self.quit()\n\n def render(self):\n self.front_end.render(self.back_end)\n\n def set_fps(self, fps):\n self.front_end.clock.tick(fps)\n\n def quit(self):\n self.front_end.quit()\n self.back_end.quit()\n self.running = False\n\n\ndef launch(args=a.Args()):\n app = App(f.FrontEnd(args), b.BackEnd(args), args)\n app.prepare()\n app.run()\n\n\nif __name__ == '__main__':\n launch()\n","sub_path":"main/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"548926576","text":"import skimage as skimage\nfrom skimage import transform, color\n\nimport random\nimport numpy as np\nfrom collections import deque\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Flatten\nfrom keras.layers import Conv2D, Dense, Flatten\nfrom keras.optimizers import Adam\nfrom tensorflow.compat.v1.keras import backend as K\n\nfrom vizdoom import DoomGame, ScreenResolution\nfrom vizdoom import *\n\nimport tensorflow.compat.v1 as tf\n\ntf.disable_v2_behavior()\n\n\ndef dqn(input_shape, action_size, learning_rate):\n\n model = Sequential()\n model.add(Conv2D(32, 8, strides=(4,4), activation='relu', input_shape=(input_shape)))\n model.add(Conv2D(64, 4, strides=(2,2), activation='relu'))\n model.add(Conv2D(64, 3, 3, activation='relu'))\n model.add(Flatten())\n model.add(Dense(512, activation='relu'))\n model.add(Dense(action_size, activation='linear'))\n\n adam = Adam(lr=learning_rate)\n model.compile(loss='mse',optimizer=adam)\n\n return model\n\n\ndef preprocessImg(img, size):\n\n img = np.rollaxis(img, 0, 3) \n img = skimage.transform.resize(img,size)\n img = skimage.color.rgb2gray(img)\n\n return img\n \n\nclass DoubleDQNAgent:\n\n def __init__(self, state_size, action_size):\n\n self.state_size = state_size\n self.action_size = action_size\n self.gamma = 0.99\n self.learning_rate = 0.0001\n self.epsilon = 1.0\n self.initial_epsilon = 1.0\n self.final_epsilon = 0.0001\n self.batch_size = 32\n self.observe = 5000\n self.explore = 50000 \n self.frame_per_action = 4\n self.update_target_freq = 3000 \n self.timestep_per_train = 100 \n\n\n self.memory = deque()\n self.max_memory = 50000\n\n\n self.model = None\n self.target_model = None\n\n self.stats_window_size= 50\n self.mavg_score = [] \n self.var_score = [] \n self.mavg_ammo_left = []\n self.mavg_kill_counts = [] \n\n def update_target_model(self):\n\n self.target_model.set_weights(self.model.get_weights())\n\n def get_action(self, state):\n\n if np.random.rand() <= self.epsilon:\n action_idx = random.randrange(self.action_size)\n else:\n q = self.model.predict(state)\n action_idx = np.argmax(q)\n return action_idx\n\n def shape_reward(self, r_t, misc, prev_misc, t):\n \n\n if (misc[0] > prev_misc[0]):\n r_t = r_t + 1\n\n if (misc[1] < prev_misc[1]):\n r_t = r_t - 0.1\n\n if (misc[2] < prev_misc[2]): \n r_t = r_t - 0.1\n\n return r_t\n\n def replay_memory(self, s_t, action_idx, r_t, s_t1, is_terminated, t):\n self.memory.append((s_t, action_idx, r_t, s_t1, is_terminated))\n if self.epsilon > self.final_epsilon and t > self.observe:\n self.epsilon -= (self.initial_epsilon - self.final_epsilon) / self.explore\n\n if len(self.memory) > self.max_memory:\n self.memory.popleft()\n\n if t % self.update_target_freq == 0:\n self.update_target_model()\n\n def train_replay(self):\n\n num_samples = min(self.batch_size * self.timestep_per_train, len(self.memory))\n replay_samples = random.sample(self.memory, num_samples)\n\n update_input = np.zeros(((num_samples,) + self.state_size)) \n update_target = np.zeros(((num_samples,) + self.state_size))\n action, reward, done = [], [], []\n\n for i in range(num_samples):\n update_input[i,:,:,:] = replay_samples[i][0]\n action.append(replay_samples[i][1])\n reward.append(replay_samples[i][2])\n update_target[i,:,:,:] = replay_samples[i][3]\n done.append(replay_samples[i][4])\n\n target = self.model.predict(update_input) \n target_val = self.model.predict(update_target)\n target_val_ = self.target_model.predict(update_target)\n\n for i in range(num_samples):\n if done[i]:\n target[i][action[i]] = reward[i]\n else:\n a = np.argmax(target_val[i])\n target[i][action[i]] = reward[i] + self.gamma * (target_val_[i][a])\n\n loss = self.model.fit(update_input, target, batch_size=self.batch_size, epochs=1, verbose=0)\n\n return np.max(target[-1]), loss.history['loss']\n\n\nif __name__ == \"__main__\":\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n K.set_session(sess)\n\n game = DoomGame()\n game.load_config(r\"C:\\Users\\Rio\\Desktop\\Review\\Code\\vizenv\\Lib\\site-packages\\vizdoom\\scenarios\\defend_the_center.cfg\")\n game.set_sound_enabled(False)\n game.set_screen_resolution(ScreenResolution.RES_640X480)\n game.set_window_visible(True)\n game.init()\n\n game.new_episode()\n game_state = game.get_state()\n misc = game_state.game_variables\n prev_misc = misc\n \n action_size = game.get_available_buttons_size()\n\n img_rows , img_cols = 64, 64\n img_channels = 4 \n\n state_size = (img_rows, img_cols, img_channels)\n agent = DoubleDQNAgent(state_size, action_size)\n\n agent.model = dqn(state_size, action_size, agent.learning_rate)\n agent.target_model = dqn(state_size, action_size, agent.learning_rate)\n\n x_t = game_state.screen_buffer\n x_t = preprocessImg(x_t, size=(img_rows, img_cols))\n s_t = np.stack(([x_t]*4), axis=2)\n s_t = np.expand_dims(s_t, axis=0)\n\n is_terminated = game.is_episode_finished()\n\n\n epsilon = agent.initial_epsilon\n GAME = 0\n t = 0\n max_life = 0\n life = 0\n\n\n life_buffer, ammo_buffer, kills_buffer = [], [], [] \n \n while not game.is_episode_finished():\n \n loss = 0\n Q_max = 0\n r_t = 0\n a_t = np.zeros([action_size])\n\n action_idx = agent.get_action(s_t)\n a_t[action_idx] = 1\n\n a_t = a_t.astype(int)\n game.set_action(a_t.tolist())\n skiprate = agent.frame_per_action\n game.advance_action(skiprate)\n\n game_state = game.get_state()\n is_terminated = game.is_episode_finished()\n\n r_t = game.get_last_reward() \n\n if (is_terminated):\n if (life > max_life):\n max_life = life\n GAME += 1\n life_buffer.append(life)\n ammo_buffer.append(misc[1])\n kills_buffer.append(misc[0])\n print (\"Episode Finish. [KILLCOUNT, AMMO REMAINING, HEALTH REMAINING] - \"+str(misc))\n game.new_episode()\n game_state = game.get_state()\n misc = game_state.game_variables\n x_t1 = game_state.screen_buffer\n\n x_t1 = game_state.screen_buffer\n misc = game_state.game_variables\n\n x_t1 = preprocessImg(x_t1, size=(img_rows, img_cols))\n x_t1 = np.reshape(x_t1, (1, img_rows, img_cols, 1))\n s_t1 = np.append(x_t1, s_t[:, :, :, :3], axis=3)\n\n r_t = agent.shape_reward(r_t, misc, prev_misc, t)\n\n if (is_terminated):\n life = 0\n else:\n life += 1\n\n prev_misc = misc\n\n agent.replay_memory(s_t, action_idx, r_t, s_t1, is_terminated, t)\n\n if t > agent.observe and t % agent.timestep_per_train == 0:\n Q_max, loss = agent.train_replay()\n \n s_t = s_t1\n t += 1\n\n if t % 10000 == 0:\n print(\"Now we save model\")\n agent.model.save_weights(r\"C:\\Users\\Rio\\Desktop\\Review\\models\\ddqn.h5\", overwrite=True)\n\n state = \"\"\n if t <= agent.observe:\n state = \"Observe\"\n elif t > agent.observe and t <= agent.observe + agent.explore:\n state = \"Explore\"\n else:\n state = \"Train\"\n\n if (is_terminated):\n print(\"TIME\", t, \"/ GAME\", GAME, \"/ STATE\", state, \\\n \"/ ACTION\", action_idx, \"/ REWARD\", r_t, \\\n \"/ LOSS\", loss)\n\n\n if GAME % agent.stats_window_size == 0 and t > agent.observe: \n print(\"Update Rolling Statistics\")\n agent.mavg_score.append(np.mean(np.array(life_buffer)))\n agent.var_score.append(np.var(np.array(life_buffer)))\n agent.mavg_ammo_left.append(np.mean(np.array(ammo_buffer)))\n agent.mavg_kill_counts.append(np.mean(np.array(kills_buffer)))\n\n life_buffer, ammo_buffer, kills_buffer = [], [], [] \n\n with open(r\"C:\\Users\\Rio\\Desktop\\Review\\statistics\\ddqn_stats.txt\", \"w\") as stats_file:\n stats_file.write('Game: ' + str(GAME) + '\\n')\n stats_file.write('Max Score: ' + str(max_life) + '\\n')\n stats_file.write('mavg_score: ' + str(agent.mavg_score) + '\\n')\n stats_file.write('var_score: ' + str(agent.var_score) + '\\n')\n stats_file.write('mavg_ammo_left: ' + str(agent.mavg_ammo_left) + '\\n')\n stats_file.write('mavg_kill_counts: ' + str(agent.mavg_kill_counts) + '\\n')\n\n","sub_path":"Code/ddqn - Save.py","file_name":"ddqn - Save.py","file_ext":"py","file_size_in_byte":8940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"227988892","text":"import pandas\nimport pickle\nimport numpy as np\nimport sympy as sp\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom matplotlib.ticker import MultipleLocator\nimport matplotlib.gridspec as gridspec\nimport sys\nfrom tqdm import tqdm\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.preprocessing import MinMaxScaler\n\npairagraph = True\n\nif pairagraph:\n data_filename = \"pairAGraph_SM_2b_all_17_NN_100_bootstraps_IQR.root\"\n pg = \"PG_\"\nelse:\n data_filename = \"data17_NN_100_bootstraps_IQR.root\"\n pg = \"\"\n\nModelName = \"models/PG_model_4b_10505050_30e_25x25_poisson_20mhh\"\n\n\ndef plotSR(mh1_0, mh2_0, r, Xhh_cut, mh1_min, mh1_max, mh2_min, mh2_max, color):\n mh1, mh2 = sp.symbols('mh1 mh2')\n sg_expr = ((mh1-mh1_0)/(r*mh1))**2 + ((mh2-mh2_0)/(r*mh2))**2\n sg_eq = sp.Eq(sg_expr, Xhh_cut**2)\n plot = sp.plot_implicit(sg_eq, \n x_var = (mh1,mh1_min,mh1_max),\n y_var = (mh2,mh2_min,mh2_max),\n show = False,\n axis_center = (mh1_min,mh2_min))\n x,y = zip(*[(x_int.mid, y_int.mid) for x_int, y_int in plot[0].get_points()[0]])\n x,y = list(x),list(y)\n plt.plot(x,y,'.',markersize=0.5,color=color)\n# Have function to integrate mhh in each bin of the fullmassplane\ndef integrate_mhh(df):\n row_list = []\n for xi in tqdm(xbins):\n for yi in ybins:\n row_list.append({\"mh1\":xi,\"mh2\":yi,\"pdf\":sum(df.loc[ (df[\"mh1\"]==xi) & (df[\"mh2\"]==yi),\"pdf\"])})\n return pandas.DataFrame(row_list)\n# Integrates the fullmassplane to get slices of mhh\ndef integrate_fmp(df):\n row_list = []\n for mhh in mhhbins[:-1]:\n row_list.append({\"mhh\":mhh,\"pdf\":sum(df.loc[df[\"mhh\"]==mhh,\"pdf\"])})\n return pandas.DataFrame(row_list)\nmh10,mh20=120,110\ndef binInSR(x,y):\n xs = x + xbinSize\n ys = y + ybinSize\n return ((0.0256 > (x -mh10)**2/x**2 +(y-mh20)**2/y**2) |\n (0.0256 > (xs-mh10)**2/xs**2+(y-mh20)**2/y**2) |\n (0.0256 > (x-mh10)**2/x**2+(ys-mh20)**2/ys**2) |\n (0.0256 > (xs-mh10)**2/xs**2+(ys-mh20)**2/ys**2))\n\n# In VR if no corner of a bin is in the SR, and at least one corner is in the VR\ndef binInVR(x,y):\n xs = x + xbinSize\n ys = y + ybinSize\n return (~binInSR(x,y) &\n (((x-123.6)**2 +(y-113.3)**2<900) |\n ((xs-123.6)**2+(y-113.3)**2<900) |\n ((x-123.6)**2+(ys-113.3)**2<900) | \n ((xs-123.6)**2+(ys-113.3)**2<900))\n )\n \n\n# Shenanigans to set up bins as close as possible to the SR\nNxbinsInSig=25\nNybinsInSig=25\nmhhbins = np.linspace(200,1000,20)\nsxmin,sxmax=103.45,142.86\nsymin,symax=94.82,130.95\nxmin,xmax = 50,250 \nymin,ymax = 40,200\nxbinSize = (sxmax-sxmin)/NxbinsInSig\nybinSize = (symax-symin)/NybinsInSig\nxbins = np.arange(sxmin-int((sxmin-xmin)/xbinSize)*xbinSize,int(xmax/xbinSize)*xbinSize,xbinSize)\nybins = np.arange(symin-int((symin-ymin)/ybinSize)*ybinSize,int(ymax/ybinSize)*ybinSize,ybinSize)\n\ndf = pandas.read_pickle(f\"{pg}data_2tag_full.p\")\ncoord_array = np.array(df[[\"m_h1\",\"m_h2\",\"m_hh\"]])\nNORM = 1.0246291\nweights = NORM*np.array(df[\"NN_d24_weight_bstrap_med_17\"])\nhist3d,[xbins,ybins,mhhbins] = np.histogramdd(coord_array,[xbins,ybins,mhhbins],weights=weights)\nxv,yv,zv = np.meshgrid(xbins[:-1],ybins[:-1],mhhbins[:-1],indexing='ij')\ndata_df = pandas.DataFrame()\ndata_df[\"mh1\"] = xv.flatten()\ndata_df[\"mh2\"] = yv.flatten()\ndata_df[\"mhh\"] = zv.flatten()\ndata_df[\"pdf\"] = hist3d.flatten()\n\n# OK 2b reweighted is loaded\n# Now load model and make prediction df over GridBins\nmodel = keras.models.load_model(ModelName)\nGridBins = data_df[[\"mh1\",\"mh2\",\"mhh\"]]\nscaler = pickle.load(open(\"MinMaxScaler4b.p\",'rb'))\nif \"2b4b\" in ModelName:\n # we want to get predictions of 4b data\n data_df[\"ntag\"] = np.array([4]*len(data_df))\n GridBins = data_df[[\"mh1\",\"mh2\",\"mhh\", 'ntag']]\n scaler = pickle.load(open(\"MinMaxScaler2b4b.p\",'rb'))\n\n# even if 2b4b model, we're only simulating NTag=4 at this point\n\nmodeldf = GridBins\nmodeldf[\"pdf\"] = model.predict(scaler.transform(GridBins), verbose=1)\n\nmodeldfSR = modeldf.loc[binInSR(modeldf[\"mh1\"],modeldf[\"mh2\"])]\nmodelmhh = list(integrate_fmp(modeldfSR)[\"pdf\"])\ndata_dfSR = data_df.loc[binInSR(data_df[\"mh1\"],data_df[\"mh2\"])]\ndatamhh = list(integrate_fmp(data_dfSR)[\"pdf\"])\n\n# Plot predicted massplane\nmodeldffmp = integrate_mhh(modeldf)\nfig = plt.figure()\nax = fig.add_subplot(111)\nxmesh = np.array(modeldffmp[\"mh1\"]).reshape((len(xbins),len(ybins))).transpose()\nymesh = np.array(modeldffmp[\"mh2\"]).reshape((len(xbins),len(ybins))).transpose()\nhmesh = np.array(modeldffmp[\"pdf\"]).reshape((len(xbins),len(ybins))).transpose()\nhmesh_2brw = hmesh\nax.pcolormesh(xmesh,ymesh,hmesh,shading='auto')\nplotSR(120,110,0.1,1.6,sxmin,sxmax,symin,symax,'r')\nplt.xlabel(\"$m_{h1}$\")\nplt.ylabel(\"$m_{h2}$\")\nplt.savefig(ModelName+\"_fullmassplane_4bNN.png\")\n#plt.show()\nplt.close()\n\n# Plot 2b reweighted massplane\nmodeldffmp = integrate_mhh(data_df)\nfig = plt.figure()\nax = fig.add_subplot(111)\nxmesh = np.array(modeldffmp[\"mh1\"]).reshape((len(xbins),len(ybins))).transpose()\nymesh = np.array(modeldffmp[\"mh2\"]).reshape((len(xbins),len(ybins))).transpose()\nhmesh = np.array(modeldffmp[\"pdf\"]).reshape((len(xbins),len(ybins))).transpose()\nax.pcolormesh(xmesh,ymesh,hmesh,shading='auto')\nplotSR(120,110,0.1,1.6,sxmin,sxmax,symin,symax,'r')\nplt.xlabel(\"$m_{h1}$\")\nplt.ylabel(\"$m_{h2}$\")\nplt.savefig(ModelName+\"_fullmassplane_2brw.png\")\n#plt.show()\nplt.close()\n\n# Plot the ratio\nwith np.errstate(divide='ignore', invalid='ignore'):\n hmesh_ratio = hmesh/hmesh_2brw\nhmesh_ratio[np.isnan(hmesh_ratio)] = 0\nfig = plt.figure()\nax = fig.add_subplot(111)\nim=ax.pcolormesh(xmesh,ymesh,hmesh_ratio,vmin=0.8,vmax=1.4, cmap='bwr')\nfig.colorbar(im, ax=ax)\nplotSR(120,110,0.1,1.6,sxmin,sxmax,symin,symax,'r')\nplt.xlabel(\"$m_{h1}$\")\nplt.ylabel(\"$m_{h2}$\")\nplt.savefig(ModelName+\"_fullmassplane_NNOver2bRW.png\")\n#plt.show()\nplt.close()\n\n# Plot mhh\nfig,axs = plt.subplots(2,1)\ngs = gridspec.GridSpec(2, 1,height_ratios=[3,1])\ngs.update(hspace=0)\n\nax = plt.subplot(gs[0])\nax.step(mhhbins,modelmhh+[modelmhh[-1]],'r',linewidth=2,where='post')\nXData = mhhbins[:-1]+(mhhbins[1]-mhhbins[0])/2\nax.errorbar(XData,datamhh,yerr=np.sqrt(datamhh),fmt='k.')\nax.set_ylabel(\"Counts\")\nax.set_xticklabels([])\nax.set_xticks([])\nax.legend([\"4b SR NN Regression\",\"2b Reweighted\"])\n\nratio = [m/d if d>0 else 100 for m,d in zip(modelmhh,datamhh)]\nerr = [r/np.sqrt(d) if d>0 else 0 for r,d in zip(ratio,datamhh)]\nax = plt.subplot(gs[1])\nax.errorbar(XData,ratio,yerr=err,fmt='k.')\nax.plot([mhhbins[0],mhhbins[-1]],[1,1],'k--',linewidth=1)\nax.set_ylim(0.75,1.25)\n#ax.set_ylim(0.9,1.1)\nax.set_xlabel(\"$m_{hh}$\"+\" (GeV)\")\nax.set_ylabel(\"$\\\\frac{Regression}{Reweighting}$\")\nax.yaxis.set_major_locator(MultipleLocator(0.2))\nax.yaxis.set_minor_locator(MultipleLocator(0.05))\nax.xaxis.set_major_locator(MultipleLocator(100))\nax.xaxis.set_minor_locator(MultipleLocator(25))\nplt.savefig(ModelName+\"_mhhSR.png\")\nplt.close()\n#plt.show()\n","sub_path":"Plot2bRWvs4bNN.py","file_name":"Plot2bRWvs4bNN.py","file_ext":"py","file_size_in_byte":7162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"320964746","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom childeshub.hub import Hub\nfrom childeshub import config\n\nCORPUS_NAME = 'childes-20180319'\nBLOCK_ORDER = 'inc_context-entropy'\nANALYZE_POS = []\nHUB_MODE = 'sem'\n\nhub = Hub(mode=HUB_MODE, corpus_name=CORPUS_NAME, part_order=BLOCK_ORDER)\n\nfor pos in ANALYZE_POS or sorted(config.Terms.pos2tags.keys()):\n # data\n y = []\n part_id = 0\n for tokens in hub.split(hub.reordered_tokens,\n hub.num_items_in_part):\n try:\n num_in_doc = len([1 for token in tokens if token in getattr(hub, pos + 's')])\n except AttributeError:\n num_in_doc = len([1 for token in tokens if token in hub.probe_store.types])\n y.append(num_in_doc)\n print('Found {} num {}s in part {}'.format(num_in_doc, pos, part_id))\n part_id += 1\n # fig\n _, ax = plt.subplots(dpi=192)\n ax.set_ylabel('Num {}'.format(pos))\n ax.set_xlabel('Partition')\n plt.title(BLOCK_ORDER)\n # plot\n x = np.arange(hub.params.num_parts)\n ax.plot(x, y, '-', alpha=0.5)\n y_fitted = hub.fit_line(x, y)\n ax.plot(x, y_fitted, '-')\n y_rolled = hub.roll_mean(y, 20)\n ax.plot(x, y_rolled, '-')\n plt.show()","sub_path":"analysis/analyze_density.py","file_name":"analyze_density.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"624231284","text":"import json\nimport unittest\nfrom datetime import datetime\nfrom unittest import TestCase\nfrom unittest.mock import patch, mock_open\n\nimport responses\nfrom requests.exceptions import HTTPError\n\nfrom pygrocy import Grocy\nfrom pygrocy.data_models.chore import AssignmentType, Chore\nfrom pygrocy.data_models.product import Product, Group, ShoppingListProduct\nfrom pygrocy.grocy_api_client import GrocyApiClient, UserDto, ProductData\nfrom test.test_const import CONST_BASE_URL, CONST_PORT, CONST_SSL\n\n\nclass TestGrocy(TestCase):\n def setUp(self):\n self.grocy_regular = Grocy(CONST_BASE_URL, \"api_key\")\n self.grocy = Grocy(\n CONST_BASE_URL, \"demo_mode\", verify_ssl=CONST_SSL, port=CONST_PORT\n )\n self.base_url = f\"{CONST_BASE_URL}:{CONST_PORT}/api\"\n self.date_test = datetime.strptime(\"2019-05-04 11:31:04\", \"%Y-%m-%d %H:%M:%S\")\n self.add_generic_data = {\"name\": \"This is a task\"}\n\n def test_init(self):\n self.assertIsInstance(self.grocy, Grocy)\n\n @unittest.skip(\"no tasks_current table in current demo data\")\n def test_get_tasks_valid(self):\n tasks = self.grocy.tasks()\n\n assert len(tasks) == 6\n assert tasks[0].id == 1\n assert tasks[0].name == \"Repair the garage door\"\n\n @unittest.skip(\"no chores_current table in current demo data\")\n def test_get_chores_valid(self):\n chores = self.grocy.chores(get_details=True)\n\n self.assertIsInstance(chores, list)\n self.assertGreaterEqual(len(chores), 1)\n for chore in chores:\n self.assertIsInstance(chore, Chore)\n self.assertIsInstance(chore.id, int)\n self.assertIsInstance(chore.last_tracked_time, datetime)\n self.assertIsInstance(chore.next_estimated_execution_time, datetime)\n self.assertIsInstance(chore.name, str)\n self.assertIsInstance(chore.last_done_by, UserDto)\n\n @responses.activate\n def test_get_chore_details_valid(self):\n details_json = \"\"\"{\n \"chore\": {\n \"id\": \"1\",\n \"name\": \"Changed towels in the bathroom\",\n \"description\": null,\n \"period_type\": \"manually\",\n \"period_days\": \"5\",\n \"row_created_timestamp\": \"2020-03-16 00:50:14\",\n \"period_config\": null,\n \"track_date_only\": \"0\",\n \"rollover\": \"0\",\n \"assignment_type\": \"who-least-did-first\",\n \"assignment_config\": null,\n \"next_execution_assigned_to_user_id\": null,\n \"consume_product_on_execution\": \"0\",\n \"product_id\": null,\n \"product_amount\": null,\n \"period_interval\": \"1\"\n },\n \"tracked_count\": 3,\n \"next_estimated_execution_time\": \"2999-12-31 23:59:59\",\n \"next_execution_assigned_user\": null\n }\"\"\"\n details_json = json.loads(details_json)\n responses.add(\n responses.GET, f\"{self.base_url}/chores/1\", json=details_json, status=200\n )\n chore_details = self.grocy.chore(1)\n self.assertIsInstance(chore_details, Chore)\n self.assertEqual(\n chore_details.assignment_type, AssignmentType.WHO_LEAST_DID_FIRST\n )\n\n @unittest.skip(\"no stock_current table in current demo data\")\n def test_product_get_details_valid(self):\n stock = self.grocy.stock()\n\n product = stock[0]\n\n api_client = GrocyApiClient(\n CONST_BASE_URL, \"demo_mode\", port=CONST_PORT, verify_ssl=CONST_SSL\n )\n product.get_details(api_client)\n\n self.assertIsInstance(product.name, str)\n self.assertIsInstance(product.id, int)\n self.assertIsInstance(product.available_amount, float)\n self.assertIsInstance(product.best_before_date, datetime)\n if product.barcodes:\n self.assertIsInstance(product.barcodes, (list, str))\n self.assertIsInstance(product.product_group_id, int)\n\n @responses.activate\n def test_product_get_details_invalid_no_data(self):\n responses.add(responses.GET, f\"{self.base_url}/stock/products/0\", status=200)\n product = self.grocy.product(0)\n self.assertIsNone(product)\n\n @unittest.skip(\"no stock_current table in current demo data\")\n def test_get_stock_valid(self):\n stock = self.grocy.stock()\n\n self.assertIsInstance(stock, list)\n self.assertGreaterEqual(len(stock), 10)\n for prod in stock:\n self.assertIsInstance(prod, Product)\n\n @responses.activate\n def test_get_stock_invalid_missing_data(self):\n resp = []\n responses.add(responses.GET, f\"{self.base_url}/stock\", json=resp, status=200)\n self.assertEqual(len(self.grocy.stock()), 0)\n\n @unittest.skip(\"no userentities table in current demo data\")\n def test_get_shopping_list_valid(self):\n shopping_list = self.grocy.shopping_list(True)\n\n self.assertIsInstance(shopping_list, list)\n self.assertGreaterEqual(len(shopping_list), 1)\n for item in shopping_list:\n self.assertIsInstance(item, ShoppingListProduct)\n self.assertIsInstance(item.id, int)\n if item.product_id:\n self.assertIsInstance(item.product_id, int)\n self.assertIsInstance(item.product, ProductData)\n self.assertIsInstance(item.product.id, int)\n self.assertIsInstance(item.amount, float)\n if item.note:\n self.assertIsInstance(item.note, str)\n\n @responses.activate\n def test_get_shopping_list_invalid_no_data(self):\n responses.add(\n responses.GET, f\"{self.base_url}/objects/shopping_list\", status=400\n )\n self.assertRaises(HTTPError, self.grocy.shopping_list)\n\n @responses.activate\n def test_get_shopping_list_invalid_missing_data(self):\n resp = []\n responses.add(\n responses.GET,\n f\"{self.base_url}/objects/shopping_list\",\n json=resp,\n status=200,\n )\n self.assertEqual(len(self.grocy.shopping_list()), 0)\n\n @unittest.skip(\"no shopping list existing in current demo data\")\n def test_add_missing_product_to_shopping_list_valid(self):\n self.assertIsNone(self.grocy.add_missing_product_to_shopping_list())\n\n @responses.activate\n def test_add_missing_product_to_shopping_list_error(self):\n responses.add(\n responses.POST,\n f\"{self.base_url}/stock/shoppinglist/add-missing-products\",\n status=400,\n )\n self.assertRaises(HTTPError, self.grocy.add_missing_product_to_shopping_list)\n\n @unittest.skip(\"no shopping list existing in current demo data\")\n def test_add_product_to_shopping_list_valid(self):\n self.grocy.add_product_to_shopping_list(3)\n\n @unittest.skip(\"no shopping list existing in current demo data\")\n def test_add_product_to_shopping_list_error(self):\n self.assertRaises(HTTPError, self.grocy.add_product_to_shopping_list, 3000)\n\n @responses.activate\n def test_clear_shopping_list_valid(self):\n responses.add(\n responses.POST, f\"{self.base_url}/stock/shoppinglist/clear\", status=204\n )\n self.grocy.clear_shopping_list()\n\n @responses.activate\n def test_clear_shopping_list_error(self):\n responses.add(\n responses.POST, f\"{self.base_url}/stock/shoppinglist/clear\", status=400\n )\n self.assertRaises(HTTPError, self.grocy.clear_shopping_list)\n\n @responses.activate\n def test_remove_product_in_shopping_list_valid(self):\n responses.add(\n responses.POST,\n f\"{self.base_url}/stock/shoppinglist/remove-product\",\n status=204,\n )\n self.grocy.remove_product_in_shopping_list(1)\n\n @responses.activate\n def test_remove_product_in_shopping_list_error(self):\n responses.add(\n responses.POST,\n f\"{self.base_url}/stock/shoppinglist/remove-product\",\n status=400,\n )\n self.assertRaises(HTTPError, self.grocy.remove_product_in_shopping_list, 1)\n\n @unittest.skip(\"no userentities table in current demo data\")\n def test_get_product_groups_valid(self):\n product_groups_list = self.grocy.product_groups()\n\n self.assertIsInstance(product_groups_list, list)\n self.assertGreaterEqual(len(product_groups_list), 1)\n for group in product_groups_list:\n self.assertIsInstance(group, Group)\n self.assertIsInstance(group.id, int)\n self.assertIsInstance(group.name, str)\n if group.description:\n self.assertIsInstance(group.description, str)\n\n @responses.activate\n def test_get_product_groups_invalid_no_data(self):\n responses.add(\n responses.GET, f\"{self.base_url}/objects/product_groups\", status=400\n )\n self.assertRaises(HTTPError, self.grocy.product_groups)\n\n @responses.activate\n def test_get_product_groups_invalid_missing_data(self):\n resp = []\n responses.add(\n responses.GET,\n f\"{self.base_url}/objects/product_groups\",\n json=resp,\n status=200,\n )\n self.assertEqual(len(self.grocy.product_groups()), 0)\n\n @responses.activate\n def test_add_product_pic_valid(self):\n with patch(\"os.path.exists\") as m_exist:\n with patch(\"builtins.open\", mock_open()):\n m_exist.return_value = True\n responses.add(\n responses.PUT,\n f\"{self.base_url}/files/productpictures/MS5qcGc=\",\n status=204,\n )\n responses.add(\n responses.PUT, f\"{self.base_url}/objects/products/1\", status=204\n )\n resp = self.grocy.add_product_pic(1, \"/somepath/pic.jpg\")\n self.assertIsNone(resp)\n\n @responses.activate\n def test_add_product_pic_invalid_missing_data(self):\n with patch(\"os.path.exists\") as m_exist:\n m_exist.return_value = False\n self.assertRaises(\n FileNotFoundError, self.grocy.add_product_pic, 1, \"/somepath/pic.jpg\"\n )\n\n @responses.activate\n def test_upload_product_picture_error(self):\n with patch(\"os.path.exists\") as m_exist:\n with patch(\"builtins.open\", mock_open()):\n m_exist.return_value = True\n api_client = GrocyApiClient(\n CONST_BASE_URL, \"demo_mode\", port=CONST_PORT, verify_ssl=CONST_SSL\n )\n responses.add(\n responses.PUT,\n f\"{self.base_url}/files/productpictures/MS5qcGc=\",\n status=400,\n )\n self.assertRaises(\n HTTPError, api_client.upload_product_picture, 1, \"/somepath/pic.jpg\"\n )\n\n @responses.activate\n def test_update_product_pic_error(self):\n api_client = GrocyApiClient(\n CONST_BASE_URL, \"demo_mode\", port=CONST_PORT, verify_ssl=CONST_SSL\n )\n responses.add(responses.PUT, f\"{self.base_url}/objects/products/1\", status=400)\n self.assertRaises(HTTPError, api_client.update_product_pic, 1)\n\n @unittest.skip(\"no stock_current table in current demo data\")\n def test_get_expiring_products_valid(self):\n\n expiring_product = self.grocy.expiring_products(True)\n\n self.assertIsInstance(expiring_product, list)\n self.assertGreaterEqual(len(expiring_product), 1)\n for prod in expiring_product:\n self.assertIsInstance(prod, Product)\n\n @responses.activate\n def test_get_expiring_invalid_no_data(self):\n resp = {\"expiring_products\": [], \"expired_products\": [], \"missing_products\": []}\n responses.add(\n responses.GET, f\"{self.base_url}/stock/volatile\", json=resp, status=200\n )\n\n self.grocy.expiring_products(True)\n\n @responses.activate\n def test_get_expiring_invalid_missing_data(self):\n resp = {}\n responses.add(\n responses.GET, f\"{self.base_url}/stock/volatile\", json=resp, status=200\n )\n\n @unittest.skip(\"no stock_current table in current demo data\")\n def test_get_expired_products_valid(self):\n\n expired_product = self.grocy.expired_products(True)\n\n self.assertIsInstance(expired_product, list)\n self.assertGreaterEqual(len(expired_product), 1)\n for prod in expired_product:\n self.assertIsInstance(prod, Product)\n\n @responses.activate\n def test_get_expired_invalid_no_data(self):\n resp = {\"expiring_products\": [], \"expired_products\": [], \"missing_products\": []}\n responses.add(\n responses.GET, f\"{self.base_url}/stock/volatile\", json=resp, status=200\n )\n\n self.grocy.expired_products(True)\n\n @responses.activate\n def test_get_expired_invalid_missing_data(self):\n resp = {}\n responses.add(\n responses.GET, f\"{self.base_url}/stock/volatile\", json=resp, status=200\n )\n\n @unittest.skip(\"no stock_current table in current demo data\")\n def test_get_missing_products_valid(self):\n\n missing_product = self.grocy.missing_products(True)\n\n self.assertIsInstance(missing_product, list)\n self.assertGreaterEqual(len(missing_product), 1)\n for prod in missing_product:\n self.assertIsInstance(prod, Product)\n self.assertIsInstance(prod.amount_missing, float)\n self.assertIsInstance(prod.is_partly_in_stock, bool)\n\n @responses.activate\n def test_get_missing_invalid_no_data(self):\n resp = {\"expiring_products\": [], \"expired_products\": [], \"missing_products\": []}\n responses.add(\n responses.GET, f\"{self.base_url}/stock/volatile\", json=resp, status=200\n )\n\n self.grocy.missing_products(True)\n\n @responses.activate\n def test_get_missing_invalid_missing_data(self):\n resp = {}\n responses.add(\n responses.GET, f\"{self.base_url}/stock/volatile\", json=resp, status=200\n )\n\n @responses.activate\n def test_get_userfields_valid(self):\n resp = {\"uf1\": 0, \"uf2\": \"string\"}\n\n responses.add(\n responses.GET, f\"{self.base_url}/userfields/chores/1\", json=resp, status=200\n )\n\n a_chore_uf = self.grocy.get_userfields(\"chores\", 1)\n\n self.assertEqual(a_chore_uf[\"uf1\"], 0)\n\n @unittest.skip(\"no userentities table in current demo data\")\n def test_get_userfields_invalid_no_data(self):\n self.assertRaises(HTTPError, self.grocy.get_userfields(\"chores\", 1))\n\n @responses.activate\n def test_set_userfields_valid(self):\n responses.add(responses.PUT, f\"{self.base_url}/userfields/chores/1\", status=204)\n self.grocy.set_userfields(\"chores\", 1, \"auserfield\", \"value\")\n\n @responses.activate\n def test_set_userfields_error(self):\n responses.add(responses.PUT, f\"{self.base_url}/userfields/chores/1\", status=400)\n self.assertRaises(\n HTTPError, self.grocy.set_userfields, \"chores\", 1, \"auserfield\", \"value\"\n )\n\n def test_get_last_db_changed_valid(self):\n\n timestamp = self.grocy.get_last_db_changed()\n\n self.assertIsInstance(timestamp, datetime)\n\n @responses.activate\n def test_get_last_db_changed_invalid_no_data(self):\n resp = {}\n responses.add(\n responses.GET,\n f\"{self.base_url}/system/db-changed-time\",\n json=resp,\n status=200,\n )\n\n self.assertIsNone(self.grocy.get_last_db_changed())\n\n @responses.activate\n def test_add_product_valid(self):\n responses.add(\n responses.POST, f\"{self.base_url}/stock/products/1/add\", status=200\n )\n self.assertIsNone(self.grocy.add_product(1, 1.3, 2.44, self.date_test))\n\n @responses.activate\n def test_add_product_error(self):\n responses.add(\n responses.POST, f\"{self.base_url}/stock/products/1/add\", status=400\n )\n self.assertRaises(\n HTTPError, self.grocy.add_product, 1, 1.3, 2.44, self.date_test\n )\n\n @responses.activate\n def test_add_generic_valid(self):\n responses.add(responses.POST, f\"{self.base_url}/objects/tasks\", status=200)\n self.assertIsNone(self.grocy.add_generic(\"tasks\", self.add_generic_data))\n\n @responses.activate\n def test_add_generic_error(self):\n responses.add(responses.POST, f\"{self.base_url}/objects/tasks\", status=400)\n self.assertRaises(\n HTTPError, self.grocy.add_generic, \"tasks\", self.add_generic_data\n )\n\n @responses.activate\n def test_consume_product_valid(self):\n responses.add(\n responses.POST, f\"{self.base_url}/stock/products/1/consume\", status=200\n )\n self.assertIsNone(self.grocy.consume_product(1, 1.3))\n\n @responses.activate\n def test_consume_product_error(self):\n responses.add(\n responses.POST, f\"{self.base_url}/stock/products/1/consume\", status=400\n )\n self.assertRaises(HTTPError, self.grocy.consume_product, 1, 1.3)\n\n @responses.activate\n def test_execute_chore_valid(self):\n responses.add(responses.POST, f\"{self.base_url}/chores/1/execute\", status=200)\n self.assertIsNone(self.grocy.execute_chore(1, 1, self.date_test))\n\n @responses.activate\n def test_execute_chore_error(self):\n responses.add(responses.POST, f\"{self.base_url}/chores/1/execute\", status=400)\n self.assertRaises(HTTPError, self.grocy.execute_chore, 1, 1, self.date_test)\n\n @responses.activate\n def test_get_meal_plan(self):\n resp_json = json.loads(\n \"\"\"[\n {\n \"id\": \"1\",\n \"day\": \"2020-08-10\",\n \"type\": \"recipe\",\n \"recipe_id\": \"1\",\n \"recipe_servings\": \"1\",\n \"note\": null,\n \"product_id\": null,\n \"product_amount\": \"0.0\",\n \"product_qu_id\": null,\n \"row_created_timestamp\": \"2020-08-12 19:59:30\",\n \"userfields\": null\n }\n ]\"\"\"\n )\n responses.add(\n responses.GET,\n f\"{self.base_url}/objects/meal_plan\",\n json=resp_json,\n status=200,\n )\n meal_plan = self.grocy.meal_plan()\n self.assertEqual(len(meal_plan), 1)\n self.assertEqual(meal_plan[0].id, 1)\n self.assertEqual(meal_plan[0].recipe_id, 1)\n\n @responses.activate\n def test_get_recipe(self):\n resp_json = json.loads(\n \"\"\"{\n \"id\": \"1\",\n \"name\": \"Pizza\",\n \"description\": \"

Mix everything

\",\n \"row_created_timestamp\": \"2020-08-12 11:37:34\",\n \"picture_file_name\": \"51si0q0wsiq5imo4f8wbIMG_5709.jpeg\",\n \"base_servings\": \"4\",\n \"desired_servings\": \"4\",\n \"not_check_shoppinglist\": \"0\",\n \"type\": \"normal\",\n \"product_id\": \"\",\n \"userfields\": null\n }\"\"\"\n )\n responses.add(\n responses.GET,\n f\"{self.base_url}/objects/recipes/1\",\n json=resp_json,\n status=200,\n )\n recipe = self.grocy.recipe(1)\n self.assertEqual(recipe.id, 1)\n self.assertEqual(recipe.name, \"Pizza\")\n self.assertEqual(recipe.base_servings, 4)\n self.assertIsInstance(recipe.get_picture_url_path(400), str)\n","sub_path":"test/test_grocy.py","file_name":"test_grocy.py","file_ext":"py","file_size_in_byte":19569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"296897891","text":"from itertools import combinations\nfrom fractions import gcd\n\nclass SumOfMultiples:\n\n def __init__(self, *factors):\n factors = factors or (3, 5)\n self._factors = self._filter_redundant_factors(factors)\n\n def _filter_redundant_factors(self, factors):\n \"\"\"Deletes duplicate factors and factors that can be divided by a\n lower factor. These factors will always produce duplicate multiples\n that all must be subtracted from the total. So better not use them\n in the first place.\n \"\"\"\n return [\n factor for factor in set(factors)\n if not any(\n other_factor for other_factor in factors\n if other_factor < factor and not factor % other_factor\n )\n ]\n\n def to(self, to):\n \"\"\"Computes the sum of multiples for all configured factors up to the\n value of the 'to' parameter. Duplicate multiples are only counted\n once in the sum.\n \"\"\"\n return sum(\n plus_or_minus * sum_of_multiples\n for plus_or_minus, sum_of_multiples\n in self._steps(to)\n )\n\n def _steps(self, to):\n plus_or_minus = +1\n\n sum_of_multiples = self._sum_of_multiples(self._factors, to)\n yield (plus_or_minus, sum_of_multiples)\n\n for combi_length in range(2, len(self._factors) + 1):\n plus_or_minus = -plus_or_minus\n factors = self._lcm_for_factor_combinations(combi_length, to)\n sum_of_multiples = self._sum_of_multiples(factors, to)\n yield (plus_or_minus, sum_of_multiples)\n\n def _lcm_for_factor_combinations(self, combi_len, to):\n return [\n factor for factor in [\n self._lcm(*factors)\n for factors in combinations(self._factors, combi_len)\n ] if factor < to\n ] \n\n def _lcm(self, *factors):\n if len(factors) == 1:\n return factors[0]\n elif len(factors) == 2:\n return (factors[0] * factors[1]) // gcd(*factors)\n else:\n lcm = factors[0]\n for factor in factors[1::]:\n lcm = self._lcm(lcm, factor)\n return lcm\n\n def _sum_of_multiples(self, factors, to):\n total = 0\n for factor in factors:\n c = (to - 1) // factor\n total += factor * (c * c + c) // 2\n return total\n","sub_path":"all_data/exercism_data/python/sum-of-multiples/a2a0de26fbf94c48bf8d6d823f3493bf.py","file_name":"a2a0de26fbf94c48bf8d6d823f3493bf.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"492404145","text":"#!/usr/bin/env python\n# Copyright (c) 2013 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\" This file just imports slaves.cfg so that the information contained can be\neasily accessed. \"\"\"\n\nimport imp\nimport os\n\n\n_path_to_slaves_cfg = os.path.abspath(os.path.join(os.path.dirname(__file__),\n 'slaves.cfg'))\n_slaves_cfg_file = imp.load_source('slaves_cfg_file', _path_to_slaves_cfg)\n\nSLAVES = _slaves_cfg_file.slaves\n\nCQ_TRYBOTS = _slaves_cfg_file.cq_trybots\n","sub_path":"master/slaves_cfg.py","file_name":"slaves_cfg.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"36194492","text":"import os\nimport requests\nimport sys\n\ntitle = sys.argv[1] # Milestone title\nstate = sys.argv[2] # The milestone state (open, closed, or all)\n\nrepo = os.environ['GITHUB_REPOSITORY'] # As in, user/repo\ntoken = os.environ['GITHUB_TOKEN'] # Github API token\n\nprint( f\"Fetching number of milestone '{title}' of repo '{repo}'\", file = sys.stderr )\n\nurl = f'https://api.github.com/repos/{repo}/milestones'\nheaders = {\n 'Accept': 'application/vnd.github.v3+json',\n 'Authorization': f'token {token}'\n}\n\npage = 1\nnumber = None\nwhile number is None:\n\n params = {\n 'state': state,\n 'sort': 'due_on',\n 'direction': 'asc',\n 'per_page': 100,\n 'page': page\n }\n\n r = requests.get( url, headers = headers, params = params )\n if r.status_code != 200:\n raise Exception( f\"HTTP request failed: code {r.status_code}\" )\n r = r.json()\n\n if not r: # Empty page\n raise Exception( \"Milestone not found\" )\n page += 1\n\n for milestone in r:\n if milestone['title'] == title:\n number = milestone['number']\n print( f\"Milestone number: {number}\", file = sys.stderr )\n\nprint( number )","sub_path":".github/scripts/get_milestone_number.py","file_name":"get_milestone_number.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"641683612","text":"#! /usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nWaf tool used to track dependencies. Using git tags to track whether a\ncompatible newer version of a specific library is available. The git\ntags must be named after the Semantic Versioning scheme defined here:\nwww.semver.org\n\nThe wscript will look like this:\n\ndef options(opt):\n opt.load('wurf_dependency_bundle')\n\ndef configure(conf):\n conf.load('wurf_dependency_bundle')\n\n\"\"\"\n\nfrom waflib.Configure import conf\nfrom waflib import Utils\nfrom waflib import Errors\n\nimport os\n\nOPTIONS_NAME = 'dependency options'\n\"\"\" Name of the options group \"\"\"\n\nDEFAULT_BUNDLE = 'ALL'\n\"\"\" Name of the default bundle \"\"\"\n\nDEFAULT_BUNDLE_PATH = 'bundle_dependencies'\n\"\"\" Default folder to use for bundled dependencies \"\"\"\n\nDEPENDENCY_PATH_KEY = '%s_DEPENDENCY_PATH'\n\"\"\" Destination of the dependency paths in the options \"\"\"\n\nDEPENDENCY_CHECKOUT_KEY = '%s_DEPENDENCY_CHECKOUT'\n\"\"\" Destination of the dependency checkouts in the options \"\"\"\n\ndependencies = dict()\n\"\"\" Dictionary storing the dependency information \"\"\"\n\n\ndef add_dependency(opt, resolver):\n \"\"\"\n Adds a dependency.\n :param resolver: a resolver object which is responsible for downloading\n the dependency if necessary\n \"\"\"\n name = resolver.name\n\n if name in dependencies:\n\n if type(resolver) != type(dependencies[name]) or \\\n dependencies[name] != resolver:\n raise Errors.WafError('Incompatible dependency added %r <=> %r '\n % (resolver, dependencies[name]))\n else:\n dependencies[name] = resolver\n\n\ndef expand_path(path):\n \"\"\"\n Simple helper to expand paths\n :param path: a directory path to be expanded\n :return: the expanded path\n \"\"\"\n return os.path.abspath(os.path.expanduser(path))\n\n\ndef options(opt):\n \"\"\"\n Adds the options needed to control dependencies to the\n options context. Options are shown when ./waf -h is invoked\n :param opt: the Waf OptionsContext\n \"\"\"\n opt.load('wurf_dependency_resolve')\n\n bundle_opts = opt.add_option_group(OPTIONS_NAME)\n\n add = bundle_opts.add_option\n\n add('--bundle', default=DEFAULT_BUNDLE, dest='bundle',\n help=\"Which dependencies to bundle\")\n\n add('--bundle-path', default=DEFAULT_BUNDLE_PATH, dest='bundle_path',\n help=\"The folder used for downloaded dependencies\")\n\n for dependency in dependencies:\n add('--%s-path' % dependency,\n dest=DEPENDENCY_PATH_KEY % dependency,\n default=False,\n help='path to %s' % dependency)\n\n add('--%s-use-checkout' % dependency,\n dest=DEPENDENCY_CHECKOUT_KEY % dependency,\n default=False,\n help='The checkout to use for %s' % dependency)\n\n\ndef configure(conf):\n \"\"\"\n The configure function for the bundle dependency tool\n :param conf: the configuration context\n \"\"\"\n conf.load('wurf_dependency_resolve')\n\n # Get the path where the bundled dependencies should be\n # placed\n bundle_path = expand_path(conf.options.bundle_path)\n\n # List all the dependencies to be bundled\n bundle_list = expand_bundle(conf, conf.options.bundle)\n\n # List all the dependencies with an explicit path\n explicit_list = explicit_dependencies(conf.options)\n\n # Make sure that no dependencies were both explicitly specified\n # and specified as bundled\n overlap = set(bundle_list).intersection(set(explicit_list))\n\n if len(overlap) > 0:\n conf.fatal(\"Overlapping dependencies %r\" % overlap)\n\n conf.env['BUNDLE_DEPENDENCIES'] = dict()\n\n # Loop over all dependencies and fetch the ones\n # specified in the bundle_list\n for name in bundle_list:\n\n Utils.check_dir(bundle_path)\n\n conf.start_msg('Resolve dependency %s' % name)\n\n key = DEPENDENCY_CHECKOUT_KEY % name\n dependency_checkout = getattr(conf.options, key, None)\n\n dependency_path = dependencies[name].resolve(\n ctx=conf,\n path=bundle_path,\n use_checkout=dependency_checkout)\n\n conf.end_msg(dependency_path)\n\n conf.env['BUNDLE_DEPENDENCIES'][name] = dependency_path\n\n for name in explicit_list:\n key = DEPENDENCY_PATH_KEY % name\n dependency_path = getattr(conf.options, key)\n dependency_path = expand_path(dependency_path)\n\n conf.start_msg('User resolve dependency %s' % name)\n conf.env['BUNDLE_DEPENDENCIES'][name] = dependency_path\n conf.end_msg(dependency_path)\n\n\ndef expand_bundle(conf, arg):\n \"\"\"\n Expands the bundle arg so that e.g. 'ALL,-gtest' becomes the\n right set of dependencies\n :param arg: list of bundle dependencies arguments\n \"\"\"\n if not arg:\n return []\n\n arg = arg.split(',')\n\n if 'NONE' in arg and 'ALL' in arg:\n conf.fatal('Cannot specify both ALL and NONE as dependencies')\n\n candidate_score = dict([(name, 0) for name in dependencies])\n\n def check_candidate(c):\n if c not in candidate_score:\n conf.fatal('Cannot bundle %s, since it is not specified as a'\n ' dependency' % c)\n\n for a in arg:\n\n if a == 'ALL':\n for candidate in candidate_score:\n candidate_score[candidate] += 1\n continue\n\n if a == 'NONE':\n continue\n\n if a.startswith('-'):\n a = a[1:]\n check_candidate(a)\n candidate_score[a] -= 1\n\n else:\n check_candidate(a)\n candidate_score[a] += 1\n\n candidates = [n for n in candidate_score if candidate_score[n] > 0]\n return candidates\n\n\ndef explicit_dependencies(options):\n \"\"\"\n Extracts the names of the dependencies where an explicit\n path have been that have been specified\n :param options: the OptParser object where Waf stores the build options\n \"\"\"\n explicit_list = []\n\n for name in dependencies:\n\n key = DEPENDENCY_PATH_KEY % name\n path = getattr(options, key, None)\n\n if path:\n explicit_list.append(name)\n\n return explicit_list\n\n\n@conf\ndef has_dependency_path(self, name):\n \"\"\"\n Returns true if the dependency has been specified\n \"\"\"\n\n if name in self.env['BUNDLE_DEPENDENCIES']:\n return True\n\n return False\n\n\n@conf\ndef dependency_path(self, name):\n \"\"\"\n Returns the dependency path\n \"\"\"\n return self.env['BUNDLE_DEPENDENCIES'][name]\n\n\n@conf\ndef is_toplevel(self):\n \"\"\"\n Returns true if the current script is the top-level wscript\n \"\"\"\n return self.srcnode == self.path\n","sub_path":"tools/wurf_dependency_bundle.py","file_name":"wurf_dependency_bundle.py","file_ext":"py","file_size_in_byte":6571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"298429759","text":"import json\nimport pickle\nimport os\nimport random\nfrom multiprocessing import Pool\nfrom transformers import RobertaTokenizerFast\n\ndump_folder = \"4096-roberta\"\nif not os.path.exists(dump_folder):\n os.mkdir(dump_folder)\n\ndef process(args):\n dataset, percentage = args\n\n data_folder = os.path.join(dataset, \"data\")\n tokenizer = RobertaTokenizerFast.from_pretrained(\"roberta-base\")\n max_seq_len = 4096\n per_batch_inst = 1024\n block_size = max_seq_len - tokenizer.num_special_tokens_to_add(pair = False)\n\n random.seed(hash(dataset))\n\n files = sorted([os.path.join(data_folder, file) for file in os.listdir(data_folder) if file.endswith(\".pickle\")])\n data_buffer = []\n\n batch = []\n file_idx = 0\n\n for file in files:\n print(file)\n with open(file, \"rb\") as f:\n data = pickle.load(f)\n data_buffer.extend(data)\n for start_idx in range(0, len(data_buffer) - block_size + 1, block_size):\n block = data_buffer[start_idx:(start_idx + block_size)]\n assert len(block) == block_size\n if random.random() < percentage:\n block = tokenizer.build_inputs_with_special_tokens(block)\n assert len(block) == max_seq_len\n batch.append(block)\n if len(batch) >= per_batch_inst:\n dump_path = os.path.join(dump_folder, f\"{dataset}-{file_idx:05}.pickle\")\n with open(dump_path, \"wb\") as dump_f:\n pickle.dump(batch, dump_f)\n batch = []\n file_idx += 1\n print(dump_path)\n data_buffer = data_buffer[(start_idx + block_size):]\n\n dump_path = os.path.join(dump_folder, f\"{dataset}-{file_idx:05}.pickle\")\n with open(dump_path, \"wb\") as dump_f:\n pickle.dump(batch, dump_f)\n batch = []\n file_idx += 1\n print(dump_path)\n\n\ndatasets = [(\"bookcorpus\", 1.0), (\"english_wiki\", 1.0), (\"realnews\", 1 / 3), (\"stories\", 1 / 3)]\npool = Pool(len(datasets))\npool.map(process, datasets)\npool.close()\n\nimport json\nfiles = sorted([file for file in os.listdir(dump_folder) if file.endswith(\".pickle\")])\nprint(json.dumps(files, indent = 4))\nrandom.seed(1)\nrandom.shuffle(files)\nsplit = int(len(files) * 0.1)\n\nwith open(os.path.join(dump_folder, \"dev.json\"), \"w\") as f:\n json.dump(files[:split], f, indent = 4)\n\nwith open(os.path.join(dump_folder, \"train.json\"), \"w\") as f:\n json.dump(files[split:], f, indent = 4)\n","sub_path":"genome_transformer/Nystromformer/data-preprocessing/preprocess_data_4096.py","file_name":"preprocess_data_4096.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"71531132","text":"# 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\nfrom argparse import Namespace\nimport warnings\nimport urllib\nfrom pathlib import Path\nimport torch\nimport esm\n\n\ndef _has_regression_weights(model_name):\n \"\"\"Return whether we expect / require regression weights;\n Right now that is all models except ESM-1v\"\"\"\n return not (\"esm1v\" in model_name)\n\n\ndef load_model_and_alphabet(model_name):\n if model_name.endswith(\".pt\"): # treat as filepath\n return load_model_and_alphabet_local(model_name)\n else:\n return load_model_and_alphabet_hub(model_name)\n\n\ndef load_hub_workaround(url):\n try:\n data = torch.hub.load_state_dict_from_url(url, progress=False, map_location=\"cpu\")\n except RuntimeError:\n # Pytorch version issue - see https://github.com/pytorch/pytorch/issues/43106\n fn = Path(url).name\n data = torch.load(\n f\"{torch.hub.get_dir()}/checkpoints/{fn}\",\n map_location=\"cpu\",\n )\n except urllib.error.HTTPError as e:\n raise Exception(f\"Could not load {url}, check if you specified a correct model name?\")\n return data\n\n\ndef load_regression_hub(model_name):\n url = f\"https://dl.fbaipublicfiles.com/fair-esm/regression/{model_name}-contact-regression.pt\"\n regression_data = load_hub_workaround(url)\n return regression_data\n\n\ndef load_model_and_alphabet_hub(model_name):\n url = f\"https://dl.fbaipublicfiles.com/fair-esm/models/{model_name}.pt\"\n model_data = load_hub_workaround(url)\n if _has_regression_weights(model_name):\n regression_data = load_regression_hub(model_name)\n else:\n regression_data = None\n return load_model_and_alphabet_core(model_data, regression_data)\n\n\ndef load_model_and_alphabet_local(model_location):\n \"\"\" Load from local path. The regression weights need to be co-located \"\"\"\n model_location = Path(model_location)\n model_data = torch.load(str(model_location), map_location=\"cpu\")\n model_name = model_location.stem\n if _has_regression_weights(model_name):\n regression_location = str(model_location.with_suffix(\"\")) + \"-contact-regression.pt\"\n regression_data = torch.load(regression_location, map_location=\"cpu\")\n else:\n regression_data = None\n return load_model_and_alphabet_core(model_data, regression_data)\n\n\ndef has_emb_layer_norm_before(model_state):\n \"\"\" Determine whether layer norm needs to be applied before the encoder \"\"\"\n return any(k.startswith(\"emb_layer_norm_before\") for k, param in model_state.items())\n\n\ndef load_model_and_alphabet_core(model_data, regression_data=None):\n if regression_data is not None:\n model_data[\"model\"].update(regression_data[\"model\"])\n\n alphabet = esm.Alphabet.from_architecture(model_data[\"args\"].arch)\n\n if model_data[\"args\"].arch == \"roberta_large\":\n # upgrade state dict\n pra = lambda s: \"\".join(s.split(\"encoder_\")[1:] if \"encoder\" in s else s)\n prs1 = lambda s: \"\".join(s.split(\"encoder.\")[1:] if \"encoder\" in s else s)\n prs2 = lambda s: \"\".join(\n s.split(\"sentence_encoder.\")[1:] if \"sentence_encoder\" in s else s\n )\n model_args = {pra(arg[0]): arg[1] for arg in vars(model_data[\"args\"]).items()}\n model_state = {prs1(prs2(arg[0])): arg[1] for arg in model_data[\"model\"].items()}\n model_state[\"embed_tokens.weight\"][alphabet.mask_idx].zero_() # For token drop\n model_args[\"emb_layer_norm_before\"] = has_emb_layer_norm_before(model_state)\n model_type = esm.ProteinBertModel\n\n elif model_data[\"args\"].arch == \"protein_bert_base\":\n\n # upgrade state dict\n pra = lambda s: \"\".join(s.split(\"decoder_\")[1:] if \"decoder\" in s else s)\n prs = lambda s: \"\".join(s.split(\"decoder.\")[1:] if \"decoder\" in s else s)\n model_args = {pra(arg[0]): arg[1] for arg in vars(model_data[\"args\"]).items()}\n model_state = {prs(arg[0]): arg[1] for arg in model_data[\"model\"].items()}\n model_type = esm.ProteinBertModel\n elif model_data[\"args\"].arch == \"msa_transformer\":\n\n # upgrade state dict\n pra = lambda s: \"\".join(s.split(\"encoder_\")[1:] if \"encoder\" in s else s)\n prs1 = lambda s: \"\".join(s.split(\"encoder.\")[1:] if \"encoder\" in s else s)\n prs2 = lambda s: \"\".join(\n s.split(\"sentence_encoder.\")[1:] if \"sentence_encoder\" in s else s\n )\n prs3 = lambda s: s.replace(\"row\", \"column\") if \"row\" in s else s.replace(\"column\", \"row\")\n model_args = {pra(arg[0]): arg[1] for arg in vars(model_data[\"args\"]).items()}\n model_state = {prs1(prs2(prs3(arg[0]))): arg[1] for arg in model_data[\"model\"].items()}\n if model_args.get(\"embed_positions_msa\", False):\n emb_dim = model_state[\"msa_position_embedding\"].size(-1)\n model_args[\"embed_positions_msa_dim\"] = emb_dim # initial release, bug: emb_dim==1\n\n model_type = esm.MSATransformer\n\n else:\n raise ValueError(\"Unknown architecture selected\")\n\n model = model_type(\n Namespace(**model_args),\n alphabet,\n )\n\n expected_keys = set(model.state_dict().keys())\n found_keys = set(model_state.keys())\n\n if regression_data is None:\n expected_missing = {\"contact_head.regression.weight\", \"contact_head.regression.bias\"}\n error_msgs = []\n missing = (expected_keys - found_keys) - expected_missing\n if missing:\n error_msgs.append(f\"Missing key(s) in state_dict: {missing}.\")\n unexpected = found_keys - expected_keys\n if unexpected:\n error_msgs.append(f\"Unexpected key(s) in state_dict: {unexpected}.\")\n\n if error_msgs:\n raise RuntimeError(\n \"Error(s) in loading state_dict for {}:\\n\\t{}\".format(\n model.__class__.__name__, \"\\n\\t\".join(error_msgs)\n )\n )\n if expected_missing - found_keys:\n warnings.warn(\n \"Regression weights not found, predicting contacts will not produce correct results.\"\n )\n\n model.load_state_dict(model_state, strict=regression_data is not None)\n\n return model, alphabet\n\n\ndef esm1_t34_670M_UR50S():\n \"\"\"34 layer transformer model with 670M params, trained on Uniref50 Sparse.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1_t34_670M_UR50S\")\n\n\ndef esm1_t34_670M_UR50D():\n \"\"\"34 layer transformer model with 670M params, trained on Uniref50 Dense.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1_t34_670M_UR50D\")\n\n\ndef esm1_t34_670M_UR100():\n \"\"\"34 layer transformer model with 670M params, trained on Uniref100.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1_t34_670M_UR100\")\n\n\ndef esm1_t12_85M_UR50S():\n \"\"\"12 layer transformer model with 85M params, trained on Uniref50 Sparse.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1_t12_85M_UR50S\")\n\n\ndef esm1_t6_43M_UR50S():\n \"\"\"6 layer transformer model with 43M params, trained on Uniref50 Sparse.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1_t6_43M_UR50S\")\n\n\ndef esm1b_t33_650M_UR50S():\n \"\"\"33 layer transformer model with 650M params, trained on Uniref50 Sparse.\n This is our best performing model, which will be described in a future publication.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1b_t33_650M_UR50S\")\n\n\ndef esm_msa1_t12_100M_UR50S():\n warnings.warn(\n \"This model had a minor bug in the positional embeddings, \"\n \"please use ESM-MSA-1b: esm.pretrained.esm_msa1b_t12_100M_UR50S()\",\n )\n return load_model_and_alphabet_hub(\"esm_msa1_t12_100M_UR50S\")\n\n\ndef esm_msa1b_t12_100M_UR50S():\n return load_model_and_alphabet_hub(\"esm_msa1b_t12_100M_UR50S\")\n\n\ndef esm1v_t33_650M_UR90S():\n \"\"\"33 layer transformer model with 650M params, trained on Uniref90.\n This is model 1 of a 5 model ensemble.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1v_t33_650M_UR90S_1\")\n\n\ndef esm1v_t33_650M_UR90S_1():\n \"\"\"33 layer transformer model with 650M params, trained on Uniref90.\n This is model 1 of a 5 model ensemble.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1v_t33_650M_UR90S_1\")\n\n\ndef esm1v_t33_650M_UR90S_2():\n \"\"\"33 layer transformer model with 650M params, trained on Uniref90.\n This is model 2 of a 5 model ensemble.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1v_t33_650M_UR90S_2\")\n\n\ndef esm1v_t33_650M_UR90S_3():\n \"\"\"33 layer transformer model with 650M params, trained on Uniref90.\n This is model 3 of a 5 model ensemble.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1v_t33_650M_UR90S_3\")\n\n\ndef esm1v_t33_650M_UR90S_4():\n \"\"\"33 layer transformer model with 650M params, trained on Uniref90.\n This is model 4 of a 5 model ensemble.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1v_t33_650M_UR90S_4\")\n\n\ndef esm1v_t33_650M_UR90S_5():\n \"\"\"33 layer transformer model with 650M params, trained on Uniref90.\n This is model 5 of a 5 model ensemble.\n\n Returns a tuple of (Model, Alphabet).\n \"\"\"\n return load_model_and_alphabet_hub(\"esm1v_t33_650M_UR90S_5\")\n","sub_path":"esm/pretrained.py","file_name":"pretrained.py","file_ext":"py","file_size_in_byte":9623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"651230520","text":"# -*- coding: utf-8 -*-\nimport simple_draw as sd\n\n# Добавить цвет в функции рисования геом. фигур. из упр lesson_004/01_shapes.py\n# (код функций скопировать сюда и изменить)\n# Запросить у пользователя цвет фигуры посредством выбора из существующих:\n# вывести список всех цветов с номерами и ждать ввода номера желаемого цвета.\n# Потом нарисовать все фигуры этим цветом\n\n# Пригодятся функции\n# sd.get_point()\n# sd.line()\n# sd.get_vector()\n# и константы COLOR_RED, COLOR_ORANGE, COLOR_YELLOW, COLOR_GREEN, COLOR_CYAN, COLOR_BLUE, COLOR_PURPLE\n# Результат решения см lesson_004/results/exercise_02_global_color.jpg\n\ncolors = ({\"Красный\": sd.COLOR_RED, \"Оранжевый\": sd.COLOR_ORANGE, \"Желтый\": sd.COLOR_YELLOW,\n \"Зеленый\": sd.COLOR_GREEN, \"Голубой\": sd.COLOR_CYAN, \"Синий\": sd.COLOR_BLUE, \"Пурпурный\": sd.COLOR_PURPLE})\n\n\ndef polygon(start_point, angle, length, number_of_angles, color=sd.COLOR_YELLOW):\n for _ in range(number_of_angles):\n vector = sd.get_vector(start_point=start_point, angle=angle, length=length)\n end_point = vector.end_point\n sd.line(start_point=start_point, end_point=end_point, color=color)\n start_point = end_point\n angle = angle - 360/number_of_angles\n\n\n# Новая функция рисования треугольника\n\n\ndef triangle_new(start_point, angle, length, color):\n number_of_angles = 3\n polygon(start_point, angle, length, number_of_angles, color)\n\n\n# Новая функция рисования четырехугольника\n\n\ndef quadrangle_new(start_point, angle, length, color):\n number_of_angles = 4\n polygon(start_point, angle, length, number_of_angles, color)\n\n\n# Новая функция рисования пятиугольника\n\n\ndef pentagon_new(start_point, angle, length, color):\n number_of_angles = 5\n polygon(start_point, angle, length, number_of_angles, color)\n\n\n# Новая функция рисования шестиугольника\n\n\ndef hexagon_new(start_point, angle, length, color):\n number_of_angles = 6\n polygon(start_point, angle, length, number_of_angles, color)\n\n\nsd.resolution = (800, 400)\n\n\nprint(\"Возможные цвета: \")\nfor i, col in enumerate(colors, 1):\n print(str(i) + \" : \" + col)\nwhile True:\n input_color = input(\"Введите желаемый цвет: \")\n if input_color == \"1\":\n color = colors[\"Красный\"]\n break\n elif input_color == \"2\":\n color = colors[\"Оранжевый\"]\n break\n elif input_color == \"3\":\n color = colors[\"Желтый\"]\n break\n elif input_color == \"4\":\n color = colors[\"Зеленый\"]\n break\n elif input_color == \"5\":\n color = colors[\"Голубой\"]\n break\n elif input_color == \"6\":\n color = colors[\"Синий\"]\n break\n elif input_color == \"7\":\n color = colors[\"Пурпурный\"]\n break\n else:\n print(\"Вы ввели некорректный цвет\")\n continue\n\n\ntriangle_new(start_point=sd.get_point(250, 40), angle=155, length=100, color=color)\nquadrangle_new(start_point=sd.get_point(650, 40), angle=155, length=100, color=color)\npentagon_new(start_point=sd.get_point(250, 200), angle=155, length=100, color=color)\nhexagon_new(start_point=sd.get_point(650, 200), angle=155, length=100, color=color)\n\n\nsd.pause()\n","sub_path":"lesson_004/02_global_color.py","file_name":"02_global_color.py","file_ext":"py","file_size_in_byte":3703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"21071418","text":"from subprocess import Popen, PIPE, STDOUT\nfrom os import path\nfrom iqa.src.utils import utils\nimport tensorflow as tf\nimport tensorflow.keras as keras\nimport grpc\nfrom tensorflow_serving.apis import predict_pb2, prediction_service_pb2_grpc\nimport numpy as np\nimport json\n\n\nTFS_HOST = 'localhost'\nTFS_PORT = 8500\n\nnimaPath = path.abspath(\"../image-quality-assessment/\")\naestheticWeigth = \"weights_mobilenet_aesthetic_0.07\"\ntechnicalWeigth = \"weights_mobilenet_technical_0.11\"\ntf.get_logger().setLevel('ERROR')\n\n\ndef classify(aesthetic,path):\n if aesthetic:\n nimaExec = \"sudo %s/predict --docker-image nima-cpu --base-model-name MobileNet --weights-file %s/models/MobileNet/%s.hdf5 --image-source %s\" % (nimaPath,nimaPath,aestheticWeigth,path)\n else:\n nimaExec = \"sudo %s/predict --docker-image nima-cpu --base-model-name MobileNet --weights-file %s/models/MobileNet/%s.hdf5 --image-source %s\" % (nimaPath,nimaPath,technicalWeigth,path)\n p = Popen(nimaExec.split(), stdin=PIPE, stdout=PIPE, stderr=STDOUT)\n output = p.stdout.read()\n return output\n\ndef calc_mean_score(score_dist):\n score_dist = normalize_labels(score_dist)\n return (score_dist * np.arange(1, 11)).sum()\n \ndef normalize_labels(labels):\n labels_np = np.array(labels)\n return labels_np / labels_np.sum()\n\ndef loadAndPreprocessImage(images):\n # Load and preprocess image\n print(\"Load and Pre Process Nima Images\")\n i = 0\n j = len(images)\n for image in images:\n print(\"(\" + str(i+1) + \" / \" + str(j) + \")\", end=\"\\r\")\n img = utils.load_image(image[\"path\"], target_size=(224, 224))\n image[\"img\"] = keras.applications.mobilenet.preprocess_input(img)\n i = i + 1\n print(\"\\n\")\n return images\n\ndef getImageQuality(image, modelName):\n # Run through model\n target = f'{TFS_HOST}:{TFS_PORT}'\n channel = grpc.insecure_channel(target)\n stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)\n request = predict_pb2.PredictRequest()\n request.model_spec.name = modelName\n request.model_spec.signature_name = 'image_quality'\n\n request.inputs['input_image'].CopyFrom(\n tf.make_tensor_proto(np.expand_dims(image, 0))\n )\n\n response = stub.Predict(request, 10.0)\n result = round(calc_mean_score(response.outputs['quality_prediction'].float_val), 2)\n # print(json.dumps({'mean_score_prediction': np.round(result, 3)}, indent=2))\n return result","sub_path":"algoritmos/nima.py","file_name":"nima.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"9709374","text":"import os, json, sys\nfrom pathlib import Path\n\nfrom azureml.core.conda_dependencies import CondaDependencies \nfrom azureml.core.image import ContainerImage\nfrom azureml.core.model import Model\nfrom azureml.core import Workspace\n\n\nif __name__ == \"__main__\":\n parentdir = str(Path(os.path.abspath(__file__)).parents[1])\n sys.path.append(parentdir)\n\n from mgmt.Workspace import svc_pr\n\n ws = Workspace.from_config(path = \"./script-outputs\", auth = svc_pr)\n with open(\"./script-outputs/model.json\", 'r') as fp:\n config = json.load(fp)\n model_name = config['model_name']\n model_version = config['model_version']\n\n # Grab the model object from the list of available models\n model_list = Model.list(workspace=ws)\n model, = (m for m in model_list if m.version==model_version and m.name==model_name)\n print('Model picked: {} \\nModel Description: {} \\nModel Version: {}'.format(model.name, model.description, model.version))\n\n\n dependencies = CondaDependencies()\n dependencies.add_conda_package(\"numpy\")\n dependencies.add_conda_package(\"matplotlib\")\n dependencies.add_conda_package(\"scikit-learn\")\n dependencies.add_conda_package(\"tensorflow\")\n dependencies.add_conda_package(\"keras\")\n dependencies.add_conda_package(\"scikit-image\")\n dependencies.add_pip_package(\"pynacl==1.2.1\")\n\n with open(\"./score/dependencies.yml\",\"w\") as f:\n f.write(dependencies.serialize_to_string())\n\n original_dir = os.getcwd()\n # Change directory since the docker container is expecting thing at the TLD\n os.chdir(\"./score\")\n image_config = ContainerImage.image_configuration(\n execution_script = \"score.py\",\n runtime = \"python\",\n conda_file = \"dependencies.yml\",\n description = \"Image with keras model on small mnist data\",\n tags = {\"data\": \"mnist\", \"type\": \"classification\"}\n )\n\n\n # Image Name can only include alphanumeric or '.' and '-'\n image = ContainerImage.create(\n name = \"mnist-h5-img\",\n models = [model], # this is the registered model object\n image_config = image_config,\n workspace = ws)\n\n image.wait_for_creation(show_output = True)\n\n # Change back to original directory for writing outputs\n os.chdir(original_dir) \n\n with open(\"./script-outputs/image.json\", 'w') as fp:\n json.dump(\n obj = {\"image_name\":image.name, \"image_version\": image.version}, \n fp = fp\n )","sub_path":"train/CreateImage.py","file_name":"CreateImage.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"498134337","text":"# -*- coding:utf-8 -*-\n\"\"\"\n\nAuthor:\n Weichen Shen,weichenswc@163.com\n\n\"\"\"\nfrom __future__ import print_function\n\nimport time\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data as Data\nfrom sklearn.metrics import *\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom config import C\nfrom lambdaRank import approxNDCG_loss\nfrom losses import endd_loss\nfrom .discriminator import Discriminators\n\ntry:\n from tensorflow.python.keras.callbacks import CallbackList\nexcept ImportError:\n from tensorflow.python.keras._impl.keras.callbacks import CallbackList\n\nfrom ..inputs import build_input_features, SparseFeat, DenseFeat, VarLenSparseFeat, get_varlen_pooling_list, \\\n create_embedding_matrix\nfrom ..layers import PredictionLayer\nfrom ..layers.utils import slice_arrays\nfrom ..callbacks import History\n\n\nclass Linear(nn.Module):\n def __init__(self, feature_columns, feature_index, init_std=0.0001, device='cpu'):\n super(Linear, self).__init__()\n self.feature_index = feature_index\n self.device = device\n self.sparse_feature_columns = list(\n filter(lambda x: isinstance(x, SparseFeat), feature_columns)) if len(feature_columns) else []\n self.dense_feature_columns = list(\n filter(lambda x: isinstance(x, DenseFeat), feature_columns)) if len(feature_columns) else []\n\n self.varlen_sparse_feature_columns = list(\n filter(lambda x: isinstance(x, VarLenSparseFeat), feature_columns)) if len(feature_columns) else []\n\n self.embedding_dict = create_embedding_matrix(feature_columns, init_std, linear=True, sparse=False,\n device=device)\n\n # nn.ModuleDict(\n # {feat.embedding_name: nn.Embedding(feat.dimension, 1, sparse=True) for feat in\n # self.sparse_feature_columns}\n # )\n # .to(\"cuda:1\")\n for tensor in self.embedding_dict.values():\n nn.init.normal_(tensor.weight, mean=0, std=init_std)\n\n if len(self.dense_feature_columns) > 0:\n self.weight = nn.Parameter(torch.Tensor(sum(fc.dimension for fc in self.dense_feature_columns), 1).to(\n device))\n torch.nn.init.normal_(self.weight, mean=0, std=init_std)\n\n def forward(self, X):\n sparse_embedding_list = [self.embedding_dict[feat.embedding_name](\n X[:, self.feature_index[feat.name][0]:self.feature_index[feat.name][1]].long()) for\n feat in self.sparse_feature_columns]\n\n dense_value_list = [X[:, self.feature_index[feat.name][0]:self.feature_index[feat.name][1]] for feat in\n self.dense_feature_columns]\n\n varlen_embedding_list = get_varlen_pooling_list(self.embedding_dict, X, self.feature_index,\n self.varlen_sparse_feature_columns, self.device)\n\n sparse_embedding_list += varlen_embedding_list\n\n if len(sparse_embedding_list) > 0 and len(dense_value_list) > 0:\n linear_sparse_logit = torch.sum(\n torch.cat(sparse_embedding_list, dim=-1), dim=-1, keepdim=False)\n linear_dense_logit = torch.cat(\n dense_value_list, dim=-1).matmul(self.weight)\n linear_logit = linear_sparse_logit + linear_dense_logit\n elif len(sparse_embedding_list) > 0:\n linear_logit = torch.sum(\n torch.cat(sparse_embedding_list, dim=-1), dim=-1, keepdim=False)\n elif len(dense_value_list) > 0:\n linear_logit = torch.cat(\n dense_value_list, dim=-1).matmul(self.weight)\n else:\n linear_logit = torch.zeros([X.shape[0], 1])\n return linear_logit\n\n\n\n\n\nclass BaseModel(nn.Module):\n def __init__(self, linear_feature_columns, dnn_feature_columns, l2_reg_linear=1e-5, l2_reg_embedding=1e-5,\n init_std=0.0001, seed=1024, task='binary', device='cpu',group_num=10):\n\n super(BaseModel, self).__init__()\n torch.manual_seed(seed)\n self.dnn_feature_columns = dnn_feature_columns\n\n self.reg_loss = torch.zeros((1,), device=device)\n self.aux_loss = torch.zeros((1,), device=device)\n self.device = device # device\n\n self.feature_index = build_input_features(\n linear_feature_columns + dnn_feature_columns)\n self.dnn_feature_columns = dnn_feature_columns\n\n self.embedding_dict = create_embedding_matrix(dnn_feature_columns, init_std, sparse=False, device=device)\n # nn.ModuleDict(\n # {feat.embedding_name: nn.Embedding(feat.dimension, embedding_size, sparse=True) for feat in\n # self.dnn_feature_columns}\n # )\n\n self.linear_model = Linear(\n linear_feature_columns, self.feature_index, device=device)\n\n self.regularization_weight = []\n\n self.add_regularization_weight(self.embedding_dict.parameters(), l2=l2_reg_embedding)\n self.add_regularization_weight(self.linear_model.parameters(), l2=l2_reg_linear)\n\n self.out = PredictionLayer(task, )\n self.to(device)\n ################################################# used for ziqiLoss #########################\n self.teacher_weight = torch.nn.parameter.Parameter(torch.randn((group_num,1)))\n self.teacher_bias = torch.nn.parameter.Parameter(torch.randn((group_num,1)))\n ####################################################################################################\n # parameters of callbacks\n self._is_graph_network = True # used for ModelCheckpoint\n self.stop_training = False # used for EarlyStopping\n self.history = History()\n\n discriminators = Discriminators([128])\n\n\n def fit(self, x=None, y=None, batch_size=None, epochs=1, verbose=1, initial_epoch=0, validation_split=0.,\n validation_data=None, shuffle=True, callbacks=None ,model_list = [\"padding\"],flag_stage=None):\n \"\"\"\n\n :param x: Numpy array of training data (if the model has a single input), or list of Numpy arrays (if the model has multiple inputs).If input layers in the model are named, you can also pass a\n dictionary mapping input names to Numpy arrays.\n :param y: Numpy array of target (label) data (if the model has a single output), or list of Numpy arrays (if the model has multiple outputs).\n :param batch_size: Integer or `None`. Number of samples per gradient update. If unspecified, `batch_size` will default to 256.\n :param epochs: Integer. Number of epochs to train the model. An epoch is an iteration over the entire `x` and `y` data provided. Note that in conjunction with `initial_epoch`, `epochs` is to be understood as \"final epoch\". The model is not trained for a number of iterations given by `epochs`, but merely until the epoch of index `epochs` is reached.\n :param verbose: Integer. 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch.\n :param initial_epoch: Integer. Epoch at which to start training (useful for resuming a previous training run).\n :param validation_split: Float between 0 and 1. Fraction of the training data to be used as validation data. The model will set apart this fraction of the training data, will not train on it, and will evaluate the loss and any model metrics on this data at the end of each epoch. The validation data is selected from the last samples in the `x` and `y` data provided, before shuffling.\n :param validation_data: tuple `(x_val, y_val)` or tuple `(x_val, y_val, val_sample_weights)` on which to evaluate the loss and any model metrics at the end of each epoch. The model will not be trained on this data. `validation_data` will override `validation_split`.\n :param shuffle: Boolean. Whether to shuffle the order of the batches at the beginning of each epoch.\n :param callbacks: List of `deepctr_torch.callbacks.Callback` instances. List of callbacks to apply during training and validation (if ). See [callbacks](https://tensorflow.google.cn/api_docs/python/tf/keras/callbacks). Now available: `EarlyStopping` , `ModelCheckpoint`\n\n :return: A `History` object. Its `History.history` attribute is a record of training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable).\n \"\"\"\n if isinstance(x, dict):\n x = [x[feature] for feature in self.feature_index]\n\n do_validation = False\n if validation_data:\n do_validation = True\n if len(validation_data) == 2:\n val_x, val_y = validation_data\n val_sample_weight = None\n elif len(validation_data) == 3:\n val_x, val_y, val_sample_weight = validation_data # pylint: disable=unpacking-non-sequence\n else:\n raise ValueError(\n 'When passing a `validation_data` argument, '\n 'it must contain either 2 items (x_val, y_val), '\n 'or 3 items (x_val, y_val, val_sample_weights), '\n 'or alternatively it could be a dataset or a '\n 'dataset or a dataset iterator. '\n 'However we received `validation_data=%s`' % validation_data)\n if isinstance(val_x, dict):\n val_x = [val_x[feature] for feature in self.feature_index]\n\n elif validation_split and 0. < validation_split < 1.:\n do_validation = True\n if hasattr(x[0], 'shape'):\n split_at = int(x[0].shape[0] * (1. - validation_split))\n else:\n split_at = int(len(x[0]) * (1. - validation_split))\n x, val_x = (slice_arrays(x, 0, split_at),\n slice_arrays(x, split_at))\n y, val_y = (slice_arrays(y, 0, split_at),\n slice_arrays(y, split_at))\n\n else:\n val_x = []\n val_y = []\n for i in range(len(x)):\n if len(x[i].shape) == 1:\n x[i] = np.expand_dims(x[i], axis=1)\n\n train_tensor_data = Data.TensorDataset(\n torch.from_numpy(\n np.concatenate(x, axis=-1)),\n torch.from_numpy(y))\n if batch_size is None:\n batch_size = 256\n train_loader = DataLoader(\n dataset=train_tensor_data, shuffle=shuffle, batch_size=batch_size)\n\n print(self.device, end=\"\\n\")\n model = self.train()\n loss_func = self.loss_func\n optim = self.optim\n\n sample_num = len(train_tensor_data)\n steps_per_epoch = (sample_num - 1) // batch_size + 1\n\n # configure callbacks\n callbacks = (callbacks or []) + [self.history] # add history callback\n callbacks = CallbackList(callbacks)\n callbacks.on_train_begin()\n callbacks.set_model(self)\n if not hasattr(callbacks, 'model'):\n callbacks.__setattr__('model', self)\n callbacks.model.stop_training = False\n\n # Train\n print(\"Train on {0} samples, validate on {1} samples, {2} steps per epoch\".format(\n len(train_tensor_data), len(val_y), steps_per_epoch))\n for epoch in range(initial_epoch, epochs):\n callbacks.on_epoch_begin(epoch)\n epoch_logs = {}\n start_time = time.time()\n loss_epoch = 0\n total_loss_epoch = 0\n total_att_variance = 0\n total_bd_loss = 0\n total_fd_loss = 0\n zi_loss = 0\n qi_loss = 0\n train_result = {}\n try:\n with tqdm(enumerate(train_loader), disable=verbose != 1) as t:\n for index, (x_train, y_train) in t:\n \n x = x_train.to(self.device).float()\n y = y_train.to(self.device).float()\n\n if((y==True).sum()==batch_size or (y==True).sum()==0):\n sample_num-=batch_size\n continue\n################################################################################################\n group_model_att_score = []\n group_pred = []\n y_group_pred = []\n dnn_group_output = []\n att_score_varience = 0.\n for i in range(1,len(model_list)): #其它阶段会跳过\n with torch.no_grad():\n import pdb\n pred_i,att_score,_,dnn_output= model_list[i](x, only_score = C.weight_only)##.squeeze()\n\n att_score = att_score.squeeze() \n att_score = att_score.detach() \n group_model_att_score.append(att_score) # att_score: [B, 1, T]\n y_group_pred.append(pred_i)\n dnn_group_output.append(dnn_output)\n import pdb\n if not C.weight_only:\n group_pred.append(pred_i.squeeze().detach())\n import pdb\n y_pred,y_att_score, fd_pred, dnn_output, causalD_loss = model(x, front_dic={\"frontdoor\": C.frontdoor, \"group_attn\": group_model_att_score})\n y_pred = y_pred.squeeze()\n y_att_score = y_att_score.squeeze()\n\n stableReg_loss = torch.zeros([]).to(x.device)\n backdoor_loss = torch.zeros([]).to(x.device)\n frontdoor_loss = torch.zeros([]).to(x.device)\n if len(model_list) > 1 and False:\n if C.weight_reg:\n if C.regloss_type == C.REGLOSS_TYPE.approx_nDCG:\n for i in range(0,len(model_list)-1):\n vote = group_model_att_score[i]+1e-9\n target_batch_stds, batch_sorted_inds = torch.sort(vote, dim=1, descending=True)\n target_batch_preds = torch.gather(y_att_score+1e-9, dim=1, index=batch_sorted_inds)\n stableReg_loss += approxNDCG_loss(target_batch_preds, target_batch_stds, label_type=C.LABEL_TYPE.MultiLabel, gpu=True, reduction='sum')\n elif C.regloss_type == C.REGLOSS_TYPE.per_kl_iv:\n for i in range(0,len(model_list)-1):\n att_score_varience += F.kl_div((y_att_score+1e-9).log(),group_model_att_score[i]+1e-9,reduction='sum')\n stableReg_loss = att_score_varience\n elif C.regloss_type == C.REGLOSS_TYPE.endd:\n import pdb\n stacked_predict = torch.stack(group_model_att_score, 1)\n constant = 0.\n ensemble_logits = torch.log(stacked_predict + 1e-9) + constant\n logits = torch.log(y_att_score + 1e-9) + constant\n stableReg_loss = endd_loss(ensemble_logits, logits)\n\n if C.backdoor:\n if C.bd_type == C.BD_TYPE.mean:\n import pdb\n bd_ii_mean = torch.mean(torch.stack(group_pred), axis=0)\n bd_si_loss = torch.nn.MSELoss(reduction='sum')(bd_ii_mean, y_pred)\n bd_ii_mean = torch.mean(torch.stack(group_model_att_score), axis=0)\n bd_ii_loss = torch.nn.MSELoss(reduction='sum')(bd_ii_mean, y_att_score)\n backdoor_loss += bd_si_loss * C.bd_lambda\n backdoor_loss += bd_ii_loss * C.bd_lambda\n elif C.bd_type == C.BD_TYPE.attn_kl:\n for i in range(0,len(model_list)-1):\n att_score_varience += F.kl_div((y_att_score+1e-9).log(),group_model_att_score[i]+1e-9,reduction='sum')\n backdoor_loss = att_score_varience * C.bd_lambda\n else:\n assert 0 == 1, \"Unsupported BD TYPE\"\n\n if C.frontdoor:\n if C.fd_type == C.FD_TYPE.ISCS:\n fd_loss = loss_func(fd_pred.squeeze(), y.squeeze(), reduction='sum') \n import pdb\n fd_distill_loss = F.mse_loss(fd_pred.squeeze().detach(), y_pred.squeeze(), reduction='sum')\n frontdoor_loss = frontdoor_loss + fd_loss + fd_distill_loss\n frontdoor_loss = frontdoor_loss * C.fd_lambda\n \n pass\n else:\n assert 0 == 1, \"Unsupported FD TYPE\"\n\n import pdb\n stableReg_loss = stableReg_loss * C.reg_lambda\n\n optim.zero_grad()\n #####################################\n # ------These code is used to debug--\n #loss = torch.tensor(0.)\n\n ####################################\n ############################# ziqi Loss ###########################\n # def get_alpha(group_pred,weight=None,bias=None):\n # \"\"\"\n # group pred: [ B X Group_num]\n # Weight : [Group_num X 1]\n # bias : [Group_num X 1]\n # \"\"\"\n # import pdb\n # # pdb.set_trace()\n # tmp = torch.stack(group_pred,axis=1)\n # alpha = tmp*weight + bias\n # alpha = alpha.squeeze()\n # alpha = torch.exp(alpha) / torch.sum(torch.exp(alpha), axis=1, keepdims=True)\n # return alpha\n # if flag_stage==3:\n # alpha = get_alpha(y_group_pred,self.teacher_weight,self.teacher_bias) # [ B X 10 ]\n # import pdb\n # # pdb.set_trace()\n # y_group_pred = torch.stack(y_group_pred, axis=1).squeeze()\n # Zt = torch.sum(alpha * y_group_pred,axis=1,keepdims=True).squeeze()\n # Zs = y_pred.squeeze()\n # Zt = torch.sigmoid(Zt)\n # Zs = torch.sigmoid(Zs)\n # # pdb.set_trace()\n # bceloss = torch.nn.BCELoss()\n\n # zi_loss = bceloss(Zs,Zt.data)\n # VS = dnn_output\n\n # VT = torch.stack(dnn_group_output,axis=1).squeeze()\n # # pdb.set_trace()\n # VT = torch.sum(VT*alpha.unsqueeze(axis=2),axis=1).squeeze()\n # qi_loss = torch.sum(torch.square(VT - VS))\n\n\n\n import pdb\n ###################################################################\n loss = loss_func(y_pred, y.squeeze(), reduction='sum') \n\n import pdb\n loss += causalD_loss\n # loss += stableReg_loss\n # loss += backdoor_loss\n # loss += frontdoor_loss\n # loss += zi_loss\n # loss += qi_loss\n reg_loss = self.get_regularization_loss()\n \n\n total_loss = loss # + reg_loss + self.aux_loss\n \n loss_epoch += loss.item()\n total_att_variance += stableReg_loss.item()\n total_bd_loss += backdoor_loss.item()\n total_fd_loss += frontdoor_loss.item()\n total_loss_epoch += total_loss.item()\n total_loss.backward()\n optim.step()\n\n import pdb\n\n # '''\n # if verbose > 0:\n # for name, metric_fun in self.metrics.items():\n # if name not in train_result:\n # train_result[name] = []\n # train_result[name].append(metric_fun(\n # y.cpu().data.numpy(), y_pred.cpu().data.numpy().astype(\"float64\")))\n # '''\n\n\n except KeyboardInterrupt:\n t.close() \n raise\n t.close()\n\n # Add epoch_logs\n import pdb\n epoch_logs[\"loss\"] = total_loss_epoch / sample_num\n###############################################################################################\n epoch_logs['att_variance'] = total_att_variance / sample_num\n epoch_logs['bd_loss'] = total_bd_loss / sample_num\n epoch_logs['fd_loss'] = total_fd_loss / sample_num\n for name, result in train_result.items():\n epoch_logs[name] = np.sum(result) / steps_per_epoch\n\n if do_validation:\n eval_result = self.evaluate(val_x, val_y, batch_size)\n for name, result in eval_result.items():\n epoch_logs[\"val_\" + name] = result\n # verbose\n if verbose > 0:\n epoch_time = int(time.time() - start_time)\n print('Epoch {0}/{1}'.format(epoch + 1, epochs))\n\n eval_str = \"{0}s - loss: {1: .4f}-sg: {2: .4f}-bd: {3: .4f}-fd: {4: .4f}\".format(\n epoch_time, epoch_logs[\"loss\"],epoch_logs[\"att_variance\"], epoch_logs['bd_loss'], epoch_logs['fd_loss'])\n\n \n # for name in self.metrics:\n # eval_str += \" - \" + name + \\\n # \": {0: .4f}\".format(epoch_logs[name])\n\n # if do_validation:\n # for name in self.metrics:\n # eval_str += \" - \" + \"val_\" + name + \\\n # \": {0: .4f}\".format(epoch_logs[\"val_\" + name])\n # '''\n print(eval_str)\n callbacks.on_epoch_end(epoch, epoch_logs)\n if self.stop_training:\n break\n\n callbacks.on_train_end()\n\n return self.history\n\n def evaluate(self, x, y, batch_size=256):\n \"\"\"\n\n :param x: Numpy array of test data (if the model has a single input), or list of Numpy arrays (if the model has multiple inputs).\n :param y: Numpy array of target (label) data (if the model has a single output), or list of Numpy arrays (if the model has multiple outputs).\n :param batch_size: Integer or `None`. Number of samples per evaluation step. If unspecified, `batch_size` will default to 256.\n :return: Dict contains metric names and metric values.\n \"\"\"\n pred_ans = self.predict(x, batch_size)\n eval_result = {}\n for name, metric_fun in self.metrics.items():\n eval_result[name] = metric_fun(y, pred_ans)\n return eval_result\n\n def predict(self, x, batch_size=256):\n \"\"\"\n\n :param x: The input data, as a Numpy array (or list of Numpy arrays if the model has multiple inputs).\n :param batch_size: Integer. If unspecified, it will default to 256.\n :return: Numpy array(s) of predictions.\n \"\"\"\n model = self.eval()\n import pdb\n if isinstance(x, dict):\n x = [x[feature] for feature in self.feature_index]\n import pdb\n for i in range(len(x)):\n if len(x[i].shape) == 1:\n x[i] = np.expand_dims(x[i], axis=1)\n\n import pdb\n \n tensor_data = Data.TensorDataset(\n torch.from_numpy(np.concatenate(x, axis=-1)))\n test_loader = DataLoader(\n dataset=tensor_data, shuffle=False, batch_size=batch_size)\n\n pred_ans = []\n with torch.no_grad():\n for index, x_test in enumerate(test_loader):\n x = x_test[0].to(self.device).float()\n y_pred,_,_,_,_ = model(x)\n y_pred = y_pred.cpu().data.numpy() # .squeeze()\n pred_ans.append(y_pred)\n\n return np.concatenate(pred_ans).astype(\"float64\")\n\n def input_from_feature_columns(self, X, feature_columns, embedding_dict, support_dense=True):\n\n sparse_feature_columns = list(\n filter(lambda x: isinstance(x, SparseFeat), feature_columns)) if len(feature_columns) else []\n dense_feature_columns = list(\n filter(lambda x: isinstance(x, DenseFeat), feature_columns)) if len(feature_columns) else []\n\n varlen_sparse_feature_columns = list(\n filter(lambda x: isinstance(x, VarLenSparseFeat), feature_columns)) if feature_columns else []\n\n if not support_dense and len(dense_feature_columns) > 0:\n raise ValueError(\n \"DenseFeat is not supported in dnn_feature_columns\")\n\n sparse_embedding_list = [embedding_dict[feat.embedding_name](\n X[:, self.feature_index[feat.name][0]:self.feature_index[feat.name][1]].long()) for\n feat in sparse_feature_columns]\n varlen_sparse_embedding_list = get_varlen_pooling_list(self.embedding_dict, X, self.feature_index,\n varlen_sparse_feature_columns, self.device)\n\n dense_value_list = [X[:, self.feature_index[feat.name][0]:self.feature_index[feat.name][1]] for feat in\n dense_feature_columns]\n\n return sparse_embedding_list + varlen_sparse_embedding_list, dense_value_list\n\n def compute_input_dim(self, feature_columns, include_sparse=True, include_dense=True, feature_group=False):\n sparse_feature_columns = list(\n filter(lambda x: isinstance(x, (SparseFeat, VarLenSparseFeat)), feature_columns)) if len(\n feature_columns) else []\n dense_feature_columns = list(\n filter(lambda x: isinstance(x, DenseFeat), feature_columns)) if len(feature_columns) else []\n\n dense_input_dim = sum(\n map(lambda x: x.dimension, dense_feature_columns))\n if feature_group:\n sparse_input_dim = len(sparse_feature_columns)\n else:\n sparse_input_dim = sum(feat.embedding_dim for feat in sparse_feature_columns)\n input_dim = 0\n if include_sparse:\n input_dim += sparse_input_dim\n if include_dense:\n input_dim += dense_input_dim\n return input_dim\n\n def add_regularization_weight(self, weight_list, l1=0.0, l2=0.0):\n # For a Parameter, put it in a list to keep Compatible with get_regularization_loss()\n if isinstance(weight_list, torch.nn.parameter.Parameter):\n weight_list = [weight_list]\n # For generators, filters and ParameterLists, convert them to a list of tensors to avoid bugs.\n # e.g., we can't pickle generator objects when we save the model.\n else:\n weight_list = list(weight_list)\n self.regularization_weight.append((weight_list, l1, l2))\n\n def get_regularization_loss(self, ):\n total_reg_loss = torch.zeros((1,), device=self.device)\n for weight_list, l1, l2 in self.regularization_weight:\n for w in weight_list:\n if isinstance(w, tuple):\n parameter = w[1] # named_parameters\n else:\n parameter = w\n if l1 > 0:\n total_reg_loss += torch.sum(l1 * torch.abs(parameter))\n if l2 > 0:\n try:\n total_reg_loss += torch.sum(l2 * torch.square(parameter))\n except AttributeError:\n total_reg_loss += torch.sum(l2 * parameter * parameter)\n\n return total_reg_loss\n\n def add_auxiliary_loss(self, aux_loss, alpha):\n self.aux_loss = aux_loss * alpha\n\n def compile(self, optimizer,\n loss=None,\n metrics=None,\n ):\n \"\"\"\n :param optimizer: String (name of optimizer) or optimizer instance. See [optimizers](https://pytorch.org/docs/stable/optim.html).\n :param loss: String (name of objective function) or objective function. See [losses](https://pytorch.org/docs/stable/nn.functional.html#loss-functions).\n :param metrics: List of metrics to be evaluated by the model during training and testing. Typically you will use `metrics=['accuracy']`.\n \"\"\"\n self.metrics_names = [\"loss\"]\n self.optim = self._get_optim(optimizer)\n self.loss_func = self._get_loss_func(loss)\n self.metrics = self._get_metrics(metrics)\n\n def _get_optim(self, optimizer):\n if isinstance(optimizer, str):\n if optimizer == \"sgd\":\n optim = torch.optim.SGD(self.parameters(), lr=0.01)\n elif optimizer == \"adam\":\n optim = torch.optim.Adam(self.parameters()) # 0.001\n elif optimizer == \"adagrad\":\n optim = torch.optim.Adagrad(self.parameters()) # 0.01\n elif optimizer == \"rmsprop\":\n optim = torch.optim.RMSprop(self.parameters())\n else:\n raise NotImplementedError\n else:\n optim = optimizer\n return optim\n\n def _get_loss_func(self, loss):\n if isinstance(loss, str):\n if loss == \"binary_crossentropy\":\n loss_func = F.binary_cross_entropy\n elif loss == \"mse\":\n loss_func = F.mse_loss\n elif loss == \"mae\":\n loss_func = F.l1_loss\n else:\n raise NotImplementedError\n else:\n loss_func = loss\n return loss_func\n\n def _log_loss(self, y_true, y_pred, eps=1e-7, normalize=True, sample_weight=None, labels=None):\n # change eps to improve calculation accuracy\n return log_loss(y_true,\n y_pred,\n eps,\n normalize,\n sample_weight,\n labels)\n\n def _get_metrics(self, metrics, set_eps=False):\n metrics_ = {}\n if metrics:\n for metric in metrics:\n if metric == \"binary_crossentropy\" or metric == \"logloss\":\n if set_eps:\n metrics_[metric] = self._log_loss\n else:\n metrics_[metric] = log_loss\n if metric == \"auc\":\n metrics_[metric] = roc_auc_score\n if metric == \"mse\":\n metrics_[metric] = mean_squared_error\n if metric == \"accuracy\" or metric == \"acc\":\n metrics_[metric] = lambda y_true, y_pred: accuracy_score(\n y_true, np.where(y_pred > 0.5, 1, 0))\n self.metrics_names.append(metric)\n return metrics_\n\n @property\n def embedding_size(self, ):\n feature_columns = self.dnn_feature_columns\n sparse_feature_columns = list(\n filter(lambda x: isinstance(x, (SparseFeat, VarLenSparseFeat)), feature_columns)) if len(\n feature_columns) else []\n embedding_size_set = set([feat.embedding_dim for feat in sparse_feature_columns])\n if len(embedding_size_set) > 1:\n raise ValueError(\"embedding_dim of SparseFeat and VarlenSparseFeat must be same in this model!\")\n return list(embedding_size_set)[0]\n","sub_path":"deepctr_torch/models/basemodel.py","file_name":"basemodel.py","file_ext":"py","file_size_in_byte":32552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"443308400","text":"from flask import Flask, request\nfrom pymongo import MongoClient\nfrom bson.json_util import dumps, object_hook\nfrom flask_cors import CORS\nimport datetime\nimport requests\nimport json\n\n\napp = Flask(__name__)\nCORS(app)\n\nclient = MongoClient()\ndb = client['metadata']\n\n\n# def toJson(data):\n# return json.dumps(data, default=json_util.default)\n\n\n@app.route('/actions/', methods=['GET'])\ndef _actions(action):\n\n doc = db.actions.find_one({'action': action})\n\n if doc:\n new_count = doc['count'] + 1\n db.actions.update_one({'action': action}, {\n '$set': {\n 'count': new_count\n },\n '$push': {\n 'history': datetime.datetime.utcnow()\n }\n })\n\n return dumps(db.actions.find({'action': action}))\n else:\n doc = {'action': action, 'count': 1, 'history': [datetime.datetime.utcnow()]}\n db.actions.insert_one(doc)\n updated_doc = db.actions.find({'action': action})\n\n return dumps(updated_doc)\n\n@app.route('/requests', methods=['GET'])\ndef _requests():\n\n cursor = db.requests.find()\n docs = [doc for doc in cursor]\n\n return dumps(docs)\n\n@app.route('/users', methods=['GET'])\ndef _users():\n\n cursor = db.users.find()\n docs = [doc for doc in cursor]\n\n return dumps(docs)\n\n\n@app.route('/listing/', methods=['GET', 'POST'])\ndef _listing(etsy_listing_id):\n\n if request.method == 'GET':\n doc = db.listings.find({'etsy_listing_id': etsy_listing_id})\n\n return dumps(doc)\n\n if request.method == 'POST':\n listing_data = request.get_json()\n db.listings.insert_one(listing_data)\n\n return dumps(listing_data)\n\n\n@app.route('/facebook')\ndef fb():\n return \"Got it\"\n\n@app.route('/customer//', methods=['GET', 'POST'])\ndef customer(email, token):\n\n import omise\n\n omise.api_secret = 'skey_test_56wq6wrjel5nxx4yhxw'\n omise.api_public = 'pkey_test_56wq6wrivc8eo0t7s0a'\n\n c = omise.Customer.create(\n email=email,\n description=\"John Doe (id: 30)\",\n card=token\n )\n return 'Customer %s created' % email\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True, threaded=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"352668427","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/fluid/common/gfd.py\n# Compiled at: 2006-12-04 09:19:16\n\"\"\"Geophysical Fluid Dynamics related stuffs\"\"\"\ntry:\n import numpy as N\nexcept:\n try:\n import numarray as N\n except:\n import Numeric as N\n\n_Omega = 2 * N.pi / ((1 + 1 / 365) * 24 * 60 * 60)\n_EarthRadius = 6378137\n\ndef f_parameter(lat, Omega=_Omega):\n \"\"\"f Coriolis parameter\n \n Input:\n lat => Latitude [Degrees]\n Omega => Angular velocity () [Radians/s]\n Output:\n f => Coriolis parameter []\n\n >>>f_parameter(0)\n 0\n >>>f_parameter(30)\n 1\n >>>f_parameter(45,1)\n 1\n \"\"\"\n theta = lat / 180.0 * N.pi\n f = 2 * Omega * N.sin(theta)\n return f\n\n\ndef beta(lat, Omega=_Omega, R=_EarthRadius):\n \"\"\"Beta parameter\n\n \"\"\"\n theta = lat / 180.0 * N.pi\n B = 2 * Omega * N.cos(theta) / R\n return B\n\n\ndef gravity(lat):\n \"\"\"Gravity in function of latitude using the 1980 IUGG formula\n Transcripted from COARE-3.0 routines (Fairall et. al.)\n\n Bulletin Geodesique, Vol 62, No 3, 1988 (Geodesist's Handbook)\n p 356, 1980 Gravity Formula (IUGG, H. Moritz)\n units are in m/sec^2 and have a relative precision of 1 part\n in 10^10 (0.1 microGal)\n code by M. Zumberge.\n\n Check SEAWATER routines use:\n Unesco 1983. Algorithms for computation of fundamental properties of \n seawater, 1983. _Unesco Tech. Pap. in Mar. Sci._, No. 44, 53 pp.\n \n A.E. Gill 1982. p.597\n \"Atmosphere-Ocean Dynamics\"\n Academic Press: New York. ISBN: 0-12-283522-0\n \n\n check values are:\n \n g = 9.780326772 at latitude 0.0\n g = 9.806199203 at latitude 45.0\n g = 9.832186368 at latitude 90.0\n \"\"\"\n gamma = 9.7803267715\n c1 = 0.0052790414\n c2 = 2.32718e-05\n c3 = 1.262e-07\n c4 = 7e-10\n phi = lat * N.pi / 180.0\n g = gamma * (1.0 + c1 * N.sin(phi) ** 2 + c2 * N.sin(phi) ** 4 + c3 * N.sin(phi) ** 6 + c4 * N.sin(phi) ** 8)\n return g\n\n\ndef find_detadx(U, f, g, balance, R=None):\n \"\"\"Estimate del eta/ del x for different force balance equilibrae\n\n Input:\n - U => Velocity magnitude\n - balance:\n - geostrophic =>\n - gradient =>\n \"\"\"\n if balance == 'geostrophic':\n detadx = f * U / g\n elif balance == 'gradient':\n detadx = (U ** 2 / R + f * U) / g\n elif balance == 'max_gradient':\n detadx = R * f ** 2 / (4 * g)\n else:\n return\n return detadx\n\n\ndef dynamic_height(delta, p):\n \"\"\"Dynamic Height in the ocean\n\n INPUT: delta => Specific Volume Anomaly\n !!! ATENTION !!!! The first dimension must be z\n !!! ATENTION !!!! It is uncomplete\n \"\"\"\n if p1 is None:\n p1 = max(p)\n p = p * 10000.0\n dp = numpy.ones(p.shape, dtype=p.dtype.type)\n dp[1:-1, :] = p[2:, :] - p[0:-2, :]\n dp[0, :] = p[1] - p[0]\n dp[-1] = p[(-1)] - p[(-2)]\n dp = dp * 0.5\n Theta = numpy.ones(p.shape, dtype=p.dtype.type)\n Theta = delta * dp\n DH = numpy.cumsum(Theta) / g\n return DH\n\n\ndef _test():\n import doctest\n doctest.testmod()","sub_path":"pycfiles/fluid-0.1.7-py2.4/gfd.py","file_name":"gfd.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"481184893","text":"# -*- coding: utf-8 -*-\nimport os\nimport flask_mongorest\nfrom flask_mongorest.resources import Resource\nfrom flask_mongorest import operators as ops\nfrom flask_mongorest.methods import Fetch\nfrom flask import Blueprint, render_template, request\nfrom css_html_js_minify import html_minify\nfrom mongoengine.queryset import DoesNotExist\nfrom json2html import Json2Html\nfrom boltons.iterutils import remap\n\nfrom mpcontribs.api import quantity_keys, delimiter\nfrom mpcontribs.api.core import SwaggerView\nfrom mpcontribs.api.cards.document import Cards\nfrom mpcontribs.api.projects.document import Projects\nfrom mpcontribs.api.contributions.document import Contributions\n\ntemplates = os.path.join(os.path.dirname(flask_mongorest.__file__), \"templates\")\ncards = Blueprint(\"cards\", __name__, template_folder=templates)\nj2h = Json2Html()\n\n\ndef visit(path, key, value):\n if isinstance(value, dict) and \"display\" in value:\n return key, value[\"display\"]\n return key not in [\"value\", \"unit\"]\n\n\nclass CardsResource(Resource):\n document = Cards\n filters = {\"is_public\": [ops.Boolean]}\n fields = [\"is_public\", \"html\"]\n\n @staticmethod\n def get_optional_fields():\n return [\"bulma\"]\n\n\nclass CardsView(SwaggerView):\n resource = CardsResource\n # no create/update to disable arbitrary html content\n # card deletion via contributions\n methods = [Fetch]\n\n def get(self, **kwargs):\n cid = kwargs[\"pk\"] # only Fetch enabled\n qfilter = lambda qs: self.has_read_permission(request, qs.clone())\n try:\n # trigger DoesNotExist if necessary (due to permissions or non-existence)\n card = self._resource.get_object(cid, qfilter=qfilter)\n if not card.html or not card.bulma:\n contrib = Contributions.objects.only(\"project\", \"data\").get(pk=cid)\n info = Projects.objects.get(pk=contrib.project.id)\n ctx = info.to_mongo()\n ctx[\"cid\"] = cid\n ctx[\"descriptions\"] = info.description.strip().split(\".\", 1)\n authors = [a.strip() for a in info.authors.split(\",\") if a]\n ctx[\"authors\"] = {\"main\": authors[0], \"etal\": authors[1:]}\n ctx[\"landing_page\"] = f\"/{contrib.project.id}/\"\n ctx[\"more\"] = f\"/{cid}\"\n data = contrib.to_mongo().get(\"data\", {})\n ctx[\"data\"] = j2h.convert(\n json=remap(data, visit=visit),\n table_attributes='class=\"table is-bordered is-striped is-narrow is-hoverable is-fullwidth\"',\n )\n card.html = html_minify(render_template(\"card.html\", **ctx))\n card.bulma = html_minify(render_template(\"card_bulma.html\", **ctx))\n card.save()\n return self._resource.serialize(card, params=request.args)\n\n except DoesNotExist:\n card = None\n try:\n card = Cards.objects.only(\"pk\").get(pk=cid)\n except DoesNotExist: # Card has never been requested before\n # create and save unexecuted card, also start entry to avoid rebuild on subsequent requests\n contrib = Contributions.objects.only(\"project\", \"is_public\").get(pk=cid)\n card = Cards(pk=cid, is_public=contrib.is_public)\n card.save()\n return self.get(**kwargs)\n\n if card is not None:\n raise DoesNotExist(\n f\"Card {card.pk} exists but user not in project group\"\n )\n","sub_path":"mpcontribs-api/mpcontribs/api/cards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"400097990","text":"# we the linearized Eady problem:\n#\n# Our approach employs the change of variable : PHI = f . phi \n# We define f = z**2 - 2z - 2/lambda so that the BC on phi are now standard Neuman.\n#\n# New variable phi obeys the following ODE:\n#\n# f DD phi + 2f' D phi + f'' phi = sin(alpha z)\n#\n# This path is general but a little hairy here. Alternatively, we write:\n#\n# PHI = I2 sin(alpha z) + c0 + c1 z (where c0,c1 are arbitrary constants)\n# f phi = I2 sin(alpha z) + c0 + c1 z (where c0,c1 are arbitrary constants)\n#\n# Introduce the galerkin decomposition of phi: phi = S gal\n# Remove the two lowest degree equations with projection matrix R2\n# R2 f S gal = R2 I2 sin(alpha z)\n\n# libraries we need\nimport numpy as np\nimport scipy.sparse as sp\nimport cheby_tools as ct\nimport scipy.fftpack as fft\nimport scipy.sparse.linalg as la\nfrom galerkin_stencils import chebyshev_galerkin_stencil_shape\nfrom galerkin_stencils import chebyshev_galerkin_stencil\nfrom galerkin_stencils import high_degree_projection_mat\nimport matplotlib.pyplot as plt\nplt.close('all')\n\n# parameters\nNZ = 256\nLy = 2500.\nLx = 2500.\nshear = 0.5 #Rossby\nnuh = 0.#1.2, here nonviscous case\nnuz = 0.01 #0.0001 same\nnuzb = 0.01 #same\nnuhb = 0.#1.2, same\nf = 100. \nfriction = 0.00001 \nbeta = 0. #8*10**(-5);# dimentionnal beta, beta = (f/H)*beta_ad\nN = 10.\nH = 1.\n\n\n# define our domain\n\ngap = 1.\ncenter = 0.5\nhTop = center + gap/2.\nhBot = center - gap/2.\n\n####################################\n####################################\n\n## Analytical solution for single most unstable mode\n\n# Considering:\n\nLd = N*H/f\nkx = 1.6/Ld #kmax, instability greatest\nprint('kx = '+str(kx))\nl = 0. \nky= l\nmu = np.sqrt(kx**2+l**2)*Ld\nmum = 1.61\nsigma_E = 0.31*shear*f/N\n\nprint ('=======')\nprint ('EADY maximum analytical growthrate sigma_E = '+str(sigma_E))\nprint ('=======')\n\nci = sigma_E/kx\ncr = 0.5*shear*H\nc = np.sqrt(ci**2+cr**2)\n\nz = np.linspace(0,H,num=NZ,endpoint=False)\ntheta_m = np.arctan(ci*shear*H*np.sinh(mum*z/H)/(mum*(c)**2*np.cosh(mum*z/H)-shear*cr*np.sinh(mum*z/H)))\npsi_m = np.sqrt(((ci*shear*H*np.sinh(mum*z/H))/(mum*c**2))**2+ (np.cosh(mum*z/H)-(shear*cr*np.sinh(mum*z/H))/(mum*c**2))**2)\n\n\nc = cr + 1.j*ci\nphi_vallis = np.cosh(mum*z/H) - np.sinh(mum*z/H)*shear*H/(mum*c)\n\n\n#plt.figure()\n#plt.plot(theta_m,z,'--',label='phase')\n#plt.plot(psi_m, z, '--',label='amplitude')\n#plt.legend()\n#plt.grid()\n#plt.title('Analytical most unstable mode')\n\n\n\n\ndef plot_waveAnalytics(waveProfile,var):\n x = np.linspace(0,4*np.pi, num=1000)\n z = np.linspace(0,H,num=NZ,endpoint=False)\n X,Z= np.meshgrid(x,z)\n expX = np.exp(1.j*X)\n _,wavePlan = np.meshgrid(x,waveProfile)\n plt.figure()\n plt.pcolormesh(x,z,(wavePlan*expX).real,shading='auto')\n plt.colorbar()\n plt.xlabel('x')\n plt.ylabel('z')\n plt.title(var)\n plt.contour(X, Z,wavePlan*expX,colors='w', linewidths=1)\n#plot_waveAnalytics(phi_vallis,'phi vallis')\n\nplot_waveAnalytics(phi_vallis,r'EADY: Analytical most unstable mode, $\\psi$')\n\n\n###################################\n###################################\n\n# wn we consider:\npx = 1.j*kx\npy = 1.j*ky\ndel2h = px**2 + py**2\n\n\n# define stencil matrices for imposing Neuman B.C.\nif (friction<1.e-8):\n BCcode = 23\nelse:\n BCcode = 21\nnelems, ncol, nrow = chebyshev_galerkin_stencil_shape ( NZ, BCcode)\ndat = np.empty((nelems), dtype=np.float_)\nrow = np.empty((nelems), dtype=np.int32 )\ncol = np.empty((nelems), dtype=np.int32 )\ndat, col, row = chebyshev_galerkin_stencil( NZ, BCcode, nelems)\nS_psi = sp.coo_matrix((dat, (row-1, col-1)) )\ndel dat, col, row # a bit of cleaning...\n\n\n# define stencil matrices for imposing Neuman B.C.\nif (friction<1.e-8):\n BCcode = 43\nelse:\n BCcode = 41\nnelems, ncol, nrow = chebyshev_galerkin_stencil_shape ( NZ, BCcode)\ndat = np.empty((nelems), dtype=np.float_)\nrow = np.empty((nelems), dtype=np.int32 )\ncol = np.empty((nelems), dtype=np.int32 )\ndat, col, row = chebyshev_galerkin_stencil( NZ, BCcode, nelems)\nS_phi = sp.coo_matrix((dat, (row-1, col-1)) )\ndel dat, col, row # a bit of cleaning...\n\n\n# define stencil matrices for imposing Neuman B.C.\nnelems, ncol, nrow = chebyshev_galerkin_stencil_shape ( NZ, 21)\ndat = np.empty((nelems), dtype=np.float_)\nrow = np.empty((nelems), dtype=np.int32 )\ncol = np.empty((nelems), dtype=np.int32 )\ndat, col, row = chebyshev_galerkin_stencil( NZ, 21, nelems)\nS_theta = sp.coo_matrix((dat, (row-1, col-1)) )\ndel dat, col, row # a bit of cleaning...\n\n# identity matrix\ncooId = sp.coo_matrix(np.eye(NZ)) \n\n# define matrix that represents multiplication by z\nCEM = ct.chebyshev_elementary_multiplication(NZ, gap, center)\n# define matrix that represents integration w.r.t. z\nCEI = ct.chebyshev_elementary_integration (NZ, gap, center)\nCEI.data[1][1] = 0.\n\n\n# projection onto the NZ-order highest coefficients\n# (discard integration constants introduced by Q.I. technique)\norder = 2 # for psi and theta\ndat = np.empty((NZ - order), dtype=np.float_)\nrow = np.empty((NZ - order), dtype=np.int32 )\ncol = np.empty((NZ - order), dtype=np.int32 )\ndat, col, row = high_degree_projection_mat( NZ, order)\nR2 = sp.coo_matrix((dat, (row-1, col-1)) )\ndel dat, col, row # a bit of cleaning...\norder = 4 # for phi\ndat = np.empty((NZ - order), dtype=np.float_)\nrow = np.empty((NZ - order), dtype=np.int32 )\ncol = np.empty((NZ - order), dtype=np.int32 )\ndat, col, row = high_degree_projection_mat( NZ, order)\nR4 = sp.coo_matrix((dat, (row-1, col-1)) )\ndel dat, col, row # a bit of cleaning...\nprojector = [R2,R4,R2]\n\nCVS = [] # Change of variable and stencil mats\n# for psi\nChange_of_vars_mat = friction * CEM.dot(CEM) + 2.*friction*hTop*CEM \\\n + (2.*(hBot - hTop) - friction* hBot**2 +2.*friction\n *hBot*hTop)*cooId \nCVS.append(Change_of_vars_mat.dot(S_psi))\n# for phi\nChange_of_vars_mat = friction * CEM.dot(CEM) + 2.*friction*hTop*CEM \\\n + (4.*(hBot - hTop) - friction* hBot**2 +2.*friction\n *hBot*hTop)*cooId \nCVS.append(Change_of_vars_mat.dot(S_phi))\n# for theta\nChange_of_vars_mat = cooId \nCVS.append(Change_of_vars_mat.dot(S_theta))\n\n# shape of the system:\neqn_sta = np.array([0, NZ-2, NZ - 4 + NZ - 2], dtype=np.int32)\neqn_num = np.array([ NZ-2, NZ - 4, NZ - 2], dtype=np.int32)\neqn_end = eqn_sta + eqn_num\nvar_sta = np.array([0, NZ-2, NZ - 4 + NZ - 2], dtype=np.int32)\nvar_num = np.array([ NZ-2, NZ - 4, NZ - 2], dtype=np.int32)\nvar_end = var_sta + var_num\n\nieqn = {\"psi\" : 0, \n \"phi\" : 1, \n \"theta\" : 2} \njvar = {\"psi\" : 0, \n \"phi\" : 1, \n \"theta\" : 2} \n\ndef add_block_to_right_spot(large_mat, eqn_str, var_str, int_order, mul_order, zsca):\n additional_block = projector[ ieqn[ eqn_str]].dot( \n (CEI**int_order).dot(\n (CEM**mul_order).dot( \n CVS[ jvar[ var_str]] \n ) \n )\n ) * zsca\n additional_block = additional_block.tocoo()\n # now we concatenate:\n row_shift = eqn_sta[ ieqn [eqn_str]]\n col_shift = var_sta[ jvar [var_str]]\n nelems = additional_block.getnnz() + large_mat.getnnz()\n rRows = np.empty((nelems,), dtype=np.int32)\n rCols = np.empty((nelems,), dtype=np.int32)\n rData = np.empty((nelems,), dtype=np.complex_)\n rRows[:large_mat.getnnz()] = large_mat.row\n rCols[:large_mat.getnnz()] = large_mat.col\n rData[:large_mat.getnnz()] = large_mat.data\n rRows[large_mat.getnnz():] = additional_block.row + row_shift\n rCols[large_mat.getnnz():] = additional_block.col + col_shift\n rData[large_mat.getnnz():] = additional_block.data\n return sp.coo_matrix((rData, (rRows, rCols)), shape = large_mat.get_shape() )\n\nz1 = 1.+0.j\n\nM = sp.coo_matrix((eqn_end[-1], var_end[-1]), dtype= np.complex_)\nL = sp.coo_matrix((eqn_end[-1], var_end[-1]), dtype= np.complex_)\n\n# build mass matrix\nM = add_block_to_right_spot(M, \"psi\", \"psi\", 2, 0, -del2h) \nM = add_block_to_right_spot(M, \"phi\", \"phi\", 4, 0, del2h**2)\nM = add_block_to_right_spot(M, \"phi\", \"phi\", 2, 0, del2h)\nM = add_block_to_right_spot(M, \"theta\", \"theta\", 2, 0, 1.+0.j)\n# build stiffness matrix\n# psi eqn\n# ... viscous term\nL = add_block_to_right_spot(L, \"psi\", \"psi\", 2, 0, -nuh*del2h**2) \nL = add_block_to_right_spot(L, \"psi\", \"psi\", 0, 0, -nuz*del2h)\n# ... Coriolis term\nL = add_block_to_right_spot(L, \"psi\", \"phi\", 1, 0, -f *del2h)\nL = add_block_to_right_spot(L, \"psi\", \"psi\", 2, 0, - beta*px)\nL = add_block_to_right_spot(L, \"psi\", \"phi\", 1, 0, beta*py)\n# ... Shear term\nL = add_block_to_right_spot(L, \"psi\", \"phi\", 2, 0, -shear*py*del2h)\nL = add_block_to_right_spot(L, \"psi\", \"psi\", 2, 1, shear*px*del2h)\n\n# phi eqn\n# ... viscous term\nL = add_block_to_right_spot(L, \"phi\", \"phi\", 4, 0, nuh*del2h**3)\nL = add_block_to_right_spot(L, \"phi\", \"phi\", 2, 0, nuh*del2h**2)\nL = add_block_to_right_spot(L, \"phi\", \"phi\", 2, 0, nuz*del2h**2)\nL = add_block_to_right_spot(L, \"phi\", \"phi\", 0, 0, nuz*del2h)\n# ... buoyancy term\nL = add_block_to_right_spot(L, \"phi\", \"theta\", 4, 0, -del2h)\n# ... Coriolis term\nL = add_block_to_right_spot(L, \"phi\", \"psi\", 3, 0, -f *del2h)\nL = add_block_to_right_spot(L, \"phi\", \"psi\", 3, 0, -beta*py)\nL = add_block_to_right_spot(L, \"phi\", \"phi\", 2, 0, -beta*px)\n# ... Shear term\n# use II z dzz phi = z phi - 2 I phi\nL = add_block_to_right_spot(L, \"phi\", \"phi\", 4, 1, - shear* px *del2h**2) # originally \"psi\",\"phi\",..\nL = add_block_to_right_spot(L, \"phi\", \"phi\", 2, 1, - shear* del2h * px)\nL = add_block_to_right_spot(L, \"phi\", \"phi\", 3, 0, 2.*shear* del2h * px)\n\n# theta eqn\n# ... diffusive term\nL = add_block_to_right_spot(L, \"theta\", \"theta\", 2, 0, nuhb*del2h)\nL = add_block_to_right_spot(L, \"theta\", \"theta\", 0, 0, nuzb+ 0.j )\n# ... shear term\nL = add_block_to_right_spot(L, \"theta\", \"theta\", 2, 1, -shear * px)\n# ... advection background\nL = add_block_to_right_spot(L, \"theta\", \"psi\", 2, 0, -shear * f * px)\nL = add_block_to_right_spot(L, \"theta\", \"phi\", 1, 0, +shear * f * py)\n# ... Background stratification\nL = add_block_to_right_spot(L, \"theta\", \"phi\", 2, 0, N**2*del2h)\n\n\nLdense = L.toarray()\nMdense = M.toarray()\n\nfrom scipy.linalg import eig\n\neigenVal, eigenVec = eig(Ldense, b=Mdense)\n\nprint ('=======')\nprint ('EADY maximum growthrate s_max = '+str(eigenVal.real.max()))\nprint ('=======')\n\n# PLOT THE SPECTRUM\n#plt.figure()\n#plt.spy(L)\nplt.figure()\nplt.plot(eigenVal.real, eigenVal.imag, 'o')\nplt.title('EADY: Spectrum with coral')\nplt.xlabel(r'Re(\\lambda)')\nplt.ylabel(r'Im(\\lambda)')\nplt.grid()\n\n# PLOT THE MOST UNSTABLE MODE\nmode_index = np.where(eigenVal.real == eigenVal.real.max())[0][0]\nallVars_galn_coefs = eigenVec[:,mode_index]\nphi_galn_coefs = allVars_galn_coefs[var_sta[jvar[\"phi\"]]:var_end[jvar[\"phi\"]]]\npsi_galn_coefs = allVars_galn_coefs[var_sta[jvar[\"psi\"]]:var_end[jvar[\"psi\"]]]\ntheta_galn_coefs = allVars_galn_coefs[var_sta[jvar[\"theta\"]]:var_end[jvar[\"theta\"]]]\n\npsi_cheb_coefs = CVS[0].dot(psi_galn_coefs)\nphi_cheb_coefs = CVS[1].dot(phi_galn_coefs)\ntheta_cheb_coefs = CVS[2].dot(theta_galn_coefs)\n\npsi_cheb_coefs[0] *= 2.\npsi_phys = fft.idct(psi_cheb_coefs) /2.\nphi_cheb_coefs[0] *= 2.\nphi_phys = fft.idct(phi_cheb_coefs) /2.\ntheta_cheb_coefs[0] *= 2.\ntheta_phys = fft.idct(theta_cheb_coefs) /2.\nz = np.cos( (2* np.linspace(0,NZ,num=NZ, endpoint=False) + 1.)/2./NZ*np.pi)*gap/2. + center\n\npsi_physcp = psi_phys/max(abs(psi_phys))\nthet = 2*np.arctan(abs(psi_physcp.imag)/(psi_physcp.real+abs(psi_physcp)))\nthet=thet-thet[NZ-1]\nzan = np.linspace(0,H,NZ)\n# Plot Amplitude and phase for coral and analytical most unstable mode\n\nplt.figure()\nplt.plot(abs(psi_physcp), z,label='with coral')\nplt.plot(psi_m,zan,'--',label='analytical solution')\nplt.title(r'EADY: Amplitude $\\psi$ for most unstable mode')\nplt.ylabel('z')\nplt.legend()\nplt.grid()\n\nplt.figure()\nplt.plot(theta_m,zan,'--',label='analytical solution')\nplt.plot(thet, z,label='with coral')\nplt.grid()\nplt.legend()\nplt.ylabel('z')\nplt.title(r'EADY: Phase $\\psi$ for most unstable mode')\n\n\ndef plot_wavePlan(waveProfile,var):\n x = np.linspace(0,4*np.pi, num=1000)\n z = center + 0.5 * gap * np.cos((2*np.linspace(0,NZ, num=NZ, endpoint=False)+1)/2./NZ*np.pi)\n X,Z= np.meshgrid(x,z)\n expX = np.exp(1.j*X)\n _,wavePlan = np.meshgrid(x,waveProfile) \n plt.figure()\n plt.pcolormesh(x,z,(wavePlan*expX).real,shading='auto')\n plt.xlabel('x')\n plt.colorbar()\n plt.ylabel('z')\n plt.title(var)\n plt.contour(X, Z,wavePlan*expX,colors='w', linewidths=1)\n#plot_wavePlan(psi_m,'ampl vallis')\nplot_wavePlan(psi_phys,'Coral most unstable mode, Psi')\nplot_wavePlan(phi_phys,'phi')\nplot_wavePlan(theta_phys,'b')\n\nplt.show()\n","sub_path":"driver_eadyQG.py","file_name":"driver_eadyQG.py","file_ext":"py","file_size_in_byte":12748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"47367175","text":"# python script to rename (slugify) ispring folder names in a directory. \n\nimport os\nfrom django.utils.text import slugify\n\n\n\"\"\" Usage:\n1. cd to directory containing files/folders that need to be renamed (slugified)\n2. run python slugify-filenames.py within above directory\n\n\"\"\"\n\ndef slugify_file(directory, fstr):\n ftrim = fstr[:-4] # remove (Web) from filename.\n ftrim = slugify(unicode(ftrim, errors='replace'))\n os.rename(\n os.path.join(directory, fstr),\n os.path.join(directory, ftrim)\n )\n\n\ndef slugify_dir(directory):\n # loop through files in dir -- rename each file by slugifying it.\n files = [i for i in os.listdir(directory) if i[0] != '.']\n for i in files:\n slugify_file(directory, i)\n\nif __name__ == '__main__':\n input_dir = os.path.abspath('.')\n slugify_dir(input_dir)\n\n","sub_path":"ggvutils/slugify-filenames.py","file_name":"slugify-filenames.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"589222274","text":"# coding:utf-8\n\"\"\"\n实例语义标注,存到一个uint8的图像上,每个语义实例根据mask计算bbox作为roi进行合成\n\"\"\"\nimport json\n\nclass jsonDataset:\n \"\"\" a coco like json dataset, build unique id for dataset\"\"\"\n\n def __init__(self):\n self.images = []\n self.categories = []\n self.annotations = []\n self.image_count = 0\n self.annotations_count = 0\n self.category_count = 0\n\n def add_category(self, category):\n \"\"\"\n add category to dataset\n :param category: dict\n :return:\n \"\"\"\n category['id'] = self.category_count\n self.category_count = self.category_count + 1\n self.categories.append(category)\n\n def add_annotation(self, annobj):\n \"\"\"\n add image with its all annotations to dataset\n :param annobj: has key image(dict) and anns(dict list)\n :return:\n \"\"\"\n annobj['image']['id'] = self.image_count\n self.image_count = self.image_count + 1\n self.images.append(annobj['image'])\n for ann in annobj['anns']:\n ann['id'] = self.annotations_count\n ann['image_id'] = annobj['image']['id']\n self.annotations_count = self.annotations_count + 1\n self.annotations.append(ann)\n\n def save_dataset(self, output_name, info=None):\n dataset = {}\n if info is not None:\n dataset['info'] = info\n dataset['images'] = self.images\n dataset['annotations'] = self.annotations\n dataset['categories'] = self.categories\n json.dump(dataset, output_name)\n\n","sub_path":"scripts/jsondataset.py","file_name":"jsondataset.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"499743325","text":"#!/usr/bin/env python\n\n\n# extractRotFromAff.py\n# A script to extract the rotaion part\n# of an affine transformation.\n# The rotation will be given as \"R.T\",\n# right the transpose of \"R\". Thus the \n# inverse transform will be in effect \"R\".\n#\n# The BeBo Company, 2018\n\n\nimport sys\nimport os\nimport subprocess\nimport time\nimport string\nimport re\nimport numpy as np\n\n\nif ( len ( sys.argv ) == 2 ) :\n cmdarg = sys.argv[1];\n if ( re.search ( \"help$\", cmdarg ) or re.match( '-h$', cmdarg ) ):\n s_1 = 'Usage: extractRotFromAff.py -basedir -filename '\n print ( s_1 );\n exit ( 1 );\n\nif ( len ( sys.argv ) != 5 ) :\n s_1 = 'Usage: extractRotFromAff.py -basedir -filename '\n print ( s_1 );\n exit ( 1 )\n\ncur_dir = os.getcwd ( )\n\nwhile ( sys.argv ):\n cmdarg = sys.argv.pop ( 0 );\n if ( cmdarg == '-basedir' ):\n base_dir = sys.argv.pop ( 0 )\n elif ( cmdarg == \"-filename\" ):\n file_name = sys.argv.pop ( 0 )\n file_name = base_dir + \"/\" + file_name\n\n\n#print( line.strip() )\nif os.path.isfile ( file_name ):\n s_1 = 'fslhd ' + file_name\n print ( s_1 )\n p = subprocess.Popen(s_1, shell = True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT )\n stdout = ((p.communicate()[0]).decode ( 'ascii' )).split( '\\n' )\n print ( stdout )\n i = 0\n while i < len ( stdout ):\n print ( i, stdout[i] )\n i += 1\n a = ( stdout[47].strip ( ) ).split ( )\n b = ( stdout[48].strip ( ) ).split ( )\n c = ( stdout[49].strip ( ) ).split ( )\n s_x = np.sqrt ( np.square ( float ( a[1] ) )\\\n + np.square ( float ( b[1] ) ) \\\n + np.square ( float ( c[1] ) ) ) \n\n s_y = np.sqrt ( np.square ( float ( a[2] ) )\\\n + np.square ( float ( b[2] ) ) \\\n + np.square ( float ( c[2] ) ) ) \n\n s_z = np.sqrt ( np.square ( float ( a[3] ) )\\\n + np.square ( float ( b[3] ) ) \\\n + np.square ( float ( c[3] ) ) ) \n\n x = np.array ( [ float ( a[1] ), float ( b[1] ), float ( c[1] ) ] ) / s_x\n y = np.array ( [ float ( a[2] ), float ( b[2] ), float ( c[2] ) ] ) / s_y\n z = np.array ( [ float ( a[3] ), float ( b[3] ), float ( c[3] ) ] ) / s_z\n R = np.array ( [ x, y, z ] )\n\n # The actual otation matrix will be \"R.T\".\n\n print ( np.dot ( R.T, R ) )\n","sub_path":"SmallAnimalBruker/python/extractRotFromAff.py","file_name":"extractRotFromAff.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"454951851","text":"from csv import reader\nfrom itertools import chain, combinations\n\n\nclass FPTree:\n @staticmethod\n class Node:\n def __init__(self, item_name, frequency, parent_node):\n self.itemName = item_name\n self.count = frequency\n self.parent = parent_node\n self.children = {}\n self.next = None\n\n def increment(self, frequency):\n self.count += frequency\n\n def display(self, ind=1):\n print(' ' * ind, self.itemName, ' ', self.count)\n for child in list(self.children.values()):\n child.display(ind + 1)\n\n @staticmethod\n def get_from_file(file_name):\n item_set_list = []\n\n with open(file_name, 'r') as file:\n csv_reader = reader(file)\n for line in csv_reader:\n line = list(filter(None, line))\n item_set_list.append(line)\n\n return item_set_list\n\n @staticmethod\n def construct_tree(item_sets, min_sup):\n header_table = {}\n frequent_pattern = {}\n\n # Counting frequency and create header table\n for idx, items in enumerate(item_sets):\n for item in items:\n if frequent_pattern.get(item) is None:\n frequent_pattern[item] = 1\n else:\n frequent_pattern[item] += 1\n\n # Deleting items below minSup\n for item in frequent_pattern.items():\n if item[1] >= min_sup:\n header_table[item[0]] = [item[1], None]\n del frequent_pattern\n if len(header_table) == 0:\n return None, None\n\n # Init Null head node\n fp_tree = FPTree.Node('Null', 1, None)\n\n # Update FP tree for each cleaned and sorted itemSet\n for item_set in item_sets:\n item_set = [\n item for item in item_set if item in header_table.keys()]\n item_set.sort(key=lambda itm: header_table[itm][0], reverse=True)\n\n # Traverse from root to leaf, update tree with given item\n current_node = fp_tree\n for item in item_set:\n current_node = FPTree.update_tree(\n item, current_node, header_table, 1)\n return fp_tree, header_table\n\n @staticmethod\n def update_header_table(item, target_node, header_table):\n if header_table[item][1] is None:\n header_table[item][1] = target_node\n else:\n current_node = header_table[item][1]\n # Traverse to the last node then link it to the target\n while current_node.next is not None:\n current_node = current_node.next\n current_node.next = target_node\n\n @staticmethod\n def update_tree(item, tree_node, header_table, frequency):\n if item in tree_node.children:\n # If the item already exists, increment the count\n tree_node.children[item].increment(frequency)\n else:\n # Create a new branch\n new_item_node = FPTree.Node(item, frequency, tree_node)\n tree_node.children[item] = new_item_node\n # Link the new branch to header table\n FPTree.update_header_table(item, new_item_node, header_table)\n\n return tree_node.children[item]\n\n @staticmethod\n def ascend_fp_tree(node, prefix_path):\n if node.parent is not None:\n prefix_path.append(node.itemName)\n FPTree.ascend_fp_tree(node.parent, prefix_path)\n\n @staticmethod\n def find_prefix_path(base_pat, header_table):\n # First node in linked list\n tree_node = header_table[base_pat][1]\n cond_pats = []\n frequency = []\n while tree_node is not None:\n prefix_path = []\n # From leaf node all the way to root\n FPTree.ascend_fp_tree(tree_node, prefix_path)\n if len(prefix_path) > 1:\n # Storing the prefix path and it's corresponding count\n cond_pats.append(prefix_path[1:])\n frequency.append(tree_node.count)\n\n # Go to next node\n tree_node = tree_node.next\n return cond_pats, frequency\n\n @staticmethod\n def mine_tree(header_table, min_sup, pre_fix, freq_items):\n # Sort the items with frequency and create a list\n sorted_item_list = [item[0] for item in sorted(\n list(header_table.items()), key=lambda p: p[1][0])]\n # Start with the lowest frequency\n for item in sorted_item_list:\n # Pattern growth is achieved by the concatenation of suffix pattern with frequent patterns generated\n # from conditional FP-tree\n new_freq_set = pre_fix.copy()\n new_freq_set.add(item)\n freq_items.append(new_freq_set)\n # Find all prefix path, construct conditional pattern base\n conditional_patt_base, frequency = FPTree.find_prefix_path(\n item, header_table)\n # Construct conditional FP Tree with conditional pattern base\n _, new_header_table = FPTree.construct_tree(\n conditional_patt_base, min_sup)\n if new_header_table is not None:\n # Mining recursively on the tree\n FPTree.mine_tree(new_header_table, min_sup,\n new_freq_set, freq_items)\n\n @staticmethod\n def power_set(s):\n return chain.from_iterable(combinations(s, r) for r in range(1, len(s)))\n\n @staticmethod\n def get_support(test_set, item_set):\n count = 0\n for itemSet in item_set:\n if set(test_set).issubset(itemSet):\n count += 1\n return count\n\n @staticmethod\n def association_rule(freq_item_set, item_set, min_conf):\n rules_new = []\n for itemSet in freq_item_set:\n subsets = FPTree.power_set(itemSet)\n item_set_sup = FPTree.get_support(itemSet, item_set)\n for s in subsets:\n confidence = float(\n item_set_sup / FPTree.get_support(s, item_set))\n if confidence >= min_conf:\n rules_new.append(\n [set(s), set(itemSet.difference(s)), confidence])\n return rules_new\n\n @staticmethod\n def fp_growth(item_set, min_sup_ratio, min_conf):\n min_sup = len(item_set) * min_sup_ratio\n fp_tree, header_table = FPTree.construct_tree(item_set, min_sup)\n if fp_tree is None:\n print('No frequent item set')\n return [], []\n else:\n freq_items = []\n FPTree.mine_tree(header_table, min_sup, set(), freq_items)\n all_rules = FPTree.association_rule(freq_items, item_set, min_conf)\n return freq_items, all_rules\n\n @staticmethod\n def fp_growth_from_file(file_name, min_sup_ratio, min_conf):\n item_set_list = FPTree.get_from_file(file_name)\n min_sup = len(item_set_list) * min_sup_ratio\n fp_tree, header_table = FPTree.construct_tree(item_set_list, min_sup)\n if fp_tree is None:\n print('No frequent item set')\n return [], []\n else:\n freq_items = []\n FPTree.mine_tree(header_table, min_sup, set(), freq_items)\n all_rules = FPTree.association_rule(\n freq_items, item_set_list, min_conf)\n return freq_items, all_rules\n\n @staticmethod\n def show_rules(rules):\n rules.sort(key=lambda _rule: _rule[2], reverse=True)\n for rule in rules:\n print(rule[0], '-->', rule[1], 'conf:', rule[2])\n\n\nif __name__ == \"__main__\":\n freqItemSet, _rules = FPTree.fp_growth_from_file(\n '/home/computer/work/univ/other/dataset/tdb.csv', 0.3, 0.95)\n\n print(freqItemSet)\n print(\"\\n\\nAssociation Rules: \")\n FPTree.show_rules(_rules)\n","sub_path":"other/t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":7839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"289999050","text":"#!/usr/bin/env python\n\n\ndef algo_baseline(datacenter):\n # Fill the caches with the maximum number of videos\n\n results = {}\n\n def remaining_size(cache_id):\n if cache_id in results:\n return datacenter.X - sum([datacenter.videos[v_id] for v_id in results[cache_id]])\n else:\n return datacenter.X\n\n for c_id in range(datacenter.C):\n results[c_id] = []\n\n video_id = 0\n while video_id < len(datacenter.videos) and remaining_size(c_id) >= datacenter.videos[video_id]:\n\n results[c_id].append(video_id)\n video_id += 1\n\n return results","sub_path":"src/algo_baseline.py","file_name":"algo_baseline.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"568961087","text":"\"\"\"\n24. O Sr. Manoel Joaquim expandiu seus negócios para além dos negócios de 1,99 e agora\npossui uma loja de conveniências. Faça um programa que implemente uma caixa\nregistradora rudimentar. O programa deverá receber um número desconhecido de\nvalores referentes aos preços das mercadorias. Um valor zero deve ser informado pelo\noperador para indicar o final da compra. O programa deve então mostrar o total da\ncompra e perguntar o valor em dinheiro que o cliente forneceu, para então calcular e\nmostrar o valor do troco. Após esta operação, o programa deverá voltar ao ponto inicial,\npara registrar a próxima compra. A saída deve ser conforme o exemplo abaixo:\n Lojas Tabajara\n Produto 1: R$ 2.20\n Produto 2: R$ 5.80\n Produto 3: R$ 0\n Total: R$ 9.00\n Dinheiro: R$ 20.00\n Troco: R$ 11.00\n\"\"\"\nfrom time import sleep\nprint(\"==========Lojas Tabajara==========\")\nloja = []\ntotalP = 0\nres = ''\ndef limpar():\n print(\"\\n\"*2)\n print(\"Gerar um novo Pedido\")\n sleep(2)\n\nwhile True:\n # Preechendo o valores dos produtos\n c = 1\n while True:\n print(\"A o Digitar [ 0 ] em um dos produtos o programa encerra.\")\n produto = float(input(f\"Digite o preço do Produto {c}: R$\"))\n loja.append(produto)\n totalP += produto\n if produto == 0:\n break\n c += 1\n valorPago = float(input(\"Dinheiro: R$\"))\n print(\"Gerando o Cumpon Fiscal...\")\n sleep(2)\n print(\"-=-\"*20)\n for i in range(len(loja)):\n print(f\"Produto {i}: R${loja[i]:.2f}\")\n troco = valorPago - totalP\n print(f\"Total: R${totalP:.2f}\")\n print(f\"Dinheiro: R${valorPago:.2f}\")\n print(f\"Troco: R${troco:.2f}\")\n\n res = input(\"Deseja continuar S/N: \").strip().upper()\n while res not in 'SsNn':\n print(\"Erro deve informa S para sim e N para não.\")\n res = input(\"Deseja continuar S/N: \").strip().upper()\n if res in 'Nn':\n break\n else:\n limpar()\nprint(\"Fim\")","sub_path":"Lista03/ex024.py","file_name":"ex024.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"531869620","text":"import numpy as np\nimport os\nfrom numpy.random import randint\n\n## Conditions de marché\n\ndemand = np.zeros(48)\nfor i in range(48):\n demand[i] = 10\n #demand[i] = randint(1,51)\n\ncost_elec_market = np.zeros(48)\nfor i in range(48):\n cost_elec_market[i] = 0\n #cost_elec_market[i] = randint(30,51)\n\n## Consommateur Industriel\n\nclass IndustrialConsumer :\n\n def __init__(self):\n self.dt = 0.5\n self.efficiency = 0.95\n self.max_power_battery = 10\n self.battery_capacity = 100\n self.battery_load = np.zeros(48)\n self.battery = np.zeros(48)\n self.electricity_purchases = np.zeros(48)\n self.load_profile = np.zeros(48)\n self.bill = np.zeros(48)\n self.battery[-1] = 50\n\n#Choice of the quantity of electricity from your battery you want to use to fulfill the demand over the time span [t,t+dt]\n def set_battery_load(self,t,battery_load):\n\n #Si la batterie n'est pas assez remplie, le joueur modifie ses décisions\n while ((battery_load/self.efficiency) > self.battery[int((t-1)*2)]):\n print(\"Battery_shortage, please modify your decisions\")\n print (\"Select a new battery_load : \")\n battery_load = int(input())\n\n #Si la batterie n'est pas assez puissante, le joueur modifie ses décisions\n while (battery_load > self.max_power_battery):\n print(\"Insufficient battery power, please modify your decisions\")\n print (\"Select a new battery_load : \")\n battery_load = int(input())\n\n #Si tout est conforme aux règles, on actualise la quantité d'électricité de la batterie utilisée pour satisfaire la demande et la quantité d'électricité restant dans la batterie\n self.battery_load[int(t*2)] = -battery_load\n self.battery[int(t*2)] = self.battery[int((t-1)*2)] - battery_load\n return(True)\n\n\n#Choice of the quantity of electricity you want to buy at time t (a part of the energy is lost because of a non-perfect battery efficiency\n def buy_electricity(self,t,Quantity):\n\n #Si le joueur n'achète pas assez d'électricité pour satisfaire la demande, il modifie ses décisions\n while ((Quantity - self.battery_load[int(t*2)]) < demand[int(t*2)]):\n print(\"You don't meet the demand, please modify your decisions\")\n print (\"Select a new quantity of electricity to buy : \")\n Quantity = int(input())\n\n #Si le surplus d'électricité achetée excède la capacité totale de la batterie, le joueur modifie ses décisions\n while ((Quantity - demand[int(t*2)])*self.efficiency + self.battery[int(t*2)] > self.battery_capacity):\n print(\"Insufficient battery capacity, please modify your decisions\")\n print (\"Select a new quantity of electricity to buy : \")\n Quantity = int(input())\n\n self.battery[int(t*2)] += (Quantity - demand[int(t*2)])*self.efficiency\n self.electricity_purchases[int(t*2)] = Quantity\n return(True)\n\n#Compute the total load over the time span [t,t+dt]\n def compute_load(self,t):\n self.load_profile[int(t*2)] = self.battery_load[int(t*2)] + demand[int(t*2)]\n\n#Compute the current bill\n def update_bill(self,t):\n self.bill[int(t*2)] = cost_elec_market[int(t*2)]*self.electricity_purchases[int(t*2)]\n\n\n## Le Jeu\n\nIC = IndustrialConsumer()\nt = 0\nwhile (t < 2):\n IC.set_battery_load(t,0)\n IC.buy_electricity(t,0)\n IC.compute_load(t)\n IC.update_bill(t)\n t += IC.dt\n\nprint('Done')\n\n\n\n\n\n\n\n\n","sub_path":"players/IndustrialConsumer.py","file_name":"IndustrialConsumer.py","file_ext":"py","file_size_in_byte":3538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"465574754","text":"from flask_wtf import FlaskForm\nfrom flask_wtf.file import FileField, FileAllowed, FileRequired\nfrom wtforms import SubmitField, StringField\nfrom wtforms.validators import DataRequired\n\n\nclass UploadFetDataForm(FlaskForm):\n yearOfGraduation = StringField(\n \"Year of Graduation (YYYY)\", validators=[DataRequired()]\n )\n schoolYear = StringField(\"Schedule Year (YYYY)\", validators=[DataRequired()])\n semester = StringField(\n \"Schedule Semester (Fall or Spring)\", validators=[DataRequired()]\n )\n csvFetStudentInputFile = FileField(\n \"FET Student Input File (*.csv format)\",\n validators=[FileAllowed([\"csv\"]), FileRequired()],\n )\n csvFetClassTeacherInputFile = FileField(\n \"FET Class Teacher Input File (*.csv format)\",\n validators=[FileAllowed([\"csv\"]), FileRequired()],\n )\n csvFetTimetableInputFile = FileField(\n \"FET Timetable Input File (*.csv format)\",\n validators=[FileAllowed([\"csv\"]), FileRequired()],\n )\n submitFetDataForm = SubmitField(\"Generate Schedule File\")\n\n","sub_path":"P2MT_App/fetTools/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"14056203","text":"import os\nimport socket\nimport logging\nfrom pathlib import Path\n\nfrom flask_log_request_id import RequestIDLogFilter\n\n\nclass Config(object):\n # Logging settings\n LOGGING_DIR = os.getenv(\"LOGGING_DIR\", \"/tmp/\")\n LOG_LEVEL = os.getenv(\"LOG_LEVEL\", \"INFO\")\n ENV = os.getenv(\"ENV\", \"local\")\n\n LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"filters\": {\n \"request_id\": {\"()\": RequestIDLogFilter},\n },\n \"formatters\": {\n \"standard\": {\n \"format\": \"%(asctime)s [%(levelname)s] %(request_id)s %(name)s %(funcName)s:%(lineno)d %(message)s\"\n }\n },\n \"handlers\": {\n \"file\": {\n \"level\": LOG_LEVEL,\n \"class\": \"logging.handlers.WatchedFileHandler\",\n \"filename\": f\"{LOGGING_DIR}/app.log\",\n \"formatter\": \"standard\",\n \"filters\": [\"request_id\"],\n },\n \"console\": {\n \"level\": \"INFO\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"standard\",\n \"filters\": [\"request_id\"],\n }\n },\n \"loggers\": {\n \"()\": {\n \"handlers\": [\"file\"],\n \"level\": \"ERROR\",\n \"propagate\": False\n }\n },\n \"root\": {\n \"handlers\": [\"file\", \"console\"],\n \"level\": \"INFO\"\n },\n }\n\n SECRET_KEY = os.getenv(\"SECRET_KEY\", \"36bf368sll2349skk3f1165565e7c71\")\n\n ENABLED_MODULES = ['api', 'nfl']\n DEBUG = False\n TESTING = False\n\n\n\nclass LocalConfig(Config):\n DEBUG = True\n TESTING = False\n\n\nclass DevelopmentConfig(Config):\n DEBUG = True\n TESTING = True\n\n\nclass QAConfig(Config):\n DEBUG = True\n TESTING = False\n\n\nclass TestConfig(Config):\n DEBUG = True\n TESTING = False\n\n\nclass ProductionConfig(Config):\n DEBUG = False\n\n\nconfig_by_name = dict(\n local=LocalConfig,\n dev=DevelopmentConfig,\n qa=QAConfig,\n test=TestConfig,\n prod=ProductionConfig,\n)\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"585928642","text":"import torch\nimport torch.nn as nn\nimport math\ndef conv(in_planes, out_planes, kernel_size=3, stride=1):\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=(kernel_size - 1) // 2,\n bias=False),\n nn.BatchNorm2d(out_planes),\n nn.LeakyReLU(0.1, inplace=True)\n )\n\ndef predict_disp(in_planes):\n return nn.Conv2d(in_planes, 1, kernel_size=3, stride=1, padding=1, bias=False)\n\n\ndef deconv(in_planes, out_planes):\n return nn.Sequential(\n nn.ConvTranspose2d(in_planes, out_planes, kernel_size=4, stride=2, padding=1, bias=True),\n nn.LeakyReLU(0.1, inplace=True)\n )\n\n\nclass DeepStereo(nn.Module):\n expansion = 1\n\n def __init__(self):\n super(DeepStereo, self).__init__()\n\n\n self.conv1 = conv(6, 64, kernel_size=7, stride=2)\n self.conv2 = conv(64, 128, kernel_size=5, stride=2)\n self.conv3 = conv(128, 256, kernel_size=5, stride=2)\n self.conv3_1 = conv(256, 256)\n self.conv4 = conv(256, 512, stride=2)\n self.conv4_1 = conv(512, 512)\n self.conv5 = conv(512, 512, stride=2)\n self.conv5_1 = conv(512, 512)\n self.conv6 = conv(512, 1024, stride=2)\n self.conv6_1 = conv(1024, 1024)\n\n self.deconv5 = deconv(1024, 512)\n self.deconv4 = deconv(1025, 256)\n self.deconv3 = deconv(769, 128)\n self.deconv2 = deconv(385, 64)\n\n self.predict_disp6 = predict_disp(1024)\n self.predict_disp5 = predict_disp(1025)\n self.predict_disp4 = predict_disp(769)\n self.predict_disp3 = predict_disp(385)\n self.predict_disp2 = predict_disp(193)\n\n self.upsampled_disp6_to_5 = nn.ConvTranspose2d(1, 1, 4, 2, 1, bias=False)\n self.upsampled_disp5_to_4 = nn.ConvTranspose2d(1, 1, 4, 2, 1, bias=False)\n self.upsampled_disp4_to_3 = nn.ConvTranspose2d(1, 1, 4, 2, 1, bias=False)\n self.upsampled_disp3_to_2 = nn.ConvTranspose2d(1, 1, 4, 2, 1, bias=False)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0,0.02 / n) # this modified initialization seems to work better, but it's very hacky\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, x):\n out_conv2 = self.conv2(self.conv1(x))\n out_conv3 = self.conv3_1(self.conv3(out_conv2))\n out_conv4 = self.conv4_1(self.conv4(out_conv3))\n out_conv5 = self.conv5_1(self.conv5(out_conv4))\n out_conv6 = self.conv6_1(self.conv6(out_conv5))\n\n disp6 = self.predict_disp6(out_conv6)\n disp6_up = self.upsampled_disp6_to_5(disp6)\n out_deconv5 = self.deconv5(out_conv6)\n\n concat5 = torch.cat((out_conv5, out_deconv5, disp6_up), 1)\n disp5 = self.predict_disp5(concat5)\n disp5_up = self.upsampled_disp5_to_4(disp5)\n out_deconv4 = self.deconv4(concat5)\n\n concat4 = torch.cat((out_conv4, out_deconv4, disp5_up), 1)\n disp4 = self.predict_disp4(concat4)\n disp4_up = self.upsampled_disp4_to_3(disp4)\n out_deconv3 = self.deconv3(concat4)\n\n concat3 = torch.cat((out_conv3, out_deconv3, disp4_up), 1)\n disp3 = self.predict_disp3(concat3)\n disp3_up = self.upsampled_disp3_to_2(disp3)\n out_deconv2 = self.deconv2(concat3)\n\n concat2 = torch.cat((out_conv2, out_deconv2, disp3_up), 1)\n disp2 = self.predict_disp2(concat2)\n\n if self.training:\n return disp2, disp3, disp4, disp5, disp6\n else:\n return disp2\n # Args:\n # input_size: The number of expected features in the input x\n # hidden_size: The number of features in the hidden state h\n # num_layers: Number of recurrent layers.\n # bias: If False, then the layer does not use bias weights b_ih and b_hh. Default: True\n # batch_first: If True, then the input and output tensors are provided as (batch, seq, feature)\n # dropout: If non-zero, introduces a dropout layer on the outputs of each RNN layer except the last layer\n # bidirectional: If True, becomes a bidirectional RNN. Default: False\n# - **input** (seq_len, batch, input_size): tensor containing the features of the input sequence.\n\ndef RNN(in_planes, out_planes):\n return nn.Sequential(\n nn.LSTM(input_size=in_planes,hidden_size=out_planes,bias=False),\n )\ndef predict_disp2(in_planes, out_planes=1):\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, bias=False)\n\ndef reduce_dimension(in_planes,out_planes = 2):\n return predict_disp2(in_planes,out_planes)\n\nclass DeepStereoRNN(nn.Module):\n expansion = 1\n\n def __init__(self,height, width):\n super(DeepStereoRNN, self).__init__()\n self.height = height\n self.width = width\n\n self.conv1 = conv(6, 64, kernel_size=7, stride=2)\n self.conv2 = conv(64, 128, kernel_size=5, stride=2)\n self.conv3 = conv(128, 256, kernel_size=5, stride=2)\n self.conv3_1 = conv(256, 256)\n self.conv4 = conv(256, 512, stride=2)\n self.conv4_1 = conv(512, 512)\n self.conv5 = conv(512, 512, stride=2)\n self.conv5_1 = conv(512, 512)\n self.conv6 = conv(512, 1024, stride=2)\n self.conv6_1 = conv(1024, 1024)\n\n self.rnn6_l = RNN(int(self.height/pow(2,6)), int(self.height/pow(2,6)))\n self.rnn6_r = RNN(int(self.height / pow(2, 6)), int(self.height / pow(2, 6)))\n\n self.rnn5_l = RNN(int(self.height/pow(2,5)), int(self.height/pow(2,5)))\n self.rnn5_r = RNN(int(self.height / pow(2, 5)), int(self.height / pow(2, 5)))\n\n self.rnn4_l = RNN(int(self.height/pow(2,4)), int(self.height/pow(2,4)))\n self.rnn4_r = RNN(int(self.height / pow(2, 4)), int(self.height / pow(2, 4)))\n\n self.rnn3_l = RNN(int(self.height/pow(2,3)), int(self.height/pow(2,3)))\n self.rnn3_r = RNN(int(self.height / pow(2, 3)), int(self.height / pow(2, 3)))\n\n self.rnn2_l = RNN(int(self.height / pow(2, 2)), int(self.height / pow(2, 2)))\n self.rnn2_r = RNN(int(self.height / pow(2, 2)), int(self.height / pow(2, 2)))\n\n\n\n self.deconv5 = deconv(1024, 512)\n self.deconv4 = deconv(1025, 256)\n self.deconv3 = deconv(769, 128)\n self.deconv2 = deconv(385, 64)\n\n self.predict_disp6_1 = reduce_dimension(1024)\n self.predict_disp5_1 = reduce_dimension(1025)\n self.predict_disp4_1 = reduce_dimension(769)\n self.predict_disp3_1 = reduce_dimension(385)\n self.predict_disp2_1 = reduce_dimension(193)\n\n self.predict_disp6 = predict_disp(2)\n self.predict_disp5 = predict_disp(2)\n self.predict_disp4 = predict_disp(2)\n self.predict_disp3 = predict_disp(2)\n self.predict_disp2 = predict_disp(2)\n\n self.upsampled_disp6_to_5 = nn.ConvTranspose2d(1, 1, 4, 2, 1, bias=False)\n self.upsampled_disp5_to_4 = nn.ConvTranspose2d(1, 1, 4, 2, 1, bias=False)\n self.upsampled_disp4_to_3 = nn.ConvTranspose2d(1, 1, 4, 2, 1, bias=False)\n self.upsampled_disp3_to_2 = nn.ConvTranspose2d(1, 1, 4, 2, 1, bias=False)\n\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0,\n 0.02 / n) # this modified initialization seems to work better, but it's very hacky\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.LSTM):\n stdv = 1.0 / math.sqrt(m.input_size * m.hidden_size)\n for weight in self.parameters():\n weight.data.uniform_(-stdv, stdv)\n # print(m)\n #predict_func = self.predict_disp6_1\n #rnn_l_func = self.rnn6_l\n #rnn_r_func = self.rnn6_r\n def rnn(self,x, predict_func, rnn_l_func, rnn_r_func):\n x = predict_func(x)\n\n x = x.transpose(0, 1)\n # (b, h, w)\n # rnn (w, b, h)\n rnn_l_in = x[0].transpose(0, 1).transpose(0, 2)\n rnn_r_in = x[1].transpose(0, 1).transpose(0, 2)\n\n inv_idx = torch.arange(rnn_l_in.size(0) - 1, -1, -1).long()\n inv_rnn_l_in = rnn_l_in[inv_idx]\n\n rnn_l_out, hidden = rnn_l_func(inv_rnn_l_in)\n rnn_r_out, hidden = rnn_r_func(rnn_r_in)\n\n # (f, w, b, h)\n rnn_out = torch.cat([rnn_l_out.unsqueeze(0), rnn_r_out.unsqueeze(0)])\n # (b,f,h,w) .t(0,1).t(0,2).t(2,3)\n out = rnn_out.transpose(0, 1).transpose(0, 2).transpose(2, 3)\n return out\n\n def forward(self, x):\n out_conv2 = self.conv2(self.conv1(x))\n out_conv3 = self.conv3_1(self.conv3(out_conv2))\n out_conv4 = self.conv4_1(self.conv4(out_conv3))\n out_conv5 = self.conv5_1(self.conv5(out_conv4))\n out_conv6 = self.conv6_1(self.conv6(out_conv5))\n\n out_rnn6 = self.rnn(out_conv6, self.predict_disp6_1,self.rnn6_l,self.rnn6_r)\n\n disp6 = self.predict_disp6(out_rnn6)\n disp6_up = self.upsampled_disp6_to_5(disp6)\n out_deconv5 = self.deconv5(out_conv6)\n\n concat5 = torch.cat((out_conv5, out_deconv5, disp6_up), 1)\n out_rnn5 = self.rnn(concat5, self.predict_disp5_1, self.rnn5_l, self.rnn5_r)\n\n disp5 = self.predict_disp5(out_rnn5)\n disp5_up = self.upsampled_disp5_to_4(disp5)\n out_deconv4 = self.deconv4(concat5)\n\n concat4 = torch.cat((out_conv4, out_deconv4, disp5_up), 1)\n out_rnn4 = self.rnn(concat4, self.predict_disp4_1, self.rnn4_l, self.rnn4_r)\n\n disp4 = self.predict_disp4(out_rnn4)\n disp4_up = self.upsampled_disp4_to_3(disp4)\n out_deconv3 = self.deconv3(concat4)\n\n concat3 = torch.cat((out_conv3, out_deconv3, disp4_up), 1)\n out_rnn3 = self.rnn(concat3, self.predict_disp3_1, self.rnn3_l, self.rnn3_r)\n\n disp3 = self.predict_disp3(out_rnn3)\n disp3_up = self.upsampled_disp3_to_2(disp3)\n out_deconv2 = self.deconv2(concat3)\n\n concat2 = torch.cat((out_conv2, out_deconv2, disp3_up), 1)\n out_rnn2 = self.rnn(concat2, self.predict_disp2_1, self.rnn2_l, self.rnn2_r)\n\n disp2 = self.predict_disp2(out_rnn2)\n\n if self.training:\n return disp2, disp3, disp4, disp5, disp6\n else:\n return disp2\n\ndef deepStereo(arch,height,width,path=None):\n \"\"\"\n Args:\n path : where to load pretrained network. will create a new one if not set\n \"\"\"\n if arch is 'DeepStereoRNN':\n model = DeepStereoRNN(height,width)\n else:\n model = DeepStereo()\n if path is not None:\n data = torch.load(path)\n if 'state_dict' in data.keys():\n model.load_state_dict(data['state_dict'])\n else:\n model.load_state_dict(data)\n return model\n\nif __name__ == '__main__':\n model = deepStereo()","sub_path":"DeepStereo/models/DeepStereo.py","file_name":"DeepStereo.py","file_ext":"py","file_size_in_byte":11228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"159261088","text":"#!/usr/bin/python2\n# -*- coding: utf-8 -*-\n\nimport urllib, re, subprocess\nfrom Tkinter import *\nimport tkFont\nimport sys\nif sys.getdefaultencoding() != 'utf-8':\n reload(sys)\n sys.setdefaultencoding('utf-8')\n\ndef get_content(url):\n html = urllib.urlopen(url).read()\n r = re.search('
([\\s\\S]*)
[\\s\\S]*
([\\s\\S]*?)
', html)\n s = r.group(1)\n s = s.replace('\\r\\n', '')\n intro = re.sub('(?m)\\s+$', '', re.sub('(?m)^\\s+', '', re.sub('<[^>]*>', '', s))) + '\\n'\n s = r.group(2)\n s = s.replace('\\r\\n', '')\n content = re.sub('(?m)^\\s+', '', s)\n content = re.sub('

', '\\n', content)\n content = re.sub('<[^(?:img)][^>]*>', '', content).replace(' ', ' ').replace('&', '&').replace('"', '\"')\n content = re.sub('', r'\\n\\1\\n', content)\n content = intro + content\n return content.splitlines()\n\ndef get_pic(contentList):\n global picList\n picList = []\n for t in contentList:\n if len(t) > 5:\n if t[0:4] == 'src=':\n picTuple = urllib.urlretrieve(t[5:-1])\n convert_pic(picTuple[0])\n pic = re.search('(.*\\.)[^\\.]*', picTuple[0]).group(1) + 'png'\n picList.append(pic)\n return picList\n\ndef convert_pic(pic):\n subprocess.call(['mogrify', '-format', 'png', pic])\n\nif __name__ == '__main__':\n\n global imglist\n imglist = []\n contentList = get_content(sys.argv[1])\n picList = get_pic(contentList)\n win = Tk()\n win.wm_title(sys.argv[2])\n win.wm_iconbitmap('@./icon.xbm')\n scrollbar = Scrollbar(win)\n scrollbar.pack(side=RIGHT, fill=Y)\n myfont = tkFont.Font(family=u\"文泉驿等宽微米黑\", size=15, weight='normal')\n text = Text(win, font=myfont, yscrollcommand=scrollbar.set)\n text.config(height=25, width=100)\n scrollbar.config(command=text.yview)\n for i in xrange(len(picList)):\n img = PhotoImage(file=picList[i])\n imglist.append(img)\n num = 0\n for t in contentList:\n if len(t) > 5:\n if t[0:4] != 'src=':\n text.insert(END, t + '\\n')\n else:\n text.image_create(END, image=imglist[num])\n text.insert(END, '\\n')\n num = num + 1\n else:\n text.insert(END, t + '\\n')\n \n text.pack()\n text.config(state=DISABLED)\n button = Button(win, text='Quit', fg='red', command=win.quit)\n button.pack(side=RIGHT)\n\n mainloop()\n","sub_path":"contents.py","file_name":"contents.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"60202873","text":"#! /usr/local/bin/pythonw\n'''\nName: Vidyadhar Thatte\nID: N10631080\n\nfile_name:REC03.py\n\nThe purpose of this program is to calculate the bill for an order of doughnuts and coffee cups and display the result\n\nconstraints:NONE\nassumptions:user enters whole number for number of cups and doughnuts\n'''\nfrom __future__ import print_function\nimport os \n\nCOFFEE_COST = 0.77\nDOUGHNUT_COST = 0.64\nTAX_RATE = 0.0846\n\n\ndef logo():\n '''prints the logo at the beginning'''\n print( \"----------------------------\" )\n print( \"The Coffee and Doughnut Shop\" )\n print( \"----------------------------\" )\n print( \" \" )\n\ndef order():\n '''This function takes the order'''\n coffeeNum = int(raw_input( \"enter the number of cups: \" ))\n doughnutNum = int(raw_input( \"enter the number of doughnuts: \" ))\n return (coffeeNum, doughnutNum)\n\n\ndef calculateBill( coffee_num, doughnut_num ):\n '''this function calculates the bill amount'''\n coffeeBill = float( coffee_num*COFFEE_COST )\n doughnutBill = float( doughnut_num*DOUGHNUT_COST )\n return ( coffeeBill, doughnutBill )\n \n\ndef calculateTax( coffee_bill, doughnut_bill ):\n '''calculates the tax'''\n coffeeTax = float( coffee_bill*COFFEE_COST )\n doughnutTax = float( doughnut_bill*DOUGHNUT_COST )\n totalTax = ( coffeeTax + doughnutTax )\n return totalTax\n\n\ndef amountOwed( coffee_bill, doughnut_bill, total_tax ):\n '''calculates the total amount to be paid'''\n owedAmt = float( ( coffee_bill + doughnut_bill ) - total_tax )\n return owedAmt\n \n\ndef printBill( coffee_num, doughnut_num, coffee_bill, doughnut_bill, total_tax, owed_amt ):\n '''prints the bill'''\n print( \"%i cups of coffee: $%.2f\"%( coffee_num, float( coffee_bill ) ) )\n print( \" %i dougnhuts: $%.2f\"%( ( doughnut_num ), float( doughnut_bill ) ) )\n print( \" tax: $%.2f\"%( total_tax ) )\n print( \" \" )\n print( \" Amount owed: $%.2f\"%( owed_amt ) )\n \n \ndef main():\n logo()\n ( coffee_num, doughnut_num ) = order()\n ( coffee_bill, doughnut_bill ) = calculateBill( coffee_num, doughnut_num )\n ( total_tax ) = calculateTax( coffee_bill, doughnut_bill )\n ( owed_amt ) = amountOwed( coffee_bill, doughnut_bill, total_tax )\n printBill( coffee_num, doughnut_num, coffee_bill, doughnut_bill, total_tax, owed_amt )\n\n\nif __name__ == '__main__':\n main()\n \n \n","sub_path":"Python/recitation/REC03.py","file_name":"REC03.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"337067458","text":"__author__ = 'Guenter Hipler '\n__copyright__ = 'Copyright (C) project swissbib, University Library Basel, Switzerland'\n__license__ = \"\"\"\n * http://opensource.org/licenses/gpl-2.0.php GNU General Public License\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License version 2,\n * as published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n \"\"\"\n__version__ = \"0.9, 10.3.2015\"\n__maintainer__ = 'Guenter Hipler'\n__email__ = 'guenter.hipler@unibas.ch'\n__status__ = \"in development\"\n__description__ = \"\"\"\n script to control the posting of documents which are weeded (shouldn't be part of the index) but are still part\n of the index (because of processes in the past)\n compare: https://github.com/swissbib/content2SearchDocs/issues/34\n \"\"\"\n\n\n\n\nimport os,sys, time, subprocess\nfrom datetime import datetime\nfrom optparse import OptionParser\n\n\n\nclass Post2SolrFrequent:\n\n\n def __init__(self):\n\n self.PROJECTDIR_DOCPROCESSING = \"/swissbib_index/solrDocumentProcessing/MarcToSolr\"\n self.PROJECTDIR_DOCPREPROCESSING = \"/swissbib_index/solrDocumentProcessing/FrequentInitialPreProcessing\"\n self.LOGDIR = self.PROJECTDIR_DOCPREPROCESSING + \"/log/update\"\n self.POSTJAR = self.PROJECTDIR_DOCPROCESSING + \"/dist/post.jar\"\n self.LOGFILE = open (self.LOGDIR + os.sep + self.currentDateTime() + \".post2SolrWeededDocs.log\",\"a\")\n self.LOGSPOST2SOLR = self.LOGDIR + \"/post2SOLR\" + self.currentDateTime() + \".log\"\n self.POSTDIRBASE_FROM = self.PROJECTDIR_DOCPROCESSING + \"/data/weedingDocumentsDeleteOnServer\"\n self.POSTDIRBASE_TO = self.PROJECTDIR_DOCPROCESSING + \"/data/outputfilesWeededProcess\"\n self.ARCHIVE_DIR = self.PROJECTDIR_DOCPROCESSING + \"/data/archiveFilesFrequent\"\n self.POST_URL = 'curl {0}?commit=false -H \"Content-Type: text/xml\" --data-binary @{1}'\n self.POST_URL_SUBPROCESS = '{0}?commit=false'\n self.POST_COMMIT = 'curl {0}?stream.body=%3Ccommit/%3E'\n\n self.PROJECTDIR_DOCPROCESSING = \"/swissbib_index/solrDocumentProcessing/MarcToSolr\"\n self.PROJECTDIR_DOCPROCESSING_MF = \"/swissbib_index/solrDocumentProcessing/MarcToSolr\"\n self.POSTCLIENTDIR = self.PROJECTDIR_DOCPROCESSING_MF + \"/dist/postclient\"\n\n self.METAFACTURE_HOME = self.POSTCLIENTDIR\n self.SOLR7_INDEX_LOGPATH = self.POSTCLIENTDIR + \"/log\"\n\n\n\n def preChecks(self,options):\n self.writeLogMessage(\"in preChecks..\")\n\n if not os.path.exists(self.PROJECTDIR_DOCPROCESSING):\n raise Exception(\"directory \" + self.PROJECTDIR_DOCPROCESSING + \" is missing\")\n\n if not os.path.exists(self.PROJECTDIR_DOCPREPROCESSING):\n raise Exception(\"directory \" + self.PROJECTDIR_DOCPREPROCESSING + \" is missing\")\n\n\n self.INPUT_DIR = options.inputDir\n self.writeLogMessage(\"base input directory: \" + self.INPUT_DIR)\n\n self.INDEX_CONFIG = options.configIndex\n self.writeLogMessage(\"index config: \" + self.INDEX_CONFIG)\n\n\n if not os.path.exists(self.POSTDIRBASE_TO):\n os.system(\"mkdir -p \" + self.POSTDIRBASE_TO)\n\n if not os.path.exists(self.LOGDIR):\n os.system(\"mkdir -p \" + self.LOGDIR)\n\n\n \"\"\"\n still todo\n\n #Check if frequent update process running: test lock file\n LOCKFILEFREQUENT=${PROJECTDIR_DOCPREPROCESSING}/.SOLRdocprocessingPID\n if [ -f $LOCKFILEFREQUENT ]\n then\n PID=`cat $LOCKFILEFREQUENT`\n ps -fp $PID >/dev/null 2>&1\n if [ $? -eq 0 ]\n then\n printf \"Frequent Update process %s is still running \\n\n posting to index and preparation of documents at\n the same time shouldn't be done. Exit\\n\" $PID >> ${LOGSPOST2SOLR}\n exit 0\n fi\n fi\n\n LOCKFILEPOSTING=${PROJECTDIR_DOCPROCESSING}/.SOLRPostingToIndexPID\n if [ -f $LOCKFILEPOSTING ]\n then\n PID=`cat $LOCKFILEPOSTING`\n ps -fp $PID >/dev/null 2>&1\n if [ $? -eq 0 ]\n then\n printf \"Posting to index process %s is still running \\n . Exit\\n\" $PID >> ${LOGSPOST2SOLR}\n exit 0\n fi\n fi\n\n\n #write PID in lock file\n echo $$ >$LOCKFILEPOSTING\n \"\"\"\n\n\n\n def moveDocuments(self):\n self.writeLogMessage(\"moving documents...\")\n os.system(\"mv \" + self.POSTDIRBASE_FROM + os.sep + \"*\" + \" \" + self.POSTDIRBASE_TO)\n\n\n def post2SOLR7MF(self):\n self.writeLogMessage(self.currentDateTime() + \" documents are now posted to SOLR 7 cluster...\")\n\n\n runIndexerClientMF = \"export METAFACTURE_HOME={MF_HOME}; cd {MF_HOME}; {MF_HOME}/sb_post2solr.sh -i {INPUT_DIR} -c {INDEX_CONFIG}\".format(\n MF_HOME=self.METAFACTURE_HOME,INPUT_DIR=self.INPUT_DIR, INDEX_CONFIG=self.INDEX_CONFIG\n )\n\n self.writeLogMessage(\"call for indexerclient: \" + runIndexerClientMF)\n os.system(runIndexerClientMF)\n self.writeLogMessage(self.currentDateTime() + \" finished posting documents to SOLR 7 cluster...\")\n\n\n def archiveAndZip(self):\n self.writeLogMessage(\" documents are now archived...\")\n os.system(\"tar zcf \" + self.ARCHIVE_DIR + os.sep + \"PostedWeededSolrDocuments\" + self.currentDateTime() + \"tar.gz \" + self.POSTDIRBASE_TO + os.sep + \"* --remove-files\")\n\n\n\n\n def __initialize(self):\n pass\n\n\n def currentDateTime(self,onlyDate = False, wait = False):\n if wait:\n time.sleep(5)\n\n if onlyDate:\n return datetime.now().strftime(\"%Y%m%d\")\n else:\n return datetime.now().strftime(\"%Y%m%d%H%M%S\")\n\n\n\n def writeLogMessage(self, message):\n self.LOGFILE.write(\"-->> \" + message + \" <<----\\n\" )\n self.LOGFILE.flush()\n\n def closeResources(self):\n\n if not self.LOGFILE is None:\n self.LOGFILE.write(\"closing logfile : {0} \\n\".format(self.currentDateTime()))\n self.LOGFILE.flush()\n self.LOGFILE.close()\n\n\n\n\n\nif __name__ == '__main__':\n\n usage = \"usage: %prog -i [INPUTDIR] \"\n\n #parser = OptionParser(usage=usage)\n parser = OptionParser(usage=usage)\n\n parser.add_option(\"-i\", \"--inputDir\", dest=\"inputDir\",\n help=\"[optional] base input dir which contains documents to be indexed \",\n default='/swissbib_index/solrDocumentProcessing/MarcToSolr/data/outputfilesWeededProcess')\n\n parser.add_option(\"-c\", \"--configIndex\", dest=\"configIndex\",\n help=\"[mandatory] index config properties \",\n default='../app.c1c2.properties')\n\n\n (options, args) = parser.parse_args()\n\n frequentPost = None\n #subprocess.call()\n #http://www.python-kurs.eu/os_modul_shell.php\n #https://docs.python.org/2/library/subprocess.html\n #http://stackoverflow.com/questions/4514751/pipe-subprocess-standard-output-to-a-variable\n #http://www.cyberciti.biz/faq/python-run-external-command-and-get-output/\n #http://eyalarubas.com/python-subproc-nonblock.html\n #http://www.daniweb.com/software-development/python/threads/281000/using-the-bash-output-in-python\n #https://cwiki.apache.org/confluence/display/solr/Uploading+Data+with+Index+Handlers\n #-> post in batch mit files!\n try:\n\n frequentPost = Post2SolrFrequent()\n frequentPost.writeLogMessage(\"pre checks: \" + frequentPost.currentDateTime())\n frequentPost.preChecks(options)\n frequentPost.writeLogMessage(\"moving documents \" + frequentPost.currentDateTime())\n frequentPost.moveDocuments()\n frequentPost.writeLogMessage(\"post 2 SOLR7: \" + frequentPost.currentDateTime())\n frequentPost.post2SOLR7MF()\n\n frequentPost.writeLogMessage(\"archiving documents: \" + frequentPost.currentDateTime())\n frequentPost.archiveAndZip()\n\n frequentPost.writeLogMessage(\"post to SOLR for weeded documents has finished: \" + frequentPost.currentDateTime())\n\n\n except Exception as argsError:\n if not frequentPost is None:\n frequentPost.writeLogMessage(\"Exception occured in control script: {0} \".format(argsError))\n\n finally:\n if not frequentPost is None:\n frequentPost.writeLogMessage(\"process finished at: {0} \".format(frequentPost.currentDateTime()))\n frequentPost.closeResources()\n\n\n\n","sub_path":"shellscripts/post2SolrWeedings.py","file_name":"post2SolrWeedings.py","file_ext":"py","file_size_in_byte":9092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"383518316","text":"from coroutil import coroutine\n\ndef simple_coroutine(a):\n print('-> coroutine started: a = ', a)\n b = yield a\n print('-> coroutine received: b = ', b)\n c = yield a+b\n print('-> Received: c = ', c)\n\n@coroutine\ndef averager():\n total = 0.0\n count = 0\n average = None\n while True:\n term = yield average\n total += term\n count += 1\n average = total/count","sub_path":"coroutines/simpleco.py","file_name":"simpleco.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"585983859","text":"\"\"\"\n例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)\n求最大值;\n\n\"\"\"\n\n\ndef findGreatestSumOfSubArray(array):\n max = array[0]\n for i, index in zip(array, range(len(array))):\n sum = 0\n for j in array[index:]:\n sum += j\n if sum > max:\n max = sum\n return max\n\n\ndef dynamic_answer(array):\n \"\"\"\n 动态规划法\n F(i):以array[i]为末尾元素的子数组的和的最大值,子数组的元素的相对位置不变\n F(i)=max(F(i-1)+array[i], array[i])\n\n res:所有子数组的和的最大值\n res=max(res,F(i))\n \"\"\"\n res = len(array) and max(array) # 寻找最强\n fi = 0 # 寻找更强\n for i in array:\n fi = max(i, fi + i)\n res = max(res, fi)\n return res\n","sub_path":"Python总结/PyExamples/niuke/findGreaterSumOfSubArray.py","file_name":"findGreaterSumOfSubArray.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"50251103","text":"#https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/\n'''\n因为已经是按照升序排列,就从头和从尾部两个flag\n如果和大于targe,尾部向前一位;如果小于,头部向后一位\n'''\nclass Solution(object):\n def twoSum(self, numbers, target):\n \"\"\"\n :type numbers: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n length = len(numbers)\n p, q = 0, length-1\n while p < q:\n if numbers[p] + numbers[q] > target:\n q -= 1\n continue\n elif numbers[p] + numbers[q] < target:\n p += 1\n continue\n elif numbers[p] + numbers[q] == target:\n return [p+1, q+1]\n return []\n","sub_path":"167/two-sum-ii-input-array-is-sorted.py","file_name":"two-sum-ii-input-array-is-sorted.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"650955114","text":"import csv\nimport sys\nimport array\n\n# helper to merge PT results into confluence table\n# source file is the actual all consolidated results from PT run\n# destination file is existing confluence table\n# output will be in new_ file - merges ave/error % from source file into dest file\n\nsourceFileName = sys.argv[1]\ndestFileName = sys.argv[2]\n\nsourceFile = open(sourceFileName, 'rb')\ndestFile = open(destFileName, 'rb')\ndestFileModified = open('new_' + destFileName, 'a')\n\nsrcCsvReader = csv.reader(sourceFile, delimiter=',', quotechar='|')\n\nnewResults = []\nfor row in srcCsvReader:\n newResults.append(row[2] + '|' + row[4] + \"|\")\n\ni = 0\nline = destFile.readline()\n\nlength = len(newResults)\n\nwhile line :\n newResult = \"N/A | N/A |\" if (length <= i) else newResults[i]\n modifiedLine = line.strip() + newResult\n destFileModified.write(modifiedLine + \"\\n\")\n line = destFile.readline()\n i = i + 1\n\n\n\n\n","sub_path":"eco-app/src/test/jmeter/python/addToConfluenceTable.py","file_name":"addToConfluenceTable.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"463754213","text":"from collections import namedtuple\r\n\r\n### set used to represent our NFA and DFA\r\nQ_N = []\r\nQ_D = []\r\nF_N = set()\r\n\r\n### definition of NFA state (using namedtuple)\r\n### num : state number\r\n### isFinal : whether this NFA state is in F_N or not\r\n### by_0 : a set of NFA state numbers (after reading input 0)\r\n### by_1 : a set of NFA state numbers (after reading input 1)\r\n### by_1 : a set of NFA state numbers (after reading input e, or without reading)\r\nNState = namedtuple(\"NState\", [\"num\", \"isFinal\", \"by_0\", \"by_1\", \"by_e\"])\r\n\r\n### definition of DFA state (defining a class)\r\n### id : unique number to identify each DFA state\r\n### subset : a set of NFA state numbers, which is used to represent this DFA state\r\n### isFinal : whether this DFA state is in F_D or not\r\n### by_0 : id of a DFA state to be reached when reading input 0\r\n### by_1 : id of a DFA state to be reached when reading input 1\r\n### isMarked : whether this DFA state is marked or not\r\nclass DState :\r\n def __init__(self):\r\n self.id = 0\r\n self.subset = set()\r\n self.isFinal = 0\r\n self.by_0 = 0\r\n self.by_1 = 0\r\n self.isMarked = False\r\n\r\n def set_id(self, id):\r\n self.id = id\r\n def set_subset(self, subset):\r\n self.subset = subset\r\n def set_isFinal(self, isFinal):\r\n self.isFinal = isFinal\r\n def set_by_0(self, by_0):\r\n self.by_0 = by_0\r\n def set_by_1(self, by_1):\r\n self.by_1 = by_1\r\n def set_isMarked(self, isMarked):\r\n self.isMarked = isMarked\r\n\r\n ### get an unique number from \"subset\" of this state and set \"id\" to this value\r\n def set_id_from_subset(self):\r\n result = 0\r\n for state_num in self.subset:\r\n result = result + pow(2, state_num)\r\n self.id = result\r\n\r\n### input\r\nN = int(input().strip())\r\nfor i in range(0, N) :\r\n line = input().strip()\r\n info_list = line.split()\r\n info_list[0] = int(info_list[0].strip()) # get \"num\" field value\r\n info_list[1] = int(info_list[1].strip()) # get \"isFinal\" field value\r\n\r\n set_0 = set()\r\n if (info_list[2].strip() != \"-\") :\r\n by_0_list = info_list[2].strip().split(\",\")\r\n for i in by_0_list:\r\n set_0.add(int(i))\r\n\r\n set_1 = set()\r\n if (info_list[3].strip() != \"-\") :\r\n by_1_list = info_list[3].strip().split(\",\")\r\n for i in by_1_list:\r\n set_1.add(int(i))\r\n\r\n set_e = set()\r\n if (info_list[4].strip() != \"-\"):\r\n by_e_list = info_list[4].strip().split(\",\")\r\n for i in by_e_list:\r\n set_e.add(int(i))\r\n\r\n info_list[2] = set_0 # get \"by_0\" field value\r\n info_list[3] = set_1 # get \"by_1\" field value\r\n info_list[4] = set_e # get \"by_e\" field value\r\n\r\n state = NState(*info_list) # make a NFA state from the field values we've gotten just before\r\n Q_N.append(state) # add that state to Q_N\r\n\r\n### construct F_N\r\nfor Q in Q_N :\r\n if (Q.isFinal == 1) :\r\n F_N.add(Q.num)\r\n\r\n### get E(q), where q is a NFA state\r\n### (a NFA state number) -> (a set of NFA state numbers)\r\ndef E(state_num) :\r\n state = Q_N[state_num]\r\n result = set()\r\n result.add(state_num)\r\n for next in state.by_e :\r\n if (next != state_num) :\r\n result = result | E(next)\r\n return result\r\n\r\n### get E(P), where P is a set of NFA states\r\n### (a set of NFA state numbers) -> (a set of NFA state numbers)\r\ndef E_set(state_num_set) :\r\n result = set()\r\n for state_num in state_num_set :\r\n result = result | E(state_num)\r\n return result\r\n\r\n### transiton from a set of NFA states to another set of NFA states (when reading 0)\r\n### (a set of NFA state numbers) -> (a set of NFA state numbers)\r\ndef transition_by_0(state_num_set) :\r\n result = set()\r\n for state_num in state_num_set :\r\n result = result | Q_N[state_num].by_0\r\n return result\r\n\r\n### transiton from a set of NFA states to another set of NFA states (when reading 1)\r\n### (a set of NFA state numbers) -> (a set of NFA state numbers)\r\ndef transition_by_1(state_num_set) :\r\n result = set()\r\n for state_num in state_num_set :\r\n result = result | Q_N[state_num].by_1\r\n return result\r\n\r\n\r\n\r\n### Initialization Step (Algorithm : 21 page in our textbook)\r\nDFA_set = set() # An id in this set indicates that the corresponding DFA state is in Q_D.\r\ninitial_state = DState()\r\ninitial_state.set_subset(E(0))\r\ninitial_state.set_id_from_subset()\r\ninitial_state.set_isMarked(True)\r\nQ_D.append(initial_state)\r\nDFA_set.add(initial_state.id)\r\n\r\n### Iteration (Algorithm : 21-22 pages in our textbook)\r\nisFound = False\r\nwhile (True) :\r\n isFound = False\r\n for Q in Q_D :\r\n if (Q.isMarked) : # a marked state P in Q_D is found\r\n isFound = True\r\n Q.set_isMarked(False) # unmark Q\r\n\r\n # for input 0\r\n R = DState()\r\n R.set_subset(E_set(transition_by_0(Q.subset)))\r\n R.set_id_from_subset()\r\n\r\n if R.id not in DFA_set : # If R is not in Q_D, add R as marked state to Q_D\r\n R.set_isMarked(True)\r\n Q_D.append(R)\r\n DFA_set.add(R.id)\r\n Q.set_by_0(R.id) # Q --(0)--> R\r\n\r\n # for input 1\r\n R = DState()\r\n R.set_subset(E_set(transition_by_1(Q.subset)))\r\n R.set_id_from_subset()\r\n if R.id not in DFA_set: # If R is not in Q_D, add R as marked state to Q_D\r\n R.set_isMarked(True)\r\n Q_D.append(R)\r\n DFA_set.add(R.id)\r\n Q.set_by_1(R.id) # Q --(1)--> R\r\n\r\n break\r\n\r\n if (isFound == False) :\r\n break\r\n\r\n### replace each value of id with actual DFA state number (by constructng a table)\r\ntable = dict()\r\nfor i, Q in enumerate(Q_D) :\r\n table[Q.id] = i\r\nfor i, Q in enumerate(Q_D) :\r\n Q.set_id(table[Q.id])\r\n Q.set_by_0(table[Q.by_0])\r\n Q.set_by_1(table[Q.by_1])\r\n\r\n### determine which DFA state is in F_D\r\nfor Q in Q_D :\r\n flag = False\r\n for q in Q.subset :\r\n if (q in F_N) :\r\n flag = True\r\n break\r\n if (flag) :\r\n Q.set_isFinal(1)\r\n else :\r\n Q.set_isFinal(0)\r\n\r\n### output\r\nprint(len(Q_D))\r\nfor i, Q in enumerate(Q_D) :\r\n print(i, Q.isFinal, Q.by_0, Q.by_1)\r\n\r\n'''\r\n### input 2\r\ninput_list = []\r\nM = int(input().strip())\r\nfor i in range(0, M) :\r\n line = input().strip()\r\n input_list.append(line)\r\n\r\n### transition function of our DFA\r\ndef next_state(state, c) :\r\n if (c == \"0\") :\r\n return state.by_0\r\n elif (c == \"1\") :\r\n return state.by_1\r\n\r\n### for each input string, print \"Yes\" if accept, \"No\" otherwise\r\nfor str in input_list :\r\n current = Q_D[0]\r\n for c in str :\r\n current = Q_D[next_state(current, c)]\r\n if (current.isFinal == 1) :\r\n print(\"Yes\")\r\n else :\r\n print(\"No\")\r\n'''","sub_path":"hw1/AT_1.py","file_name":"AT_1.py","file_ext":"py","file_size_in_byte":6941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"367612016","text":"# -*- coding: utf-8 -*-\n# MIT License\n#\n# Copyright (c) 2017 Kai Arulkumaran\n#\n# Permission 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#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n# ==============================================================================\nfrom collections import deque\nimport random\nimport cv2\nimport torch\nimport procgen\nimport numpy as np \n\nclass Env:\n\n def __init__(self, args):\n \n self.env= procgen.ProcgenEnv(1,args.game ,distribution_mode='easy')\n self.training = True # Consistent with model training mode\n self.actions=range(self.env.action_space.n)\n self.device = args.device\n self.window= args.history_length\n self.state_buffer = deque([], maxlen=args.history_length)\n\n def step(self, action):\n # Repeat action 4 times, max pool over last 2 frames\n frame_buffer = torch.zeros(2, 3, 64, 64, device=self.device)\n reward, done = 0, False\n for t in range(4):\n ob, rew, done,_ = self.env.step(np.array([action]))\n reward += rew\n if t == 2:\n frame_buffer[0] = self._get_state(ob)\n elif t == 3:\n frame_buffer[1] = self._get_state(ob)\n if done:\n break\n observation = frame_buffer.max(0)[0]\n self.state_buffer.append(observation)\n # Return state, reward, done\n return torch.stack(list(self.state_buffer), 0), reward, done\n\n def _reset_buffer(self):\n for _ in range(self.window):\n self.state_buffer.append(torch.zeros(3,64, 64 ,dtype=torch.float32, device=self.device))\n\n def _get_state(self,ob):\n state = ob['rgb'][0].transpose(2,0,1);\n return torch.tensor(state, dtype=torch.float32, device=self.device).div_(255)\n \n def reset(self):\n # Reset internals\n self._reset_buffer()\n observation = self._get_state(self.env.reset())\n # Process and return \"initial\" state\n self.state_buffer.append(observation)\n return torch.stack(list(self.state_buffer), 0)\n # Uses loss of life as terminal signal\n def train(self):\n self.training = True\n\n # Uses standard terminal signal\n def eval(self):\n self.training = False\n\n def action_space(self):\n return len(self.actions)\n\n def render(self):\n cv2.imshow('screen', self.ale.getScreenRGB()[:, :, ::-1])\n cv2.waitKey(1)\n\n def close(self):\n cv2.destroyAllWindows()\n","sub_path":"LocalProcEnv.py","file_name":"LocalProcEnv.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"31908351","text":"from Sprite.Plane import Plane\nfrom enum import Enum\n\n\n#敌机类\nclass Enemy(Plane):\n #敌机类型\n class Type(Enum):\n NoneType = 0\n EnemySoldier = 1\n EnemyLeader = 2\n EnemyGeneral = 3\n\n def __init__(self):\n super().__init__()\n\n #表明这个敌机属于哪个敌机类型\n self.type = Enemy.Type.NoneType\n\n #移动函数 传入下边界,敌机向下移动,当超过边界的时候,返回false,否则返回true\n def move(self, down):\n self.y += self.dy\n if self.y >= down:\n return False\n else:\n return True\n","sub_path":"Sprite/Enemy.py","file_name":"Enemy.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"490594193","text":"#\n# piUML - UML diagram generator.\n#\n# Copyright (C) 2010 - 2012 by Artur Wroblewski \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n\nfrom piuml.data import lca, lsb, MWalker, Align, Relationship, \\\n Element, PackagingElement, NodeGroup\nfrom piuml.layout.solver import *\nfrom piuml.style import Area\n\nfrom collections import OrderedDict\nimport logging\nlog = logging.getLogger('piuml.layout.cl')\n\n\nclass LayoutError(Exception):\n \"\"\"\n Layout exception.\n \"\"\"\n\n\nclass Layout(object):\n \"\"\"\n Layout processor.\n\n :Attributes:\n ast\n piUML source parsed tree.\n align\n Cache of alignment information per nodes common parent.\n lines\n Cache of lines with tail and head nodes as key.\n \"\"\"\n def __init__(self, ast):\n \"\"\"\n Create layout processor.\n \"\"\"\n super(Layout, self).__init__()\n self.ast = ast\n self.align = OrderedDict()\n self.lines = {}\n self.solver = Solver()\n\n\n def layout(self, solve=True):\n \"\"\"\n Layout diagram items on the diagram.\n\n :Parameters:\n solve\n Do not solve constraints if False (useful for layout unit\n testing).\n \"\"\"\n dab = DefaultAlignBuilder(self)\n cb = ConstraintBuilder(self)\n\n self._create_align_cache()\n dab.preorder(self.ast, reverse=True) # find default alignment\n self._create_align_groups()\n self._create_line_cache()\n cb.preorder(self.ast, reverse=True) # create constraints\n if solve:\n self.solver.solve()\n\n\n def _create_line_cache(self):\n \"\"\"\n Find all lines and create line length cache.\n \"\"\"\n lines = (l for l in self.ast if isinstance(l, Relationship))\n for l in lines:\n # find siblings\n t, h = l.tail, l.head\n t, h = level(self.ast, t, h)\n\n length = self.lines.get((t.id, h.id), 0) \n self.lines[t.id, h.id] = max(length, l.style.min_length)\n\n length = self.lines.get((h.id, t.id), 0) \n self.lines[h.id, t.id] = max(length, l.style.min_length)\n\n\n def _create_align_cache(self):\n \"\"\"\n Create alignment information cache - the aligment information is\n groupped by common nodes parent.\n \"\"\"\n align = (k for n in self.ast if n.name == 'layout' for k in n.data)\n\n for a in align:\n p = lca(self.ast, *a.nodes)\n if p not in self.align:\n self.align[p] = []\n self.align[p].append(a)\n\n\n def _create_align_groups(self):\n all_align = [(p, a) for p, a in self.align.items()]\n for parent, align_info in all_align:\n for a in list(align_info):\n p = lca(parent, *a.nodes)\n nodes = lsb(p, *a.nodes)\n if set(parent.children) == set(nodes):\n log.debug('no group for {}'.format(a))\n continue\n\n log.debug('group {}: {} -> {}'.format(a.id,\n tuple(n.id for n in a.nodes),\n tuple(n.id for n in nodes)))\n log.debug('group {}: remove {} from {}'.format(a.id,\n tuple(n.id for n in nodes),\n p.id))\n # fixme: reparent function?\n idx = p.children.index(nodes[0])\n for n in nodes:\n p.children.remove(n)\n n.parent = None\n\n log.debug('group {}: {}'.format(a.id,\n tuple(n.id for n in nodes)))\n ng = NodeGroup(a.id, children=nodes)\n # fixme: reparent function?\n ng.parent = p\n if idx < len(p):\n p.children.insert(idx, ng)\n else:\n p.children.append(ng)\n log.debug('group {} created in {}'.format(ng.id, p.id))\n\n\n\nclass DefaultAlignBuilder(MWalker):\n \"\"\"\n Default align builder.\n\n Walks through the piUML's AST and updates alignment cache with default\n alignment definition.\n\n :Attributes:\n ast\n piUML's AST.\n align\n Alignment cache.\n \"\"\"\n def __init__(self, layout):\n \"\"\"\n Create default alignment builder for the layout.\n \"\"\"\n self.ast = layout.ast\n self.align = layout.align\n\n\n def v_packagingelement(self, node):\n \"\"\"\n Update alignment cache with default alignment information.\n\n :Parameters:\n node\n The node for which default alignment has to be found.\n \"\"\"\n # get all alignment info\n if node not in self.align:\n self.align[node] = []\n\n align_info = self.align[node]\n\n used_nodes = djset()\n for a in align_info:\n used_nodes.add(level(node, *a.nodes))\n heads = set(used_nodes.heads())\n\n if __debug__:\n log.debug('{} used nodes: {}'.format(node.id, used_nodes))\n log.debug('{} defined align: {}'.format(node.id, align_info))\n\n default = Align('middle')\n default.nodes = [k for k in node\n if (k in heads or k not in used_nodes)\n and type(k) in (Element, PackagingElement)]\n # fixme: and k.can_align]])\n\n if __debug__:\n log.debug('{} default align: {}'.format(node.id, default))\n\n if len(default.nodes) > 1:\n # append default align at the end to have more intuitive\n # alignment groups\n align_info.append(default)\n\n v_diagram = v_packagingelement\n\n\n\nclass ConstraintBuilder(MWalker):\n def __init__(self, layout):\n \"\"\"\n Create constraints builder for the layout.\n \"\"\"\n super(ConstraintBuilder, self).__init__()\n self.ast = layout.ast\n self.solver = layout.solver\n self.align = layout.align\n self.lines = layout.lines\n\n\n def _align_nodes(self, node):\n \"\"\"\n Align children of the node.\n \n The default children alignment is determined. The children are\n aligned using both default and user defined alignment information.\n \"\"\"\n align_info = self.align.get(node, [])\n log.debug('align nodes of {}: {}'.format(node, align_info))\n\n for a in align_info:\n if __debug__:\n assert all(isinstance(k, Element) for k in a.nodes)\n assert a.type in ALIGN_CONSTRAINTS\n\n # get alignment and span functions\n f_a, f_s = ALIGN_CONSTRAINTS[a.type]\n f_a(self, *a.nodes)\n f_s(self, *level(node, *a.nodes))\n\n\n def v_element(self, node):\n \"\"\"\n Constraint element and its children using alignment information.\n\n :Parameters:\n node\n Node to constraint.\n \"\"\"\n self.size(node)\n if node.parent:\n self.within(node, node.parent)\n\n if isinstance(node, PackagingElement) and len(node) > 0:\n self._align_nodes(node)\n\n v_nodegroup = v_diagram = v_packagingelement = v_element\n\n def v_ielement(self, node):\n nodes = []\n left = None # find left node for hspan\n l_len = 0 # left side length\n right = None # find right node for hspan\n r_len = 0 # right side length\n\n # find nodes for alignment - the components in case of assembly\n for e in node.data['lines']:\n if e.head.cls != node.cls:\n if left is None:\n left = e.head\n l_len = max(l_len, e.style.min_length)\n nodes.append(e.head)\n if e.tail.cls != node.cls:\n if right is None:\n right = e.tail\n r_len = max(r_len, e.style.min_length)\n nodes.append(e.tail)\n\n left, right = level(self.ast, left, right)\n self.lines[left.id, right.id] = r_len + l_len\n self.lines[right.id, left.id] = r_len + l_len\n\n self.between(node, nodes)\n\n\n def add_c(self, c):\n self.solver.add(c)\n\n\n def size(self, node):\n self.add_c(MinSize(node.style))\n\n\n def within(self, node, parent):\n if __debug__:\n log.debug('{} within {}'.format(node.id, parent.id))\n ns = node.style\n mar = ns.margin\n ps = parent.style\n pad = ps.padding\n\n # put packaged elements between head and rest of compartements \n top = ps.compartment[0] + pad.top + pad.bottom\n bottom = ps.min_size.height - (top + pad.bottom)\n\n top = max(mar.top, top)\n right = max(mar.right, pad.right)\n bottom = max(mar.bottom, bottom)\n left = max(mar.left, pad.left)\n\n cpad = Area(top, right, bottom, left)\n self.add_c(Within(ns, ps, cpad))\n\n\n def between(self, node, nodes):\n ns = node.style\n others = [n.style for n in nodes]\n self.add_c(Between(ns, others))\n\n\n def top(self, *nodes):\n def f(k1, k2):\n if __debug__:\n log.debug('{} top {}'.format(k1.id, k2.id))\n self.add_c(TopEq(k1.style, k2.style))\n self._apply(f, nodes)\n\n def bottom(self, *nodes):\n def f(k1, k2):\n if __debug__:\n log.debug('{} bottom {}'.format(k1.id, k2.id))\n self.add_c(BottomEq(k1.style, k2.style))\n self._apply(f, nodes)\n\n def middle(self, *nodes):\n def f(k1, k2):\n if __debug__:\n log.debug('{} middle {}'.format(k1.id, k2.id))\n self.add_c(MiddleEq(k1.style, k2.style))\n self._apply(f, nodes)\n\n def left(self, *nodes):\n def f(k1, k2):\n if __debug__:\n log.debug('{} left {}'.format(k1.id, k2.id))\n self.add_c(LeftEq(k1.style, k2.style))\n self._apply(f, nodes)\n\n def right(self, *nodes):\n def f(k1, k2):\n if __debug__:\n log.debug('{} right {}'.format(k1.id, k2.id))\n self.add_c(RightEq(k1.style, k2.style))\n self._apply(f, nodes)\n\n def center(self, *nodes):\n def f(k1, k2):\n if __debug__:\n log.debug('{} center {}'.format(k1.id, k2.id))\n self.add_c(CenterEq(k1.style, k2.style))\n self._apply(f, nodes)\n\n\n def hspan(self, *nodes):\n def f(k1, k2):\n if __debug__:\n log.debug('{} hspan {}'.format(k1.id, k2.id))\n assert k1 is not k2, '{} vs. {}'.format(k1, k2)\n m = k1.style.margin.right + k2.style.margin.left\n l = self.lines.get((k1.id, k2.id), 0)\n self.add_c(MinHDist(k1.style, k2.style, max(l, m)))\n self._apply(f, nodes)\n\n\n def vspan(self, *nodes):\n def f(k1, k2):\n if __debug__:\n log.debug('{} vspan {}'.format(k1.id, k2.id))\n assert k1 is not k2, '{} vs. {}'.format(k1, k2)\n m = k1.style.margin.bottom + k2.style.margin.top\n l = self.lines.get((k1.id, k2.id), 0)\n self.add_c(MinVDist(k1.style, k2.style, max(l, m)))\n self._apply(f, nodes)\n\n\n def _apply(self, f, node):\n for k1, k2 in zip(node[:-1], node[1:]):\n f(k1, k2)\n\n\nclass djset(object):\n \"\"\"\n Disjoint set data structure.\n\n :Arguments:\n data\n Disjoint set partitions.\n \"\"\"\n def __init__(self, *args):\n \"\"\"\n Create disjoint set with all arguments added to the structure.\n\n :Parameters:\n *args\n List of items to be added.\n \"\"\"\n self.data = OrderedDict()\n self.update(*args)\n\n\n def update(self, *args):\n \"\"\"\n Update disjoint set with the arguments.\n\n :Parameters:\n *args\n List of items to be added.\n \"\"\"\n for a in args:\n self.add(a)\n\n\n def add(self, values):\n \"\"\"\n Add collection of values to the disjoint set.\n \"\"\"\n fv = values[0]\n values = set(values)\n data = enumerate(self.data.items())\n for i, (kv, vd) in data:\n if values & vd:\n vd.update(values)\n values = vd\n fv = kv\n break\n\n for i, (kv, vd) in data:\n if values & vd:\n values.update(vd)\n del self.data[kv]\n\n if fv not in self.data:\n self.data[fv] = values\n\n\n def heads(self):\n \"\"\"\n Get all partition heads.\n \"\"\"\n return self.data.keys()\n\n\n def __contains__(self, key):\n return any(key in v for v in self.data.values())\n\n\n def __len__(self):\n return sum(len(v) for v in self.data.values())\n\n\n def __nonzero__(self):\n return bool(self.data)\n\n\n def __repr__(self):\n return ', '.join('{}: {}'.format(k, v) for k, v in self.data.items())\n\n\n\ndef level(ast, *nodes):\n \"\"\"\n Given the collection of nodes find all nodes having the same direct\n ancestor.\n \"\"\"\n p = lca(ast, *nodes)\n return lsb(p, *nodes)\n\n\n# map align types to ConstraintBuilder methods \nALIGN_CONSTRAINTS = {\n 'top': (ConstraintBuilder.top, ConstraintBuilder.hspan),\n 'middle': (ConstraintBuilder.middle, ConstraintBuilder.hspan),\n 'bottom': (ConstraintBuilder.bottom, ConstraintBuilder.hspan),\n 'left': (ConstraintBuilder.left, ConstraintBuilder.vspan),\n 'center': (ConstraintBuilder.center, ConstraintBuilder.vspan),\n 'right': (ConstraintBuilder.right, ConstraintBuilder.vspan),\n}\n\n# vim: sw=4:et:ai\n","sub_path":"src/piuml/layout/cl.py","file_name":"cl.py","file_ext":"py","file_size_in_byte":14100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"345790672","text":"import pandas as pd\r\nfrom strsimpy.jaro_winkler import JaroWinkler\r\njarowinkler = JaroWinkler()\r\n\r\ndf_alltrails=pd.read_csv('../Datasets/er_alltrails.csv')\r\nuniq_np_at=set(df_alltrails['national_park'].unique())\r\n\r\n\r\n\r\n\r\ndf_other3=pd.read_csv(\"../Datasets/er_pe_npr_wiki.csv\")\r\n\r\n# ER sequoia\r\ndf_other3.loc[1,\"hotel_name\"]=df_other3[df_other3['id']==63]['hotel_name'].values\r\ndf_other3.loc[1,\"hotel_price\"]=df_other3[df_other3['id']==63]['hotel_price'].values\r\ndf_other3.loc[35,\"hotel_name\"]=df_other3[df_other3['id']==63]['hotel_name'].values\r\ndf_other3.loc[35,\"hotel_price\"]=df_other3[df_other3['id']==63]['hotel_price'].values\r\ndf_other3.drop(63, axis=0, inplace=True)\r\n\r\n# ER arches\r\ndf_other3.loc[23,\"hotel_name\"]=df_other3[df_other3['id']==64]['hotel_name'].values\r\ndf_other3.loc[23,\"hotel_price\"]=df_other3[df_other3['id']==64]['hotel_price'].values\r\ndf_other3.loc[9,\"hotel_name\"]=df_other3[df_other3['id']==64]['hotel_name'].values\r\ndf_other3.loc[9,\"hotel_price\"]=df_other3[df_other3['id']==64]['hotel_price'].values\r\ndf_other3.drop(64, axis=0, inplace=True)\r\n\r\n# ER wrangel\r\ndf_other3['name'].replace(\"Wrangell-St.Elias National Park\", \"Wrangell–St. Elias National Park and Preserve\", inplace=True)\r\n\r\n\r\n\r\nuniq_np_o3=set(df_other3['name'].unique())\r\n\r\n\r\n\r\n\r\nintersec=uniq_np_o3.intersection(uniq_np_at)\r\n\r\ndiff=uniq_np_o3.difference(intersec)\r\n\r\ner_dict={}\r\nfor i in list(diff):\r\n pn=i.split()[0]\r\n for j in list(uniq_np_at):\r\n if pn==j.split()[0]: #BLOCKING\r\n sim=jarowinkler.similarity(i,j)\r\n if i not in er_dict.keys():\r\n er_dict[i]=(j,sim)\r\n elif er_dict[i][1]my_thres:\r\n df_other3['name'].replace(key,value[0], inplace=True)\r\n diff.remove(key)\r\n\r\n\r\n\r\n# REMOVING THOSE NP NOT IN ALLTRAILS\r\nfor np in diff:\r\n df_other3.drop(df_other3.loc[df_other3['name']==np].index, inplace=True)\r\n\r\ndf_other3.rename(columns={\"name\":\"national_park\"}, inplace=True)\r\n\r\n#State spelling ER\r\ndf_other3['state'].replace('Tennesse', 'Tennessee', inplace=True)\r\n\r\n\r\ndf_other3.reset_index(inplace=True)\r\ndf_other3.drop('index', axis=1, inplace=True)\r\n\r\n\r\n\r\n\r\n\r\ndf_other3['id']=range(len(df_other3)) \r\ndf_other3.to_csv('../Datasets/er_other3.csv', index=False) \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# EXTRA\r\n\r\n\r\n# a=pd.DataFrame(df_alltrails['national_park'].value_counts())\r\n# a.reset_index(inplace=True)\r\n# a.rename(columns={'index':'name'}, inplace=True)\r\n\r\n\r\n# a['np']=list(a['name'].str.contains('National Park'))\r\n# a=sorted(uniq_np_o3)\r\n# b=a[a['np']==True]\r\n# b['id']=range(len(b))\r\n# b=b[['id','name']]\r\n\r\n# jarowinkler = JaroWinkler()\r\n# my_thres=0.69\r\n# list_id=[]\r\n# list_names=[]\r\n# dict_id={}\r\n\r\n# wikidata=b\r\n# df_final=df_other\r\n\r\n# for i in range(len(wikidata)):\r\n# for j in range(len(df_final)):\r\n# t=(wikidata.iloc[i,0], df_final.iloc[j,0]) \r\n# ans=jarowinkler.similarity(wikidata.iloc[i,1],df_final.iloc[j,1])\r\n \r\n# if ans>my_thres:\r\n# if wikidata.iloc[i,0] not in dict_id.keys():\r\n# dict_id[wikidata.iloc[i,0]]=(df_final.iloc[j,0],df_final.iloc[j,1],ans)\r\n# list_id.append(t)\r\n# list_names.append((wikidata.iloc[i,1],df_final.iloc[j,1]))\r\n# elif ans>dict_id[wikidata.iloc[i,0]][-1]:\r\n# list_id.remove((wikidata.iloc[i,0],dict_id[wikidata.iloc[i,0]][0]))\r\n# list_names.remove((wikidata.iloc[i,1],dict_id[wikidata.iloc[i,0]][1]))\r\n# dict_id[wikidata.iloc[i,0]]=(df_final.iloc[j,0],df_final.iloc[j,1],ans)\r\n# list_id.append(t)\r\n# list_names.append((wikidata.iloc[i,1],df_final.iloc[j,1]))\r\n# else:\r\n# pass \r\n","sub_path":"Part2_DataCleaning_ER_IE/er_other3.py","file_name":"er_other3.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"520155587","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2016-present, CloudZero, Inc. All rights reserved.\n# Licensed under the BSD-style license. See LICENSE file in the project root for full license information.\nfrom cloudzerocli.utils.aws import extract_trail_tags\nfrom cloudzerocli.utils.formatters import create_random_string, render_template\n\n\ndef test_create_random_string():\n rs1 = create_random_string()\n rs2 = create_random_string()\n\n assert rs1 != rs2\n\n\ndef test_extract_trail_tags():\n sample_data = {'ResourceTagList': [\n {'ResourceId': 'arn:aws:cloudtrail:us-east-1:111111111111:trail/cloudzero-prime-trail-1aot5',\n 'TagsList': [{'Key': 'cloudzero', 'Value': '2017-01-04T06:44:34.990909+00:00'}]}],\n 'ResponseMetadata': {'RequestId': '467b7fec-d45b-11e6-ae0f-99b7ac4d41c0', 'HTTPStatusCode': 200,\n 'HTTPHeaders': {'x-amzn-requestid': '467b7fec-d45b-11e6-ae0f-99b7ac4d41c0',\n 'content-type': 'application/x-amz-json-1.1',\n 'content-length': '190',\n 'date': 'Fri, 06 Jan 2017 21:58:37 GMT'}, 'RetryAttempts': 0}}\n\n result = extract_trail_tags(sample_data)\n assert result['cloudzero'] == '2017-01-04T06:44:34.990909+00:00'\n\n result = extract_trail_tags(\"bad data\")\n assert result is None\n\n\ndef test_render_template():\n input_data = '{\"mooshoo\": \"${pork}\", \"foo\": \"${bar}\", \"don\\'t\": \"${replace} me bro\"}'\n template_mapping = {'bar': 'HAMSTER', 'pork': 'WOO'}\n expected_output = '{\"mooshoo\": \"WOO\", \"foo\": \"HAMSTER\", \"don\\'t\": \"${replace} me bro\"}'\n\n assert expected_output == render_template(input_data, template_mapping)\n","sub_path":"test/unit/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"259592855","text":"import unittest\nimport pandas as pd \nimport numpy as np \nimport Entrepidus_generator\n\nclass TestEntrepidus(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n \n cls.df_sales_columns = ['Country', 'Diageo Customer ID', 'Diageo Customer Name', \n 'Invoice number', 'Type of Invoice', 'Invoice Date', 'Store code', 'Product Code', \n 'Quantity', 'Unit of measure', 'Total Amount WITHOUT TAX', 'Total Amount WITH TAX', \n 'Currency Code', 'Sales Representative Code']\n\n cls.df_pebac_product_reference_columns = ['Dist_Code', 'Distributor', 'Product_store_id', 'Country', 'Diageo_Sku',\n 'Relevant', 'Scale']\n\n cls.df_entrepidus_columns = ['Date', 'Store Number', 'Store Name', 'Chain', 'Supervisor', 'Region',\n 'Commune', 'Merchandiser', 'Chain SKU Code', 'Diageo SKU Code',\t'Desc Producto & Cód.',\n 'Category', 'Sub Category', 'Brand', 'Brand Variant', 'Unit Size', 'Unit Sold', \n 'Sales Value wotax', 'Sales Value wtax', 'Currency Code', 'Distributor', 'Country', \n 'Inventory Unit', 'Diageo_dist_auxiliar_column', 'Aux_product_relevance']\n\n cls.df_dist_names_columns = ['Distributor_country', 'Distributor_id', 'Distributor_name']\n\n cls.df_product_master_columns = ['Material', 'Description', \n 'Main Group', 'Subcategory', 'Brand', 'Brand Variant', 'Unit Size']\n \n cls.df_customer_catalogue_columns = ['Distributor_id', 'Store_id', 'Store_name']\n\n\n def test_getting_user_input(self):\n\n root_path = 'C:/Users/BACELKEN/Documents/Automation'\n catalogs_root_path = '../../../Catalogs/Traditional_STR/'\n product_by_distributor_file_name = 'pebac_ref_prod.xlsx'\n STR_indicator = False\n country = 'Argentina'\n\n sales_file_path = root_path + '/sales.txt'\n store_txt_file_path = root_path + '/store.txt'\n pebac_master_data_product_file_path = catalogs_root_path + 'Product_catalog/' + product_by_distributor_file_name\n product_master_path = catalogs_root_path + 'Product_catalog/product_master.xlsx'\n customer_catalog_file_path = catalogs_root_path + 'Customer_catalog/' + country + '_customer_catalog.xlsx'\n dist_names_file_path = catalogs_root_path + 'dist_names.xlsx'\n customer_filling_reference_file_path = catalogs_root_path + 'Customer_catalog/z_customer_reference.xlsx'\n\n entrepidus_stock_directory_path = '/'.join(root_path.split('/')[:-1])\n entrepidus_stock_file_path = entrepidus_stock_directory_path + '/Entrepidus_STOCK.csv'\n\n expected_paths = [sales_file_path, pebac_master_data_product_file_path, \n product_master_path, customer_catalog_file_path, dist_names_file_path, root_path,\n entrepidus_stock_file_path, store_txt_file_path, customer_filling_reference_file_path]\n\n \n self.assertEqual(Entrepidus_generator.getting_system_paths(root_path, \n country, STR_indicator), expected_paths) \n\n\n def test_sanitizing_sales_file(self):\n\n df_sales = pd.DataFrame(columns=self.df_sales_columns)\n \n df_sales['Quantity'] = ['55-', 37]\n df_sales['Total Amount WITH TAX'] = ['88-','']\n df_sales['Total Amount WITHOUT TAX'] = [77, '56.7-']\n df_sales['Product Code'] = ['0034', '877']\n df_sales['Store code'] = ['001111111111159', '123']\n df_sales.fillna('', inplace=True)\n\n df_expected = pd.DataFrame(columns=self.df_sales_columns)\n\n df_expected['Quantity'] = [-55, 37]\n df_expected['Total Amount WITH TAX'] = [-88.0, 0]\n df_expected['Total Amount WITHOUT TAX'] = [77, -56.7]\n df_expected['Product Code'] = ['34', '877']\n df_expected['Store code'] = ['111111111115', '123']\n df_expected.fillna('', inplace=True)\n\n pd.testing.assert_frame_equal(Entrepidus_generator.sanitizing_sales_file(df_sales), df_expected)\n\n\n def test_sanitizing_df_pebac_product_reference(self):\n\n df_pebac_product_reference = pd.DataFrame(columns=self.df_pebac_product_reference_columns)\n \n #Creating expected DataFrame\n df_expected = pd.DataFrame(columns=self.df_pebac_product_reference_columns)\n df_expected['Scale'] = [6.0, 1.0]\n\n #Setting values in Scale column - to be tested\n df_pebac_product_reference['Scale'] = [6, np.nan]\n #Simulating a special character in the DataFrame header\n df_pebac_product_reference.rename(columns={ 'Country':'�Country'}, inplace=True)\n\n pd.testing.assert_frame_equal(Entrepidus_generator.sanitizing_df_pebac_product_reference(df_pebac_product_reference), df_expected)\n\n \n def test_setting_df_entrepidus_and_sales(self):\n \n df_sales = pd.DataFrame(columns=self.df_sales_columns)\n df_entrepidus = pd.DataFrame(columns=self.df_entrepidus_columns)\n df_expected = pd.DataFrame(columns=self.df_entrepidus_columns)\n\n df_sales_update = {\n 'Country': 'Argentina',\n 'Total Amount WITHOUT TAX': -56.8,\n 'Total Amount WITH TAX': -17.0,\n 'Currency Code': 'ARS',\n 'Store code': '123',\n 'Invoice Date': '20200813',\n 'Product Code': '555444',\n 'Diageo Customer Name': 'Peñaflor',\n 'Quantity': 55.0,\n 'Inventory Unit': 0,\n 'Diageo Customer ID': '123456',\n 'Unit of measure': 'BTL'\n }\n df_sales = df_sales.append(df_sales_update, ignore_index=True)\n\n df_expected_to_be_updated = {\n 'Country': 'Argentina',\n 'Sales Value wotax': -56.8,\n 'Sales Value wtax': -17.0,\n 'Currency Code': 'ARS',\n 'Store Number': '123',\n 'Date': '20200813',\n 'Chain SKU Code': '555444',\n 'Distributor': 'Peñaflor',\n 'Unit Sold': 55.0,\n 'Inventory Unit': 0,\n 'Diageo_dist_auxiliar_column': '123456',\n 'Aux_unit_of_measure': 'btl'\n }\n df_expected = df_expected.append(df_expected_to_be_updated, ignore_index=True)\n \n pd.testing.assert_frame_equal(Entrepidus_generator.setting_df_entrepidus_and_sales(df_entrepidus, df_sales), df_expected, check_dtype=False)\n\n\n def test_assigning_dist_names_and_country_to_entrepidus(self):\n\n df_dist_names = pd.DataFrame(columns=self.df_dist_names_columns)\n df_entrepidus = pd.DataFrame(columns=self.df_entrepidus_columns)\n df_expected = pd.DataFrame(columns=self.df_entrepidus_columns)\n\n df_dist_names['Distributor_country'] = ['Peru']\n df_dist_names['Distributor_id'] = ['288039']\n df_dist_names['Distributor_name'] = ['Jandy']\n\n df_entrepidus['Diageo_dist_auxiliar_column'] = ['288039']\n df_entrepidus['Distributor'] = ['Jandiii']\n df_entrepidus['Country'] = ['PERIVIS']\n\n df_expected['Diageo_dist_auxiliar_column'] = ['288039']\n df_expected['Distributor'] = ['Jandy']\n df_expected['Country'] = ['Peru']\n\n returned_df_entrepidus = Entrepidus_generator.assigning_dist_names_and_country_to_entrepidus(df_entrepidus, df_dist_names)\n\n df_expected = df_expected.sort_index(axis=1, ascending=True)\n returned_df_entrepidus = returned_df_entrepidus.sort_index(axis=1, ascending=True)\n\n pd.testing.assert_frame_equal(returned_df_entrepidus, df_expected)\n\n\n def test_searching_diageo_sku(self):\n\n df_sales = pd.DataFrame(columns=self.df_sales_columns)\n df_pebac_product_reference = pd.DataFrame(columns=self.df_pebac_product_reference_columns)\n df_entrepidus = pd.DataFrame(columns=self.df_entrepidus_columns)\n df_expected = pd.DataFrame(columns=self.df_entrepidus_columns)\n \n df_pebac_product_reference['Dist_Code'] = ['123', '456']\n df_pebac_product_reference['Product_store_id'] = ['444', '777']\n df_pebac_product_reference['Diageo_Sku'] = ['XXX', 'LLL']\n df_pebac_product_reference['Relevant'] = ['Y', 'Y']\n df_pebac_product_reference['Scale'] = [4, 17]\n\n #Setting indexes to the DataFrame df_pebac_product_reference\n df_pebac_product_reference.set_index(['Dist_Code', 'Product_store_id'], inplace=True) \n df_pebac_product_reference = df_pebac_product_reference[~df_pebac_product_reference.index.duplicated(keep='first')]\n\n df_entrepidus['Diageo_dist_auxiliar_column'] = ['123', '456']\n df_entrepidus['Chain SKU Code'] = ['444', '777']\n\n df_expected['Diageo_dist_auxiliar_column'] = ['123', '456']\n df_expected['Chain SKU Code'] = ['444', '777']\n df_expected['Diageo SKU Code'] = ['XXX', 'LLL']\n df_expected['Aux_product_relevance'] = ['Y', 'Y']\n\n returned_df_entrepidus = Entrepidus_generator.searching_diageo_sku(df_sales, df_pebac_product_reference, df_entrepidus)\n\n df_expected = df_expected.sort_index(axis=1, ascending=True)\n returned_df_entrepidus = returned_df_entrepidus.sort_index(axis=1, ascending=True)\n\n pd.testing.assert_frame_equal(returned_df_entrepidus, df_expected)\n\n\n def test_filling_product_details(self):\n\n df_product_master = pd.DataFrame(columns=self.df_product_master_columns)\n df_entrepidus = pd.DataFrame(columns=self.df_entrepidus_columns)\n df_expected = pd.DataFrame(columns=self.df_entrepidus_columns)\n\n update_prod_master = {\n 'Material': '999', \n 'Description': 'Test description', \n 'Main Group': 'Cachaça', \n 'Subcategory': 'Pinga', \n 'Brand': 'Vodka',\n 'Brand Variant': 'Ardente',\n 'Unit Size': 650\n }\n\n #I am doing this way just to update the DataFrame through a dict\n df_product_master = df_product_master.append(update_prod_master, ignore_index=True)\n\n df_entrepidus['Diageo SKU Code'] = ['999']\n\n df_expected['Diageo SKU Code'] = ['999']\n df_expected['Desc Producto & Cód.'] = ['Test description']\n df_expected['Category'] = ['Cachaça']\n df_expected['Sub Category'] = ['Pinga']\n df_expected['Brand'] = ['Vodka']\n df_expected['Brand Variant'] = ['Ardente']\n df_expected['Unit Size'] = 650\n \n returned_df_entrepidus = Entrepidus_generator.filling_product_details(df_entrepidus, df_product_master)\n\n #Sorting columns to obtain same columns order to both parsed and expected DataFrames\n df_expected = df_expected.sort_index(axis=1, ascending=True)\n returned_df_entrepidus = returned_df_entrepidus.sort_index(axis=1, ascending=True)\n\n pd.testing.assert_frame_equal(returned_df_entrepidus, df_expected, check_dtype=False)\n\n\n def test_calculating_quantity(self):\n\n df_pebac_product_reference = pd.DataFrame(columns=self.df_pebac_product_reference_columns)\n df_entrepidus = pd.DataFrame(columns=self.df_entrepidus_columns)\n df_expected = pd.DataFrame(columns=self.df_entrepidus_columns)\n\n df_pebac_product_reference['Dist_Code'] = ['123']\n df_pebac_product_reference['Product_store_id'] = ['xxx']\n df_pebac_product_reference['Scale'] = 7.0\n\n df_entrepidus['Diageo_dist_auxiliar_column'] = ['123']\n df_entrepidus['Chain SKU Code'] = ['xxx']\n df_entrepidus['Unit Sold'] = 3.0\n\n df_expected['Diageo_dist_auxiliar_column'] = ['123']\n df_expected['Chain SKU Code'] = ['xxx']\n df_expected['Unit Sold'] = 21.0\n\n returned_df_entrepidus = Entrepidus_generator.calculating_quantity(df_entrepidus, df_pebac_product_reference)\n\n #Sorting columns to obtain same columns order to both parsed and expected DataFrames\n df_expected = df_expected.sort_index(axis=1, ascending=True)\n returned_df_entrepidus = returned_df_entrepidus.sort_index(axis=1, ascending=True)\n\n pd.testing.assert_frame_equal(returned_df_entrepidus, df_expected, check_dtype=False)\n\n\n def test_getting_store_name(self):\n df_customer_catalogue = pd.DataFrame(columns=self.df_customer_catalogue_columns)\n df_entrepidus = pd.DataFrame(columns=self.df_entrepidus_columns)\n df_expected = pd.DataFrame(columns=self.df_entrepidus_columns)\n\n df_customer_catalogue['Distributor_id'] = ['123']\n df_customer_catalogue['Store_id'] = ['xxx']\n df_customer_catalogue['Store_name'] = ['store ABC']\n\n df_entrepidus['Diageo_dist_auxiliar_column'] = ['123', '456']\n df_entrepidus['Store Number'] = ['xxx', 'yyy']\n df_entrepidus['Store Name'] = ['', '']\n\n df_expected['Diageo_dist_auxiliar_column'] = ['123', '456']\n df_expected['Store Number'] = ['xxx', 'yyy']\n df_expected['Store Name'] = ['store ABC', '0000 - NOT FOUND']\n\n expected_new_stores = ['456|yyy']\n\n res = Entrepidus_generator.getting_store_name(df_entrepidus, df_customer_catalogue)\n returned_df_entrepidus = res[0]\n returned_new_stores = res[1]\n\n #Sorting columns to obtain same columns order to both parsed and expected DataFrames\n df_expected = df_expected.sort_index(axis=1, ascending=True)\n returned_df_entrepidus = returned_df_entrepidus.sort_index(axis=1, ascending=True)\n\n pd.testing.assert_frame_equal(returned_df_entrepidus, df_expected, check_dtype=False)\n self.assertEqual(returned_new_stores, expected_new_stores)\n \n\nif __name__ == '__main__':\n unittest.main()","sub_path":"testing_entrepidus_generator.py","file_name":"testing_entrepidus_generator.py","file_ext":"py","file_size_in_byte":13430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"222766572","text":"import math\n# RSI starts\ndef RSI(close, t):\n n = len(close)\n rsi = []\n Ups = 0.0\n Downs = 0.0\n for j in range(t-1):\n rsi.append(-1)\n #Ye sabse pehla avgU/avgD find karne ke liye simple average vala step\n for i in range(1,t):\n diff = close[i] - close[i-1]\n if(diff > 0):\n Ups += diff\n else:\n Downs += (-diff)\n\n preU = Ups/t\n preD = Downs/t\n #simple average mil gaya to hamara pehla rsi bi mil gaya\n rs = preU/preD\n rsi.append( (100 - (100/(1+rs))) )\n #yaha se prev_avgUp vala loop\n Ups = 0.0\n Downs = 0.0\n for i in range(t,n):\n diff = close[i] - close[i-1]\n if(diff > 0):\n Ups = diff\n Downs = 0.0\n else:\n Downs = (-diff)\n Ups = 0.0\n u = (1/t)*Ups + ((t-1)/t)*preU\n d = (1/t)*Downs + ((t-1)/t)*preD\n preU = u #Update previous-Up and previous-Down\n preD = d\n rs = u/d\n rsi.append( (100 - (100/(1+rs))) ) #RSI for a particular date\n return rsi\n#RSI Ends Here\n\n#SMA starts here\ndef SMA(close, t):\n mas = []\n for i in range(t - 1):\n mas.append(-1)\n for i in range(len(close) - t + 1):\n summ = 0\n for j in range(i, t + i):\n summ = summ + close[j]\n meann = summ / t\n mas.append(meann)\n return mas\n#SMA Ends here\n\n# Weighted Moving Average(WMA) Starts Here\n# Reference for code is taken from tradingview\ndef WMA(close, t):\n wma = []\n for i in range(t - 1):\n wma.append(-1)\n for i in range(t-1, len(close)):\n norm = 0.0\n summ = 0.0\n for j in range(0, t):\n weight = (t-j)*t\n norm = norm + weight\n summ = summ + (close[i-j]*weight)\n wma.append(summ/norm)\n return wma\n# WMA Ends Here\n\n# Rolling Moving Average(RMA) Starts here\ndef RMA(close, t):\n rma = []\n sma = SMA(close, t)\n for i in range(t):\n rma.append(sma[i])\n for i in range(t, len(close)):\n rma.append( (rma[i-1]*(t-1) + close[i])/t )\n return rma\n# RMA Ends here\n\n# Rate Of Change(ROC) Starts here\ndef ROC(close, t):\n roc = []\n for i in range(t-1):\n roc.append(-1)\n for i in range(t-1, len(close)):\n sum = 100*(close[i]-close[i-t])/close[i-t]\n roc.append(sum)\n return roc\n# ROC Ends here\n\n#EMA Starts Here\ndef EMA(close, t):\n sma= 0.0\n n = len(close)\n for i in range(t):\n sma += close[i]\n sma = sma/(t)\n ema = []\n for j in range(t-1):\n ema.append(-1)\n ema.append(sma)\n m = 2/(t+1)\n for i in range(t,n):\n e = close[i]*m + ema[i-1]*(1-m)\n ema.append(e)\n return ema\n#EMA ends here\n\n# From Here Pivot Points\nfinal_high = []\nfinal_low = []\nfinal_close = []\nfinal_counts = []\n\ndef assigning(countt,high_maxx,low_minn,closee):\n final_counts.append(countt)\n final_high.append(high_maxx)\n final_low.append(low_minn)\n final_close.append(closee)\n\ndef pivot_points(close,high,low,date):\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n final_high.clear()\n final_low.clear()\n final_close.clear()\n final_counts.clear()\n\n for i in range(len(close)):\n date_st = str(date[i])\n if date_st[3] == \"0\" and date_st[4] == \"1\":\n if flag == 12:\n assigning(count,high_max,low_min,close[i-1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min :\n low_min = low[i]\n flag = 1\n count += 1\n elif date_st[3] == \"0\" and date_st[4] == \"2\":\n if flag == 1:\n assigning(count,high_max,low_min,close[i-1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 2\n count += 1\n elif date_st[3] == \"0\" and date_st[4] == \"3\":\n if flag == 2:\n assigning(count, high_max, low_min, close[i - 1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 3\n count += 1\n elif date_st[3] == \"0\" and date_st[4] == \"4\":\n if flag == 3:\n assigning(count, high_max, low_min, close[i - 1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 4\n count += 1\n elif date_st[3] == \"0\" and date_st[4] == \"5\":\n if flag == 4:\n assigning(count, high_max, low_min, close[i - 1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 5\n count += 1\n elif date_st[3] == \"0\" and date_st[4] == \"6\":\n if flag == 5:\n assigning(count, high_max, low_min, close[i - 1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 6\n count += 1\n elif date_st[3] == \"0\" and date_st[4] == \"7\":\n if flag == 6:\n assigning(count, high_max, low_min, close[i - 1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 7\n count += 1\n elif date_st[3] == \"0\" and date_st[4] == \"8\":\n if flag == 7:\n assigning(count, high_max, low_min, close[i - 1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 8\n count += 1\n elif date_st[3] == \"0\" and date_st[4] == \"9\":\n if flag == 8:\n assigning(count, high_max, low_min, close[i - 1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 9\n count += 1\n elif date_st[3] == \"1\" and date_st[4] == \"0\":\n if flag == 9:\n assigning(count, high_max, low_min, close[i - 1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 10\n count += 1\n elif date_st[3] == \"1\" and date_st[4] == \"1\":\n if flag == 10:\n assigning(count, high_max, low_min, close[i - 1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 11\n count += 1\n elif date_st[3] == \"1\" and date_st[4] == \"2\":\n if flag == 11:\n assigning(count, high_max, low_min, close[i - 1])\n flag = 0\n count = 0\n high_max = 0\n low_min = 320000\n else:\n if high[i] > high_max:\n high_max = high[i]\n if low[i] < low_min:\n low_min = low[i]\n flag = 12\n count += 1\n\n pivot_point = []\n resistance_1 = []\n resistance_2 = []\n resistance_3 = []\n support_1 = []\n support_2 = []\n support_3 = []\n pivot_point_pr = []\n resistance_1_pr = []\n resistance_2_pr = []\n resistance_3_pr = []\n support_1_pr = []\n support_2_pr = []\n support_3_pr = []\n\n for i in range(len(final_counts)):\n pivot_point_pr.append((final_high[i]+final_low[i]+final_close[i])/3)\n support_1_pr.append((2*pivot_point_pr[i])-final_high[i])\n resistance_1_pr.append((2*pivot_point_pr[i])-final_low[i])\n support_2_pr.append(pivot_point_pr[i] - final_high[i] + final_low[i])\n resistance_2_pr.append(pivot_point_pr[i] + final_high[i] - final_low[i])\n support_3_pr.append(support_1_pr[i] - final_high[i] + final_low[i])\n resistance_3_pr.append(resistance_1_pr[i] + final_high[i] - final_low[i])\n for i in range(final_counts[0]):\n pivot_point.append(0)\n resistance_1.append(0)\n resistance_2.append(0)\n resistance_3.append(0)\n support_1.append(0)\n support_2.append(0)\n support_3.append(0)\n for i in range(1, len(final_counts)):\n for j in range(final_counts[i]):\n pivot_point.append(pivot_point_pr[i])\n resistance_1.append(resistance_1_pr[i])\n resistance_2.append(resistance_2_pr[i])\n resistance_3.append(resistance_3_pr[i])\n support_1.append(support_1_pr[i])\n support_2.append(support_2_pr[i])\n support_3.append(support_3_pr[i])\n return pivot_point,support_1,support_2,support_3,resistance_1,resistance_2,resistance_3\n\n#Pivot Points Ends Here\n\n#MACD Starts From Here\ndef EMA_d(close, t):\n sma = 0.0\n n = len(close)\n for i in range(t):\n sma += close[i]\n sma = sma / (t)\n ema = []\n ema.append(sma)\n m = 2 / (t + 1)\n for i in range(t, n):\n e = close[i] * m + ema[i - t] * (1 - m)\n ema.append(e)\n return ema\n\n\ndef EMA_MACD(t, macd):\n sma = 0.0\n n = len(macd)\n for i in range(t):\n sma += macd[i]\n sma = sma / (t)\n ema = []\n ema.append(sma)\n m = 2 / (t + 1)\n for i in range(t, n):\n e = macd[i] * m + ema[i - t] * (1 - m)\n ema.append(e)\n return ema\n\n\ndef MACD(close, x, y, z):\n val_pr = EMA_d(close, x)\n val2_pr = EMA_d(close, y)\n val = []\n val2 = []\n for i in range(x - 1):\n val.append(0)\n for i in range(y - 1):\n val2.append(0)\n\n for i in range(len(val_pr)):\n val.append(val_pr[i])\n for i in range(len(val2_pr)):\n val2.append(val2_pr[i])\n\n macd_line = []\n macd_histogram = []\n signal_line = []\n\n for i in range(len(val)):\n macd_line.append(val[i] - val2[i])\n\n for i in range(z - 1):\n signal_line.append(0)\n\n signal_line_pr = EMA_MACD(z, macd_line)\n\n for i in range(len(signal_line_pr)):\n signal_line.append(signal_line_pr[i])\n\n for i in range(len(val)):\n macd_histogram.append(macd_line[i] - signal_line[i])\n\n return macd_line, signal_line, macd_histogram\n\n#MACD Ends Here\n\n#Bollinger Band Starts Here\ndef bollinger_band(close,n,r):\n up = []\n lo = []\n ma = []\n for i in range(n-1):\n up.append(0)\n lo.append(0)\n ma.append(0)\n for i in range(len(close)-n+1):\n sum = 0\n sqr = 0\n for j in range(i, n+i):\n sum = sum + close[j]\n meann = sum/n\n ma.append(sum / n)\n for z in range(i, n+i):\n sq = close[z]-meann\n sqr = sqr + (sq*sq)\n varr = sqr/n\n std = math.sqrt(varr)\n up.append(meann + (r*std))\n lo.append(meann - (r*std))\n return up,lo,ma\n\n#Bollinger Band Ends here\n\n#Fibonacci Retracement start here\ndef fib_retracement(p1, p2):\n list =[0, 0.236, 0.382, 0.5, 0.618, 0.786, 1, 1.618, 2.618, 3.618, 4.236]\n dict = {}\n dist = p2 - p1\n for val in list:\n dict[str(val) ] = (p2 - dist*val)\n return dict\n#Fibonacci Retracement ends here\n\n#Money Flow Index starts here\ndef MFI(high,low,close,volume,t):\n mfi = [] #money flow index\n typ = [] #typical price\n raw_money = [] #raw money flow\n mfr = [] #money flow ratio\n for i in range(t):\n mfi.append(-1)\n mfr.append(-1)\n ind = 1\n typ.append( (high[0] + low[0] + close[0]) / 3)\n raw_money.append(typ[0]*volume[0]) #first time assume it is positive\n\n for i in range(1,len(close)):\n typ.append( (high[i] + low[i] + close[i])/3 )\n if(typ[ind] > typ[ind-1]):\n raw_money.append( typ[i]*volume[i] )\n else:\n raw_money.append( -typ[i]*volume[i] )\n ind = ind + 1\n for i in range(t, len(close)):\n positive_flows = 0.0\n negative_flows = 0.0\n for j in range(t):\n if(raw_money[i-j] > 0):\n positive_flows += raw_money[i-j]\n else:\n negative_flows += -raw_money[i-j]\n if(negative_flows != 0): ratio = positive_flows/negative_flows\n else: ratio = positive_flows\n mfr.append( ratio )\n mfi.append( (100- (100/(1+ratio)) ) )\n return mfi\n#Money Flow Index ends here\n\n\n\n# Stochastic Rsi Starts ahi thi\n\n\ndef Rsi_high(high, t):\n\n rsi_H = []\n for i in range(0,t-1):\n rsi_H.append(-1)\n\n\n i = 0\n for j in range(t, len(high)+1):\n HIGH = high[i:t]\n rsi_H.append(max(HIGH))\n t += 1\n i += 1\n\n return rsi_H\n\n\n\ndef Rsi_low(low, t):\n\n rsi_L = []\n for i in range(0,t-1):\n rsi_L.append(-1)\n\n i = 0\n\n for j in range(t, len(low) + 1):\n if low!=-1:\n LOW = low[i:t]\n rsi_L.append(min(LOW))\n t += 1\n i += 1\n\n return rsi_L\n\ndef stoch(source, high, low, t,rt,close):\n rsi_high = []\n rsi_low = []\n\n rsi_low = Rsi_low(high, t)\n rsi_high = Rsi_high(low, t)\n\n count=0\n for x in rsi_low:\n if(x==-1):\n count+=1\n\n Stochastic=[]\n for i in range(0,count):\n Stochastic.append(-1)\n\n cnt=0\n rsi=RSI(close,rt)\n for i in range(count,(len(source))):\n y=(rsi[i]-rsi_low[i])\n z=(rsi_high[i]-rsi_low[i])\n w=y/z\n Stochastic.append(w*100)\n cnt+=1\n\n\n return Stochastic,count\n\ndef sma(rsi,t,count):\n x=[]\n cnt=0\n for i in range(0,count):\n x.append(-1)\n cnt+=1\n for i in range(t-1):\n x.append(-1)\n cnt += 1\n\n cnt+=1\n cnt1=cnt\n\n for i in range(cnt,len(rsi)+1):\n temp=rsi[cnt1-t:cnt1]\n sum=0.0000\n for j in temp:\n sum=sum+j\n\n sum=sum/t\n cnt1+=1\n del temp\n x.append(sum)\n\n\n return x\n\n\ndef S_RSI(Close, t, K, D, rt):\n # rt=rsi peroid\n # t=Stochastic Rsi Period\n # K=main line\n # D= moving average of K\n\n rsi =RSI(Close, rt)\n Stochstic,count=stoch(rsi, rsi, rsi,t,rt,Close)\n k = sma(Stochstic,K,count)\n d = sma(k,D,count)\n\n return k,d\n\n #k= blue line on trading view\n #d= orange line on trading view\n\n# Stochastic Rsi Ends Here\n\n#Ichimoku Cloud Starts ahi thi\n\ndef IC_high(high,t):\n\n ic_high = []\n for i in range(0,t-1):\n ic_high.append(-1)\n\n i = 0\n for j in range(t, len(high)+1):\n HIGH = high[i:t]\n ic_high.append(max(HIGH))\n t += 1\n i += 1\n\n return ic_high\n\ndef IC_low(low,high,t):\n\n ic_low = []\n for i in range(0,t-1):\n ic_low.append(-1)\n\n i = 0\n for j in range(t, len(high)+1):\n LOW= low[i:t]\n ic_low.append(min(LOW))\n t += 1\n i += 1\n\n return ic_low\n\ndef average(ic_high,ic_low,high):\n cnt=0\n cnt1=0\n cnt2=0\n avg=[]\n for i in ic_high:\n if i == -1:\n cnt1=cnt1+1\n\n for i in ic_low:\n if i == -1:\n cnt2=cnt2+1\n\n if cnt2>cnt1:\n cnt=cnt2\n else:\n cnt=cnt1\n\n for i in range(0,cnt):\n avg.append(-1)\n\n for i in range (cnt,len(high)):\n avg.append((ic_high[i]+ic_low[i])/2)\n\n return avg\n\ndef lag(close,time):\n lag1=[]\n\n for i in close:\n lag1.append(i)\n\n return lag1\n\ndef Icloud(high,low,close,c_period,b_period,span_b_period,lag_span_period):\n\n #c_line is conversion line also known as Tenken-san\n #b_line is base line also known as kijun-san\n #other all are time peroids\n\n c_high=IC_high(high,c_period)\n c_low=IC_low(low,high,c_period)\n conversion_line=average(c_high,c_low,high)\n\n b_high=IC_high(high,b_period)\n b_low=IC_low(low,high,b_period)\n base_line=average(b_high,b_low,high)\n\n span_a=average(conversion_line,base_line,high)\n\n span_b_high = IC_high(high,span_b_period)\n span_b_low = IC_low(low,high,span_b_period)\n span_b= average(span_b_high,span_b_low,high)\n\n lag_span=lag(close,lag_span_period)\n\n return conversion_line,base_line,span_a,span_b,lag_span\n #the last array of all values is matching with last value on trading view.\n\n#Ichimoku Cloud Ends Here\n\n#ATR Starts Ahi Thi\n\ndef tr(high,low,close):\n X=[]\n Y=[-1]\n Z=[-1]\n TR=[-1]\n for i in range(len(low)):\n X.append(high[i]-low[i])\n\n for i in range(1,len(high)):\n Y.append(abs(high[i]-close[i-1]))\n\n for i in range(1,len(low)):\n Z.append(abs(low[i]-close[i-1]))\n\n for i in range(1,len(low)):\n TR.append(max(X[i],Y[i],Z[i]))\n\n return TR\n\ndef ATR(source,t):\n#Source Might be EITHER EMA,RMA,SMA OR WMA.\n#At the moment WMA & RMA isn't added so it will return None\n#T Is Time Period\n#take source as a string\n\n TR=tr()\n\n source=source.upper()\n\n if source==\"EMA\":\n ema=EMA(TR,t)\n elif source == \"RMA\":\n rma=RMA(TR,t)\n elif source == \"WMA\":\n wma=WMA(TR,t)\n else:\n sma=SMA(TR,t)\n\n #for returning\n if source==\"EMA\":\n return ema\n elif source == \"RMA\":\n return rma\n elif source == \"WMA\":\n return wma\n else:\n return sma\n\n#ATR Ends Here\n\n#William %R Starts Ahi Thi\n\ndef WILLIAM_R(source,t,high,low):\n\n W_R=[]\n\n for i in range(0,t-1):\n W_R.append(-1)\n\n # hh is highest high\n #ll is lowest low\n hh=Rsi_high(high,t)\n ll=Rsi_low(low,t)\n\n for i in range(t-1,len(source)):\n x=source[i]-hh[i]\n y=hh[i]-ll[i]\n z=x/y\n z=z*(100)\n W_R.append(z)\n\n\n return W_R\n\n\n#William %R Ends Here\n\n#Super Trend Starts Ahi Thi\n#tx3 uses rma in atr & super trend uses atr so if you want to check use rma in atr in tx3\ndef ST(s_atr,t_atr,mul,high,low,close):\n #s_atr Is Source for ATR & t_atr is Time Period For ATR\n #mul is multiplier\n up=[]\n down=[]\n f_down=[]\n f_up=[]\n st=[]\n cnt=0\n atr=ATR(s_atr,t_atr)\n for i in range(0,t_atr-1):\n up.append(-1)\n f_up.append(-1)\n down.append(-1)\n f_down.append(-1)\n st.append(-1)\n cnt+=1\n for i in range(cnt,len(high)):\n x=high[i]\n y=low[i]\n z=(x+y)/2\n w=atr[i]*mul\n up.append(z+w)\n down.append(z-w)\n for i in range(cnt,len(close)):\n\n if (i!=len(close)):\n if ( (up[i] < f_up[i-1]) or (close[i-1] > f_up[i-1])):\n f_up.append(up[i])\n else:\n f_up.append(f_up[i-1])\n\n if ( (down[i]>f_down[i-1]) or (close[i-1]f_up[i])):\n st.append(f_down[i])\n elif((st[i-1]==f_down[i-1]) and (close[i]>f_down[i])):\n st.append(f_down[i])\n elif((st[i-1]==f_down[i-1]) and (close[i] -2]\nelse:\n \n real_training_data_set = sorted(json_data, key=lambda x: (x['id']), reverse=False) \n real_training_data_set = [item for item in real_training_data_set[:i_partial_count] if item['y_val'] > -2]\n \n \nreal_training_data_set_sorted = sorted(real_training_data_set, key=lambda x: (x['id']), reverse=False)\n\n\nlogger.info(\"len of real_training_data_set_sorted = %d \", len(real_training_data_set_sorted))\n\ntmp_list_X_raw = []\ntmp_list_Y_raw = []\ntmp_files_list_raw = []\ntmp_pure_files_list_raw = []\n\n\nfor data_point in real_training_data_set_sorted:\n \n #tmp_list_X_raw.append(data_point['text'])\n\t\n i_se = data_point['i_sentiment_estimate']\n \n str_st = data_point['text']\n \n if b_use_original_text:\n #str_st = data_point['text_simple_cleanup']\n str_st = data_point['text_letter_and_num']\n else:\n str_st = data_point['senti_text']\n \n if i_se >= 15:\n str_st += \" . imdbsuperpositive \"\n elif i_se < 15 and i_se >= 5:\n str_st += \" . imdbstrongpositive \"\n elif i_se < 5 and i_se > -5:\n pass\n elif i_se <= -5 and i_se > -15:\n str_st += \" . imdbstrongnegitive \"\n elif i_se <= -15:\n str_st += \" . imdbsupernegitive \"\n else:\n pass\n \n tmp_list_X_raw.append(str_st)\t\n tmp_list_Y_raw.append(data_point['y_val'])\t\n \n\t\n tmp_files_list_raw.append(data_point['full_file_name'])\t\n tmp_pure_files_list_raw.append(data_point['id'])\n\nX_list_raw.extend(tmp_list_X_raw)\nY_list_raw.extend(tmp_list_Y_raw)\n\nall_files_list_raw.extend(tmp_files_list_raw)\n\n\nlogger.info(\"end pre-process for training datas... \")\n\n\n\n\n\nlogger.info(\"begin pre-process for testing datas... \")\n\n\nX_list_real_test_raw = []\nY_list_real_test_raw = []\n\nall_files_list_real_test_raw = []\nall_pure_files_list_real_test_raw = []\n\n\n\njsonFile = open(str_json_fn_testing, \"r\") # Open the JSON file for reading\njson_data = json.load(jsonFile) # Read the JSON into the buffer\njsonFile.close() # Close the JSON file\n\n\nreal_testing_data_set = []\n\n\nif not b_partial:\n real_testing_data_set = [item for item in json_data if item['y_val'] > -2]\nelse:\n real_testing_data_set = [item for item in json_data[:i_partial_count] if item['y_val'] > -2]\n\n\nreal_testing_data_set_sorted = sorted(real_testing_data_set, key=lambda x: (x['id']), reverse=False)\n\n\nlogger.info(\"len of real_testing_data_set_sorted = %d \", len(real_testing_data_set_sorted))\n\ntmp_list_X_raw = []\ntmp_list_Y_raw = []\ntmp_files_list_raw = []\ntmp_pure_files_list_raw = []\n\n\nfor data_point in real_testing_data_set_sorted:\n \n #tmp_list_X_raw.append(data_point['text'])\n \n #tmp_list_X_raw.append(data_point['senti_text'])\n \n \n i_se = data_point['i_sentiment_estimate']\n \n str_st = data_point['text'] \n if b_use_original_text:\n #str_st = data_point['text']\n #str_st = data_point['text_simple_cleanup']\n str_st = data_point['text_letter_and_num']\n else:\n str_st = data_point['senti_text']\n \n if i_se >= 15:\n str_st += \" . imdbsuperpositive \"\n elif i_se < 15 and i_se >= 5:\n str_st += \" . imdbstrongpositive \"\n elif i_se < 5 and i_se > -5:\n pass\n elif i_se <= -5 and i_se > -15:\n str_st += \" . imdbstrongnegitive \"\n elif i_se <= -15:\n str_st += \" . imdbsupernegitive \"\n else:\n pass\n \n tmp_list_X_raw.append(str_st)\n\n tmp_list_Y_raw.append(data_point['y_val'])\t\n\t\n tmp_files_list_raw.append(data_point['full_file_name'])\t\n tmp_pure_files_list_raw.append(data_point['id'])\n\nX_list_real_test_raw.extend(tmp_list_X_raw)\nY_list_real_test_raw.extend(tmp_list_Y_raw)\n\nall_files_list_real_test_raw.extend(tmp_files_list_raw)\nall_pure_files_list_real_test_raw.extend(tmp_pure_files_list_raw)\n\n\nlogger.info(\"end pre-process for testing datas... \")\n\n\n\n\n\n\n# seems that the all data (both training and testing) are combined together and then being splited, \n# according to train_size and test_size parameters of train_test_split\n#X_train, X_test, y_train, y_test = train_test_split(newsgroups.data, newsgroups.target, train_size=0.6, test_size=0.4)\n\n\nlogger.info(\"start train_test_split. \")\n\n\ni_random_state=20\n\nX_train, X_test, Y_train, Y_test, all_files_train, all_files_test = train_test_split(X_list_raw, Y_list_raw, all_files_list_raw, train_size=0.8, test_size=0.2, random_state=i_random_state)\n\n\nlogger.info(\"end train_test_split. \")\n\nprint(\"len of X_train, X_test, Y_train, Y_test, all_files_train, all_files_test \\n\", len(X_train), len(X_test), len(Y_train), len(Y_test), len(all_files_train), len(all_files_test))\n\ni_random_index = 15\n\nprint(\"\\n\\n i_random_index = \", i_random_index)\n\nprint(\"\\n\\n\\n\\n item of X_train: ==============================================================\\n\")\nprint(X_train[i_random_index])\n\nprint(\"\\n\\n\\n\\n item of Y_train: ==============================================================\\n\")\nprint(Y_train[i_random_index])\n\nprint(\"\\n\\n\\n\\n item of all_files_train: ==============================================================\\n\")\nprint(all_files_train[i_random_index])\n\n\n\n\ni_random_index = 18\n\nprint(\"\\n\\n i_random_index = \", i_random_index)\n\nprint(\"\\n\\n\\n\\n item of X_test: ==============================================================\\n\")\nprint(X_test[i_random_index])\n\nprint(\"\\n\\n\\n\\n item of Y_test: ==============================================================\\n\")\nprint(Y_test[i_random_index])\n\nprint(\"\\n\\n\\n\\n item of all_files_test: ==============================================================\\n\")\nprint(all_files_test[i_random_index])\n\n\n\n\n\ni_random_index = 20\n\nprint(\"\\n\\n i_random_index = \", i_random_index)\n\nprint(\"\\n\\n\\n\\n item of X_list_real_test_raw: ==============================================================\\n\")\nprint(X_list_real_test_raw[i_random_index])\n\nprint(\"\\n\\n\\n\\n item of Y_list_real_test_raw: ==============================================================\\n\")\nprint(Y_list_real_test_raw[i_random_index])\n\nprint(\"\\n\\n\\n\\n item of all_files_list_real_test_raw: ==============================================================\\n\")\nprint(all_files_list_real_test_raw[i_random_index])\n\n\n\n\n\nX_train_whole = []\n\nX_train_whole.extend(X_train)\nX_train_whole.extend(X_test)\n\nY_train_whole = []\n\nY_train_whole.extend(Y_train)\nY_train_whole.extend(Y_test)\n\n\nall_files_whole_train = []\n\nall_files_whole_train.extend(all_files_train) \nall_files_whole_train.extend(all_files_test)\n\n\n\n\n\n\nprint(\"len of X_train_whole and Y_train_whole\", len(X_train_whole), len(Y_train_whole))\n\n\nprint(\"len of X_train and Y_train\", len(X_train), len(Y_train))\n\n\n\n\nbnb = Bernoulli_NaiveBayes_Classifier()\n\n\nlogger.info(\"start fit for pclf\")\n\n \n \n#pclf.fit(X_train_whole[0:200], Y_train_whole[0:200])\n\n#pclf.fit(X_train_whole, Y_train_whole)\n\n#pclf.fit(X_train, Y_train)\n\nbnb.fit(X_train, Y_train)\n\n\n\nlogger.info(\"end fit for pclf\")\n\n\n#tmp_vect_X = pclf.named_steps['vect'].X\n\n\n#print(\"\\n\\n\\n\\n tfidf idf_\", tmp_vect_X, len(tmp_vect_X), type(tmp_vect_X), tmp_vect_X.shape)\n\n\nprint(\"Number of features found: \", len(bnb.features))\n\n\n\n\n\n\nlogger.info(\"start predict for X_test \")\n\n#Y_test_pred = model_search_LR.predict(X_test)\n\n#Y_test_cv_pred = cross_val_predict(pclf, X_test, Y_test, cv=5, n_jobs=2)\n\nY_test_pred = []\n\n\n#Y_test_pred = pclf.predict(X_test)\n\n\n\nY_test_pred = bnb.predict(X_test)\n\nprint(metrics.classification_report(Y_test, Y_test_pred, digits=5))\n\n\n\nY_test_cv_pred = []\nY_test_cv_pred.extend([0] * int(len(Y_test) / 2))\nY_test_cv_pred.extend([1] * int(len(Y_test) / 2))\n\nprint(\"\\n\\n type and len of Y_test_cv_pred: \", type(Y_test_cv_pred), len(Y_test_cv_pred))\n\n\nlogger.info(\"end predict for X_test\")\n\n\n\n\nprint(\"\\n\\n\\n\\n\")\n\n\n\nlogger.info(\"start metrics.classification_report \")\n\nprint(\"\\n\\nmetrics.classification_report for Y_test and Y_test_pred \\n\")\n\nprint(metrics.classification_report(Y_test, Y_test_pred, digits=5))\n\n\nprint(\"\\n\\nmetrics.classification_report for Y_test and Y_test_cv_pred \\n\")\n\nprint(metrics.classification_report(Y_test, Y_test_cv_pred, digits=5))\n\nlogger.info(\"end metrics.classification_report \")\n\n\n\n\n\nlogger.info(\"start predict for X_list_real_test_raw \")\n\n#Y_real_test_pred = model_search_LR.predict(X_list_real_test_raw)\nY_real_test_pred = []\n\n\nY_real_test_pred = bnb.predict(X_list_real_test_raw)\n\nlogger.info(\"end predict for X_list_real_test_raw\")\n\n\n\nprint(\"\\n\\n\\n\\n\")\n\n#print(\"Y_test = \\n\\n\", Y_test, type(Y_test))\n\nprint(\"\\n\\n\\n\\n\")\n\n\n\n#list_Y_test_pred = Y_test_pred.tolist()\n\n#print(\"list_Y_test_pred = \\n\\n\", list_Y_test_pred, type(list_Y_test_pred))\n\nprint(\"\\n\\n\\n\\n\")\n\n\n#Y_test_cv_pred\n\n#list_Y_test_cv_pred = Y_test_cv_pred.tolist()\n\n#print(\"list_Y_test_cv_pred = \\n\\n\", list_Y_test_cv_pred, type(list_Y_test_cv_pred))\n\n\n\n\nprint(\"\\n\\n\\n\\n\")\n\n#list_Y_real_test_pred = Y_real_test_pred.tolist()\nlist_Y_real_test_pred = Y_real_test_pred\n\n\n#print(\"list_Y_real_test_pred = \\n\\n\", list_Y_real_test_pred, type(list_Y_real_test_pred))\n\n\nprint(\"\\n\\n\\n\\n\")\n\n\nprint(\"len of list_Y_real_test_pred: \", len(list_Y_real_test_pred))\n\n\n\nprint(\"\\n\\n\\n\\n\")\n\n\n\n\n\ncur_time = int(time.time())\n\nprint(\"cur_time = \", cur_time)\n\nstr_file_name_tw = \"../csv/group12_\" + \"bernoulli_nb\" + \"_\" + str(cur_time) + \"_submission\" + str_fn_postfix + \".csv\"\n\n\ncsv_stat_all_data = []\n\ni_index = 0\n\nfor item_predict in list_Y_real_test_pred:\n \n csv_stat_item = {}\n \n tmp_pure_file_name = all_pure_files_list_real_test_raw[i_index]\n wlist = tmp_pure_file_name.split('.')\n \n csv_stat_item['id'] = int(wlist[0])\n\n csv_stat_item['category'] = item_predict\n #csv_stat_item['category'] = item_predict \n \n i_index += 1\n \n csv_stat_all_data.append(csv_stat_item)\n\n\n\ncsv_set_sorted = sorted(csv_stat_all_data, key=lambda x: (x['id']), reverse=False)\n\n\nwith open(str_file_name_tw, 'wt', newline='') as csvfile:\n \n csv_writer = csv.writer(csvfile, dialect='excel')\n \n \n header = ['Id', 'Category']\n csv_writer.writerow(header)\n \n for data_point in csv_set_sorted:\n \n row = [data_point['id'], data_point['category']]\n #str_to_write = \"\\n\" + str(data_point['id']) + \",\" + str(data_point['category'])\n #fout_tw.write(str_to_write)\n csv_writer.writerow(row)\n \n \n\n\nlogger.info(\"program ends. \")\n\n\n\n\n\n","sub_path":"Deliverables/codeV4/imdb_sentiment_bernoulli_nb.py","file_name":"imdb_sentiment_bernoulli_nb.py","file_ext":"py","file_size_in_byte":12538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"603931615","text":"### Module imports ###\nimport os\nfrom collections import defaultdict\n\n\n### Global Variables ###\n\n\n### Class declarations ###\nclass ExtractData:\n\n def __init__(self, train_path, test_path):\n self.train_path = train_path\n self.test_path = test_path\n # list to store tuples of sentences and its tag\n self.all_tuples = []\n\n # dictionary to store the word and all tags of that word\n self.word_tags = defaultdict(set)\n\n # set to store the unique tags\n self.unique_tags = set()\n\n def word_tag_tuples(self):\n with open(self.train_path, 'r') as f:\n for line in f:\n # list of tuples for a sentence\n tuples_sentence_l = []\n tuple_words = line.strip('\\n').split()\n\n # add '*' at the start of a sentence\n tuples_sentence_l.append(('*', '*'))\n tuples_sentence_l.append(('*', '*'))\n\n # word tag\n for tup in tuple_words:\n split = tup.split('/')\n split_word = '/'.join(split[:-1])\n split_tag = split[-1]\n\n # saving the unique tags\n if split_tag not in self.unique_tags:\n self.unique_tags.add(split_tag)\n\n # add word-tag pair to list\n tuples_sentence_l.append((split_word, split_tag))\n # add all tags of a word to dictionary\n self.word_tags[split_word].add(split_tag)\n\n # add sentence to all tuples list\n self.all_tuples.append(tuples_sentence_l)\n # add tag * to word tag\n self.word_tags['*'] = '*'\n return self.all_tuples, self.word_tags, self.unique_tags\n\n def word_tag_test(self):\n sentence_l, tags_l = [], []\n with open(self.test_path, 'r') as f:\n for line in f:\n # list of tuples for a sentence\n words_l, tag_sent = ['*', '*'], ['*', '*']\n tuple_words = line.strip('\\n').split()\n\n # word tag\n for tup in tuple_words:\n split = tup.split('/')\n split_word = '/'.join(split[:-1])\n split_tag = split[-1]\n words_l.append(split_word)\n tag_sent.append(split_tag)\n sentence_l.append(words_l)\n tags_l.append(tag_sent)\n return sentence_l, tags_l\n\n\n### Function declarations ###\n","sub_path":"week4-5/POS_Tagging/hmm/read_from_file.py","file_name":"read_from_file.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"96622417","text":"import RPi.GPIO as GPIO #import GPIO from RPI Library\nimport time #Import Time in case we need delay\ndef turn(): #Define Method (Begin Method Turn())\n GPIO.setmode(GPIO.BOARD) #Set the Input and output board\n\n ControlPin = [11,13,15, 16] #Declare one dimensional array of pins to be used\n #(Clockwise)\n\n for pin in ControlPin: #Enhanced for loop through the controlpins\n GPIO.setup(pin, GPIO.OUT) #Make every controlpin set for output\n GPIO.output(pin, 0) #output nothing for now (initialize)\n \n seq = [ [1,0,0,0], #Stepper motor sequence for full steps\n #[1,1,0,0],\n [0,1,0,0],\n #[0,1,1,0],\n [0,0,1,0],\n #[0,0,1,1],\n [0,0,0,1],\n #[1,0,0,1]\n ]\n for i in range(200): #Run for loop 200 times\n for halfstep in range(4): #run for loops 4 times\n for pin in range(4): #run for loop 4 times\n GPIO.output(ControlPin[pin], seq[halfstep][pin])\n #for each run, output to the pin needed and use sequence\n #for half-step or full step\n time.sleep(0.001) #delay a little\n GPIO.cleanup() #clean up all pins and reset them\n#end Method Turn()\nturn();\n#call defined method so we can call from outside compiler\n\n\n#REFERENCES: GAVIN MACDONALD (youtube.com/watch?v=Dc16mKFA7Fo)","sub_path":"xturnright(kim).py","file_name":"xturnright(kim).py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"135309939","text":"# -*- coding: utf-8 -*-\n\"\"\"Implementation of Rapid Automatic Keyword Extraction algorithm.\n\nAs described in the paper `Automatic keyword extraction from individual\ndocuments` by Stuart Rose, Dave Engel, Nick Cramer and Wendy Cowley.\n\"\"\"\n\nimport string\nfrom collections import Counter, defaultdict\nfrom itertools import chain, groupby, product\n\nimport nltk\nfrom enum import Enum\nfrom nltk.tokenize import wordpunct_tokenize\nimport os\nfrom multiprocessing import Lock, Value, Process\nimport multiprocessing as mp\nfrom concurrent.futures import ProcessPoolExecutor\nfrom functools import reduce\nimport pickle\nimport re\nfrom sqlitedict import SqliteDict\nimport time\n\nclass DocCounter(object):\n def __init__(self, initval=0):\n self.val = Value('L', initval)\n self.lock = Lock()\n\n def increment(self):\n with self.lock:\n self.val.value += 1\n if self.val.value % 1000 == 0:\n print(\"{} documents scanned\".format(self.val.value))\n\n def value(self):\n with self.lock:\n v = self.val.value\n return v\n\nclass Metric(Enum):\n \"\"\"Different metrics that can be used for ranking.\"\"\"\n DEGREE_TO_FREQUENCY_RATIO = 0 # Uses d(w)/f(w) as the metric\n WORD_DEGREE = 1 # Uses d(w) alone as the metric\n WORD_FREQUENCY = 2 # Uses f(w) alone as the metric\n\n\ncntr = DocCounter()\ndoc_preprocess_func = None\npargs = None\ndb = None\ndb_lock = Lock()\nmp_manager = mp.Manager()\nq = mp_manager.Queue()\nlock = Lock()\n\n\ndef file_writer_process(output_folder, prefix, q, lock):\n print(\"writer process started\")\n pl_dict = SqliteDict(os.path.join(output_folder, \"{0}_{1}.sqlite\".format(prefix, \"phrase_list\")), tablename=\"phrase_list\", autocommit=True)\n coc_dict = SqliteDict(os.path.join(output_folder, \"{0}_{1}.sqlite\".format(prefix, \"co_occ\")), tablename=\"co_occ\", autocommit=True)\n wd_dict = SqliteDict(os.path.join(output_folder, \"{0}_{1}.sqlite\".format(prefix, \"word_dist\")), tablename=\"word_dist\", autocommit=True)\n local_cntr = 0\n while(True):\n data = None\n lock.acquire()\n if(not q.empty()):\n data = q.get()\n lock.release()\n if data is not None:\n word_dist, co_occ, phrase_list = data\n pl_dict[local_cntr] = phrase_list\n coc_dict[local_cntr] = co_occ\n wd_dict[local_cntr] = word_dist\n local_cntr += 1\n print(\"Written {0} documents\".format(local_cntr))\n if(local_cntr%1000 == 0):\n print(\"Written {0} documents\".format(local_cntr))\n pl_dict.commit()\n coc_dict.commit()\n wd_dict.commit()\n else:\n time.sleep(0.1)\n\n\ndef rake_process(raw_doc):\n cntr.increment()\n if doc_preprocess_func is None:\n doc = raw_doc\n else:\n doc = doc_preprocess_func(raw_doc)\n rake = RakeProcess(**pargs)\n rake.extract_keywords_from_text(doc)\n word_dist = rake.get_word_frequency_distribution()\n co_occ = rake.get_word_co_occurance_graph()\n phrase_list = rake.get_phrase_list()\n with db_lock:\n db.phrase_list.insert_one({\"list\": list(phrase_list)})\n db.word_dist.insert_one({\"list\": dict(word_dist)})\n db.co_occ.insert_one({\"list\": dict(co_occ)})\n #q.put([word_dist, co_occ, phrase_list])\n\n return True\n\nclass DistributedRake(object):\n def __init__(\n self,\n output_folder,\n prefix = \"\",\n stopwords=None,\n punctuations=None,\n language=\"english\",\n ranking_metric=Metric.DEGREE_TO_FREQUENCY_RATIO,\n max_length=100000,\n min_length=1,\n ):\n global pargs\n pargs = {\"stopwords\": stopwords,\n \"punctuations\": punctuations,\n \"language\": language,\n \"ranking_metric\": ranking_metric,\n \"max_length\": max_length,\n \"min_length\": min_length}\n\n if isinstance(ranking_metric, Metric):\n self.metric = ranking_metric\n else:\n self.metric = Metric.DEGREE_TO_FREQUENCY_RATIO\n\n self.output_folder = output_folder\n self.prefix = prefix\n\n def digest_docs(self, doc_itr, mongodb_obj, doc_func = None, num_workers=mp.cpu_count(), chunksize=1000):\n global doc_preprocess_func\n global db\n db = mongodb_obj\n doc_preprocess_func = doc_func\n db[\"phrase_list\"]\n db[\"word_dist\"]\n db[\"co_occ\"]\n # print(\"Spawning writer process\")\n # writer_process = Process(target = file_writer_process, args = (self.output_folder, self.prefix, q, lock))\n # writer_process.start()\n # print(\"Starting Process Pool\")\n with ProcessPoolExecutor(max_workers=num_workers) as executor:\n result = executor.map(rake_process, doc_itr, chunksize=chunksize)\n print(\"process pool map created\")\n # while(True):\n # try:\n # data = next(result)\n # lock.acquire()\n # q.put(data)\n # lock.release()\n # time.sleep(0.1)\n # except Exception as e:\n # print(e)\n # break\n\n # while(not q.empty()):\n # time.sleep(1)\n\n #writer_process.terminate()\n\n\n\n # def store_results(self, folder, prefix=\"\"):\n # with open(os.path.join(folder, prefix + \"ranked_phrases.pkl\"), \"wb\") as wf:\n # pickle.dump(self.ranked_phrases, wf)\n #\n # with open(os.path.join(folder, prefix + \"rank_list.pkl\"), \"wb\") as wf:\n # pickle.dump(self.rank_list, wf)\n #\n # with open(os.path.join(folder, prefix + \"frequency_dist.pkl\"), \"wb\") as wf:\n # pickle.dump(self.frequency_dist, wf)\n #\n # with open(os.path.join(folder, prefix + \"word_degree.pkl\"), \"wb\") as wf:\n # pickle.dump(self.degree, wf)\n\n # def get_phrase_list(self):\n # return self.phrase_list\n #\n # def get_word_frequency_distribution(self):\n # \"\"\"Method to fetch the word frequency distribution in the given text.\n #\n # :return: Dictionary (defaultdict) of the format `word -> frequency`.\n # \"\"\"\n # return self.frequency_dist\n #\n # def get_word_co_occurance_graph(self):\n # \"\"\"Method to fetch the degree of words in the given text. Degree can be\n # defined as sum of co-occurances of the word with other words in the\n # given text.\n # \"\"\"\n # return self.co_occ\n #\n # def get_ranked_phrases(self):\n # \"\"\"Method to fetch ranked keyword strings.\n #\n # :return: List of strings where each string represents an extracted\n # keyword string.\n # \"\"\"\n # return self.ranked_phrases\n #\n # def get_ranked_phrases_with_scores(self):\n # \"\"\"Method to fetch ranked keyword strings along with their scores.\n #\n # :return: List of tuples where each tuple is formed of an extracted\n # keyword string and its score. Ex: (5.68, 'Four Scoures')\n # \"\"\"\n # return self.rank_list\n #\n # def get_word_degree(self):\n # return self.degree\n\n # def build_word_degree(self):\n # self.degree = defaultdict(int)\n # for key in self.co_occ:\n # self.degree[key] = sum(self.co_occ[key].values())\n #\n # def build_ranklist(self):\n # \"\"\"Method to rank each contender phrase using the formula\n #\n # phrase_score = sum of scores of words in the phrase.\n # word_score = d(w)/f(w) where d is degree and f is frequency.\n #\n # :param phrase_list: List of List of strings where each sublist is a\n # collection of words which form a contender phrase.\n # \"\"\"\n # self.rank_list = []\n # for phrase in self.phrase_list:\n # rank = 0.0\n # for word in phrase:\n # if self.metric == Metric.DEGREE_TO_FREQUENCY_RATIO:\n # rank += 1.0 * self.degree[word] / self.frequency_dist[word]\n # elif self.metric == Metric.WORD_DEGREE:\n # rank += 1.0 * self.degree[word]\n # else:\n # rank += 1.0 * self.frequency_dist[word]\n # self.rank_list.append((rank, \" \".join(phrase)))\n # self.rank_list.sort(reverse=True)\n # self.ranked_phrases = [ph[1] for ph in self.rank_list]\n\n\nclass RakeProcess(object):\n \"\"\"Rapid Automatic Keyword Extraction Algorithm.\"\"\"\n\n def __init__(\n self,\n stopwords=None,\n punctuations=None,\n language=\"english\",\n ranking_metric=Metric.DEGREE_TO_FREQUENCY_RATIO,\n max_length=100000,\n min_length=1,\n ):\n \"\"\"Constructor.\n\n :param stopwords: List of Words to be ignored for keyword extraction.\n :param punctuations: Punctuations to be ignored for keyword extraction.\n :param language: Language to be used for stopwords\n :param max_length: Maximum limit on the number of words in a phrase\n (Inclusive. Defaults to 100000)\n :param min_length: Minimum limit on the number of words in a phrase\n (Inclusive. Defaults to 1)\n \"\"\"\n # By default use degree to frequency ratio as the metric.\n if isinstance(ranking_metric, Metric):\n self.metric = ranking_metric\n else:\n self.metric = Metric.DEGREE_TO_FREQUENCY_RATIO\n\n # If stopwords not provided we use language stopwords by default.\n self.stopwords = stopwords\n if self.stopwords is None:\n self.stopwords = nltk.corpus.stopwords.words(language)\n else:\n self.stopwords.extend(nltk.corpus.stopwords.words(language))\n self.stopwords = list(set(self.stopwords))\n\n # If punctuations are not provided we ignore all punctuation symbols.\n self.punctuations = punctuations\n if self.punctuations is None:\n self.punctuations = string.punctuation\n\n # All things which act as sentence breaks during keyword extraction.\n self.to_ignore = set(chain(self.stopwords, self.punctuations)).union(set(['',' ']))\n\n # Assign min or max length to the attributes\n self.min_length = min_length\n self.max_length = max_length\n\n # Stuff to be extracted from the provided text.\n self.frequency_dist = None\n self.word_co_occurance_graph = None\n self.phrase_list = None\n\n def extract_keywords_from_text(self, text):\n \"\"\"Method to extract keywords from the text provided.\n\n :param text: Text to extract keywords from, provided as a string.\n \"\"\"\n sentences = nltk.tokenize.sent_tokenize(text)\n self.extract_keywords_from_sentences(sentences)\n\n def extract_keywords_from_sentences(self, sentences):\n \"\"\"Method to extract keywords from the list of sentences provided.\n\n :param sentences: Text to extraxt keywords from, provided as a list\n of strings, where each string is a sentence.\n \"\"\"\n self.phrase_list = self._generate_phrases(sentences)\n self._build_frequency_dist(self.phrase_list)\n self._build_word_co_occurance_graph(self.phrase_list)\n\n def get_phrase_list(self):\n return self.phrase_list\n\n def get_word_frequency_distribution(self):\n \"\"\"Method to fetch the word frequency distribution in the given text.\n\n :return: Dictionary (defaultdict) of the format `word -> frequency`.\n \"\"\"\n return self.frequency_dist\n\n def get_word_co_occurance_graph(self):\n \"\"\"Method to fetch the degree of words in the given text. Degree can be\n defined as sum of co-occurances of the word with other words in the\n given text.\n \"\"\"\n return self.word_co_occurance_graph\n\n def _build_frequency_dist(self, phrase_list):\n \"\"\"Builds frequency distribution of the words in the given body of text.\n\n :param phrase_list: List of List of strings where each sublist is a\n collection of words which form a contender phrase.\n \"\"\"\n self.frequency_dist = Counter(chain.from_iterable(phrase_list))\n\n def _build_word_co_occurance_graph(self, phrase_list):\n \"\"\"Builds the co-occurance graph of words in the given body of text to\n compute degree of each word.\n\n :param phrase_list: List of List of strings where each sublist is a\n collection of words which form a contender phrase.\n \"\"\"\n\n\n co_occurance_graph = defaultdict(self.dd_lambda)\n for phrase in phrase_list:\n # For each phrase in the phrase list, count co-occurances of the\n # word with other words in the phrase.\n #\n # Note: Keep the co-occurances graph as is, to help facilitate its\n # use in other creative ways if required later.\n for (word, coword) in product(phrase, phrase):\n co_occurance_graph[word][coword] += 1\n\n self.word_co_occurance_graph = co_occurance_graph\n\n\n def _generate_phrases(self, sentences):\n \"\"\"Method to generate contender phrases given the sentences of the text\n document.\n\n :param sentences: List of strings where each string represents a\n sentence which forms the text.\n :return: Set of string tuples where each tuple is a collection\n of words forming a contender phrase.\n \"\"\"\n phrase_list = set()\n # Create contender phrases from sentences.\n regex = re.compile('[^a-zA-Z]')\n for sentence in sentences:\n word_list = [word.lower() for word in wordpunct_tokenize(sentence)]\n word_list = list(chain(*[regex.sub(' ', w).split(' ') for w in word_list]))\n phrase_list.update(self._get_phrase_list_from_words(word_list))\n return phrase_list\n\n def _get_phrase_list_from_words(self, word_list):\n \"\"\"Method to create contender phrases from the list of words that form\n a sentence by dropping stopwords and punctuations and grouping the left\n words into phrases. Only phrases in the given length range (both limits\n inclusive) would be considered to build co-occurrence matrix. Ex:\n\n Sentence: Red apples, are good in flavour.\n List of words: ['red', 'apples', \",\", 'are', 'good', 'in', 'flavour']\n List after dropping punctuations and stopwords.\n List of words: ['red', 'apples', *, *, good, *, 'flavour']\n List of phrases: [('red', 'apples'), ('good',), ('flavour',)]\n\n List of phrases with a correct length:\n For the range [1, 2]: [('red', 'apples'), ('good',), ('flavour',)]\n For the range [1, 1]: [('good',), ('flavour',)]\n For the range [2, 2]: [('red', 'apples')]\n\n :param word_list: List of words which form a sentence when joined in\n the same order.\n :return: List of contender phrases that are formed after dropping\n stopwords and punctuations.\n \"\"\"\n groups = groupby(word_list, self.filter_word)\n phrases = [tuple(group[1]) for group in groups if group[0]]\n return list(\n filter(\n self.filter_phrase, phrases\n )\n )\n\n def filter_word(self, x):\n return x not in self.to_ignore\n\n def filter_phrase(self, x):\n return self.min_length <= len(x) <= self.max_length\n\n def dd_lambda(self):\n return defaultdict(int)","sub_path":"rake_nltk/distributed_rake.py","file_name":"distributed_rake.py","file_ext":"py","file_size_in_byte":15661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"218354514","text":"print (\"Please think of a number between 0 and 100!\")\nx = 100\nans = 0\nlow = 0\nhigh = x\nans = (high + low)/2\nuser_input = ''\n\nwhile user_input != 'c':\n \n print (\"Is your secret number \" + str(ans) + \"?\"),\n user_input = raw_input(\"Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.\")\n \n if user_input == 'h':\n high = ans\n elif user_input == 'l':\n low = ans\n elif user_input =='c':\n break\n else:\n print (\"Sorry I did not understand your input\")\n \n ans = (high + low)/2\n \nprint (\"Game over. Your secret number was: \" +str(ans))\n","sub_path":"st_coding_1/Code_solutions/numberGuess 2.py","file_name":"numberGuess 2.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"250967775","text":"from datetime import datetime\nfrom app.config import requestURI, postURI, keymd5, payload, headers\nfrom app.api import getResponse\nfrom pytz import utc, timezone\nimport xmltodict\nimport requests\nimport logging\n# import json\n\n### Logging\n\nlogging.basicConfig(level=logging.WARN)\n\n### Daily Job\n\ndef filterAnswerbyDate(dt):\n if dt.date() == datetime.today().date():\n return True\n return False\n\nlatest_input = []\ncurrent_data = []\nlatest_value = {}\nfiltered_data = []\n\ndef postData(filteredData):\n url = postURI + '/add_price_return_newid'\n r = requests.post(url, data = filteredData, headers = headers)\n try:\n now = datetime.now()\n now = now.strftime('%d/%b/%Y %H:%M:%S')\n log = xmltodict.parse(r.text)\n return_id = log['string']['#text']\n log = 'SUCCESS [' + now + '] - INPUT ID:' + return_id\n print(log)\n except xmltodict.expat.ExpatError:\n log = r.text\n logging.error(log)\n filtered_data.append({\n 'payload': filteredData.split('&'),\n 'return_id': return_id\n })\n return True\n\ndef filterData(answer, par_id, meta, submitter_id):\n correction = []\n resp = [\n {'key':'keymd5', 'value':keymd5},\n {'key':'ACC_ID', 'value': submitter_id},\n ]\n subDate = answer['submissionDate']\n date_val = datetime.strptime(subDate, '%Y-%m-%dT%H:%M:%SZ')\n date_here = utc.localize(date_val).astimezone(timezone('Asia/Singapore'))\n check_date = filterAnswerbyDate(date_here)\n if check_date:\n new_date = datetime.strftime(date_here,'%Y/%m/%d')\n resp.append({'key':'Date_var', 'value':str(new_date)})\n correction.append(str(new_date))\n else:\n return False\n for mt in meta:\n try:\n values = answer['responses'][par_id][0][mt['id']]\n if mt['type'] == 'CASCADE':\n resp.append({'key':'ID_Commodity', 'value':values[2]['code']})\n resp.append({'key':'ID_Agency', 'value':values[1]['code']})\n correction.append(values[2]['code'])\n correction.append(values[1]['code'])\n elif mt['type'] == 'DATE':\n pass\n else:\n resp.append({'key':mt['variableName'],'value':str(values)})\n except:\n resp.append({'key':mt['variableName'],'value':'0'})\n corr = \" \".join(str(x) for x in correction)\n if corr in latest_input:\n logging.warn('PASS: DUPLICATED VALUE')\n odate = datetime.strptime(latest_value[corr]['date'],'%Y-%m-%d %H:%M:%S')\n if date_val > odate:\n print('GETTING THE LATEST VALUE')\n latest_value[corr] = {'payload':payload(resp), 'date':str(date_val)}\n return True\n return False\n latest_input.append(corr)\n latest_value.update({corr:{'payload':payload(resp), 'date':str(date_val)}})\n return True\n\ndef getRawData(survey_id, form_id):\n data = getResponse(requestURI + '/surveys/' + survey_id)\n # submitter ID\n submitter_id = data['name'].split('_')[1]\n meta = data['forms'][0]['questionGroups'][0]['questions']\n for form in data['forms']:\n par_id = form['questionGroups'][0]['id']\n answers = getResponse(requestURI + '/form_instances?survey_id=' + survey_id + '&form_id=' + form_id)\n for answer in answers['formInstances']:\n try:\n filterData(answer, par_id, meta, submitter_id)\n except:\n pass\n return\n\ndef updateAll():\n data = getResponse(requestURI + '/surveys?folder_id=38000001')\n for dt in data['surveys']:\n sid = getResponse(requestURI + '/surveys/' + dt['id'])\n getRawData(dt['id'], sid['forms'][0]['id'])\n for corr in latest_input:\n postData(latest_value[corr]['payload'])\n now = datetime.now()\n now = now.strftime('%d/%b/%Y %H:%M:%S')\n if not latest_input:\n logging.warn(\" [\"+ now + \"] DATA NOT FOUND\")\n else:\n print('\\n--- DATA SENT ---\\n')\n # file = now.strftime('%Y%d%b%H%M%S')\n # with open('./data-'+ file +'.json', 'w') as outfile:\n # json.dump(filtered_data, outfile)\n # print(filtered_data)\n print('\\n--- CRON JOB FINISHED ---')\n\n\nprint('\\n--- CRON JOB IS STARTED ---\\n')\nupdateAll()\n","sub_path":"flow-api/Jobs_GreenCoffee_TriggerUpdate/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"374863461","text":"import requests\nimport time\nfrom datetime import datetime , timedelta\nimport json\nimport bz2\nimport pickle\nimport win32ui\nimport os\nframerate = 20\n\nimport traceback\n\n\n\nimport psutil\nimport subprocess \n\nSkimFilePath = \"D:/ECRanked/Skims\"\nReplayFilePath = \"D:/ECRanked/Skims\"\n\ndef process_exists(process_name):\n call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name\n # use buildin check_output right away\n output = subprocess.check_output(call).decode()\n # check in last line for process name\n last_line = output.strip().split('\\r\\n')[-1]\n # because Fail message could be translated\n return last_line.lower().startswith(process_name.lower())\n\n\nCrashGameID = \"\"\ndef HandleGame():\n \n r = requests.get('http://127.0.0.1:6721/session')\n startingTime = time.time() \n t=time.time()\n CurrentGame = dict()\n FrameCount = 0\n ActivePlayerList = dict()\n jsonData = r.json()\n #Game just starting up\n print(\"GAME STARTED\")\n print(f\"SESSION ID = \\\"{jsonData['sessionid']}\\\"\")\n\n CurrentGame = dict()\n CurrentGame[\"sessionid\"] = jsonData[\"sessionid\"]\n CurrentGame[\"map_name\"] = jsonData[\"map_name\"]\n CurrentGame[\"start_time\"] = datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\")\n CurrentGame[\"framerate\"] = 10\n CurrentGame[\"players\"] = dict()\n CurrentGame[\"data\"] = []\n CrashGameID = \"\" \n while True:\n try:\n r = requests.get('http://127.0.0.1:6721/session')\n if r.status_code == 404:\n print(f\"Game Finish! {CurrentGame['sessionid']}\") \n\n CrashGameID == \"\"\n CurrentGame[\"players\"] = ActivePlayerList\n\n if CurrentGame['map_name'] == \"mpl_combat_dyson\" : mapSaveLocation = \"dyson\" \n if CurrentGame['map_name'] == \"mpl_combat_combustion\" : mapSaveLocation = \"combustion\" \n if CurrentGame['map_name'] == \"mpl_combat_fission\" : mapSaveLocation = \"fission\" \n if CurrentGame['map_name'] == \"mpl_combat_gauss\" : mapSaveLocation = \"surge\" \n with bz2.BZ2File(f\"{ReplayFilePath}/{mapSaveLocation}/[{CurrentGame['start_time']}] {CurrentGame['sessionid']}.rawreplayv3\", 'wb') as f:\n pickle.dump(CurrentGame, f)\n \n saveStrippedVersion(CurrentGame,ActivePlayerList)\n \n break\n\n\n \n\n jsonData = r.json()\n if CrashGameID != \"\" and CrashGameID != jsonData[\"sessionid\"]:\n print(f\"Game Crash Finish! {CurrentGame['sessionid']}\") \n\n CrashGameID == \"\"\n CurrentGame[\"players\"] = ActivePlayerList\n\n if CurrentGame['map_name'] == \"mpl_combat_dyson\" : mapSaveLocation = \"dyson\" \n if CurrentGame['map_name'] == \"mpl_combat_combustion\" : mapSaveLocation = \"combustion\" \n if CurrentGame['map_name'] == \"mpl_combat_fission\" : mapSaveLocation = \"fission\" \n if CurrentGame['map_name'] == \"mpl_combat_gauss\" : mapSaveLocation = \"surge\" \n with bz2.BZ2File(f\"{ReplayFilePath}/{mapSaveLocation}/[{CurrentGame['start_time']}] {CurrentGame['sessionid']}.rawreplayv3\", 'wb') as f:\n pickle.dump(CurrentGame, f)\n saveStrippedVersion(CurrentGame,ActivePlayerList)\n\n break\n\n #During entire game\n FrameCount += 1\n t += 1/framerate\n jsonData = r.json()\n\n frameData = dict()\n teamData = jsonData[\"teams\"]\n\n frameData[\"teams\"] = []\n\n for i in range(3):\n team = teamData[i]\n SavedTeamData = list()\n if \"players\" in team:\n for player in team[\"players\"]:\n if str(player[\"userid\"]) not in ActivePlayerList:\n PlayerData = dict()\n PlayerData[\"name\"] = player[\"name\"]\n PlayerData[\"number\"] = player[\"number\"]\n PlayerData[\"level\"] = player[\"level\"]\n PlayerData[\"playerID\"] = len(ActivePlayerList)\n ActivePlayerList[str(player[\"userid\"])] = PlayerData\n \n id = ActivePlayerList[str(player[\"userid\"])][\"playerID\"]\n SavedPlayerData = dict()\n SavedPlayerData[\"id\"] = id\n SavedPlayerData[\"r\"] = [player[\"rhand\"][\"pos\"],player[\"rhand\"][\"forward\"],player[\"rhand\"][\"left\"],player[\"rhand\"][\"up\"]]\n SavedPlayerData[\"l\"] = [player[\"lhand\"][\"pos\"],player[\"lhand\"][\"forward\"],player[\"lhand\"][\"left\"],player[\"lhand\"][\"up\"]]\n SavedPlayerData[\"h\"] = [player[\"head\"][\"position\"],player[\"head\"][\"forward\"],player[\"head\"][\"left\"],player[\"head\"][\"up\"]]\n SavedPlayerData[\"b\"] = [player[\"body\"][\"position\"],player[\"head\"][\"forward\"],player[\"head\"][\"left\"],player[\"head\"][\"up\"]]\n SavedPlayerData[\"v\"] = player[\"velocity\"]\n SavedTeamData.append(SavedPlayerData)\n frameData[\"teams\"].append(SavedTeamData)\n\n\n \n\n\n CurrentGame[\"data\"].append(frameData)\n time.sleep(max(0,t-time.time())) \n value = timedelta(seconds=t-startingTime)\n print(f\"Capturing Frame! [{FrameCount}] ({value})\")\n except Exception as e: \n traceback.print_exc()\n print(\"Game Crash!\")\n CrashGameID = CurrentGame[\"sessionid\"]\n print(\"Waiting 5s\")\n time.sleep(5)\n if not process_exists(\"echovr.exe\"):\n print(\"Echo VR Restarting!\")\n subprocess.Popen(['run.bat'])\n print(\"Waiting 30s\")\n time.sleep(45)\n else:\n for proc in psutil.process_iter():\n # check whether the process name matches\n if proc.name() == \"echovr.exe\":\n proc.kill()\n if proc.name() == \"BsSndRpt64.exe\":\n proc.kill()\n print(\"Waiting 10s\")\n time.sleep(10)\n print(\"Done!\") \n\n\n\n\n \n \n\ndef saveStrippedVersion(CurrentGame,ActivePlayerList):\n PositionData = dict()\n \n PositionData[\"sessionid\"] = CurrentGame[\"sessionid\"]\n PositionData[\"map_name\"] = CurrentGame[\"map_name\"]\n PositionData[\"framerate\"] = CurrentGame[\"framerate\"]\n PositionData[\"start_time\"] = CurrentGame[\"start_time\"]\n PositionData[\"players\"] = CurrentGame[\"players\"]\n\n\n PlayerPosData = dict()\n\n\n\n #Loop Through all the frames\n for frameData in CurrentGame[\"data\"]:\n teamData = frameData[\"teams\"]\n for team in teamData:\n for player in team:\n playerID = str(player[\"id\"])\n if playerID not in PlayerPosData:\n PlayerPosData[playerID] = list()\n \n PlayerPosData[playerID].append(player[\"h\"][0])\n\n\n PositionData[\"Data\"] = PlayerPosData\n\n\n\n CurrentGame[\"players\"] = ActivePlayerList\n if CurrentGame['map_name'] == \"mpl_combat_dyson\" : mapSaveLocation = \"dyson\" \n if CurrentGame['map_name'] == \"mpl_combat_combustion\" : mapSaveLocation = \"combustion\" \n if CurrentGame['map_name'] == \"mpl_combat_fission\" : mapSaveLocation = \"fission\" \n if CurrentGame['map_name'] == \"mpl_combat_gauss\" : mapSaveLocation = \"surge\" \n print(\"saving position replay\")\n with open(f\"{SkimFilePath}/{mapSaveLocation}/[{CurrentGame['start_time']}] {CurrentGame['sessionid']}.ecrs\", 'w') as f:\n f.write(json.dumps(PositionData))\n\n\nwhile True:\n try:\n r = requests.get('http://127.0.0.1:6721/session')\n if r.status_code == 200:\n HandleGame()\n else:\n time.sleep(10)\n except:\n if not process_exists(\"echovr.exe\"):\n subprocess.Popen(['run.bat'])\n time.sleep(20) ","sub_path":"APICapture.py","file_name":"APICapture.py","file_ext":"py","file_size_in_byte":8041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"64171555","text":"def quit_func(): ##Quits and Destroys the board(main window)\r\n global quitflag\r\n quit_box = messagebox.askyesno('Play Scrabble: Family Edition','Do you want to quit ?')\r\n if quit_box == 1:\r\n board.quit()\r\n board.destroy()\r\n return\r\n\r\ndef generate_bag(): ##Generates letters and append them to bag\r\n bag=[]\r\n for i in range(9):\r\n bag.append(\"A\")\r\n for i in range(2):\r\n bag.append(\"B\")\r\n for i in range(2):\r\n bag.append(\"C\")\r\n for i in range(4):\r\n bag.append(\"D\")\r\n for i in range(12):\r\n bag.append(\"E\")\r\n for i in range(2):\r\n bag.append(\"F\")\r\n for i in range(3):\r\n bag.append(\"G\")\r\n for i in range(1):\r\n bag.append(\"H\")\r\n for i in range(9):\r\n bag.append(\"I\")\r\n for i in range(9):\r\n bag.append(\"J\")\r\n for i in range(1):\r\n bag.append(\"K\")\r\n for i in range(4):\r\n bag.append(\"L\")\r\n for i in range(2):\r\n bag.append(\"M\")\r\n for i in range(6):\r\n bag.append(\"N\")\r\n for i in range(8):\r\n bag.append(\"O\")\r\n for i in range(2):\r\n bag.append(\"P\")\r\n for i in range(1):\r\n bag.append(\"Q\")\r\n for i in range(6):\r\n bag.append(\"R\")\r\n for i in range(4):\r\n bag.append(\"S\")\r\n for i in range(6):\r\n bag.append(\"T\")\r\n for i in range(4):\r\n bag.append(\"U\")\r\n for i in range(2):\r\n bag.append(\"V\")\r\n for i in range(2):\r\n bag.append(\"W\")\r\n for i in range(1):\r\n bag.append(\"X\")\r\n for i in range(2):\r\n bag.append(\"Y\")\r\n for i in range(1):\r\n bag.append(\"Z\")\r\n for i in range(2):\r\n bag.append(\"#\")\r\n shuffle(bag)\r\n return bag\r\n\r\ndef generating_racks(number_of_players,bag): ##Generates rack for each player\r\n players_racks=[]\r\n for i in range(number_of_players):\r\n tmp=[]\r\n for k in range(7):\r\n tmp.append(bag.pop())\r\n players_racks.append(tmp)\r\n return players_racks\r\n\r\ndef inserting_letters_into_player_tiles(letters_lst): ##Overwriting tile's text with rack alphabets\r\n global tiles\r\n y=0\r\n for x in letters_lst:\r\n but = Button(tile_frame, text = x, height = 2, width = 5, borderwidth = 5, bg = 'white', fg = 'black')\r\n if y<=4:\r\n but.grid(row = 0, column = y)\r\n\r\n else:\r\n but.grid(row = 1, column = y-5)\r\n tiles[(y)] = but\r\n tiles[(y)].bind(\"\",tilefunc)\r\n tiles[(y)].bind('', buttonhover)\r\n y=y+1\r\n return\r\n\r\ndef word_challenge(word): ##Calls a function what checks the work through the dictionary\r\n return dic.search(word)\r\n \r\ndef check_word(arr, l, r, x): ##Binary search implementaion, searches through the dictionary for the word \r\n while l <= r: \r\n mid = l + (r - l) // 2\r\n if arr[mid] == x: \r\n return True \r\n elif arr[mid] < x: \r\n l = mid + 1\r\n else: \r\n r = mid - 1\r\n return False\r\n\r\ndef radio_check(radio,wordlen,x,y): ##With repect to direction selected, it checks the word should not go out of bounds of board\r\n radiolen = False\r\n if radio == 0:\r\n return False\r\n elif radio == 1:\r\n if wordlen <= (15-x):\r\n radiolen = True\r\n elif radio == 2:\r\n if wordlen <= (15-y):\r\n radiolen = True\r\n \r\n if radiolen == False:\r\n messagebox.showerror('Play Scrabble: Family Edition','Your word lenght exceeded the block available.\\n Try Again!')\r\n return False\r\n return True\r\n\r\ndef partition(arr,low,high): ##These 3 functions are used when a challenge is made\r\n i = ( low-1 ) # index of smaller element \r\n pivot = arr[high] # pivot \r\n \r\n for j in range(low , high): \r\n \r\n # If current element is smaller than the pivot \r\n if arr[j] < pivot: \r\n \r\n # increment index of smaller element \r\n i = i+1 \r\n arr[i],arr[j] = arr[j],arr[i] \r\n \r\n arr[i+1],arr[high] = arr[high],arr[i+1] \r\n return ( i+1 ) \r\n\r\ndef quickSort(arr,low,high): ##When a new word is introduced to our dictionary it gets appended\r\n if low < high: \r\n \r\n # pi is partitioning index, arr[p] is now \r\n # at right place \r\n pi = partition(arr,low,high) \r\n \r\n # Separately sort elements before \r\n # partition and after partition \r\n quickSort(arr, low, pi-1) \r\n quickSort(arr, pi+1, high) \r\n\r\ndef sort_dictionary(words): ##and then our dictionary is sorted so we can use binary search again\r\n #l=len(words)\r\n #quickSort(words,0,l-1)\r\n words.sort()\r\n\r\n #testing\r\n if os.path.exists(\"dic.txt\"): \r\n os.remove(\"dic.txt\") \r\n \r\n file = open(\"dic.txt\", \"w\")\r\n for k in words:\r\n file.write(k+\"\\n\") \r\n file.close()\r\n return words\r\n\r\ndef temprefill(racktemp): ##When an error occurs, this function restores the rack with its default letters\r\n tmp_rack = all_tiles[counter-1]\r\n for x in racktemp:\r\n tmp_rack.append(x)\r\n all_tiles[counter-1] = tmp_rack\r\n racktemp = []\r\n\r\ndef refilling_tray(): ##After each turn this function makes sure that players rack has 7 letters\r\n tmp_rack = all_tiles[counter-1]\r\n while len(tmp_rack) < 7:\r\n tmp = bag.pop()\r\n tmp_rack.append(tmp)\r\n all_tiles[counter-1] = tmp_rack\r\n\r\ndef check_if_word_in_rack(word_main,counter): ##This functions check that are the letters required available in the rack \r\n global racktemp, blank\r\n tmp_rack = all_tiles[counter-1]\r\n if word_main in tmp_rack:\r\n tmp_rack.remove(word_main)\r\n racktemp.append(word_main)\r\n all_tiles[counter-1] = tmp_rack\r\n return True\r\n elif '#' in tmp_rack:\r\n blank.append(word_main)\r\n tmp_rack.remove('#')\r\n racktemp.append('#')\r\n all_tiles[counter-1] = tmp_rack\r\n return True\r\n return False\r\n\r\ndef rack_empty(counter): ##It checks for the lenght of the rack for scoring purpose\r\n\tif len(all_tiles[counter-1]) == 0:\r\n\t\treturn True\r\n\treturn False\r\n \r\ndef score_checker(word, list_of_scores): ##Calculates indivisual tile's score\r\n global dl ,tl, blank\r\n score = 0\r\n my_string = list(word)\r\n\r\n for i in my_string:\r\n if i in dl:\r\n score = score + (2*Tilescore[i])\r\n dl.pop(dl.index(i))\r\n elif i in tl:\r\n score = score + (3*Tilescore[i])\r\n tl.pop(tl.index(i))\r\n else:\r\n score = score + (Tilescore[i])\r\n \r\n for x in blank:\r\n score = score - (Tilescore[x])\r\n \r\n blank = []\r\n return score\r\n\r\ndef scoring(word,counter): ##It checks and applies DWS & TWS and updates the score\r\n global tempscore, dw, tw\r\n winsound.PlaySound('Score.wav', winsound.SND_FILENAME + winsound.SND_ASYNC)\r\n tempscore = tempscore + score_checker(word, Tilescore)\r\n if dw > 0:\r\n tempscore = tempscore*(2*dw)\r\n dw = 0\r\n\r\n if tw > 0:\r\n tempscore = tempscore*(3*tw)\r\n tw = 0\r\n\r\n if rack_empty(counter) == True:\r\n tempscore = tempscore + 50","sub_path":"func3.0.py","file_name":"func3.0.py","file_ext":"py","file_size_in_byte":7150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"517816659","text":"import asyncio\nimport json\nimport random\nimport time\nfrom kademlia.node import Node\nfrom kademlia.router import RoutingTable\nfrom kademlia.storage import Storage\n\nTIMEOUT = 10 # RPC timeout.\nK = 20\nALPHA = 3\n\n\ndef stub(func):\n assert(func.__name__[:4] == \"ext_\") # sanity check.\n\n async def rpc_stub(self, node, *args):\n loop = asyncio.get_event_loop()\n msg = {\"id\": random.getrandbits(32), \"node\": self.id, \"call\": True, \"rpc\": func.__name__[4:], \"args\": args}\n self.transport.sendto(json.dumps(msg).encode(\"UTF-8\"), node.addr)\n #print(\"sent rpc \" + json.dumps(msg) + \" to \" + str(node.addr) + \" id: \" + str(node.id))\n f = asyncio.Future()\n self.waiting[msg[\"id\"]] = (f, loop.call_later(TIMEOUT+random.randint(0,TIMEOUT), self._timeout, msg[\"id\"]), node)\n await f\n return f.result()\n return rpc_stub\n\n\ndef rpc(func):\n def rpc_func(self, *args):\n return func(self, *args)\n return rpc_func\n\n\nclass KademliaNode(asyncio.DatagramProtocol):\n def __init__(self, id, addr):\n self.id = id\n self.addr = addr\n self.waiting = {}\n self.transport = None\n self.table = RoutingTable(self, K)\n self.chunks = Storage()\n self.players = Storage()\n self._timeouts = {}\n self._fails = {}\n loop = asyncio.get_running_loop()\n\n def refresh():\n print(\"Refreshing stale buckets and republishing kv pairs.\")\n asyncio.ensure_future(self.table.refresh_buckets(self.table.get_stale_buckets()))\n self.republish_keys()\n self.refresh = loop.call_later(3600, refresh)\n\n self.refresh = loop.call_later(3600, refresh)\n\n def connection_made(self, transport):\n self.transport = transport\n\n def connection_lost(self, exc):\n print(f\"we died somehow? {exc}\")\n\n def datagram_received(self, data, addr):\n asyncio.ensure_future(self._handle_datagram(data, addr))\n\n def error_received(self, exc: Exception):\n print(exc)\n\n async def _handle_datagram(self, data, addr):\n msg = json.loads(data.decode(\"UTF-8\"))\n #print(\"received \" + str(msg) + \" at \" + str(self.id))\n node = self.table.get_node_if_contact(msg[\"node\"])\n node = Node(msg[\"node\"], addr) if node is None else node\n if msg[\"call\"]:\n func = getattr(self, msg[\"rpc\"], None)\n if func is None or not callable(func) or func.__name__ != \"rpc_func\":\n return\n res = json.dumps(\n {\"id\": msg[\"id\"], \"node\": self.id, \"call\": False, \"rpc\": msg[\"rpc\"], \"ret\": func(*msg[\"args\"])})\n #print(\"return to sender \" + res + \" \" + str(node.id))\n self.transport.sendto(res.encode(\"UTF-8\"), addr)\n else:\n if msg[\"id\"] in self.waiting:\n self.waiting[msg[\"id\"]][1].cancel()\n self.waiting[msg[\"id\"]][0].set_result(msg[\"ret\"])\n del self.waiting[msg[\"id\"]]\n self._process_contact(node)\n\n def _process_contact(self, node):\n self._fails[node.id] = 0\n if node.id == self.id:\n return\n\n # send values that need to be sent.\n if self.table.get_node_if_contact(node.id) is not None: # if node is not new then there's nawt to do.\n return\n\n self.table.add_contact(node)\n\n # send all values it needs\n for key in self.chunks:\n nearby = self.table.nearest_nodes_to(key)\n if len(nearby) > 0:\n if not (node.id ^ key < nearby[-1].id ^ key and self.id ^ key < nearby[0].id ^ key):\n continue\n asyncio.ensure_future(self.ext_store_chunk(node, key, self.chunks[key]))\n\n def _timeout(self, msg_id):\n node = self.waiting[msg_id][2]\n print(\"RPC call timed out to \" + str(node.id) + \"(\" + str(node.addr) + \") from \" + str(self.id) + \" msgid: \" + str(msg_id))\n self.waiting[msg_id][0].set_result(None)\n del self.waiting[msg_id]\n if node.id not in self._fails:\n self._fails[node.id] = 0\n self._fails[node.id] = self._fails[node.id] + 1\n if self._fails[node.id] >= 5:\n self.table.remove_contact(node) # this is not correct to kademlia implementation, need to add 5 failure removal\n print(\"timed out done now yeet\")\n self._timeouts[node] = time.monotonic()\n\n @stub\n async def ext_ping(self, node):\n pass\n\n @stub\n async def ext_find_node(self, node, node_id):\n pass\n\n @stub\n async def ext_find_chunk(self, node, key):\n pass\n\n @stub\n async def ext_find_player(self, node, key):\n pass\n\n @stub\n async def ext_store_chunk(self, node, key, value):\n pass\n\n @stub\n async def ext_store_player(self, node, key, value):\n pass\n\n @rpc\n def ping(self):\n return self.id\n\n @rpc\n def find_node(self, node_id):\n return list(map(lambda node: (node.id, node.addr[0], node.addr[1]), self.table.nearest_nodes_to(node_id)))\n\n @rpc\n def find_chunk(self, key):\n if key in self.chunks:\n return self.chunks[key]\n return self.find_node(key)\n\n @rpc\n def find_player(self, key):\n if key in self.players:\n return self.players[key]\n return self.find_node(key)\n\n @rpc\n def store_chunk(self, key, value):\n self.chunks[key] = value\n\n @rpc\n def store_player(self, key, value):\n self.players[key] = value\n\n async def lookup(self, key_or_id, value=False, find_type=None):\n nodes = self.table.nearest_nodes_to(key_or_id) + [Node(self.id,self.addr)]\n queried = [Node(self.id, self.addr)]\n found_new = False\n while len(nodes) > 0:\n best = nodes[0]\n multicast = []\n unqueried = list(filter(lambda n: n not in queried and (n not in self._timeouts or time.monotonic() - self._timeouts[n] > 600), nodes)) # don't query recently failed nodes\n for i in range(0, min(ALPHA if found_new else K, len(unqueried))):\n multicast.append(unqueried.pop(0))\n res = await asyncio.gather(*[find_type(n, key_or_id) if value else self.ext_find_node(n, key_or_id) for n in multicast])\n queried += multicast\n for i in range(0, len(res)):\n if res[i] is None:\n continue\n if value and type(res[i]) != list: # this means we cannot store lists in DHT.\n return res[i] # have found value, return it.\n nodes += list(map(lambda x: self.table.get_node_if_contact(x[0]) if self.table.get_node_if_contact(x[0]) is not None else Node(x[0], (x[1], x[2])), res[i]))\n nodes = list(set(nodes))\n nodes.sort(key=lambda n: n.id ^ key_or_id)\n nodes = nodes[:K] # only keep K best.\n found_new = (best != nodes[0])\n if found_new or len(list(filter(lambda x: x not in queried, nodes))) > 0:\n continue\n break\n return None if value else nodes\n\n async def lookup_count(self, key_or_id, value=False, find_type=None):\n nodes = self.table.nearest_nodes_to(key_or_id)\n queried = [Node(self.id, ())]\n found_new = False\n while len(nodes) > 0:\n best = nodes[0]\n multicast = []\n unqueried = list(filter(\n lambda n: n not in queried and (n not in self._timeouts or time.monotonic() - self._timeouts[n] > 600),\n nodes)) # don't query recently failed nodes\n for i in range(0, min(ALPHA if found_new else K, len(unqueried))):\n multicast.append(unqueried.pop(0))\n res = await asyncio.gather(\n *[find_type(n, key_or_id) if value else self.ext_find_node(n, key_or_id) for n in multicast])\n queried += multicast\n for i in range(0, len(res)):\n if res[i] is None:\n continue\n if value and type(res[i]) != list: # this means we cannot store lists in DHT.\n return res[i] # have found value, return it.\n nodes += list(map(lambda x: self.table.get_node_if_contact(x[0]) if self.table.get_node_if_contact(\n x[0]) is not None else Node(x[0], (x[1], x[2])), res[i]))\n nodes = list(set(nodes))\n nodes.sort(key=lambda n: n.id ^ key_or_id)\n nodes = nodes[:K] # only keep K best.\n found_new = (best != nodes[0])\n if found_new or len(list(filter(lambda x: x not in queried, nodes))) > 0:\n continue\n break\n return len(queried)\n\n async def insert(self, key, value, store_type=None):\n nodes = await self.lookup(key)\n await asyncio.gather(*[store_type(n, key, value) for n in nodes])\n\n async def bootstrap(self, node):\n self.table.add_contact(node)\n await self.lookup(self.id)\n await self.table.refresh_buckets(self.table.buckets[i] for i in range(self.table.get_first_nonempty_bucket()+1, len(self.table.buckets))) # should this be different?\n\n def republish_keys(self):\n now = time.monotonic()\n for key in self.chunks:\n value = self.chunks[key]\n t = self.chunks.time[key]\n if now - t > 3600:\n del self.chunks[key]\n asyncio.ensure_future(self.insert(key, value, store_type=self.ext_store_chunk))\n for key in self.players:\n value = self.players[key]\n t = self.players.time[key]\n if now - t > 3600:\n del self.players[key]\n asyncio.ensure_future(self.insert(key, value, store_type=self.ext_store_player))\n","sub_path":"Code/Server/kademlia/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":9754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"494288964","text":"# Sequência de números de 1 a 10.\n'''\ncont = 1\nwhile cont <= 10:\n print(cont, '→ ', end='')\n cont += 1\nprint('Acabou')\n'''\n# Loop infinito com o mesmo algoritmo, apenas trocando o limite de 10 números para \"enquanto for verdade\".\n'''\ncont = 1\nwhile True:\n print(cont, '→ ', end='')\n cont += 1\nprint('Acabou')\n'''\n# Tratando vários valores COM GAMBIARRA:\n'''\nn = s = 0\nwhile n != 999:\n n = int(input('Digite um número: '))\n s += n\ns -= 999 # GAMBIARRA!\nprint(f'A soma vale {s}.')\n'''\n# Tratando vários valores SEM GAMBIARRA:\nn = s = 0\nwhile True:\n n = int(input('Digite um número: '))\n if n == 999:\n break\n s += n\nprint(f'A soma vale {s}.')\n","sub_path":"aula14a.py","file_name":"aula14a.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"44443674","text":"\"\"\"\r\nDeveloped by Guy Bland, Junior Cyber Security Analyst on behalf of ParaFlare.\r\nUse of this code is strictly limited.\r\nYeah, I know it's shit code, get off my back Ben.\r\n\"\"\"\r\nimport netifaces\r\nimport os\r\nimport re\r\nimport subprocess\r\nimport nmap\r\nimport json\r\nfrom subprocess import PIPE\r\n\r\n# Global variables\r\nroutes = {}\r\nsubnets = []\r\nsystem_os: str = os.name\r\nlive_hosts = []\r\nports = []\r\ndirectory = \"tmp\"\r\nfilename = \"output.json\"\r\nsystems = {}\r\nnetwork = {}\r\nhost_count = 0\r\n\r\n\r\ndef check_reqs():\r\n\r\n if os.name == \"posix\":\r\n wheremap = subprocess.Popen([\"which\", \"nmap\"], stdout=PIPE, stderr=PIPE)\r\n result = wheremap.communicate()[0]\r\n if \"nmap\" not in str(result):\r\n print(\"nmap not in path\")\r\n else:\r\n print(\"nmap found\")\r\n else:\r\n print(\"Add Windows path check\")\r\n\r\n\r\n# Get local network details (interfaces, ip, mac, gateway)\r\ndef get_net_info():\r\n \"\"\"\"\"\r\n # get_net_info()\r\n \r\n * Iterates through network adapters to return, local IPv4 addresses, MAC addresses and gateway.\r\n \r\n * Each new subnet discovered is passed to the scan_subnet() function\r\n and appended to the subnets list to avoid double dipping.\r\n \"\"\"\"\"\r\n for iface in netifaces.interfaces():\r\n iface_details = netifaces.ifaddresses(iface)\r\n if netifaces.AF_INET in iface_details:\r\n d_gateway = netifaces.gateways()[\"default\"][netifaces.AF_INET]\r\n for details in iface_details[netifaces.AF_LINK]:\r\n for i_mac in details:\r\n mac = i_mac\r\n for ip_interfaces in iface_details[netifaces.AF_INET]:\r\n for key, i_ip in ip_interfaces.items():\r\n if key == 'addr' and i_ip != '127.0.0.1':\r\n ip = i_ip\r\n mask = re.search(r\"(.*)\\.(.*)\\.(.*)\\.(.*)\", ip)\r\n if mask:\r\n netmask = \"{}.{}.{}.1\".format(mask.group(1), mask.group(2), mask.group(3))\r\n if netmask not in subnets:\r\n subnets.append(netmask)\r\n print(\"Adapter: \", iface, \"\\nIP: \", ip, \"\\nMAC: \", mac, \"\\nGateway: \", d_gateway[0], \"\\nSubnet: {}/24\\n\".format(netmask))\r\n scan_subnet(netmask)\r\n\r\n\r\n# Get routes to each host\r\ndef trace(ipaddress):\r\n \"\"\"\"\"\r\n # trace()\r\n \r\n * Responsible for discovering the number of hops between and time between a host.\r\n \r\n * It generates separate commands depending on the detected OS, \r\n and then uses regex to split the information into groups.\r\n \"\"\"\"\"\r\n if system_os == \"nt\":\r\n cmd = \"tracert\"\r\n elif system_os == \"posix\":\r\n cmd = \"traceroute\"\r\n else:\r\n print(\"[-] OS {} isn't supported\".format(system_os))\r\n traceroute = subprocess.Popen([cmd, ipaddress], stdout=PIPE, stderr=PIPE)\r\n raw = ((traceroute.communicate()[0]).decode(\"utf-8\")).splitlines()\r\n results = list(map(lambda x: x.strip(), raw))\r\n\r\n for line in results:\r\n # Hop was unsuccessful\r\n if re.match(r\"^\\s*(\\d+)\\s+\\*\\s+\\*\\s+\\*\", line, re.IGNORECASE):\r\n print(\"\\t[-] Hop was unsuccessful\")\r\n break\r\n # Hop was successful\r\n elif re.match(r\"^\\s*(\\d+)\\s+([a-z0-9\\.\\-]+)\\s+\\((\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\)\\s(.+)$\", line, re.IGNORECASE):\r\n m = re.search(r\"^\\s*(\\d+)\\s+([a-z0-9\\.\\-]+)\\s+\\((\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\)\\s(.+)$\", line, re.IGNORECASE)\r\n hop, name, ip, rest, = m.group(1), m.group(2), m.group(3), m.group(4)\r\n print(\"\\n\\t{} {} {} {}\\n\".format(hop, name, ip, rest))\r\n routes[name] = ip\r\n\r\n\r\ndef scan_subnet(subnet):\r\n \"\"\"\"\"\r\n # scan_subnet()\r\n \r\n * Uses the subnet gathered from get_net_info(), it performs 3 scans to account for network instability.\r\n \r\n * This nmap scan is quick host discovery, with no detection of ports or services. \r\n \r\n * Those functions are handled by scan_hosts() which is called on each discovered IPv4 address\r\n \r\n * build_json_structure() is executed once all individual discovered addresses have been scanned, \r\n completing the JSON structure.\r\n \"\"\"\"\"\r\n # Scan the subnet to identify alive hosts\r\n nm = nmap.PortScanner()\r\n netmask = \"{}{}\".format(subnet, \"/24\")\r\n print(\"[*] Scanning subnet {}\".format(netmask))\r\n # Perform 3 nmap scans to account for network inconsistency\r\n for _ in range(3):\r\n nm.scan(netmask, arguments=\"-sP\")\r\n for host in nm.all_hosts():\r\n if nm[host].state() == \"up\" and nm[host]['status']['reason'] != \"localhost-response\" and nm[host]['addresses']['ipv4'] not in live_hosts:\r\n live_hosts.append(nm[host]['addresses']['ipv4'])\r\n print(\"\\n[+] Host {} is alive\".format(nm[host]['addresses']['ipv4']))\r\n scan_hosts(nm[host]['addresses']['ipv4'], netmask, 0)\r\n build_json_structure(netmask=netmask, join=True)\r\n\r\n\r\n# Iterate through the list of alive hosts and scan for open tcp ports\r\ndef scan_hosts(available_host, netmask, failure):\r\n \"\"\"\"\"\r\n # scan_hosts()\r\n \r\n * Passes discovered IPv4 addresses from scan_subnet(), the associated subnet, and a separate failure value.\r\n \r\n * The failure variable is used as hosts don't always respond, or may go down inbetween discovery and scan.\r\n \r\n * 4 unsuccessful scans will be attempted before the function moves onto another address. \r\n \"\"\"\"\"\r\n if failure <= 3:\r\n ip = available_host\r\n print(\"\\t[*] Performing port scan on {}\".format(ip))\r\n ps = nmap.PortScanner()\r\n ps.scan(ip, arguments=\"-O -F --top-ports 100\")\r\n if ps.all_hosts():\r\n for host in ps.all_hosts():\r\n sys_info = {}\r\n hostname = ps[host].hostname()\r\n print(\"\\tHost: {}\".format(ps[host].hostname()))\r\n if 'osmatch' in ps[host]:\r\n for osmatch in ps[host]['osmatch']:\r\n print(\"\\tOS: {1} ({0}% Match)\".format(osmatch['accuracy'], osmatch['name']))\r\n if 'osclass' in osmatch:\r\n for osclass in osmatch['osclass']:\r\n print(\"\\tType: {0}\\n\\tVendor: {1}\\n\".format(osclass['type'], osclass['vendor']))\r\n sys_info = {\"os\": \"{}\".format(osmatch['name']), \"type\": \"{}\".format(osclass['type']), \"vendor\": \"{}\".format(osclass['vendor'])}\r\n\r\n else:\r\n print(\"OS: Unknown\")\r\n ports_list = []\r\n if 'tcp' in ps[host]:\r\n try:\r\n lports = ps[host]['tcp'].keys()\r\n for port in lports:\r\n if ps[host]['tcp'][port]['state'] == 'open':\r\n print(\"\\t\\ttcp/{} : {}\".format(port, ps[host]['tcp'][port]['state']))\r\n ports_list.append(port)\r\n\r\n except Exception as er:\r\n # print(\"\\t\\t[-] No open ports\")\r\n print(\"Port Exception: {}\".format(er))\r\n trace(host)\r\n build_json_structure(available_host, ports_list, sys_info, hostname, netmask=netmask, count=host_count++1)\r\n else:\r\n print(\"\\t\\t[-] No open ports\")\r\n\r\n trace(host)\r\n build_json_structure(available_host, ports_list, sys_info, hostname, netmask=netmask, count=host_count++1)\r\n else:\r\n failure += 1\r\n scan_hosts(available_host, netmask, failure)\r\n else:\r\n return None\r\n\r\n\r\ndef dump_data(data):\r\n \"\"\"\"\"\r\n # dump_data()\r\n \r\n * Builds the file / directory structure, and outputs the parsed JSON data to a local file 'tmp/output.json', \r\n first detecting in the structure already exists.\r\n \"\"\"\"\"\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n if not os.path.exists(\"{}/{}\".format(directory, filename)):\r\n f = open(\"{}/{}\".format(directory, filename), \"w+\")\r\n f.write(data)\r\n else:\r\n f = open(\"{}/{}\".format(directory, filename), \"a\")\r\n f.write(data)\r\n\r\n\r\ndef build_json_structure(host=\"\", ports_list=\"\", sys_info=\"\", hostname=False, count=host_count, netmask=\"\", join=False):\r\n \"\"\"\"\"\r\n # build_json_structure()\r\n \r\n * Checks if join has been defined, this variable indicates that the structure is complete, and adds the last key,\r\n the subnet which all the information sits beneath.\r\n \r\n * If not yet defined, then the structure is still being constructed, and builds the JSON structure in reverse.\r\n \r\n * First associates the host (ip) with it's discovered system info, then adds a list of open ports that were detected\r\n on that address.\r\n \r\n * Once the structure is built, join=True and join_subnet() is invoked with the primary key added.\r\n \"\"\"\"\"\r\n if not join:\r\n print(sys_info)\r\n print(netmask)\r\n print(\"Count: {}\".format(count))\r\n systems[count] = {}\r\n systems[count][\"hostname\"] = hostname\r\n systems[count][\"ports\"] = ports_list\r\n systems[count][\"ipv4\"] = host\r\n systems[count][\"mask\"] = netmask\r\n\r\n if \"os\" in sys_info:\r\n systems[count][\"os\"] = sys_info[\"os\"]\r\n systems[count][\"type\"] = sys_info[\"type\"]\r\n systems[count][\"vendor\"] = sys_info[\"vendor\"]\r\n\r\n global host_count\r\n host_count = host_count + 1\r\n\r\n elif join:\r\n network[\"network\"] = systems\r\n join_subnet(network)\r\n\r\n\r\ndef join_subnet(subnet):\r\n \"\"\"\"\"\r\n # join_subnet()\r\n \r\n * The subnet is added as the primary key, and the JSON structure is outputted to a local file via dump_data()\r\n \"\"\"\"\"\r\n dump_data(json.dumps(subnet, indent=4))\r\n\r\n\r\nget_net_info()\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"575841446","text":"#SVM\n#匯入套件\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#read.csv\ndata = pd.read_csv('social_network_ads.csv')\nx = data.iloc[:, [2,3]].values\ny = data.iloc[:, 4].values\n\n#分為測試訓練集\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y,\n test_size = 0.25, random_state = 0)\n\n#特徵縮放(應變數不需要,要0或1)\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nx_train = sc.fit_transform(x_train)\nx_test = sc.fit_transform(x_test)\n\n#建立SVM模型\nfrom sklearn.svm import SVC\nmodel = SVC(kernel = 'linear', random_state = 0)\nmodel.fit(x_train, y_train)\n\n#預測\ny_pred = model.predict(x_test)\n\n#混淆矩陣(查看正確率) 88%\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\n#視覺化\nfrom matplotlib.colors import ListedColormap\nx_set, y_set = x_train, y_train\n\n#meshgrid畫出座標點上網格(可以為n維)\n#產生所有的座標點\n#-1 及+1 是要使兩邊留白(多一個單位)\nx1, x2 = np.meshgrid(np.arange(start = x_set[:, 0].min() - 1,\n stop = x_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = x_set[:, 1].min() - 1,\n stop = x_set[:, 1].max() + 1,step = 0.01))\n\n#contour分界(預測網格的值並上色)\nplt.contourf(x1, x2, model.predict(np.array([x1.ravel(),\n x2.ravel()]).T).reshape(x1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\n\n#設定邊界\nplt.xlim(x1.min(), x1.max())\nplt.ylim(x2.min(), x2.max())\n\n#迴圈\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(x_set[y_set == j, 0], x_set[y_set == j, 1],\n c = ListedColormap(('orange','blue'))(i), label = j)\n\nplt.title('classifier (train_set)')\nplt.xlabel('Age')\nplt.ylabel('EstimatedSalary')\nplt.legend()\nplt.show() \n\n#測試集\nx_set, y_set = x_test, y_test\nx1, x2 = np.meshgrid(np.arange(start = x_set[:, 0].min() - 1,\n stop = x_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = x_set[:, 1].min() - 1,\n stop = x_set[:, 1].max() + 1,step = 0.01))\n\n#contour分界(預測網格的值並上色)\nplt.contourf(x1, x2, model.predict(np.array([x1.ravel(),\n x2.ravel()]).T).reshape(x1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\n\n#設定邊界\nplt.xlim(x1.min(), x1.max())\nplt.ylim(x2.min(), x2.max())\n\n#迴圈\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(x_set[y_set == j, 0], x_set[y_set == j, 1],\n c = ListedColormap(('orange','blue'))(i), label = j)\n\nplt.title('classifier (test_set)')\nplt.xlabel('Age')\nplt.ylabel('EstimatedSalary')\nplt.legend()\nplt.show() \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"SVM/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"505230465","text":"# Copyright (C) 2023 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n#\n\nimport openvino.runtime as ov\nfrom openvino.runtime import Core, Type, OVAny, properties\n\ndevice_name = 'CPU'\nxml_path = 'model.xml'\ncore = ov.Core()\ncore.set_property(\"CPU\", ov.properties.intel_cpu.sparse_weights_decompression_rate(0.8))\nmodel = core.read_model(model=xml_path)\n# ! [ov:intel_cpu:multi_threading:part0]\n# Use one logical processor for inference\ncompiled_model_1 = core.compile_model(model=model, device_name=device_name, config={properties.inference_num_threads(1)})\n\n# Use logical processors of Efficient-cores for inference on hybrid platform\ncompiled_model_2 = core.compile_model(model=model, device_name=device_name, config={properties.hint.scheduling_core_type(properties.hint.SchedulingCoreType.ECORE_ONLY)})\n\n# Use one logical processor per CPU core for inference when hyper threading is on\ncompiled_model_3 = core.compile_model(model=model, device_name=device_name, config={properties.hint.enable_hyper_threading(False)})\n# ! [ov:intel_cpu:multi_threading:part0]\n\n# ! [ov:intel_cpu:multi_threading:part1]\n# Disable CPU threads pinning for inference when system supoprt it\ncompiled_model_4 = core.compile_model(model=model, device_name=device_name, config={properties.hint.enable_cpu_pinning(False)})\n# ! [ov:intel_cpu:multi_threading:part1]\nassert compiled_model_1\nassert compiled_model_2\nassert compiled_model_3\nassert compiled_model_4\n","sub_path":"docs/snippets/cpu/multi_threading.py","file_name":"multi_threading.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"573300322","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom .article import Article\n\n\nclass NewsArticle(Article):\n \"\"\"Defines a news article.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :param _type: Constant filled by server.\n :type _type: str\n :ivar id: A String identifier.\n :vartype id: str\n :ivar web_search_url: The URL To Bing's search result for this item.\n :vartype web_search_url: str\n :ivar name: The name of the thing represented by this object.\n :vartype name: str\n :ivar url: The URL to get more information about the thing represented by\n this object.\n :vartype url: str\n :ivar image: An image of the item.\n :vartype image:\n ~azure.cognitiveservices.search.newssearch.models.ImageObject\n :ivar description: A short description of the item.\n :vartype description: str\n :ivar alternate_name: An alias for the item\n :vartype alternate_name: str\n :ivar bing_id: An ID that uniquely identifies this item.\n :vartype bing_id: str\n :ivar thumbnail_url: The URL to a thumbnail of the item.\n :vartype thumbnail_url: str\n :ivar provider: The source of the creative work.\n :vartype provider:\n list[~azure.cognitiveservices.search.newssearch.models.Thing]\n :ivar date_published: The date on which the CreativeWork was published.\n :vartype date_published: str\n :ivar video: A video of the item.\n :vartype video:\n ~azure.cognitiveservices.search.newssearch.models.VideoObject\n :ivar word_count: The number of words in the text of the Article.\n :vartype word_count: int\n :ivar category: The news category that the article belongs to. For\n example, Sports. If the news category cannot be determined, the article\n does not include this field.\n :vartype category: str\n :ivar headline: A Boolean value that indicates whether the news article is\n a headline. If true, the article is a headline. The article includes this\n field only for news categories requests that do not specify the category\n query parameter.\n :vartype headline: bool\n :ivar clustered_articles: A list of related news articles.\n :vartype clustered_articles:\n list[~azure.cognitiveservices.search.newssearch.models.NewsArticle]\n \"\"\"\n\n _validation = {\n '_type': {'required': True},\n 'id': {'readonly': True},\n 'web_search_url': {'readonly': True},\n 'name': {'readonly': True},\n 'url': {'readonly': True},\n 'image': {'readonly': True},\n 'description': {'readonly': True},\n 'alternate_name': {'readonly': True},\n 'bing_id': {'readonly': True},\n 'thumbnail_url': {'readonly': True},\n 'provider': {'readonly': True},\n 'date_published': {'readonly': True},\n 'video': {'readonly': True},\n 'word_count': {'readonly': True},\n 'category': {'readonly': True},\n 'headline': {'readonly': True},\n 'clustered_articles': {'readonly': True},\n }\n\n _attribute_map = {\n '_type': {'key': '_type', 'type': 'str'},\n 'id': {'key': 'id', 'type': 'str'},\n 'web_search_url': {'key': 'webSearchUrl', 'type': 'str'},\n 'name': {'key': 'name', 'type': 'str'},\n 'url': {'key': 'url', 'type': 'str'},\n 'image': {'key': 'image', 'type': 'ImageObject'},\n 'description': {'key': 'description', 'type': 'str'},\n 'alternate_name': {'key': 'alternateName', 'type': 'str'},\n 'bing_id': {'key': 'bingId', 'type': 'str'},\n 'thumbnail_url': {'key': 'thumbnailUrl', 'type': 'str'},\n 'provider': {'key': 'provider', 'type': '[Thing]'},\n 'date_published': {'key': 'datePublished', 'type': 'str'},\n 'video': {'key': 'video', 'type': 'VideoObject'},\n 'word_count': {'key': 'wordCount', 'type': 'int'},\n 'category': {'key': 'category', 'type': 'str'},\n 'headline': {'key': 'headline', 'type': 'bool'},\n 'clustered_articles': {'key': 'clusteredArticles', 'type': '[NewsArticle]'},\n }\n\n def __init__(self):\n super(NewsArticle, self).__init__()\n self.category = None\n self.headline = None\n self.clustered_articles = None\n self._type = 'NewsArticle'\n","sub_path":"azure-cognitiveservices-search-newssearch/azure/cognitiveservices/search/newssearch/models/news_article.py","file_name":"news_article.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"382302736","text":"from __future__ import annotations # noqa\nfrom dataclasses import dataclass\nfrom operator import itemgetter\nfrom typing import Dict, List, Tuple\n\nfrom dataclasses_json import dataclass_json\n\nfrom docsim.utils.utils import uniq\n\n\n@dataclass\nclass RankItem:\n \"\"\"\n both a prediction result or a ground truth\n recall, precision and ap considere self as a ground truth\n \"\"\"\n query_id: str\n scores: Dict[Tuple[str, str], float] # (docid, tag) -> score\n\n def get_doc_scores(self) -> Dict[str, float]:\n return {key[0]: score for key, score in self.scores.items()}\n\n def get_tag_scores(self) -> Dict[str, float]:\n return {key[1]: score for key, score in self.scores.items()}\n\n def pred_tags(self,\n n_top: int) -> List[str]:\n sorted_score: List[str] = [\n tag for tag, _ in sorted(self.get_tag_scores().items(),\n key=itemgetter(1),\n reverse=True)]\n unique_tags: List[str] = uniq(orig=sorted_score, n_top=n_top)\n return unique_tags\n\n def __len__(self) -> int:\n return len(self.scores)\n\n\n@dataclass_json\n@dataclass\nclass ColDocument:\n docid: str\n title: str\n text: str\n tags: List[str]\n\n @classmethod\n def mapping(cls) -> Dict:\n return {\n 'properties': {\n 'docid': {\n 'type': 'keyword'\n },\n 'title': {\n 'type': 'text',\n 'analyzer': 'english'\n },\n 'text': {\n 'type': 'text',\n 'analyzer': 'english'\n },\n 'tags': {\n 'type': 'keyword'\n }\n }\n }\n","sub_path":"docsim/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"233867538","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport json\r\nimport re\r\nurl = 'https://www.dme.ru/shopping/shop/'\r\ndomain = \"\".join(re.findall('(https?://)?(www\\.)?([-\\w.]+)', url)[0])\r\nstran = requests.get(url).text\r\nc = BeautifulSoup(stran, 'lxml')\r\nmag = {}\r\n\r\ndan = (c.find('div', class_='shadows_left')\r\n .find('div', class_='shadows_right')\r\n .find('div', class_='layout')\r\n .find('div', class_='main')\r\n .find('div', class_='right_column')\r\n .find('div', class_='content')\r\n .find('div', class_='simple')\r\n .find('div', class_='simple')\r\n .find('div')\r\n .find('div'))\r\n\r\n\r\ndan = dan.findAll(['a', 'h2', 'p'])\r\n\r\nkey = ''\r\nfor item in dan:\r\n if item.name == 'h2':\r\n mag.update({item.text: {'title': item.text, 'place': 'неизвестно', 'magazins': []}})\r\n key = item.text\r\n\r\n elif key and item.name == 'p' and 'располож' in item.text:\r\n pattern = re.compile('расположен[\\w]?\\s', re.IGNORECASE)\r\n mag[key]['place'] = re.split(pattern, item.text)[1]\r\n\r\n elif key and item.name == 'a' and item.text:\r\n mag_url = domain + (item.attrs[\"href\"] if item.attrs['href'][0] == '/' else f'/{item.attrs[\"href\"]}')\r\n mag[key]['magazins'].append({'title': item.text, 'url': mag_url})\r\n\r\nwith open('Zach.json', 'w', encoding='utf-8') as f:\r\n json.dump(mag, f, ensure_ascii=False)\r\n","sub_path":"zachet/zach.py","file_name":"zach.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"195494429","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom mock import MagicMock, patch\n\nLED_PIN = 26\nBTN_PIN = 5\nHOST = 'test_host'\nPORT = 1883\nPUSHED_PAYLOAD = 'pushed'\nDEVICE_TYPE = 'robot'\nDEVICE_ID = 'robot01'\n\nMockNeopixel = MagicMock()\nMockRPi = MagicMock()\nMockTime = MagicMock()\nMockArgparse = MagicMock()\nMockArgumentParser = MagicMock()\nMockArg = MagicMock()\nMockArg.host = HOST\nMockArg.port = PORT\nMockArg.device_type = DEVICE_TYPE\nMockArg.device_id = DEVICE_ID\nMockArg.pushed_payload = PUSHED_PAYLOAD\n\nMockArgparse.ArgumentParser.return_value = MockArgumentParser\nMockArgumentParser.parse_args.return_value = MockArg\n\nmodules = {\n \"neopixel\": MockNeopixel,\n \"RPi\": MockRPi,\n \"RPi.GPIO\": MockRPi.GPIO,\n \"time\": MockTime,\n \"argparse\": MockArgparse,\n}\npatcher = patch.dict(\"sys.modules\", modules)\npatcher.start()\n","sub_path":"tests/module_mock.py","file_name":"module_mock.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"387057570","text":"\nimport ray\nimport pandas as pd\nimport numpy as np\nimport os\nimport re\nimport datetime\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.feature_selection import SequentialFeatureSelector\nfrom sklearn.pipeline import Pipeline\nfrom sklearn import metrics\nimport traceback\nimport warnings\nwarnings.filterwarnings(\"ignore\")\npd.options.mode.chained_assignment = None\n\n\ndef pre_process_data(df, null_threshold):\n \"\"\"\n Drops Date and Unix Date columns from the data.\n Drops the columns which has null values more than specified null_threshold.\n Replaces infinite values with NAN.\n Drops the rows which has null values.\n\n Parameters\n ----------\n data : dataframe\n\n null_threshold : numeric\n numeric value describing the amount of null values that can be present.\n\n Returns\n -------\n data : dataframe\n an updated dataframe after performing all the opertaions.\n \"\"\"\n\n df.drop(columns=['Date'], axis=1, inplace=True)\n total = df.shape[0]\n for col in df.columns:\n if null_threshold * total / 100 < df[col].isnull().sum():\n df.drop(columns=[col], axis=1, inplace=True)\n df.replace([np.inf, -np.inf], np.nan, inplace=True)\n df[df.columns] = (df[df.columns].astype(str)).apply(pd.to_numeric, errors='coerce')\n df.dropna(axis=0, inplace=True)\n return df\n\n\ndef error_metrics(y_true, y_pred):\n rmse = metrics.mean_squared_error(y_true, y_pred) ** 0.5\n mae = metrics.mean_absolute_error(y_true, y_pred)\n mse = metrics.mean_squared_error(y_true, y_pred)\n r2_score = metrics.r2_score(y_true, y_pred)\n return {\"root_mean_squared_error\": rmse, \"mean_absolute_error\": mae, \"mean_squared_error\": mse, \"r2_score\": r2_score}\n\n\ndef split_dataset(X, Y, t):\n tr = int(len(X)*t)\n tt = len(X) - tr\n xtr = X[:tr]\n xtt = X[tr:tr+tt]\n ytr = Y[:tr]\n ytt = Y[tr:tr+tt]\n return (xtr, xtt, ytr, ytt)\n\n\ndef remove_next_columns(df, column):\n cols = [col for col in df.columns if \"next\" not in col.lower()]\n cols.append(column)\n df = df[cols]\n return (df, column)\n\n\ndef remove_cp_columns(df):\n cols = [col for col in df.columns if not col.lower().startswith(\"cp\")]\n df = df[cols]\n return df\n\n\ndef remove_previous_columns(df, column):\n cols = [col for col in df.columns if not col.lower().startswith(\"previous\")]\n cols.append(column)\n df = df[cols]\n return df\n\n\ndef remove_max_avg_min_columns(df):\n cols = [col for col in df.columns if not (col.lower().startswith(\n \"max\") or col.lower().startswith(\"avg\") or col.lower().startswith(\"min\"))]\n df = df[cols]\n return df\n\n\ndef run_linear(X_train, X_test, Y_train, Y_test, num, col, security_code):\n linear_pipeline = Pipeline([(\"feature_selection\", SequentialFeatureSelector(LinearRegression(\n ), n_jobs=None, n_features_to_select=num)), (\"linear_regression\", LinearRegression())])\n linear_pipeline.fit(X_train, Y_train)\n # pickle.dump(linear_pipeline, open(os.path.join(\n # modelpath, str(security_code) + \"_\" + col + \".sav\", 'wb')))\n Y_pred = linear_pipeline.predict(X_test)\n result = error_metrics(Y_test, Y_pred)\n selected_features = X_train.columns[linear_pipeline[\"feature_selection\"].get_support(\n )].tolist()\n result.update({\"selected_features\": selected_features})\n result.update({\"numoffeatures\": len(selected_features)})\n result.update({\"predicted_column\": col})\n result.update({\"model\": \"linear\"})\n result.update({\"actual\": Y_test.values.tolist()})\n result.update({\"predicted\": Y_pred.tolist()})\n return result\n\n\ndef run_models(df, col, security_code):\n ref = df.copy()\n days = int(re.findall(r\"\\d+\", col)[0])\n # start = df['Date'].iloc[0] + datetime.timedelta(days=days)\n # end = df['Date'].iloc[-1] - datetime.timedelta(days=days)\n # df = df[df.Date.between(start, end)]\n df = pre_process_data(df, 60)\n df[df.columns] = (df[df.columns].astype(str)).apply(\n pd.to_numeric, errors='coerce')\n df, column = remove_next_columns(df, col)\n X = df.drop(columns=[column])\n Y = df[column]\n X_train, X_test, Y_train, Y_test = split_dataset(X, Y, 0.70)\n num = 0.33\n linres = run_linear(X_train, X_test, Y_train, Y_test,\n num, column, security_code)\n linres.update({\"close\": ref.loc[X_test.index]\n ['Close Price'].values.tolist()})\n linres.update({\"date\": ref.loc[X_test.index]['Date'].apply(\n lambda row: row.strftime('%Y-%m-%d')).values.tolist()})\n\n return linres\n\n\n@ray.remote\ndef run_companies_lb(security_code, col):\n try:\n security_code = str(security_code)\n df = pd.read_csv(os.path.join(path, \"gr\"+security_code+\".csv\"))\n df = df.iloc[::-1].reset_index(drop=True)\n df['Date'] = pd.to_datetime(df['Date'])\n df = df[necessary_columns]\n result = run_models(df, col, security_code)\n result.update({\"company\": security_code})\n return result\n except:\n return None\n\n\n@ray.remote\ndef run_companies_ub(security_code, col):\n try:\n security_code = str(security_code)\n df = pd.read_csv(os.path.join(path, \"gr\"+security_code+\".csv\"))\n df = df.iloc[::-1].reset_index(drop=True)\n df['Date'] = pd.to_datetime(df['Date'])\n df = df[necessary_columns]\n result = run_models(df, col, security_code)\n result.update({\"company\": security_code})\n return result\n except:\n return None\n\n\ndef intial_run():\n fullresult = []\n for security_code in sp500companies:\n try:\n print(security_code)\n lbresult = run_companies_lb.remote(\n security_code, columns_to_predict[2])\n ubresult = run_companies_ub.remote(\n security_code, columns_to_predict[3])\n result = ray.get([lbresult, ubresult])\n if result[0] != None and result[1] != None:\n fullresult.extend(result)\n except:\n traceback.print_exc()\n resultdf = pd.DataFrame(fullresult)\n resultdf.to_csv(os.path.join(os.getcwd(), \"Data\",\n \"next_60_days.csv\"), index=None)\n\n\ndef create_files(days):\n filename = \"next_{}_days.csv\".format(days)\n df = pd.read_csv(os.path.join(npath, filename))\n\n sp500 = pd.read_csv(os.path.join(npath,\"SP500companies.csv\")).set_index(\"Security Code\")\n cols = ['predicted_column', 'actual',\n 'predicted', 'close', 'date', 'company']\n df = df[cols]\n\n df['company'] = df['company'].apply(\n lambda row: str(int(row)) + \"-\" + re.sub('[!@#$%^&*(.)-=,\\\\\\/\\']', '', sp500.loc[int(row), \"Security Name\"]).upper())\n for n, g in df.groupby(by=['company']):\n try:\n print(n)\n g = g.reset_index(drop=True)\n lower = g.iloc[0] if \"LB\" in g[\"predicted_column\"].iloc[0] else g.iloc[1]\n upper = g.iloc[0] if \"UB\" in g[\"predicted_column\"].iloc[0] else g.iloc[1]\n\n date = [d.strip()\n for d in lower['date'][1:-1].replace(\"\\'\", \"\").split(\",\")]\n close = [float(c.strip()) for c in lower['close'][1:-1].split(\",\")]\n actual_lb = [float(a.strip())\n for a in lower['actual'][1:-1].split(\",\")]\n predicted_lb = [float(p.strip())\n for p in lower['predicted'][1:-1].split(\",\")]\n actual_ub = [float(a.strip())\n for a in upper['actual'][1:-1].split(\",\")]\n predicted_ub = [float(p.strip())\n for p in upper['predicted'][1:-1].split(\",\")]\n\n cols = [\"date\", \"close\", \"actual lb\",\n \"predicted lb\", \"actual ub\", \"predicted ub\"]\n refdf = pd.DataFrame(zip(date, close, actual_lb,\n predicted_lb, actual_ub, predicted_ub), columns=cols)\n\n refdf[\"actual ub close diff\"] = abs(\n refdf[\"close\"] - refdf[\"close\"] * refdf[\"actual ub\"])\n refdf[\"predicted ub close diff\"] = abs(\n refdf[\"close\"] - refdf[\"close\"] * refdf[\"predicted ub\"])\n refdf[\"actual lb close diff\"] = abs(\n refdf[\"close\"] - refdf[\"close\"] * refdf[\"actual lb\"])\n refdf[\"predicted lb close diff\"] = abs(\n refdf[\"close\"] - refdf[\"close\"] * refdf[\"predicted lb\"])\n refdf[\"predicted lb ub diff\"] = refdf[\"predicted ub close diff\"] - \\\n refdf[\"predicted lb close diff\"]\n refdf[\"predicted lb %\"] = 1 - refdf[\"predicted lb\"]\n refdf[\"predicted ub %\"] = refdf[\"predicted ub\"] - 1\n refdf[\"invest\"] = refdf.apply(lambda row: True if row[\"predicted lb %\"] < 0.01 and (\n row[\"predicted ub %\"] - row[\"predicted lb %\"]) > 0.1 else False, axis=1)\n refdf[\"exit\"] = refdf.apply(lambda row: True if row[\"predicted ub %\"] < 0.01 and (\n row[\"predicted ub %\"] + row[\"predicted lb %\"]) > 0.05 else False, axis=1)\n if os.path.exists(os.path.join(simpath, str(n[:6])+\"_\"+str(days)+\".csv\")):\n os.remove(os.path.join(simpath, str(n[:6])+\"_\"+str(days)+\".csv\"))\n refdf.to_csv(os.path.join(simpath, str(n[:6])+\"_\"+str(days)+\".csv\"), index=None)\n else:\n refdf.to_csv(os.path.join(simpath, str(n[:6])+\"_\"+str(days)+\".csv\"), index=None)\n \n except Exception as e:\n print(e)\n \nnecessary_columns = [\"Date\", \"Close Price\", \"Previous 360 days UB\", \"Min Inc % in 180 days\", \"Next 60 days LB\", \"Previous 720 days UB\", \"No. of Trades GR\", \"CP % LV 180 days\", \"Max Inc % in 180 days\", \"Next 1080 days LB\", \"CP % BA 180 days\", \"Next Day Low Price GR\", \"Max Dec % in 90 days\", \"Expenditure GR\", \"CP % HV 90 days\", \"Min Dec % in 365 days\", \"Max Dec % in 365 days\", \"CP % HV 7 days\", \"CP % BA 7 days\", \"Avg Inc % in 365 days\", \"Min Inc % in 90 days\", \"Avg Inc % in 180 days\", \"Total Turnover (Rs.) GR\", \"Low Price GR\", \"Previous 1080 days UB\", \"CP % HV 180 days\", \"Next 180 days UB\", \"No.of Shares GR\", \"Previous 60 days UB\", \"CP % BA 90 days\", \"Avg Inc % in 90 days\", \"Sequential Increase %\", \"WAP GR\", \"CP % BA 30 days\", \"Avg Dec % in 180 days\", \"Previous 720 days LB\", \"EPS GR\", \"Deliverable Quantity GR\", \"Next 360 days UB\", \"CP % HV 365 days\", \"Spread Close-Open GR\", \"Min Dec % in 180 days\", \"Next 30 days LB\", \"Sequential Increase\", \"Previous 360 days LB\",\n \"Alpha GR\", \"CP % LV 365 days\", \"Dividend Value GR\", \"Sequential Decrease\", \"Next 360 days LB\", \"Avg Dec % in 365 days\", \"Net Profit GR\", \"CP % LV 7 days\", \"CP % HV 30 days\", \"% Deli. Qty to Traded Qty GR\", \"Min Inc % in 365 days\", \"Sequential Decrease %\", \"Beta GR\", \"Next 30 days UB\", \"High Price GR\", \"Spread High-Low GR\", \"Income GR\", \"Max Dec % in 180 days\", \"Previous 30 days UB\", \"Next 90 days UB\", \"Next 90 days LB\", \"Next 1080 days UB\", \"Open Price GR\", \"Next 720 days LB\", \"Max Inc % in 365 days\", \"Previous 90 days LB\", \"Previous 90 days UB\", \"Next 60 days UB\", \"Avg Dec % in 90 days\", \"Previous 30 days LB\", \"Previous 1080 days LB\", \"Next Day Open Price GR\", \"Next Day High Price GR\", \"CP % BA 365 days\", \"Max Inc % in 90 days\", \"Revenue GR\", \"CP % LV 30 days\", \"Min Dec % in 90 days\", \"Next 180 days LB\", \"Previous 180 days LB\", \"Close Price GR\", \"CP % LV 90 days\", \"Previous 60 days LB\", \"Previous 180 days UB\", \"Next 720 days UB\", \"Next Day Close Price GR\"]\ncolumns_to_predict = ['Next 30 days LB', 'Next 30 days UB', 'Next 60 days LB', 'Next 60 days UB', 'Next 90 days LB', 'Next 90 days UB', 'Next 180 days LB',\n 'Next 180 days UB', 'Next 360 days LB', 'Next 360 days UB', 'Next 720 days LB', 'Next 720 days UB', 'Next 1080 days LB', 'Next 1080 days UB']\n\ndays = 60\nnpath = os.path.join(os.getcwd(), \"Data\")\nsimpath = os.path.join(os.getcwd(), \"Data\", \"Simulation\")\npath = os.path.join(os.getcwd(), \"Data\", \"GRStock\")\nsp500 = pd.read_csv(os.path.join(os.getcwd(), \"Data\", \"SP500companies.csv\"))\nsp500companies = sp500['Security Code'].values.tolist()\nsp500companies.sort()\nray.init(ignore_reinit_error=True)\nintial_run()\ncreate_files(days)","sub_path":"Algorithms/Daily-ScrapingAndFeatureCreationAndPrediction/predict60.py","file_name":"predict60.py","file_ext":"py","file_size_in_byte":12084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"30045378","text":"import os \n\npath ='/Users/tfaux/Documents/workspace/testTulip/data/contacts/'\nfor fich in os.listdir(path):\n\tprint(\"path+fich \"+ path+fich)\n\tif fich != \"scriptContacts.py\":\n\t\tfichier = open(path+fich, \"r\", encoding = 'cp1252')\n\t\tfor line in fichier:\n\t\t\tsplitline = line.split(\"\t\",)\n\t\t\tif len(splitline) >1:\n\t\t\t\tf=open(path+splitline[1]+\".cnt\",\"r\")\n\t\t\t\tlines = f.readlines()\n\t\t\t\tf.close()\n\t\t\t\tf=open(path+splitline[1]+\".cnt\",\"w\")\n\t\t\t\tprint(splitline[1])\n\t\t\t\tfor line in lines:\n\t\t\t\t\tcurrentline = line.split(\"\t\",)\n\t\t\t\t\tif splitline[0] != currentline[0] or splitline[1] != currentline[2] or splitline[2] != currentline[1] or splitline[3] != currentline[3] or splitline[4] != currentline[4]:\n\t\t\t\t\t\tf.write(line)\n\t\t\t\tf.close()\n\t\tfichier.close()","sub_path":"data/scriptContacts.py","file_name":"scriptContacts.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"536475951","text":"lessons_meta = [\n # NB: Kind of an ugly ouroboros bootstrapping process here where we need some version of this\n # metadata (with placeholder scriptids/slugs) in order to push initial kernel versions, which\n # then lets us update this with the actual scriptids/slugs.\n dict(topic='syntax, variable assignment, and numbers',\n exercise=dict(\n title='Exercise: Syntax, Variables, and Numbers',\n scriptid=1275163,\n ),\n tutorial=dict(\n title='Hello, Python',\n ),\n # Keys later added to each of exercise and tutorial:\n # - filename (e.g. ex_1.ipynb)\n # - slug (e.g. colinmorris/hello-python)\n # - title (exercise only. set to \"Exercise ({tutorial_title})\")\n ),\n\n dict(topic='functions and getting help',\n exercise=dict(\n scriptid=1275158,\n ),\n tutorial=dict(\n title='Functions and Getting Help',\n ),\n ),\n \n dict(topic='booleans and conditionals',\n exercise=dict(\n scriptid=1275165,\n ),\n tutorial=dict(\n title='Booleans and Conditionals',\n ),\n ),\n \n dict(topic='lists and tuples',\n exercise=dict(\n scriptid=1275173,\n ),\n tutorial=dict(\n title='Lists',\n ),\n ),\n \n dict(topic='loops and list comprehensions',\n exercise=dict(\n scriptid=1275177,\n ),\n tutorial=dict(\n title='Loops and List Comprehensions',\n ),\n ),\n \n dict(topic='strings and dictionaries',\n exercise=dict(\n scriptid=1275185,\n ),\n tutorial=dict(\n title='Strings and Dictionaries',\n ),\n ),\n \n dict(topic='imports',\n exercise=dict(\n scriptid=1275190,\n ),\n tutorial=dict(\n title='Working with External Libraries',\n ),\n ),\n]\n\ndef slugify(title):\n s = title.replace('(', '').replace(')', '').replace(',', '').replace(':', '').lower()\n tokens = s.split()\n return '-'.join(tokens)\n\nfor i, lesson in enumerate(lessons_meta):\n num = i + 1\n lesson['exercise']['filename'] = 'ex_{}.ipynb'.format(num)\n lesson['tutorial']['filename'] = 'tut_{}.ipynb'.format(num)\n ex = lesson['exercise']\n tut = lesson['tutorial']\n if 'title' not in ex:\n ex['title'] = 'Exercise: {}'.format(tut['title'])\n for thing in [ex, tut]:\n thing['slug'] = 'colinmorris/' + slugify(thing['title'])\n\n# Haaaaack.\nif __name__ == 'builtins':\n c = get_config()\n\n c.NbConvertApp.notebooks = ['*.ipynb']\n c.Exporter.preprocessors = ['lesson_preprocessor.LearnLessonPreprocessor']\n\n c.LearnLessonPreprocessor.lessons_metadata = lessons_meta\n","sub_path":"notebooks/partials/python/nbconvert_config.py","file_name":"nbconvert_config.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"389352944","text":"# Copyright 2017 The TensorFlow Authors All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for affnist_input_record.\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nimport skimage.io as skio\n\nimport affnist_input_record\n\nAFFNIST_DATA_DIR = '../../testdata/affnist/'\n\nclass AffnistInputRecordTest(tf.test.TestCase):\n\n def testTrain(self):\n with self.test_session(graph=tf.Graph()) as sess:\n new_height = 28\n features = affnist_input_record.inputs(\n data_dir=AFFNIST_DATA_DIR,\n batch_size=1,\n split='train',\n new_height=new_height,\n batch_capacity=2)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n images, labels, recons_image = sess.run([features['images'], features['labels'], features['recons_image']])\n if new_height is None:\n image_dim = 40\n else:\n image_dim = new_height\n self.assertEqual((1, 10), labels.shape)\n self.assertEqual(1, np.sum(labels))\n self.assertItemsEqual([0, 1], np.unique(labels))\n self.assertEqual(image_dim, features['height'])\n self.assertEqual((1, image_dim, image_dim, 1), images.shape)\n self.assertEqual(recons_image.shape, images.shape)\n self.assertAllEqual(recons_image, images)\n\n skio.imsave(\"decoded.jpg\",images[0].squeeze())\n\n coord.request_stop()\n for thread in threads:\n thread.join()\n\nif __name__ == '__main__':\n tf.test.main()\n","sub_path":"research/capsules/input_data/affnist/affnist_input_record_test.py","file_name":"affnist_input_record_test.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"540766918","text":"import turtle\nimport random\n\ndef grelha(dim,lado):\n \"\"\"Desenha uma grelha dim x dim em que cada célula tem de lado.\"\"\"\n turtle.color(\"gray\")\n tam = (dim*lado)\n x = -tam//2\n y = tam//2\n turtle.penup()\n turtle.goto(x,y)\n\n # Desenha linha\n for lin in range(dim+1):\n turtle.pendown()\n turtle.forward(tam)\n turtle.penup()\n turtle.setposition(x,turtle.ycor() - lado)\n # Desenha colunas\n turtle.setposition(x,y)\n turtle.rt(90)\n for col in range(dim+1):\n turtle.pendown()\n turtle.forward(tam)\n turtle.penup()\n turtle.setposition(turtle.xcor() + lado,y) \n turtle.hideturtle()\n \n \n \n \ndef grelha_2(dim,lado):\n \"\"\"Desenha uma grelha dim x dim em que cada célula tem de lado lado.\"\"\"\n turtle.color(\"gray\")\n tam = (dim*lado)\n x = -tam//2\n y = tam//2\n turtle.penup()\n turtle.goto(x,y)\n for lin in range(dim): \n # Desenha linha de quadrados\n for col in range(dim):\n turtle.pendown()\n quadrado(lado) \n turtle.penup()\n turtle.setx(turtle.xcor() + lado)\n # reposiciona\n turtle.penup()\n turtle.setposition(x, turtle.ycor()-lado) \n turtle.hideturtle()\n\ndef passeio(dim, lado, passos): \n # Prepara grelha\n turtle.speed(0)\n grelha_2(dim,lado)\n turtle.color('red')\n turtle.home()\n turtle.pendown()\n # Passeio\n turtle.speed(6)\n turtle.dot()\n turtle.showturtle()\n lim_x = lim_y = (dim*lado)//2\n cor_x = 0\n cor_y = 0\n for i in range(passos):\n vai_para = random.choice(['N','E','S','W'])\n if (vai_para == 'N') and (cor_y < lim_y):\n cor_y += lado\n turtle.setheading(90)\n turtle.fd(lado)\n elif (vai_para == 'E') and (cor_x < lim_x):\n cor_x += lado\n turtle.setheading(0)\n turtle.fd(lado)\n elif (vai_para == 'S') and (cor_y > -lim_y):\n cor_y -= lado\n turtle.setheading(270)\n turtle.fd(lado)\n elif (vai_para == 'W') and (cor_x > -lim_x):\n cor_x -= lado\n turtle.setheading(180)\n turtle.fd(lado) \n else:\n print((vai_para,turtle.xcor(),turtle.ycor()))\n continue\n \n \ndef quadrado(lado):\n for i in range(4):\n turtle.fd(lado)\n turtle.rt(90)\n \nif __name__ == '__main__':\n #grelha_2(4,20)\n passeio(8,20,50)\n turtle.exitonclick()","sub_path":"controlo/programas/grelha.py","file_name":"grelha.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"605699754","text":"# - *- coding: utf- 8 - *-\nimport telebot\n#multiprocess:\nimport multiprocessing\nimport os\n#import threading\nimport time\nimport datetime\nimport sqlite3\nimport requests\n# подключаем модуль работы с БД\nfrom db_main import *\nimport requests\nimport json\nfrom telebot import types\nfrom config import token, botlink, database_name, SFHH, EFHH, SSHH, ESHH, FHCM, SHCM, MOB\nfrom secrets import token_bytes\nfrom coincurve import PublicKey\nfrom sha3 import keccak_256\n\nbot = telebot.TeleBot(token)\n# первоначальная инициализация БД\ninit_tables()\nglobal EthToken\nEthToken = \"7UQF8ZIRHENNVS6F3YKDRXPD1SF5AMHURD\"\nglobal pricestart\npricestart = 100\nprint(pricestart)\nglobal betx\nbetx = 1.5\nupordownitog = 0\nglobal finishprice1\nglobal finishprice2\nfinishprice1 = 0\nfinishprice2 = 0\nglobal winwinbet1\nglobal winwinbet2\nwinwinbet1 = 0\nwinwinbet2 = 0\nglobal pricestart1\nglobal pricestart2\npricestart1 = 0\npricestart2 = 0\n\n#####################################\nmanager = multiprocessing.Manager()\n# Define a list (queue) for tasks and computation results\ntasks = manager.Queue()\nresults = manager.Queue()\npool = multiprocessing.Pool(processes=3)\nprocesses = []\n\ndef extract_uid(text):\n # get the user tg_id\n return text.split()[1] if len(text.split()) > 1 else None\n\ndef is_first_half_hour():\n mint = datetime.now().minute\n if(mint>=SFHH and mint<=EFHH):\n return True\n elif(mint>=SSHH and mint<=ESHH):\n return False\n\ndef percentage(percent, whole):\n return (percent * whole) / 100.0\n\ndef check_ref_system(summ, tg_id):\n usr = get_user(tg_id)\n if usr.ref_tg_id == 0:\n return summ\n else:\n mine = percentage(90, summ)\n their = percentage(10, summ)\n their = their + get_user_ballance(usr.ref_tg_id).balance\n update_user_ballance(usr.ref_tg_id, {'balance': their})\n return mine\n\ndef background(): # фоновый def для парсинга курса eth в usd\n global pricestart\n global pricestart1\n global pricestart2\n global finishprice1\n global finishprice2\n pid = 'PID:'+ str(os.getpid())+' :: '\n print(pid+'Starting background()')\n while True:\n nowglaw = datetime.now().minute\n if nowglaw == 0 or nowglaw == 30:\n r = requests.get(\n 'https://www.coingecko.com/price_charts/279/usd/24_hours.json').json()\n pricestart = r['stats'][-1][1] # цена eth в usd\n if nowglaw == 0:\n pricestart1 = pricestart\n finishprice2 = pricestart\n\n\n if nowglaw == 30:\n pricestart2 = pricestart\n finishprice1 = pricestart\n\n #print(pid+str(pricestart))\n #print(pid+str(pricestart1))\n #print(pid+str(pricestart2))\n #print(pid+str(finishprice1))\n #print(pid+str(finishprice2))\n\n time.sleep(2)\n\n\ndef dapezda(): # фоновый def для парсинга курса eth в usd\n global pricestart\n global finishprice1\n global finishprice2\n global winwinbet1\n global winwinbet2\n global pricestart1\n global pricestart2\n d = 0\n b = 0\n pid = 'PID:'+ str(os.getpid())+' :: '\n print(pid+'Starting dapezda()')\n while True:\n nowglaw = datetime.now().minute\n if nowglaw == 1:\n b = 0\n if d <= 0:\n if finishprice2 >= pricestart2:\n winwinbet2 = 1\n\n elif finishprice2 <= pricestart2:\n winwinbet2 = 0\n\n if nowglaw == 31:\n d = 0\n if b <= 0:\n if finishprice1 >= pricestart1:\n winwinbet1 = 1\n\n elif finishprice1 <= pricestart1:\n winwinbet1 = 0\n\n\n\n time.sleep(2)\n\n\ndef background_process_bets():\n global winwinbet1\n global winwinbet2\n global betx\n \n mint = datetime.now().minute\n pid = 'PID:'+ str(os.getpid())+' :: '\n print(pid+'Starting background_process_bets()')\n \n if(mint==FHCM or mint==SHCM):\n print(pid+'Starting process bets....') \n if is_first_half_hour():\n #первая половина часа обрабатывается тут:\n winbets = get_bet(winwinbet1)\n else:\n #вторая половина часа обрабатывается тут:\n winbets = get_bet(winwinbet2, True)\n\n\n print(pid+' Found bets:')\n print(winbets)\n \n for bet in winbets:\n win = get_user_ballance(bet.tg_id) + bet.bet_summ * betx\n print(pid+' User '+str(bet.tg_id)+' has winned '+str(win))\n update_user(bet.tg_id, {'balance': win})\n delete_bets(is_first_half_hour())\n time.sleep(60)\n\n#pezdaaa = threading.Thread(name='dapezda', target=dapezda())\n#pezdaaa.start()\n#1\nnew_process = multiprocessing.Process(\n target=background\n)\nprocesses.append(new_process)\nnew_process.start()\n#2\nnew_process = multiprocessing.Process(\n target=dapezda\n)\n#3 Clear Bets:\nnew_process = multiprocessing.Process(\n target=background_process_bets\n)\nprocesses.append(new_process)\nnew_process.start()\n\nmap(lambda new_process: new_process.join(), processes)\n\n\ndef check_stavka():\n\n mint = datetime.now().minute\n if(mint>=SFHH and mint<=EFHH):\n return 1\n elif(mint>=SSHH and mint<=ESHH):\n return 2\n else:\n return 0\n\n@bot.message_handler(commands=['start'])\ndef send_welcome(message):\n user_id = message.from_user.id\n print(user_id)\n if (not user_exists(user_id)):\n private_key = keccak_256(token_bytes(32)).digest()\n public_key = PublicKey.from_valid_secret(private_key).format(compressed=False)[1:]\n addr = keccak_256(public_key).digest()[-20:]\n addr = addr.hex()\n print('private_key:', private_key.hex())\n print('eth addr:', '0x' + addr)\n unique_code = extract_uid(message.text)\n if unique_code:\n # create new user with wallet\n newuserdata = {'balance': 0, 'tg_id': user_id, 'wallet_addr': '0x' + str(addr),\n 'wallet_key': '' + str(private_key.hex()), 'ref_tg_id': int(unique_code)} \n else:\n # create new user with wallet\n newuserdata = {'balance': 0, 'tg_id': user_id, 'wallet_addr': '0x' + str(addr),\n 'wallet_key': '' + str(private_key.hex()), 'ref_tg_id': 0}\n add_new_user(newuserdata)\n \n bot.send_message(message.chat.id, \"Это тотализатор BetEther для p2p ставок на курс Ethereum \\n\\nℹ️ Подробнее о том, как играть: \\nhttps://graph.org/Instrukciya-kak-stavit-08-02\", reply_markup=menu_keyboard, disable_web_page_preview=True)\n bot.register_next_step_handler(message, menu)\n\n\n@bot.message_handler(content_types=['text'])\ndef menu(message):\n if message.text == \"💰 Кошелёк ETH\":\n bal_ = 0\n if(user_exists(message.from_user.id)):\n bal_ = get_user(message.from_user.id).balance\n bal2_ = get_user_ballance(message.from_user.id).balance\n bot.send_message(message.from_user.id, f\"ETH кошелек баланс равен {bal2_}\", reply_markup=balance, disable_web_page_preview=True)\n bot.register_next_step_handler(message, menu)\n\n if message.text == \"🎲 Betting\":\n bot.send_message(message.from_user.id,\n \"Тут вы можете осуществлять ставки на курс ETH\\n\\nПодробнее: https://graph.org/Instrukciya-kak-stavit-08-02\",\n reply_markup=betiti, disable_web_page_preview=True)\n bot.register_next_step_handler(message, menu)\n\n if message.text == \"🚀 О сервисе\":\n bot.send_message(message.from_user.id, \"Это тотализатор Bitoto для p2p ставок на курс Bitcoin\\n\\nℹ️ Подробнее о том, как играть в тотализатор: bitoto.io/instruction\\n\\nСайт проекта: bitoto.io\", reply_markup=servese, disable_web_page_preview=True)\n bot.register_next_step_handler(message, menu)\n if message.text == \"🤝 Партнёрам\":\n uid=message.from_user.id\n reflink = \"\\n\\nВот твоя ссылка:\\n\" + botlink + f\"?start={uid}\"\n bot.send_message(message.from_user.id, \"💵 Партнерская программа 🤝\\n\\nПриглашай новых пользователей в двухуровневую реферальную программу и получай пассивный доход от комиссий тотализатора! 💵\\n\\n🔥 Зарабатывай до 7% от суммы выигрыша твоих рефералов!!!\\n\\n1 уровень: 5%\\n2 уровень: 2%\\n\\n📌 Пример: Ты пригласил партнера, который выиграл 1 ETH, ты получишь выплату в 0.05 ETH Если твой партнер пригласит еще партнеров, то с каждого из них - ты будешь получать еще 2%\\n\\nВыходит, что если твой партнер и его партнер выиграют каждый по 1 ETH, то ты получишь - 0.07 ETH на свой баланс.\"+reflink, disable_web_page_preview=True)\n bot.register_next_step_handler(message, menu)\n\n\n@bot.message_handler(content_types=['text'])\ndef upstavkaa(message):\n cs = check_stavka()\n if message.text == \"🔙 Назад\":\n bot.send_message(message.from_user.id, \"Отмена\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu)\n elif cs == 0:\n bot.send_message(message.from_user.id, \"Игра закрыта\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu) \n else:\n user_id = message.from_user.id\n print(user_id)\n txtvopr = float(message.text)\n print(txtvopr)\n print('upstavkaa CS:', cs)\n \n if txtvopr>get_user_ballance(user_id).balance:\n bot.send_message(message.from_user.id, \"У вас недостаточно денег на балансе\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu)\n \n else:\n # сохраняем ставку\n if cs == 1:\n second_time = False\n elif cs == 2:\n second_time = True\n \n betdata = {'tg_id': user_id, 'bet_summ': (txtvopr), 'second_time': second_time, 'bet_target': 1}\n print(betdata)\n add_new_bet(betdata)\n update_user_ballance(user_id, {'balance': get_user_ballance(user_id).balance - txtvopr})\n \n bot.send_message(message.from_user.id, f\"Вы сделали ставку Выше на сумму {txtvopr} ETH\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu)\n\n\n@bot.message_handler(content_types=['text'])\ndef outstavkaa(message):\n cs = check_stavka()\n if message.text == \"🔙 Назад\":\n bot.send_message(message.from_user.id, \"Отмена\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu)\n elif cs == 0:\n bot.send_message(message.from_user.id, \"Игра закрыта\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu) \n else:\n user_id = message.from_user.id\n print(user_id)\n txtvopr = float(message.text)\n print(txtvopr)\n print('outstavka CS:', cs)\n \n if txtvopr>get_user_ballance(user_id).balance:\n bot.send_message(message.from_user.id, \"У вас недостаточно денег на балансе\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu)\n \n else:\n # сохраняем ставку\n if cs == 1:\n second_time = False\n elif cs == 2:\n second_time = True\n \n betdata = {'tg_id': user_id, 'bet_summ': (txtvopr), 'second_time': second_time, 'bet_target': 0}\n print(betdata)\n add_new_bet(betdata)\n update_user_ballance(user_id, {'balance': get_user_ballance(user_id).balance - txtvopr})\n \n bot.send_message(message.from_user.id, f\"Вы сделали ставку Выше на сумму {txtvopr} ETH\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu)\n\n@bot.message_handler(content_types=['text'])\ndef inputoutsumm(message):\n if message.text == \"🔙 Назад\":\n bot.send_message(message.from_user.id, \"Отмена\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu)\n\n else:\n user_id = message.from_user.id\n print(user_id)\n txtvopr = float(message.text)\n print(txtvopr)\n \n bal_ = get_user_ballance(user_id).balance\n if txtvopr > bal_:\n bot.send_message(message.from_user.id, f\"У вас недостаточно денег для вывода! На вашем кошельке {bal_} ETH, а вы запрашиваете {txtvopr} ETH\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu)\n else:\n newb_ = bal_ - txtvopr\n update_user_ballance(user_id, {'balance':newb_})\n update_out(user_id, {'out_summ': txtvopr})\n bot.send_message(message.from_user.id, f\"Вы хотите вывести {txtvopr} ETH\\nВведите адрес кошелька для вывода\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, inputoutaddr)\n\n@bot.message_handler(content_types=['text'])\ndef inputoutaddr(message):\n if message.text == \"🔙 Назад\":\n bot.send_message(message.from_user.id, \"Отмена\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu)\n else:\n user_id = message.from_user.id\n print(user_id)\n txtvopr = message.text\n print(txtvopr)\n \n update_out(user_id, {'wallet_addr': txtvopr})\n bot.send_message(message.from_user.id, f\"Адрес для вывода: {txtvopr} ETH\\nОжидайте вывода!\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, outoutmoney)\n\n@bot.message_handler(content_types=['text'])\ndef outoutmoney(message):\n message = bot.send_message(message.from_user.id, \"Ожидайте перевода\", reply_markup=menu_keyboard)\n bot.register_next_step_handler(message, menu)\n\n@bot.callback_query_handler(func=lambda call: True)\ndef callback_processing(call):\n global walletn\n global wallet\n global EthToken\n\n if call.data == \"refreshbal\":\n telegram_user_id = call.from_user.id\n bal_ = 1\n bot.answer_callback_query(call.id)\n usr = get_user(call.from_user.id, False)\n addr = usr['wallet_addr']\n response = requests.get(f\"https://api.etherscan.io/api?module=account&action=balance&address={addr}&tag=latest&apikey={EthToken}\")\n balnowwal = int(response.json()[\"result\"]) / 1000000000000000000\n #берет нынешний баланс адреса эфириум\n \n usr = get_user(call.from_user.id, False)\n baloldwal = usr['balance']\n #берет старый баланс адреса из бд user_wallet\n\n razbal = check_ref_system(balnowwal - baloldwal, telegram_user_id)\n #находит разницу балансов(новго от старого)\n\n wallet = get_user_ballance(call.from_user.id, False)\n oldbalhum = wallet['balance']\n #берет старый баланс человека из бд user_ballance\n \n newbalhum = oldbalhum + razbal\n #суммирует разницу балансов адресов и нынешний баланс и получает новый баланс\n\n update_user(call.from_user.id, {'balance': balnowwal})\n #записывает нынешний баланс адреса в бд user_wallet\n \n update_user_ballance(telegram_user_id, {'balance': newbalhum})\n #записывает новый баланс юзера в бд user_ballance\n\n wallet = get_user_ballance(call.from_user.id, False)\n bal_ = wallet['balance']\n\n\n message = bot.send_message(call.from_user.id, f\"Ваш баланс: {bal_}\")\n\n if call.data == \"upst\":\n bot.answer_callback_query(call.id)\n message = bot.send_message(call.from_user.id, f\"Какую сумму ты хочешь поставить на повышение?\",\n reply_markup=back_keyboard)\n bot.register_next_step_handler(message, upstavkaa)\n\n if call.data == \"outst\":\n bot.answer_callback_query(call.id)\n message = bot.send_message(call.from_user.id, f\"Какую сумму ты хочешь поставить на понижение?\",\n reply_markup=back_keyboard)\n bot.register_next_step_handler(message, outstavkaa)\n\n if call.data == \"out-money\":\n user = get_user(call.from_user.id)\n if(get_user_ballance(call.from_user.id).balance <= MOB):\n message = bot.send_message(call.from_user.id, f\"Не достаточно денег на балансе. Минимальная сумма для вывода {MOB}\", reply_markup=back_keyboard)\n bot.register_next_step_handler(message, menu)\n \n else:\n message = bot.send_message(call.from_user.id, f\"Какую сумму ты хочешь вывести?\", reply_markup=back_keyboard)\n bot.register_next_step_handler(message, inputoutsumm)\n \n if call.data == \"in-money\":\n # check if user exsist or not\n if(not user_exists(call.from_user.id)):\n private_key = keccak_256(token_bytes(32)).digest()\n public_key = PublicKey.from_valid_secret(private_key).format(compressed=False)[1:]\n addr = keccak_256(public_key).digest()[-20:] \n addr = addr.hex()\n print('private_key:', private_key.hex())\n print('eth addr:', '0x'+addr ) \n \n #create new user with wallet\n newuserdata = {'balance':0, 'tg_id': call.from_user.id, 'wallet_addr': '0x'+ str(addr), 'wallet_key': ''+ str(private_key.hex())}\n add_new_user(newuserdata)\n \n else:\n usr = get_user(call.from_user.id, False)\n private_key = usr['wallet_key']\n addr = usr['wallet_addr']\n print('private_key:', private_key)\n print('eth addr:', addr)\n \n bot.answer_callback_query(call.id)\n bot.send_message(call.from_user.id, f\"Вот твой ETH адрес для пополнения:\")\n bot.send_message(call.from_user.id, f\"{addr}\",reply_markup=refreshbaba)\n\n if call.data == \"igra\":\n nowm = datetime.now().minute\n if 0 <= nowm <= 10 or 30 <= nowm <= 40:\n bot.answer_callback_query(call.id)\n bot.send_message(call.from_user.id, \"Доступные интервалы на данный момент:\", reply_markup=interv)\n else:\n bot.answer_callback_query(call.id)\n ost = 2\n if 40 <= nowm <= 60:\n ost = 60 - nowm - 1\n if 10 <= nowm <= 30:\n ost = 30 - nowm - 1\n bot.send_message(call.from_user.id,\n f\"😔 На данный момент нет доступных интервалов\\n\\nДо начала розыгрыша осталось {ost} минут\")\n if call.data == \"30min\":\n r = requests.get(\n 'https://www.coingecko.com/price_charts/279/usd/24_hours.json').json()\n priceprice = r['stats'][-1][1] # цена eth в usd\n nowm = datetime.now().minute\n bot.answer_callback_query(call.id)\n if 30 <= nowm <= 59:\n ost2 = 60 - nowm\n if 0 <= nowm <= 29:\n ost2 = 30 - nowm\n textvopr = get_user(call.from_user.id)\n print(textvopr)\n bot.send_message(call.from_user.id,\n f\"💥🎰 30 минутный интервал\\n\\nУ тебя есть время чтобы сделать ставку что курс ETH будет выше или ниже чем {pricestart}$ через {ost2} минуты\\n\\nПоставили Выше: 0.0000 ETH\\n\\nПоставили Ниже: 0.0000 ETH\\n\\nETH будет выше или ниже чем {pricestart}$ через {ost2} минуты по паре Binance ETH/USDT ?\\n\\nАктуальный курс Binance: {priceprice}$\",\n reply_markup=stavka)\n\n elif call.data == \"my-igra\":\n bot.answer_callback_query(call.id)\n textvopr = get_user(call.from_user.id)\n print(textvopr)\n bot.send_message(call.from_user.id,\n \"🚀 Тут ты можешь посмотреть информацию о розыгрышах, в которых ты принимаешь участие прямо сейчас\\n\\nНа данный момент ты не принимаешь участие ни в одном розыгрыше\")\n #elif call.data == \"out-money\":\n # message = bot.send_message(call.from_user.id, \"Напиши адрес внешнего ETH кошелька\")\n # bot.register_next_step_handler(message, outoutmoney)\n\n\n\nrefreshbaba = types.InlineKeyboardMarkup(row_width=1)\n\nrefreshbaba.add(types.InlineKeyboardButton('Обновить баланс', callback_data=\"refreshbal\"))\n\n\nbalance = types.InlineKeyboardMarkup(row_width=2)\n\nbalance.add(types.InlineKeyboardButton('📥 Внести', callback_data=\"in-money\"),\n types.InlineKeyboardButton('📤 Вывести', callback_data=\"out-money\"),\n types.InlineKeyboardButton('Обновить баланс', callback_data=\"refreshbal\"))\n\nservese = types.InlineKeyboardMarkup(row_width=2)\n\nservese.add(types.InlineKeyboardButton('☕ Чат', url='https://t.me/EthBet_chat'),\n types.InlineKeyboardButton('🛠 Поддержка', url='https://t.me/EthBet_Support'),\n types.InlineKeyboardButton('📮 Новости', url='https://t.me/News_EthBet'),\n types.InlineKeyboardButton('📋 FAQ', url='https://graph.org/Instrukciya-kak-stavit-08-02'))\n\nbetiti = types.InlineKeyboardMarkup(row_width=2)\n\nbetiti.add(types.InlineKeyboardButton('🎰 Розыгрыши', callback_data=\"igra\"),\n types.InlineKeyboardButton('🎮 Мои ставки', callback_data=\"my-igra\"),\n types.InlineKeyboardButton('🔕 Отключить рассылку', callback_data=\"off-talk\"))\n\nmenu_keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\nmenu_keyboard.add(types.KeyboardButton(\"💰 Кошелёк ETH\"), types.KeyboardButton(\"🎲 Betting\"),\n types.KeyboardButton(\"🚀 О сервисе\"), types.KeyboardButton(\"🤝 Партнёрам\"))\n\nyesno = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\nyesno.add(types.KeyboardButton(\"Да\"), types.KeyboardButton(\"Нет\"))\n\ninterv = types.InlineKeyboardMarkup(row_width=2)\n\ninterv.add(types.InlineKeyboardButton('⌛ 30 минутный интервал', callback_data=\"30min\"))\n\nstavka = types.InlineKeyboardMarkup(row_width=2)\n\nstavka.add(types.InlineKeyboardButton('📈 Выше', callback_data=\"upst\"),\n types.InlineKeyboardButton('📉 Ниже', callback_data=\"outst\"),\n types.InlineKeyboardButton('🔃 Обновить данные', callback_data=\"30min\"))\n\nback_keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)\nback_keyboard.add(types.KeyboardButton(\"🔙 Назад\"))\n\nbot.infinity_polling(True)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":24083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"359237716","text":"import sys, pygame\nfrom pygame import *\nimport threading\nimport time\nimport os\nfrom Button import Button\nfrom test_res import test_res\nfrom qesandans import qesandans\nfrom PIL import ImageTk, Image\nimport random\n\nfilename = \"sgl_bg1_100_1\" # 结果文件名\nmode = 100 # 对比度选择 100 50 20 10\nstimu_delaytime = [0, 2, 4, 6, 8, 10, 12, 14, 16] # 9个时间\n#stimu_delaytime = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n#stimu_delaytime = [52,52,52,52,52,52,25,52,52]\n#stimu_delaytime = [352,352,352,352,352,352,352,352,352]\n\nbg_appeartime = 60 # 每一张背景图片呈现的时间,单位1000/60ms\nbg_appearnum = 10 # 每一个trail呈现的图片数目\ntrail_bgtime = bg_appeartime * bg_appearnum # 每一个trail背景图片呈现的总时间\ntrail_times = 91 # 呈现trail次数\nnum = 0 # 储藏回答问题的总数目\ntrail_num = [] # 存储每一个trail结束后,回答问题的总数目\nciji_shape = 4\ntm_pra = 200 # 刺激图片透明度,0为透明,255为完全不透明\nhigh_time = 60\nlow_time = 5\n\npygame.init()\ninfoObject = pygame.display.Info()\nsize = width, height = infoObject.current_w, infoObject.current_h # 控制文本框的大小\nlist_time_res = [0] * trail_times\nwindow = pygame.display.set_mode(size, FULLSCREEN | HWSURFACE | DOUBLEBUF)\nsurBtnNormal = pygame.image.load(\"../picture_resourse/btn_normal.png\").convert_alpha()\nsurBtnMove = pygame.image.load(\"../picture_resourse/btn_move.png\").convert_alpha()\nsurBtnDown = pygame.image.load(\"../picture_resourse/btn_down.png\").convert_alpha()\n# 按钮使用的字体\nbtnFont = pygame.font.SysFont(\"lisu\", 40)\ndelay_time = 0 # 问卷进行的时间,单位1000/60ms\n\nwhile (os.path.exists(\"../result/{}.txt\".format(filename))):\n filename = filename + \"_2\"\n\n\ndef get_ranlist(t1, t2): # 生成时间下限为t1,时间上限为t2,而且总时长为600的时间序列,单位1/60s。\n sumtime = 0\n list = []\n while(sumtime<600):\n tem = random.randint(t1,t2)\n sumtime = sumtime+tem\n list.append(tem)\n outtime = list.pop()\n list.append(600-sumtime+outtime)\n return list\n# 产生1-9的随机数,确定刺激在9张背景图中哪一张后出现\ndef time_random1():\n num = random.randint(1, 9)\n return num\ndef get_listsum(list,n):\n res = 0\n for i in range(0,n):\n res = res+list[i]\n return res\n\n# 生成0-6的随机数,前后都是闭区间\ndef time_random2():\n num = random.randint(0, 6)\n return num\n\n# 生成1-10的随机数,前后都是闭区间\ndef time_random4():\n num = random.randint(1, 10)\n return num\n\ndef time_random5():\n num = random.randint(60, 540)\n return num\n\ndef toc(t1):\n t = time.time()\n return (t - t1) * 1000\n\n\n# 计算进来的两个数组,的正确率\ndef acc(a, b):\n num = len(b) if len(a) > len(b) else len(a)\n sum = 0\n for i in range(0, num):\n if a[i] == b[i]:\n sum = sum + 1\n try:\n return \"{:.2%}\".format(sum / num)\n except:\n pass\n\n\n# 返回的str为字符串,res为字符串算式的正确与否,1为正确,-1为错误\ndef strrandom(): # 生成随机算数\n num1 = random.randint(0, 50)\n num2 = random.randint(0, 50)\n p = random.uniform(0, 1)\n if p > 0.5:\n sum = num1 + num2\n res = 1\n else:\n sum = random.randint(50, 100)\n res = -1\n str = \"{}+{}={}?\".format(num1, num2, sum)\n return str, res\n\n\ndef getfiles(Path):\n \"\"\"获取图片文件名。\"\"\"\n files = os.listdir(Path)\n\n for x in files:\n if not (x.endswith('.jpg') or x.endswith('.JPG') or x.endswith('.png')):\n files.remove(x)\n return files\n\n\nqesandans_appeartime = [] # 储存问卷呈现时间\nfor i in range(0, trail_times):\n qesandans_appeartime.append((i + 1) * bg_appeartime * bg_appearnum)\n\nciji_wzx = [] # 决定刺激出现的x坐标\nciji_wzy = [] # 决定刺激出现的y坐标\nfor i in range(0,trail_times):\n pic_local = random.randint(1,4)\n if pic_local == 1:\n ciji_wzx.append(random.randint(0,int((ciji_shape-1) * width / ciji_shape)-10))\n ciji_wzy.append(0)\n elif pic_local == 2:\n ciji_wzx.append(random.randint(0,int((ciji_shape-1) * width / ciji_shape)-10))\n ciji_wzy.append(int((ciji_shape-1) * height / ciji_shape)-10)\n elif pic_local == 3:\n ciji_wzx.append(0)\n ciji_wzy.append(random.randint(0,int((ciji_shape-1) * height / ciji_shape)-10))\n elif pic_local == 4:\n ciji_wzx.append(int((ciji_shape-1) * width / ciji_shape)-10)\n ciji_wzy.append( random.randint(0,int((ciji_shape-1) * height / ciji_shape)-10))\n\nappear_time = [] # 储存刺激出现的时间\nend_time = [] # 储存刺激结束的时间\nstimu_delaytime_list = [] # 储存每一次随机产生的刺激延迟时间\nfor i in range(0, 10):\n stimu_delaytime_list.extend(stimu_delaytime)\nrandom.shuffle(stimu_delaytime_list)\nfor i in range(0,trail_times-1):\n appear_time.append(i*600+time_random5())\nfor i in range(0,len(appear_time)):\n end_time.append(appear_time[i]+stimu_delaytime_list[i])\n\n# stimu_delaytime_list.append(0)\n# for time_i in range(1, trail_times + 1):\n# if stimu_delaytime_list[time_i - 1] == 0:\n# continue\n# else:\n# appear_time.append(\n# trail_bgtime * (time_i - 1) + time_random1() * bg_appeartime - stimu_delaytime_list[time_i - 1])\n\nmyfont = pygame.font.SysFont('宋体', 150)\nmyfont1 = pygame.font.SysFont('宋体', 30)\nanswer = [] # 储存问题1回答\nresult = [] # 储存问题1的正确答案\nsurface = [] # 储存表面呈现的算式\nquestion = [] # feiqi问卷问题\nanswer2 = [0, 0, 0, 0] # feiqi储存问卷的回答\npic_ciji = [] # 储存呈现的刺激图片列表\nquestion.append(myfont1.render(\"Do you see something else?\", False, (200, 200, 10)))\n\nfor i in range(0, 3000):\n str, res = strrandom()\n surface.append(myfont.render(str, False, (200, 0, 10)))\n result.append(res)\n# print(result)\nimagebox = []\nimagebox2 = []\nPath = \"../database/database1/cat_{}\".format(mode)\nPath2 = \"../database/database1/apple_{}\".format(mode)\nPath3 = \"../database/database1/banana_{}\".format(mode)\nPath4 = \"../database/database1/butterfly_{}\".format(mode)\nPath5 = \"../database/database1/cattle_{}\".format(mode)\nPath6 = \"../database/database1/dog_{}\".format(mode)\nPath7 = \"../database/database1/durian_{}\".format(mode)\nPath8 = \"../database/database1/grape_{}\".format(mode)\nPath9 = \"../database/database1/mug_{}\".format(mode)\nPath10 = \"../database/database1/panda_{}\".format(mode)\nPath11 = \"../database/database1/tiger_{}\".format(mode)\n\nfiles = getfiles(Path)\nfiles2 = getfiles(Path2)\nfiles3 = getfiles(Path3)\nfiles4 = getfiles(Path4)\nfiles5 = getfiles(Path5)\nfiles6 = getfiles(Path6)\nfiles7 = getfiles(Path7)\nfiles8 = getfiles(Path8)\nfiles9 = getfiles(Path9)\nfiles10 = getfiles(Path10)\nfiles11 = getfiles(Path11)\n\n\nbg_num = 280 # 图片数目\nstimu_num = trail_times # 刺激图片数目\nfor i in range(0, bg_num):\n picture = pygame.image.load(Path + '\\\\' + files[i]).convert()\n picture = pygame.transform.scale(picture, (width, height))\n imagebox.append(picture)\nimagebox.extend(imagebox)\nimagebox.extend(imagebox)\nimagebox.extend(imagebox)\nrandom.shuffle(imagebox)\n\nfor i in range(0, trail_times): #pic_ciji = []\n ciji_random = time_random4()\n ciji_path = ''\n ciji_file = []\n if ciji_random == 1:\n ciji_path = Path2\n ciji_file = files2\n pic_ciji.append('苹果')\n elif ciji_random == 2:\n ciji_path = Path3\n ciji_file = files3\n pic_ciji.append('香蕉')\n elif ciji_random == 3:\n ciji_file = files4\n ciji_path = Path4\n pic_ciji.append('蝴蝶')\n elif ciji_random == 4:\n ciji_file = files5\n ciji_path = Path5\n pic_ciji.append('牛')\n elif ciji_random == 5:\n ciji_file = files6\n ciji_path = Path6\n pic_ciji.append('狗')\n elif ciji_random == 6:\n ciji_file = files7\n ciji_path = Path7\n pic_ciji.append('榴莲')\n elif ciji_random == 7:\n ciji_file = files8\n ciji_path = Path8\n pic_ciji.append('葡萄')\n elif ciji_random == 8:\n ciji_file = files9\n ciji_path = Path9\n pic_ciji.append('杯子')\n elif ciji_random == 9:\n ciji_file = files10\n ciji_path = Path10\n pic_ciji.append('熊猫')\n elif ciji_random == 10:\n ciji_file = files11\n ciji_path = Path11\n pic_ciji.append('老虎')\n picture = pygame.image.load(ciji_path + '\\\\' + ciji_file.pop()).convert()\n picture = pygame.transform.scale(picture, (int(width / ciji_shape), int(height / ciji_shape)))\n picture.set_alpha(tm_pra) # 0透明 255不透明\n imagebox2.append(picture)\n#pic_ciji.reverse()\n\n# for i in range(0, bg_num):\n# picture = pygame.image.load(Path + '\\\\' + files[i])\n# picture = pygame.transform.scale(picture, (width, height))\n# imagebox.append(picture)\n# for i in range(0, 220):\n# picture = pygame.image.load(Path + '\\\\' + files[i])\n# picture = pygame.transform.scale(picture, (width, height))\n# imagebox.append(picture)\n# for i in range(0, 80):\n# picture = pygame.image.load(Path2 + '\\\\' + files2[i]).convert()\n# picture = pygame.transform.scale(picture, (int(width / 3), int(height / 3)))\n# imagebox2.append(picture)\n# imagebox2.extend(imagebox2)\n# random.shuffle(imagebox2)\n# list = [2,62,122,182,242,302,362,422,500,560,620,680,740,800,860,1300]\nlist0 = []\nlist0.append(1)\nlist = []# 储存背景出现的时间\nfor i in range(0,trail_times):\n list_tem = get_ranlist(low_time,high_time)\n list0.extend(list_tem)\nfor i in range(1,len(list0)):\n list.append(get_listsum(list0,i)-1)\nlist[0]=1\n# num = 0\ncount = 1\nt2 = 0\nres = 0\nt1 = time.time()\nwhile 1:\n while t2 - delay_time < 1000 / 60 * (count + 1):\n t2 = toc(t1)\n count = count + 1\n if count == list[-1]:\n fp = open(\"../result/{}.txt\".format(filename), 'w', encoding=\"utf-8\") # 如果有这个文件就打开,如果没有这个文件就创建一个txt文件\n for i in range(0, len(list_time_res) - 1):\n fp.write(\"{}\\t\".format(stimu_delaytime_list[i])) # 储存该次刺激出现的时间,单位1/60s\n fp.write(\"{} \".format(list_time_res[i])) # 储存本次问卷的答案\n fp.write(\"{}\\n\".format(pic_ciji[i])) # 储存本次出现的刺激种类\n fp.write(\"{}:{}\".format(\"回答正确率\", acc(answer, result)))\n fp.close()\n print(\"{}:{}\".format(\"回答正确率\", acc(answer, result)))\n # for __i in list_time_res:\n # print(__i)\n\n sys.exit()\n for event in pygame.event.get(): # 获取用户当前所做动作的事件列表\n if event.type == pygame.QUIT:\n fp = open(\"../result/{}.txt\".format(filename), 'w', encoding='utf-8') # 如果有这个文件就打开,如果没有这个文件就创建一个 txt文件\n\n for i in range(0, len(list_time_res) - 1):\n fp.write(\"{}\\t\".format(stimu_delaytime_list[i]))\n fp.write(\"{} \".format(list_time_res[i]))\n fp.write(\"{}\\n\".format(pic_ciji[i])) # 储存本次出现的刺激种类\n fp.write(\"{}:{}\".format(\"回答正确率\", acc(answer, result)))\n fp.close()\n print(trail_num)\n\n sys.exit()\n elif event.type == KEYDOWN:\n # 检测按键是否是a或者left\n if event.key == K_ESCAPE:\n fp = open(\"../result/{}.txt\".format(filename), 'w', encoding='utf-8') # 如果有这个文件就打开,如果没有这个文件就创建一个 txt文件\n for i in range(0, len(list_time_res) - 1):\n fp.write(\"{}\\t\".format(stimu_delaytime_list[i]))\n fp.write(\"{} \".format(list_time_res[i]))\n fp.write(\"{}\\n\".format(pic_ciji[i])) # 储存本次出现的刺激种类\n fp.write(\"{}:{}\".format(\"回答正确率\", acc(answer, result)))\n fp.close()\n sys.exit()\n if res <= -2:\n if event.key == K_RIGHT:\n answer2[abs(res) - 2] = 1\n\n elif event.key == K_LEFT:\n answer2[abs(res) - 2] = -1\n else:\n if event.key == K_RIGHT:\n num = num + 1\n answer.append(1)\n elif event.key == K_LEFT:\n num = num + 1\n answer.append(-1)\n # 5秒时进入问卷\n if count in qesandans_appeartime:\n time_start1 = toc(t1)\n listnum = int(count / trail_bgtime - 1)\n # print(\"time_start1:{}\".format(time_start1))\n qesans0 = qesandans(window=window, t1=t1, time_start=time_start1, delay_time=delay_time,\n list_time_res=list_time_res, list_num=listnum, weight=width, height=height)\n qesans0.run()\n delay_time = qesans0.get_delaytime()\n trail_num.append(num)\n\n for i in range(0, len(list)):\n if count == list[i]:\n # 显示背景照片\n window.blit(imagebox[i], (0, 0))\n res = i\n pygame.display.update()\n # print(toc(t1))\n # print(i)\n for i in range(0,len(appear_time)):\n if count>=appear_time[i] and count<=end_time[i] and appear_time[i]!=end_time[i]:\n flag = i\n break\n else:\n flag = -1\n # elif count in appear_time: # 存储刺激照片出现时间的数组\n # pic_local = time_random4()\n # if pic_local==1:\n # window.blit(imagebox2.pop(), (random.randint(0,int((ciji_shape-1) * width / ciji_shape)-10), 0)) # 显示刺激照片 width, height\n # elif pic_local==2:\n # window.blit(imagebox2.pop(), (random.randint(0,int((ciji_shape-1) * width / ciji_shape)-10), int((ciji_shape-1) * height / ciji_shape)-10))\n # elif pic_local == 3:\n # window.blit(imagebox2.pop(), (0, random.randint(0,int((ciji_shape-1) * height / ciji_shape)-10)))\n # elif pic_local==4:\n # window.blit(imagebox2.pop(), (int((ciji_shape-1) * width / ciji_shape)-10, random.randint(0,int((ciji_shape-1) * height / ciji_shape)-10)))\n # flag = -1\n # pygame.display.update()\n # # print(toc(t1))\n # # print(count)\n # break\n\n if res >= 0 and flag == -1:\n window.blit(imagebox[res], (0, 0))\n # 显示背景照片\n if res >= 0 and flag >=0:\n window.blit(imagebox[res], (0, 0))\n window.blit(imagebox2[flag],(ciji_wzx[flag],ciji_wzy[flag]))\n\n if res > -2 and res != -1:\n window.blit(surface[num], (11 * width / 30+10, 2 * height / 5))\n # 显示问题\n if res <= -2:\n window.fill((0, 0, 0))\n window.blit(question[0], (2 * width / 5, 2 * height / 5))\n # 显示试卷\n pygame.display.update()\n","sub_path":"common_bg1/bg1_1119.py","file_name":"bg1_1119.py","file_ext":"py","file_size_in_byte":14941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"247341430","text":"import numpy as np\n\n#Data Analysis\nimport matplotlib.pyplot as plt\n\ntest_scores = [12, 99, 65, 85, 42]\ntest_names = [\"Andy\", \"Martin\", \"Zahara\", \"Vuyo\", \"Ziyaad\"]\nx_pos = [i for i, _ in enumerate(test_names)]\n#labels on the x-axis\n#labeling and visuals\nplt.bar(x_pos, test_scores, color='blue')\nplt.xlabel(\"Names\")\nplt.ylabel(\"Marks(%\")\nplt.xticks(x_pos, test_names)\nplt.show()\n","sub_path":"DAdaDistribution.py","file_name":"DAdaDistribution.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"450523297","text":"# Importing the libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom numpy import array\r\nfrom sklearn.model_selection import train_test_split # Using Skicit-learn to split data into training and testing sets\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.feature_selection import RFE\r\nfrom sklearn.linear_model import RidgeCV, LassoCV, Ridge, Lasso\r\nimport matplotlib\r\nimport xgboost\r\nimport shap\r\n\r\n# First step is to inspect data and perform data cleaning\r\n# Read csv file into a pandas data frame\r\ndf1 = pd.read_csv(\"intern_data.csv\", index_col=0)\r\ndf2 = pd.read_csv(\"intern_test.csv\")\r\n\r\n# Determine if there is any missing value. This is done by checking if \"isnull().values.any()\" is True or False, if True\r\n# means that there is/are missing value(s) in the dataset and vice versa.\r\n# (Note that I didn't normalize the input values because through inspection\r\n# of the minimum and maximum values of each feature array, the range lies between 0 to 1, so there is no need to\r\n# normalize\r\n\r\nprint('Checking if there is any missing values in the datasets:')\r\nif df1.isnull().values.any():\r\n print(\"There are missing values in training data. Need further inspection\")\r\nelse:\r\n print(\"No missing values in the intern_data.csv file. Good to go!\")\r\n\r\nif df2.isnull().values.any():\r\n print(\"There are missing values in training data. Need further inspection\\n\")\r\nelse:\r\n print(\"No missing values in the intern_test.csv file. Good to go!\\n\")\r\n\r\n\r\n# save the column index of intern_test.csv into an array\r\ncolumn_index = df2.get(df2.columns[0])\r\ncolumn_index = array(column_index)\r\n\r\n# now we can remove the first column of the intern_test.csv for model predictions\r\ndf2 = df2.drop(df2.columns[0], axis=1)\r\n\r\n# One-hot encode the data using pandas get_dummies because there are string values\r\ndf1 = pd.get_dummies(df1)\r\ndf2 = pd.get_dummies(df2)\r\n\r\n# get all the features and store them to X1, notice that all the features are used because after examining feature\r\n# importance using recursive feature elimination (RFE), Lasso and SHAP values, features like a, h_white, c_yellow etc.\r\n# have low importance, but does not represent noise. Removing them does not necessarily improve the results\r\nX1 = df1.drop('y', axis=1)\r\nY1 = df1.y\r\nX2 = df2\r\n\r\n# First one, is to use recursive feature elimination (RFE) using a linear regressor\r\nprint(\"\\n For Recursive Feature Elimination:\")\r\nmodel = LinearRegression() # Initializing RFE model\r\nrfe = RFE(model, 7) # Transforming data using RFE\r\nX_rfe = rfe.fit_transform(X1, Y1) # Fitting the data to model\r\nmodel.fit(X_rfe, Y1)\r\nprint(rfe.ranking_)\r\n\r\ncols = list(X1.columns)\r\nmodel = LinearRegression() # Initializing RFE model\r\nrfe = RFE(model, 10) # Transforming data using RFE\r\nX_rfe = rfe.fit_transform(X1, Y1) # Fitting the data to model\r\ntemp = pd.Series(rfe.support_, index=cols)\r\nselected_features_rfe = temp[temp==True].index\r\nprint(selected_features_rfe)\r\n\r\n\r\n# Second one is by using LassoCV, we try to see which features are important to us\r\nreg = LassoCV()\r\nreg.fit(X1, Y1)\r\nprint(\"\\n For Lasso CV:\")\r\nprint(\"Best alpha using built-in LassoCV: %f\" % reg.alpha_)\r\nprint(\"Best score using built-in LassoCV: %f\" % reg.score(X1, Y1))\r\ncoef = pd.Series(reg.coef_, index = X1.columns)\r\n\r\nprint(\"Lasso picked \" + str(sum(coef != 0)) + \" variables and eliminated the other \" + str(sum(coef == 0)) + \" variables\")\r\n\r\n\r\nimp_coef = coef.sort_values()\r\nmatplotlib.rcParams['figure.figsize'] = (8.0, 10.0)\r\nimp_coef.plot(kind = \"barh\")\r\nplt.title(\"Feature importance using Lasso Model\")\r\nplt.show()\r\n\r\n\r\n# Third one is using SHAP values - it can show how much each predictor contributes,\r\n# either positively or negatively\r\nprint(\"\\n For SHAP values:\")\r\n# load JS visualization code to notebook\r\nshap.initjs()\r\n\r\nmodel = xgboost.train({\"learning_rate\": 0.01}, xgboost.DMatrix(X1, label=Y1), 100)\r\n# (same syntax works for LightGBM, CatBoost, and scikit-learn models)\r\nexplainer = shap.TreeExplainer(model)\r\nshap_values = explainer.shap_values(X1)\r\nshap.summary_plot(shap_values, X1, plot_type=\"bar\")\r\nshap.summary_plot(shap_values, X1)\r\n\r\n\r\n","sub_path":"adobe_questions/adobe_feature_selection.py","file_name":"adobe_feature_selection.py","file_ext":"py","file_size_in_byte":4233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"5146148","text":"# James Morrissey\n# computingID: jpm9rk\n# Approximate the integral using composite trapezoidal rule, composite midpoint rule, and composite Simpson's rule\n\nimport math\n\n\ndef function(x):\n \"\"\"\n Return the value e^-x.\n\n :param x: (float)\n :return: return e^-x\n \"\"\"\n return math.exp(-x)\n\n\nTRUE_VALUE = 0.6321205588285577 # true value\nH1 = 1/33 # step size defined by (b-a)/n\nF_INIT = function(0) # f(x_0)\n\ntotal = 0\nfor i in range(1, 33):\n total += 2*function(i*H1)\n# The resulting approximation from the composite trapezoidal rule, smallest n is 33\nresult1 = (total + F_INIT + function(1)) * H1/2\n\n\nsum1 = 0\nsum2 = 0\nH2 = 1/4\n# say n=20, m = 10\n\nfor j in range(1, 3):\n sum1 += 4 * function((2 * j - 1)*H2)\n\nfor j in range(1, 2):\n sum2 += 2 * function((2 * j)*H2)\n# The resulting approximation from the composite Simpson's rule, smallest n is 4\nresult2 = (H2/3) * (F_INIT + sum1 + sum2 + function(1))\n\nH3 = 1/46\nsum3 = 0\nfor j in range(1,24):\n sum3 += 2 * H3 * function((2 * j-1) * H3)\n# The resulting approximation from the composite midpoint formula, smallest n is 23\nresult3 = sum3\n\nprint('approximation using composite trapezoidal rule is', result1, ', for n = 33')\nprint('approximation using composite simpson rule is', result2, ', for n = 4')\nprint('approximation using composite midpoint rule is', result3, ', for n = 23')\n\n\n\n\n\n\n\n","sub_path":"MORRISSEY_65_15.py","file_name":"MORRISSEY_65_15.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"359374853","text":"def get_min_vote(val, sorted_s, total_vote):\n\tmin_vote = total_vote\n\tcur_val = val + total_vote\n\tnum_esses = len(sorted_s)\n\tnot_done = 1\n\tidx = 0\n\twhile idx < num_esses:\n\t\tnum = idx + 1\n\t\tcur_s = sorted_s[idx]\n\t\tif(idx == num_esses - 1):\n\t\t\tmin_vote = min_vote - ((cur_val - cur_s) * num / (num + 1))\n\t\t\tbreak\n\t\tnext_s = sorted_s[idx+1]\n\t\tif(cur_val < cur_s):\n\t\t\tbreak\n\t\tif(cur_val <= next_s):\n\t\t\tmin_vote = min_vote - ((cur_val - cur_s) * num / (num + 1))\n\t\t\tbreak\n\t\tdiff = (next_s - cur_s)*float(num)\n\t\tif(cur_val - diff >= next_s):\n\t\t\tcur_val = cur_val - diff\n\t\t\tmin_vote = min_vote - diff\n\t\telse:\n\t\t\tmin_vote = min_vote - (((cur_val - next_s) + (diff/float(num))) * num / (num + 1))\n\t\t\tbreak\n\t\tidx = idx+1\n\tif(min_vote <= 0.0):\n\t\treturn 0.0\n\treturn float(min_vote)/float(total_vote)\n\nfileprefix = 'a-small-3'\nreader = open(fileprefix+'.in', 'r')\nwriter = open(fileprefix+'.out', 'w')\nnum_cases = int(reader.readline())\nfor input_number in xrange(1, num_cases+1):\n\tvals = [float(num) for num in reader.readline().split()]\n\tN = int(vals[0])\n\tesses = vals[1:]\n\ttotal_vote = float(sum(esses))\n\tsorted_s = sorted(esses)\n\tmin_vote = {}\n\tfor idx in xrange(N):\n\t\tval = sorted_s.pop(idx)\n\t\tmin_vote[int(val)] = get_min_vote(val, sorted_s, total_vote)\n\t\tsorted_s.insert(idx,val)\n\toutput = ''\n\tfor val in esses:\n\t\toutput += ' '+str(min_vote[int(val)]*100)\n\twriter.write('Case #'+str(input_number)+\":\"+str(output)+'\\n')\n\t\n","sub_path":"solutions_1480487_0/Python/ml2/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"632926691","text":"import os\nimport math\nimport datetime\n\nfrom tqdm import tqdm\n\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\nimport bert\nfrom bert import BertModelLayer\nfrom bert.loader import StockBertConfig, map_stock_config_to_params, load_stock_weights\nfrom bert.tokenization.bert_tokenization import FullTokenizer\n\nimport seaborn as sns\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\ntrain_base_dir = \"/home/shravan/Downloads/train/\"\nvalid_base_dir = \"/home/shravan/Downloads/valid/\"\ntrain_count = 11\n\n\ndef load_datasets():\n train_df = pd.DataFrame()\n for name in os.listdir(train_base_dir):\n file_path = os.path.join(train_base_dir, name)\n train_df = pd.concat([train_df,\n pd.read_csv(file_path, sep=',', names=[\"sentences\", \"polarity\"])],\n ignore_index=True\n )\n break\n\n valid_df = pd.DataFrame()\n for name in os.listdir(valid_base_dir):\n file_path = os.path.join(valid_base_dir, name)\n valid_df = pd.concat([valid_df,\n pd.read_csv(file_path, sep=',', names=[\"sentences\", \"polarity\"])],\n ignore_index=True\n )\n break\n\n return train_df, valid_df\n\n\ntrain, test = load_datasets()\n\nbert_abs_path = '/home/shravan/Downloads/'\nbert_model_name = 'multi_cased_L-12_H-768_A-12'\n\nbert_ckpt_dir = os.path.join(bert_abs_path, bert_model_name)\nbert_ckpt_file = os.path.join(bert_ckpt_dir, \"bert_model.ckpt\")\nbert_config_file = os.path.join(bert_ckpt_dir, \"bert_config.json\")\n\n\n# Preprocessing\nclass IntentDetectionData:\n DATA_COLUMN = 'sentences'\n LABEL_COLUMN = 'polarity'\n\n def __init__(self, train, test, tokenizer: FullTokenizer, classes, max_seq_len):\n self.tokenizer = tokenizer\n self.max_seq_len = 0\n self.classes = classes\n\n # print(train[IntentDetectionData.DATA_COLUMN].str.len().sort_values().index())\n train, test = map(lambda df: df.reindex(df[IntentDetectionData.DATA_COLUMN].str.len().sort_values().index),\n [train, test])\n\n ((self.train_x, self.train_y), (self.test_x, self.test_y)) = map(self._prepare, [train, test])\n\n print(\"max seq_len\", self.max_seq_len)\n self.max_seq_len = min(self.max_seq_len, max_seq_len)\n self.train_x, self.test_x = map(self._pad, [self.train_x, self.test_x])\n\n def _prepare(self, df):\n x, y = [], []\n\n for _, row in tqdm(df.iterrows()):\n text, label = row[IntentDetectionData.DATA_COLUMN], row[IntentDetectionData.LABEL_COLUMN]\n tokens = self.tokenizer.tokenize(text)\n tokens = ['[CLS]'] + tokens + ['[SEP]']\n token_ids = self.tokenizer.convert_tokens_to_ids(tokens)\n self.max_seq_len = max(self.max_seq_len, len(token_ids))\n x.append(token_ids)\n y.append(self.classes.index(label))\n\n return np.array(x), np.array(y)\n\n def _pad(self, ids):\n x = []\n for input_ids in ids:\n input_ids = input_ids[:min(len(input_ids), self.max_seq_len - 2)]\n input_ids = input_ids + [0] * (self.max_seq_len - len(input_ids))\n x.append(np.array(input_ids))\n\n return np.array(x)\n\n\ntokenizer = FullTokenizer(vocab_file=os.path.join(bert_ckpt_dir, 'vocab.txt'))\n\nt = tokenizer.tokenize('ಶುಭ ದಿನ')\nprint(t)\n\nds = tokenizer.convert_tokens_to_ids(t)\nprint(ds)\n\n\ndef create_model(max_seq_len, bert_ckpt_file):\n with tf.io.gfile.GFile(bert_config_file, 'r') as reader:\n bc = StockBertConfig.from_json_string(reader.read())\n bert_params = map_stock_config_to_params(bc)\n bert_params.adapter_size = None\n bert = BertModelLayer.from_params(bert_params, name='bert')\n\n input_ids = keras.layers.Input(shape=(max_seq_len,), dtype='int32', name='input_ids')\n bert_output = bert(input_ids)\n\n cls_out = keras.layers.Lambda(lambda seq: seq[:, 0, :])(bert_output)\n cls_out = keras.layers.Dropout(0.5)(cls_out)\n logits = keras.layers.Dense(units=768, activation='tanh')(cls_out)\n logits = keras.layers.Dropout(0.5)(logits)\n logits = keras.layers.Dense(units=len(classes), activation='softmax')(logits)\n\n model = keras.Model(inputs=input_ids, outputs=logits)\n model.build(input_shape=(None, max_seq_len))\n\n load_stock_weights(bert, bert_ckpt_file)\n\n return model\n\n\nclasses = train.polarity.unique().tolist()\n\ndata = IntentDetectionData(train, test, tokenizer, classes, max_seq_len=128)\n\nprint(data.train_x.shape)\n\n# Training:\n\nmodel = create_model(data.max_seq_len, bert_ckpt_file)\n\nprint(model.summary())\n\nmodel.compile(\n optimizer=keras.optimizers.Adam(1e-5),\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['mae']\n)\n\nlog_dir = 'log/intent_detection' + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%s\")\ntensorboard_callback = keras.callbacks.TensorBoard(log_dir=log_dir)\n\nhistory = model.fit(\n x=data.train_x,\n y=data.train_y,\n validation_split=0.1,\n batch_size=16,\n shuffle=True,\n epochs=1,\n callbacks=[tensorboard_callback]\n\n)\n\n#check_point_path = '/home/shravan/dissertation/bert_model'\n#tf.saved_model.save(model, check_point_path)\n# model.save(check_point_path)\n\n\n\n\n","sub_path":"sentiment_analysis/bert/scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"634736892","text":"# messaging.py\n# utility functions regarding messaging\nimport socket\nfrom queue import Queue\nfrom time import time, sleep\nfrom threading import Thread\n\nfrom config import cfg\n\n\nclass Messenger:\n def __init__(self):\n # Connect to twitch IRC server\n self.socket = socket.socket()\n self.socket.connect((cfg.TWITCH_IRC_HOST, cfg.TWITCH_IRC_PORT))\n self.socket.send(\"PASS {}\\r\\n\".format(cfg.BOT_PASS).encode(\"utf-8\"))\n self.socket.send(\"NICK {}\\r\\n\".format(cfg.BOT_NICK).encode(\"utf-8\"))\n self.socket.send(\"JOIN #{}\\r\\n\".format(cfg.BROADCASTER_CHANNEL).encode(\"utf-8\"))\n\n # Prepare outbound message queue\n self.twitch_chat_queue = Queue()\n self.drain_twitch_chat_queue = Thread(target=self._flush_twitch_chat_queue, daemon=True).start()\n self.active = True\n\n def stop(self):\n with self.twitch_chat_queue.mutex:\n self.twitch_chat_queue.queue.clear()\n self.active = False\n self.socket.shutdown(socket.SHUT_RDWR)\n self.socket.close()\n\n def chat(self, msg):\n self.__send(\"PRIVMSG #{} :{}\".format(cfg.BROADCASTER_CHANNEL, msg))\n\n def whisper(self, msg, user):\n self.__send(\"PRIVMSG #jtv :/w {} {}\".format(user, msg))\n\n # Function: asyncChat\n # Send a chat message to the server\n # Sent from a new thread after a given delay\n # Parameters:\n # sock -- socket over which to send the message\n # msg -- message to send\n # delay -- delay in seconds\n def async_chat(self, msg, delay):\n sleep(delay)\n self.chat(msg)\n\n # Function: ban\n # Ban a user from the channel\n # Parameter:\n # sock -- socket over which to send the message\n # user -- the user to be banned\n def ban(self, user):\n self.__send(\".ban {}\".format(user))\n\n # Function: timeout\n # Timeout a user from the channel\n # Parameters:\n # sock -- socket over which to send the message\n # user -- the user to be timeouted\n # seconds -- the length of the timeout\n def timeout(self, user, seconds=600):\n self.__send(\".timeout {} {}\".format(user, seconds))\n\n def periodic_message(self, func, delay):\n \"\"\"sends a periodic message determined by the result of func every delay seconds\"\"\"\n while self.active:\n try:\n self.chat(func())\n except Exception as e:\n print(\"Exception in messaging.threadTimedMessages()\")\n print(e)\n sleep(delay)\n\n def __send(self, msg):\n if self.active:\n msg = msg.replace(\"\\n\", \"\")\n msg = msg.strip(\" \")\n msg += \"\\r\\n\"\n msg = msg.encode(\"utf-8\")\n if msg.find(\"PRIVMSG\" == 0): # twitch chat messages\n self.twitch_chat_queue.put(msg)\n else:\n self.socket.send(msg)\n\n def _flush_twitch_chat_queue(self):\n frequency = cfg.MSG_PER_INTERVAL / cfg.MSG_INTERVAL_SEC\n allowance = cfg.MSG_PER_INTERVAL\n last = time()\n while True:\n if self.twitch_chat_queue and not self.twitch_chat_queue.empty():\n current = time()\n elapsed = current - last\n last = current\n allowance += elapsed * frequency\n if allowance > cfg.MSG_PER_INTERVAL:\n allowance = cfg.MSG_PER_INTERVAL\n if allowance < 1:\n left_to_wait = (1 - allowance) / frequency\n last += left_to_wait\n sleep(left_to_wait)\n allowance = 0\n else:\n allowance -= 1\n self.socket.send(self.twitch_chat_queue.get())\n","sub_path":"src/messenger.py","file_name":"messenger.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"382034578","text":"debug = False\n\n# Performs an iterative deepening negamax search. Returns best move for current state and value assosicated\ndef negamaxIDS(game, maxDepth, utilityFunction = None):\n global debug\n bestValue = -float('infinity')\n bestMove = None\n # bestMove = game.getMoves()[0]\n for depth in range(1, maxDepth+1):\n value, move = negamax(game, depth, utilityFunction)\n # Should I check for failure??????????????????????????\n # Why would negamax return infinity???????????????????\n if value in {None, float('Inf')}: # removed-> , -float('Inf')\n if debug: print('***Depth {} found {} for move {}'.format(depth, value, move))\n continue\n if value == game.getWinningValue(): # Found winning move, so return it\n if debug: print('Found winning value at depth {} with move {}'.format(depth, move))\n return value, move\n if value > bestValue: # Found a new best move\n bestValue = value\n bestMove = move\n if debug:\n print('Depth {} has value {} for move {}'.format(depth, value, move))\n print('AND BestValue {} for BestMove {}'.format(bestValue, bestMove))\n return bestValue, bestMove\n\n\n# Returns the best move for the current state of the game and the value associated\ndef negamax(game, depthLeft, utilityFunction = None):\n # If at terminal state or depth limit, return utility value and move None\n if game.isOver() or depthLeft == 0:\n if debug: print('Negamax Base Case will return ------------------- ', game.getUtility())\n return game.getUtility(utilityFunction), None # call to negamax knows the move\n # Find best move and its value from current state\n bestValue, bestMove = None, None\n for move in game.getMoves():\n # Apply a move to current state\n game.makeMove(move)\n # Use depth-first search to find eventual utility value and back it up.\n # Negate it because it will come back in context of next player\n value, _ = negamax(game, depthLeft-1, utilityFunction)\n if debug: print('\\tDepth {}, Value {}, Move {}, Player {}'.format(depthLeft, value, move, game.nextPiece))\n # Remove the move from current state, to prepare for trying a different move\n game.unmakeMove(move)\n if value is None:\n continue\n value = - value\n if bestValue is None or value > bestValue:\n # Value for this move is better than moves tried so far from this state.\n bestValue, bestMove = value, move\n return bestValue, bestMove","sub_path":"Connect 4 A.I. - Final Project/Negamax.py","file_name":"Negamax.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"264709455","text":"from bokeh.plotting import figure, output_notebook, show\n \ndef Return_Benchmark(result):\t\n '''Plot algorithm_period_return and benchmark_period_return.\n Change output_notebook() to get a file output.\n\n Parameters\n ----------\n result is the result passed into analyze in a zipline algorithm. \n '''\n rtn = list(result.algorithm_period_return)\n rtn_bm = list(result.benchmark_period_return)\n dates = list(result.index)\n \n output_notebook()\n \n p = figure(width=800, height=350, x_axis_type=\"datetime\")\n p.line(dates, rtn_bm, color='darkgrey', line_dash='dashed', legend='Benchmark')\n p.line(dates, rtn, color='navy', legend='Algorithm')\n p.legend.location = \"top_left\"\n p.grid.grid_line_alpha=0\n p.xaxis.axis_label = 'Date'\n p.yaxis.axis_label = 'Return'\n p.ygrid.band_fill_color=\"olive\"\n p.ygrid.band_fill_alpha = 0.1\n \n show(p)","sub_path":"ziplinebokeh.py","file_name":"ziplinebokeh.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"466234043","text":"from __future__ import division\nimport math\nimport random\n\nfrom calc import Matrix\n\n# The Projectable object represents any object that is projectable\n# These objects should implement the 'project' method\nclass Projectable():\n def project(self):\n raise NotImplementedError()\n\n\t\t\n# The Point object represents a point object in 3 Dimensional space\nclass Point():\n def __init__(self, my_x, my_y, my_z):\n self.x = my_x\n self.y = my_y\n self.z = my_z\n\n def __str__(self):\n return 'Point (%s, %s, %s)' % (self.x, self.y, self.z)\n\n def getX(self):\n return self.x\n\n def getY(self):\n return self.y\n\n def getZ(self):\n return self.z\n\n def setPosition(self, new_x, new_y, new_z):\n self.x = new_x\n self.y = new_y\n self.z = new_z\n\n def addPosition(self, new_x, new_y, new_z):\n self.x += new_x\n self.y += new_y\n self.z += new_z\n\n def copyAddPosition(self, new_x, new_y, new_z):\n return Point(self.x + new_x, self.y + new_y, self.z + new_z)\n\n def getHomCoords(self):\n return Matrix(4,1).setTo([[self.x], [self.y], [self.z], [1]])\n \n\n# The Line Object represents a line between two points\nclass Line(Projectable):\n def __init__(self, point_a, point_b):\n self.pt_a = point_a\n self.pt_b = point_b\n\n def __str__(self):\n return 'Line (%s, %s)' % (self.pt_a, self.pt_b)\n\n def getLength(self):\n a = abs(self.pt_a.getX() - self.pt_b.getX())\n b = abs(self.pt_a.getY() - self.pt_b.getY())\n c = abs(self.pt_a.getZ() - self.pt_b.getZ())\n return math.sqrt(a**2 + b**2 + c**2)\n\n def addPosition(self, new_x, new_y, new_z):\n self.pt_a.addPosition(new_x, new_y, new_z)\n self.pt_b.addPosition(new_x, new_y, new_z)\n\n def getRelativeAngle(self, line):\n pass\n\n def getPoints(self):\n return [self.pt_a, self.pt_b]\n\n def project(self, camera):\n camera.projectLine(self)\n \n\t\n# The Cube object represents a cube in 3d space\nclass Cube(Projectable):\n def __init__(self, point_center, size):\n cx = point_center.getX()\n cy = point_center.getY()\n cz = point_center.getZ()\n self.lines = [\n Line(Point(cx,cy,cz), Point(cx+size,cy,cz)),\n Line(Point(cx,cy,cz), Point(cx,cy+size,cz)),\n Line(Point(cx,cy,cz), Point(cx,cy,cz+size)),\n Line(Point(cx+size,cy,cz), Point(cx+size,cy+size,cz)),\n Line(Point(cx+size,cy,cz), Point(cx+size,cy,cz+size)),\n Line(Point(cx,cy+size,cz), Point(cx+size,cy+size,cz)),\n Line(Point(cx,cy+size,cz), Point(cx,cy+size,cz+size)),\n Line(Point(cx,cy,cz+size), Point(cx+size,cy,cz+size)),\n Line(Point(cx,cy,cz+size), Point(cx,cy+size,cz+size)),\n Line(Point(cx+size,cy+size,cz), Point(cx+size,cy+size,cz+size)),\n Line(Point(cx+size,cy,cz+size), Point(cx+size,cy+size,cz+size)),\n Line(Point(cx,cy+size,cz+size), Point(cx+size,cy+size,cz+size)),\n ]\n\n def project(self, camera):\n for line in self.lines:\n line.project(camera)\n\n\n# The Polygon object represents a polygon\nclass Polygon(Projectable):\n def __init__(self, point_a, point_b, point_c):\n self.pt_a = point_a\n self.pt_b = point_b\n self.pt_c = point_c\n self.lines = [\n Line(self.pt_a, self.pt_b),\n Line(self.pt_b, self.pt_c),\n Line(self.pt_a, self.pt_c),\n ]\n \n def __str__(self):\n return 'Polygon (%s, %s, %s,)' % (self.pt_a, self.pt_b, self.pt_c)\n \n def getArea(self):\n b = Line(self.pt_a, self.pt_b).getLength()\n return b\n\n def project(self, camera):\n for line in self.lines:\n line.project(camera)\n\n# The house object represents a house\n\nclass Roof():\n def fetch_projectables(self):\n raise NotImplementedError()\n\nclass House(Projectable):\n def __init__(self, point_origin, size_cube, height_roof, roof_type):\n roof = roof_type(point_origin, size_cube, height_roof)\n roof_elems = roof.fetch_projectables()\n self.house = [\n Cube(point_origin, size_cube\n ), \n ] + roof_elems\n \n def project(self, camera):\n for obj in self.house:\n obj.project(camera)\n\nclass PointyRoof(Roof):\n def __init__(self, point_origin, size_cube, height_roof):\n pt_pl_center = point_origin.copyAddPosition(size_cube/2, -height_roof, size_cube/2) \n self.roof = [\n Polygon(point_origin,\n point_origin.copyAddPosition(size_cube, 0, 0),\n pt_pl_center\n ),\n Polygon(point_origin.copyAddPosition(0, 0, size_cube),\n point_origin.copyAddPosition(size_cube, 0, size_cube),\n pt_pl_center\n ), \n ]\n\n def fetch_projectables(self):\n return self.roof\n\nclass TriangleRoof(Roof):\n def __init__(self, point_origin, size_cube, height_roof):\n pt_pl_front = point_origin.copyAddPosition(size_cube/2, -height_roof, 0) \n pt_pl_back = point_origin.copyAddPosition(size_cube/2, -height_roof, size_cube)\n self.roof = [\n Polygon(point_origin,\n point_origin.copyAddPosition(size_cube, 0, 0),\n pt_pl_front\n ),\n Polygon(point_origin.copyAddPosition(0, 0, size_cube),\n point_origin.copyAddPosition(size_cube, 0, size_cube),\n pt_pl_back\n ),\n Line(pt_pl_front, pt_pl_back\n ), \n ]\n \n def fetch_projectables(self):\n return self.roof\n\nclass SlopedRoofXnegative(Roof):\n def __init__(self, point_origin, size_cube, height_roof):\n pt_pl_front = point_origin.copyAddPosition(0, -height_roof, 0) \n pt_pl_back = point_origin.copyAddPosition(0, -height_roof, size_cube)\n self.roof = [\n Polygon(point_origin,\n point_origin.copyAddPosition(size_cube, 0, 0),\n pt_pl_front\n ),\n Polygon(point_origin.copyAddPosition(0, 0, size_cube),\n point_origin.copyAddPosition(size_cube, 0, size_cube),\n pt_pl_back\n ),\n Line(pt_pl_front, pt_pl_back\n ), \n ]\n \n def fetch_projectables(self):\n return self.roof\n\nclass SlopedRoofXpositive(Roof):\n def __init__(self, point_origin, size_cube, height_roof):\n pt_pl_front = point_origin.copyAddPosition(size_cube, -height_roof, 0) \n pt_pl_back = point_origin.copyAddPosition(size_cube, -height_roof, size_cube)\n self.roof = [\n Polygon(point_origin,\n point_origin.copyAddPosition(size_cube, 0, 0),\n pt_pl_front\n ),\n Polygon(point_origin.copyAddPosition(0, 0, size_cube),\n point_origin.copyAddPosition(size_cube, 0, size_cube),\n pt_pl_back\n ),\n Line(pt_pl_front, pt_pl_back\n ), \n ]\n \n def fetch_projectables(self):\n return self.roof\n\nclass RandomRoof(Roof):\n def __init__(self, point_origin, size_cube, max_height):\n i = random.randint(1, 4)\n height_roof = random.uniform(0, max_height)\n roof_type = {\n 1 : PointyRoof,\n 2 : TriangleRoof,\n 3 : SlopedRoofXnegative,\n 4 : SlopedRoofXpositive\n }\n random_roof = roof_type[i](point_origin, size_cube, height_roof)\n self.roof_elems = random_roof.fetch_projectables()\n \n\n def fetch_projectables(self):\n return self.roof_elems\n\nclass Street(Projectable):\n def __init__(self, street_origin, house_size, max_roof_height, house_count):\n self.street = [] \n for i in range(0, house_count):\n house_origins = street_origin.copyAddPosition(house_size*i, 0, 0)\n self.street += [House(house_origins, house_size, max_roof_height, RandomRoof)]\n\n \n \n def project(self, camera):\n for house in self.street:\n house.project(camera)\n \n\n\n \n","sub_path":"src/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":8243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"340214008","text":"def CBAM(input, reduction):\n \"\"\"\n @Convolutional Block Attention Module\n \"\"\"\n\n _, width, height, channel = input.get_shape() # (B, W, H, C)\n\n # channel attention\n x_mean = tf.reduce_mean(input, axis=(1, 2), keepdims=True) # (B, 1, 1, C)\n x_mean = tf.layers.conv2d(x_mean, channel // reduction, 1, activation=tf.nn.relu, name='CA1') # (B, 1, 1, C // r)\n x_mean = tf.layers.conv2d(x_mean, channel, 1, name='CA2') # (B, 1, 1, C)\n\n x_max = tf.reduce_max(input, axis=(1, 2), keepdims=True) # (B, 1, 1, C)\n x_max = tf.layers.conv2d(x_max, channel // reduction, 1, activation=tf.nn.relu, name='CA1', reuse=True)\n # (B, 1, 1, C // r)\n x_max = tf.layers.conv2d(x_max, channel, 1, name='CA2', reuse=True) # (B, 1, 1, C)\n\n x = tf.add(x_mean, x_max) # (B, 1, 1, C)\n x = tf.nn.sigmoid(x) # (B, 1, 1, C)\n x = tf.multiply(input, x) # (B, W, H, C)\n\n # spatial attention\n y_mean = tf.reduce_mean(x, axis=3, keepdims=True) # (B, W, H, 1)\n y_max = tf.reduce_max(x, axis=3, keepdims=True) # (B, W, H, 1)\n y = tf.concat([y_mean, y_max], axis=-1) # (B, W, H, 2)\n y = tf.layers.conv2d(y, 1, 7, padding='same', activation=tf.nn.sigmoid) # (B, W, H, 1)\n y = tf.multiply(x, y) # (B, W, H, C)\n\n return y\n","sub_path":"attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"553755197","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('hatch', '0022_stem_website'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='stem',\n name='website',\n ),\n migrations.AddField(\n model_name='stem',\n name='website',\n field=models.TextField(blank=True, max_length=150000),\n ),\n ]\n","sub_path":"neuron_django/hatch/migrations/0023_auto_20160108_0419.py","file_name":"0023_auto_20160108_0419.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"144803108","text":"import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom Experiment1 import Diamond\nfrom Experiment2 import DrawLine\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super(MainWindow, self).__init__()\n\n self.experiment = dict()\n\n self.experiment['实验一 绘制金刚石图案'] = Diamond\n self.experiment['实验二 绘制任意斜率直线段'] = DrawLine\n\n self.about = '姓名:\\t范家铭\\n班级:\\t计科17-3\\n学号:\\t201701060503'\n self.initUI()\n\n def initUI(self):\n\n self.setWindowTitle('图形学实验')\n self.resize(1200, 800)\n\n menu = self.menuBar()\n fileMenu = menu.addMenu('&File')\n draw_menu = menu.addMenu('&Draw')\n\n exit_action = QAction('&Exit', self)\n exit_action.triggered.connect(self.close)\n fileMenu.addAction(exit_action)\n\n for k, v in self.experiment.items():\n action = QAction(k, self)\n action.triggered.connect(\n (lambda x: lambda: self.setCentralWidget(x(self)))(v)\n )\n draw_menu.addAction(action)\n\n # diamond_action = QAction('&Diamond', self)\n # diamond_action.triggered.connect(\n # (lambda x: lambda: self.setCentralWidget(x(self)))(Diamond)\n # )\n # draw_menu.addAction(diamond_action)\n\n about_action = QAction('&About', self)\n about_action.triggered.connect(\n lambda: QMessageBox.about(self, 'about', self.about)\n )\n menu.addAction(about_action)\n\n def keyPressEvent(self, event: QKeyEvent):\n if self.centralWidget() is not None:\n self.centralWidget().keyPressEvent(event)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n main_window = MainWindow()\n main_window.show()\n sys.exit(app.exec_())","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"221397102","text":"n = input()\nconst = list(n)\nconst = int(''.join(const))\nif const > 54:\n const -= 54\nelse: const =0\nfor i in range(55):\n res = const+sum(list(map(int, str(const))))\n if res == int(n):\n break\n if const == int(n):\n const =0\n break\n const+=1\nprint(const)","sub_path":"week2/2231_분해합.py","file_name":"2231_분해합.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"364276999","text":"\"\"\"\nDOCSTRING\n\"\"\"\nimport collections\nimport keras\nimport Levenshtein\nimport matplotlib.pyplot as pyplot\nimport numpy\nimport os\nimport pickle\nimport random\nimport sklearn\nimport sys\nimport zipfile\n\n# variables\nBATCH_SIZE = 64\nEMPTY = 0\nEOS = 1\nMAXLEND = 25 # 0 - if we dont want to use description at all\nMAXLENH = 25\nMODEL = keras.models.Sequential()\nRNN_SIZE = 512 # must be same as 160330-word-gen\nSEED = 42\n# derivative variables\nACTIVATION_RNN_SIZE = 40 if MAXLEND else 0\nMAXLEN = MAXLEND + MAXLENH\n\nclass SimpleContext(keras.layers.core.Lambda):\n \"\"\"\n DOCSTRING\n \"\"\"\n def __init__(self, **kwargs):\n super(SimpleContext, self).__init__(Train.simple_context, **kwargs)\n self.supports_masking = True\n\n def compute_mask(self, input, input_mask=None):\n return input_mask[:,MAXLEND:]\n \n def get_output_shape_for(self, input_shape):\n nb_samples = input_shape[0]\n n = 2 * (RNN_SIZE - ACTIVATION_RNN_SIZE)\n return (nb_samples, MAXLENH, n)\n\nclass Train:\n \"\"\"\n DOCSTRING\n \"\"\"\n def __init__(self):\n \"\"\"\n DOCSTRING\n \"\"\"\n rnn_layers = 3\n batch_norm = False\n # training parameters\n p_W, p_U, p_dense, p_emb, weight_decay = 0, 0, 0, 0, 0\n self.optimizer = 'adam'\n self.LR = 1e-4\n self.nflips = 10\n self.nb_train_samples = 30000\n self.nb_val_samples = 3000\n with open('data/%s.pkl'%'vocabulary-embedding', 'rb') as fp:\n embedding, self.idx2word, word2idx, self.glove_idx2idx = pickle.load(fp)\n self.vocab_size, embedding_size = embedding.shape\n with open('data/%s.data.pkl'%'vocabulary-embedding', 'rb') as fp:\n X, Y = pickle.load(fp)\n self.nb_unknown_words = 10\n print('number of examples', len(X), len(Y))\n print('dimension of embedding space for words', embedding_size)\n print('vocabulary size', self.vocab_size)\n print('last %d words can be used as place holders for unknown words' % self.nb_unknown_words)\n print('total number of different words', len(self.idx2word), len(word2idx))\n print('number of words outside vocabulary which we can substitute using glove similarity',\n len(self.glove_idx2idx))\n print('number of words that will be regarded as unknown(unk)/out-of-vocabulary(oov):',\n len(self.idx2word) - self.vocab_size - len(self.glove_idx2idx))\n for i in range(self.nb_unknown_words):\n self.idx2word[self.vocab_size-1-i] = '<%d>'%i\n self.oov0 = self.vocab_size - self.nb_unknown_words\n for i in range(self.oov0, len(self.idx2word)):\n self.idx2word[i] = self.idx2word[i] + '^'\n self.X_train, self.X_test, self.Y_train, self.Y_test = (\n sklearn.model_selection.train_test_split(\n X, Y, test_size=self.nb_val_samples, random_state=SEED))\n len(self.X_train), len(self.Y_train), len(self.X_test), len(self.Y_test)\n del X\n del Y\n self.idx2word[EMPTY] = '_'\n self.idx2word[EOS] = '~'\n i = 334\n self.prt('H', self.Y_train[i])\n self.prt('D', self.X_train[i])\n i = 334\n self.prt('H', self.Y_test[i])\n self.prt('D', self.X_test[i])\n # seed weight initialization\n random.seed(SEED)\n numpy.random.seed(SEED)\n self.regularizer = keras.regularizers.l2(weight_decay) if weight_decay else None\n MODEL.add(keras.layers.embeddings.Embedding(\n self.vocab_size, embedding_size, input_length=MAXLEN,\n W_regularizer=self.regularizer, dropout=p_emb, weights=[embedding],\n mask_zero=True, name='embedding_1'))\n for i in range(rnn_layers):\n lstm = keras.layers.recurrent.LSTM(\n RNN_SIZE, return_sequences=True, W_regularizer=self.regularizer,\n U_regularizer=self.regularizer, b_regularizer=self.regularizer,\n dropout_W=p_W, dropout_U=p_U, name='lstm_%d'%(i+1))\n MODEL.add(lstm)\n MODEL.add(keras.layers.core.Dropout(p_dense, name='dropout_%d' % (i+1)))\n\n def __call__(self):\n \"\"\"\n DOCSTRING\n \"\"\"\n if ACTIVATION_RNN_SIZE:\n MODEL.add(SimpleContext(name='simplecontext_1'))\n MODEL.add(keras.layers.wrappers.TimeDistributed(keras.layers.core.Dense(\n self.vocab_size, W_regularizer=self.regularizer,\n b_regularizer=self.regularizer, name='timedistributed_1')))\n MODEL.add(keras.layers.core.Activation('softmax', name='activation_1'))\n # opt = keras.optimizers.Adam(lr=self.LR) # reduce learning rate\n MODEL.compile(loss='categorical_crossentropy', optimizer=self.optimizer)\n keras.backend.set_value(MODEL.optimizer.lr, numpy.float32(self.LR))\n self.inspect_model(MODEL)\n if 'train' and os.path.exists('data/%s.hdf5'%'train'):\n MODEL.load_weights('data/%s.hdf5'%'train')\n samples = [self.lpadd([3]*26)]\n # pad from right (post) so the first maxlend will be description followed by headline\n data = keras.preprocessing.sequence.pad_sequences(\n samples, maxlen=MAXLEN, value=EMPTY, padding='post', truncating='post')\n numpy.all(data[:,MAXLEND] == EOS)\n data.shape, map(len, samples)\n probs = MODEL.predict(data, verbose=0, batch_size=1)\n probs.shape\n self.gensamples(skips=2, batch_size=BATCH_SIZE, k=10, temperature=1.0)\n self.test_gen(self.gen(self.X_train, self.Y_train, batch_size=BATCH_SIZE))\n self.test_gen(self.gen(\n self.X_train, self.Y_train, nflips=6, model=MODEL, debug=False,\n batch_size=BATCH_SIZE))\n valgen = self.gen(self.X_test, self.Y_test, nb_batches=3, batch_size=BATCH_SIZE)\n for i in range(4):\n self.test_gen(valgen, 1)\n history = {}\n traingen = self.gen(\n self.X_train, self.Y_train, batch_size=BATCH_SIZE,\n nflips=self.nflips, model=MODEL)\n valgen = self.gen(\n self.X_test, self.Y_test, nb_batches=self.nb_val_samples//BATCH_SIZE,\n batch_size=BATCH_SIZE)\n r = next(traingen)\n r[0].shape, r[1].shape, len(r)\n for iteration in range(500):\n print('Iteration', iteration)\n h = MODEL.fit_generator(\n traingen, samples_per_epoch=self.nb_train_samples, nb_epoch=1,\n validation_data=valgen, nb_val_samples=self.nb_val_samples)\n for k,v in h.history.iteritems():\n history[k] = history.get(k,[]) + v\n with open('data/%s.history.pkl' % 'train', 'wb') as fp:\n pickle.dump(history, fp, -1)\n MODEL.save_weights('data/%s.hdf5' % 'train', overwrite=True)\n self.gensamples(batch_size=BATCH_SIZE)\n\n def beamsearch(\n self,\n predict,\n start,\n k=1,\n maxsample=MAXLEN,\n use_unk=True,\n empty=EMPTY,\n eos=EOS,\n temperature=1.0):\n \"\"\"\n variation to https://github.com/ryankiros/skip-thoughts/blob/master/decoding/search.py\n \n return k samples (beams) and their NLL scores, each sample is a sequence of labels,\n all samples starts with an `empty` label and end with `eos` or truncated to length of `maxsample`.\n You need to supply `predict` which returns the label probability of each sample.\n `use_unk` allow usage of `oov` (out-of-vocabulary) label in samples\n \"\"\"\n def sample(energy, n, temperature=temperature):\n \"\"\"\n Sample at most n elements according to their energy.\n \"\"\"\n n = min(n,len(energy))\n prb = numpy.exp(-numpy.array(energy) / temperature )\n res = []\n for _ in range(n):\n z = numpy.sum(prb)\n r = numpy.argmax(numpy.random.multinomial(1, prb/z, 1))\n res.append(r)\n prb[r] = 0.0 # make sure we select each element only once\n return res\n #dead_k = 0 # samples that reached eos\n dead_samples = []\n dead_scores = []\n live_k = 1 # samples that did not yet reached eos\n live_samples = [list(start)]\n live_scores = [0]\n while live_k:\n # for every possible live sample calc prob for every possible label \n probs = predict(live_samples, empty=empty)\n # total score for every sample is sum of -log of word prb\n cand_scores = numpy.array(live_scores)[:,None] - numpy.log(probs)\n cand_scores[:,empty] = 1e20\n if not use_unk:\n for i in range(self.nb_unknown_words):\n cand_scores[:,self.vocab_size-1-i] = 1e20\n live_scores = list(cand_scores.flatten())\n # find the best (lowest) scores we have from all possible dead samples and\n # all live samples and all possible new words added\n scores = dead_scores + live_scores\n ranks = sample(scores, k)\n n = len(dead_scores)\n ranks_dead = [r for r in ranks if r < n]\n ranks_live = [r - n for r in ranks if r >= n]\n dead_scores = [dead_scores[r] for r in ranks_dead]\n dead_samples = [dead_samples[r] for r in ranks_dead]\n live_scores = [live_scores[r] for r in ranks_live]\n # append the new words to their appropriate live sample\n voc_size = probs.shape[1]\n live_samples = [live_samples[r//voc_size] + [r%voc_size] for r in ranks_live]\n # live samples that should be dead\n # even if len(live_samples) == maxsample we dont want it dead because\n # we want one last prediction out of it to reach a headline of maxlenh\n zombie = [s[-1] == eos or len(s) > maxsample for s in live_samples]\n # add zombies to the dead\n dead_samples += [s for s,z in zip(live_samples, zombie) if z]\n dead_scores += [s for s,z in zip(live_scores, zombie) if z]\n #dead_k = len(dead_samples)\n # remove zombies from the living \n live_samples = [s for s,z in zip(live_samples, zombie) if not z]\n live_scores = [s for s,z in zip(live_scores, zombie) if not z]\n live_k = len(live_samples)\n return dead_samples + live_samples, dead_scores + live_scores\n\n def conv_seq_labels(self, xds, xhs, nflips=None, model=None, debug=False):\n \"\"\"\n Description and headlines are converted to padded input vectors.\n Headlines are one-hot to label.\n \"\"\"\n BATCH_SIZE = len(xhs)\n assert len(xds) == BATCH_SIZE\n x = [self.vocab_fold(self.lpadd(xd) + xh) for xd, xh in zip(xds, xhs)] # input does not have 2nd eos\n x = keras.preprocessing.sequence.pad_sequences(\n x, maxlen=MAXLEN, value=EMPTY, padding='post', truncating='post')\n x = self.flip_headline(x, nflips=nflips, model=model, debug=debug)\n y = numpy.zeros((BATCH_SIZE, MAXLENH, self.vocab_size))\n for i, xh in enumerate(xhs):\n xh = self.vocab_fold(xh) + [EOS] + [EMPTY] * MAXLENH # output has eos\n xh = xh[:MAXLENH]\n y[i,:,:] = keras.utils.np_utils.to_categorical(xh, self.vocab_size)\n return x, y\n \n def flip_headline(self, x, nflips=None, model=None, debug=False):\n \"\"\"\n Given a vectorized input (after `pad_sequences`),\n flip some of the words in the second half (headline),\n with words predicted by the model.\n \"\"\"\n if nflips is None or model is None or nflips <= 0:\n return x\n BATCH_SIZE = len(x)\n assert numpy.all(x[:,MAXLEND] == EOS)\n probs = model.predict(x, verbose=0, batch_size=BATCH_SIZE)\n x_out = x.copy()\n for b in range(BATCH_SIZE):\n # pick locations we want to flip\n # 0 ... maxlend-1 are descriptions and should be fixed\n # maxlend is eos and should be fixed\n flips = sorted(random.sample(range(MAXLEND + 1, MAXLEN), nflips))\n if debug and b < debug:\n print(b, )\n for input_idx in flips:\n if x[b,input_idx] == EMPTY or x[b,input_idx] == EOS:\n continue\n # convert from input location to label location\n # the output at maxlend (when input is eos) is fed as input at maxlend + 1\n label_idx = input_idx - (MAXLEND + 1)\n prob = probs[b,label_idx]\n w = prob.argmax()\n if w == EMPTY: # replace accidental empty with oov\n w = self.oov0\n if debug and b < debug:\n print('%s => %s' % (self.idx2word[x_out[b,input_idx]], self.idx2word[w]), )\n x_out[b,input_idx] = w\n if debug and b < debug:\n print()\n return x_out\n\n def gen(\n self,\n Xd,\n Xh,\n batch_size=BATCH_SIZE,\n nb_batches=None,\n nflips=None,\n model=None,\n debug=False,\n seed=SEED):\n \"\"\"\n Yield batch. For training use nb_batches=None.\n For validation generate deterministic results repeating every nb_batches.\n While training it is good idea to flip once in a while the values of the headlines\n From the value taken from Xh to value generated by the model.\n \"\"\"\n c = nb_batches if nb_batches else 0\n while True:\n xds = []\n xhs = []\n if nb_batches and c >= nb_batches:\n c = 0\n new_seed = random.randint(0, sys.maxsize)\n random.seed(c + 123456789 + seed)\n for _ in range(BATCH_SIZE):\n t = random.randint(0, len(Xd) - 1)\n xd = Xd[t]\n s = random.randint(min(MAXLEND, len(xd)), max(MAXLEND, len(xd)))\n xds.append(xd[:s])\n xh = Xh[t]\n s = random.randint(min(MAXLENH, len(xh)), max(MAXLENH, len(xh)))\n xhs.append(xh[:s])\n # undo the seeding before we yield inorder not to affect the caller\n c += 1\n random.seed(new_seed)\n yield self.conv_seq_labels(xds, xhs, nflips=nflips, model=model, debug=debug)\n\n def gensamples(\n self,\n skips=2,\n k=10,\n batch_size=BATCH_SIZE,\n short=True,\n temperature=1.0,\n use_unk=True):\n \"\"\"\n DOCSTRING\n \"\"\"\n i = random.randint(0, len(self.X_test)-1)\n print('HEAD:', ' '.join(self.idx2word[w] for w in self.Y_test[i][:MAXLENH]))\n print('DESC:', ' '.join(self.idx2word[w] for w in self.X_test[i][:MAXLEND]))\n sys.stdout.flush()\n print('HEADS:')\n x = self.X_test[i]\n samples = []\n if MAXLEND == 0:\n skips = [0]\n else:\n skips = range(\n min(MAXLEND, len(x)), max(MAXLEND, len(x)),\n abs(MAXLEND-len(x)) // skips + 1)\n for s in skips:\n start = self.lpadd(x[:s])\n fold_start = self.vocab_fold(start)\n sample, score = self.beamsearch(\n predict=self.keras_rnn_predict, start=fold_start, k=k,\n temperature=temperature, use_unk=use_unk)\n assert all(s[MAXLEND] == EOS for s in sample)\n samples += [(s, start, scr) for s, scr in zip(sample, score)]\n samples.sort(key=lambda x:x[-1])\n codes = []\n for sample, start, score in samples:\n code = ''\n words = []\n sample = self.vocab_unfold(start, sample)[len(start):]\n for w in sample:\n if w == EOS:\n break\n words.append(self.idx2word[w])\n code += chr(w//(256*256)) + chr((w//256)%256) + chr(w%256)\n if short:\n distance = min([100] + [-Levenshtein.jaro(code, c) for c in codes])\n if distance > -0.6:\n print(score, ' '.join(words))\n else:\n print(score, ' '.join(words))\n codes.append(code)\n\n def inspect_model(self, model):\n \"\"\"\n DOCSTRING\n \"\"\"\n for i, l in enumerate(model.layers):\n print(i, 'cls=%s name=%s'%(type(l).__name__, l.name))\n weights = l.get_weights()\n for weight in weights:\n print(self.str_shape(weight), )\n print()\n \n def keras_rnn_predict(self, samples, empty=EMPTY, model=MODEL, maxlen=MAXLEN):\n \"\"\"\n For every sample, calculate probability for every possible label.\n You need to supply your RNN model and maxlen (the length of sequences it can handle).\n \"\"\"\n sample_lengths = map(len, samples)\n assert all(l > MAXLEND for l in sample_lengths)\n assert all(l[MAXLEND] == EOS for l in samples)\n # pad from right (post) so the first maxlend will be description followed by headline\n data = keras.preprocessing.sequence.pad_sequences(\n samples, maxlen=MAXLEN, value=empty, padding='post', truncating='post')\n probs = model.predict(data, verbose=0, batch_size=BATCH_SIZE)\n return numpy.array(\n [prob[sample_length-MAXLEND-1] for prob, sample_length in zip(probs, sample_lengths)])\n\n def lpadd(self, x, maxlend=MAXLEND, eos=EOS):\n \"\"\"\n left (pre) pad a description to maxlend and then add eos.\n The eos is the input to predicting the first word in the headline.\n \"\"\"\n assert maxlend >= 0\n if maxlend == 0:\n return [eos]\n n = len(x)\n if n > maxlend:\n x = x[-maxlend:]\n n = maxlend\n return [EMPTY] * (maxlend-n) + x + [eos]\n\n def prt(self, label, x):\n \"\"\"\n DOCSTRING\n \"\"\"\n print(label + ':', )\n for w in x:\n print(self.idx2word[w], )\n print()\n\n def simple_context(\n self,\n X,\n mask,\n n=ACTIVATION_RNN_SIZE,\n maxlend=MAXLEND,\n maxlenh=MAXLENH):\n \"\"\" \n DOCSTRING\n \"\"\"\n desc, head = X[:,:maxlend,:],X[:,maxlend:,:]\n head_activations, head_words = head[:,:,:n], head[:,:,n:]\n desc_activations, desc_words = desc[:,:,:n], desc[:,:,n:]\n # activation for every head word and every desc word\n activation_energies = keras.backend.batch_dot(\n head_activations, desc_activations, axes=(2,2))\n # NOTE: do not use description words that are masked out\n activation_energies = activation_energies + -1e20*keras.backend.expand_dims(\n 1.0-keras.backend.cast(mask[:,:maxlend], 'float32'), 1)\n # for every head word compute weights for every desc word\n activation_energies = keras.backend.reshape(activation_energies, (-1, maxlend))\n activation_weights = keras.backend.softmax(activation_energies)\n activation_weights = keras.backend.reshape(activation_weights, (-1, MAXLENH, maxlend))\n # for every head word compute weighted average of desc words\n desc_avg_word = keras.backend.batch_dot(activation_weights, desc_words, axes=(2,1))\n return keras.backend.concatenate((desc_avg_word, head_words))\n \n def str_shape(self, x):\n \"\"\"\n DOCSTRING\n \"\"\"\n return 'x'.join(map(str, x.shape))\n\n def test_gen(self, gen, n=5):\n \"\"\"\n DOCSTRING\n \"\"\"\n Xtr, Ytr = next(gen)\n for i in range(n):\n assert Xtr[i,MAXLEND] == EOS\n x = Xtr[i,:MAXLEND]\n y = Xtr[i,MAXLEND:]\n yy = Ytr[i,:]\n yy = numpy.where(yy)[1]\n self.prt('L', yy)\n self.prt('H', y)\n if MAXLEND:\n self.prt('D', x)\n\n def vocab_fold(self, xs):\n \"\"\"\n Convert list of word indexes that may contain words outside vocab_size to words inside.\n If a word is outside, try first to use glove_idx2idx to find a similar word inside.\n If none exist then replace all accurancies of the same unknown word with <0>, <1>, ...\n \"\"\"\n xs = [x if x < self.oov0 else self.glove_idx2idx.get(x,x) for x in xs]\n # the more popular word is <0> and so on\n outside = sorted([x for x in xs if x >= self.oov0])\n # if there are more than nb_unknown_words oov words then put them all in nb_unknown_words-1\n outside = dict((x, self.vocab_size-1-min(i, self.nb_unknown_words-1)) for i,x in enumerate(outside))\n xs = [outside.get(x, x) for x in xs]\n return xs\n\n def vocab_unfold(self, desc, xs):\n \"\"\"\n DOCSTRING\n \"\"\"\n # assume desc is the unfolded version of the start of xs\n unfold = {}\n for i, unfold_idx in enumerate(desc):\n fold_idx = xs[i]\n if fold_idx >= self.oov0:\n unfold[fold_idx] = unfold_idx\n return [unfold.get(x,x) for x in xs]\n\nclass VocabularyEmbedding:\n \"\"\"\n DOCSTRING\n \"\"\"\n def __init__(self):\n \"\"\"\n DOCSTRING\n \"\"\"\n self.file_name = 'vocabulary-embedding'\n self.seed = 42\n self.vocab_size = 40000\n self.embedding_dim = 100\n self.lower = False # dont lower case the text\n file_name_0 = 'tokens' # this is the name of the data file\n with open('data/%s.pkl' % file_name_0, 'rb') as fp:\n self.heads, self.desc, keywords = pickle.load(fp)\n if self.lower:\n self.heads = [h.lower() for h in self.heads]\n if self.lower:\n self.desc = [h.lower() for h in self.desc]\n i=0\n self.heads[i]\n self.desc[i]\n keywords[i]\n len(self.heads), len(set(self.heads))\n len(self.desc), len(set(self.desc))\n\n def __call__(self):\n \"\"\"\n DOCSTRING\n \"\"\"\n vocab, vocabcount = self.get_vocab(self.heads + self.desc)\n print('...', len(vocab))\n pyplot.plot([vocabcount[w] for w in vocab])\n pyplot.gca().set_xscale(\"log\", nonposx='clip')\n pyplot.gca().set_yscale(\"log\", nonposy='clip')\n pyplot.title('word distribution in headlines and discription')\n pyplot.xlabel('rank')\n pyplot.ylabel('total appearances')\n self.empty = 0 # RNN mask of no data\n self.eos = 1 # end of sentence\n self.start_idx = self.eos + 1 # first real word\n word2idx, self.idx2word = self.get_idx(vocab, vocabcount)\n fname = 'glove.6B.%dd.txt' % self.embedding_dim\n datadir_base = os.path.expanduser(os.path.join('~', '.keras'))\n if not os.access(datadir_base, os.W_OK):\n datadir_base = os.path.join('/tmp', '.keras')\n datadir = os.path.join(datadir_base, 'datasets')\n glove_name = os.path.join(datadir, fname)\n if not os.path.exists(glove_name):\n path = keras.utils.data_utils.get_file(\n 'glove.6B.zip', origin='http://nlp.stanford.edu/data/glove.6B.zip')\n with zipfile.ZipFile(os.path.join(datadir, path), 'r') as zip_ref:\n zip_ref.extractall(datadir)\n glove_n_symbols = sum(1 for line in open(glove_name))\n glove_n_symbols = int(glove_n_symbols[0].split()[0])\n glove_index_dict = {}\n glove_embedding_weights = numpy.empty((glove_n_symbols, self.embedding_dim))\n globale_scale=0.1\n with open(glove_name, 'r') as fp:\n i = 0\n for l in fp:\n l = l.strip().split()\n w = l[0]\n glove_index_dict[w] = i\n glove_embedding_weights[i,:] = map(float,l[1:])\n i += 1\n glove_embedding_weights *= globale_scale\n glove_embedding_weights.std()\n for w,i in glove_index_dict.items():\n w = w.lower()\n if w not in glove_index_dict:\n glove_index_dict[w] = i\n # generate random embedding with same scale as glove\n numpy.random.seed(self.seed)\n shape = (self.vocab_size, self.embedding_dim)\n scale = glove_embedding_weights.std()*numpy.sqrt(12)/2 # uniform and not normal\n embedding = numpy.random.uniform(low=-scale, high=scale, size=shape)\n print('random-embedding/glove scale', scale, 'std', embedding.std())\n # copy from glove weights of words that appear in our short vocabulary (idx2word)\n c = 0\n for i in range(self.vocab_size):\n w = self.idx2word[i]\n g = glove_index_dict.get(w, glove_index_dict.get(w.lower()))\n if g is None and w.startswith('#'): # glove has no hastags\n w = w[1:]\n g = glove_index_dict.get(w, glove_index_dict.get(w.lower()))\n if g is not None:\n embedding[i,:] = glove_embedding_weights[g,:]\n c+=1\n print('number of tokens, in small vocab, found in glove and copied to embedding',\n c, c/float(self.vocab_size))\n glove_thr = 0.5\n word2glove = {}\n for w in word2idx:\n if w in glove_index_dict:\n g = w\n elif w.lower() in glove_index_dict:\n g = w.lower()\n elif w.startswith('#') and w[1:] in glove_index_dict:\n g = w[1:]\n elif w.startswith('#') and w[1:].lower() in glove_index_dict:\n g = w[1:].lower()\n else:\n continue\n word2glove[w] = g\n normed_embedding = embedding/numpy.array(\n [numpy.sqrt(numpy.dot(gweight,gweight)) for gweight in embedding])[:,None]\n nb_unknown_words = 100\n glove_match = []\n for w,idx in word2idx.items():\n if idx >= self.vocab_size - nb_unknown_words and w.isalpha() and w in word2glove:\n gidx = glove_index_dict[word2glove[w]]\n gweight = glove_embedding_weights[gidx,:].copy()\n # find row in embedding that has the highest cos score with gweight\n gweight /= numpy.sqrt(numpy.dot(gweight,gweight))\n score = numpy.dot(normed_embedding[:self.vocab_size - nb_unknown_words], gweight)\n while True:\n embedding_idx = score.argmax()\n s = score[embedding_idx]\n if s < glove_thr:\n break\n if self.idx2word[embedding_idx] in word2glove:\n glove_match.append((w, embedding_idx, s)) \n break\n score[embedding_idx] = -1\n glove_match.sort(key = lambda x: -x[2])\n print('# of glove substitutes found', len(glove_match))\n for orig, sub, score in glove_match[-10:]:\n print(score, orig,'=>', self.idx2word[sub])\n glove_idx2idx = dict((word2idx[w],embedding_idx) for w, embedding_idx, _ in glove_match)\n Y = [[word2idx[token] for token in headline.split()] for headline in self.heads]\n len(Y)\n pyplot.hist(map(len, Y), bins=50)\n X = [[word2idx[token] for token in d.split()] for d in self.desc]\n len(X)\n pyplot.hist(map(len, X), bins=50)\n with open('data/%s.pkl' % self.file_name,'wb') as fp:\n pickle.dump((embedding, self.idx2word, word2idx, glove_idx2idx), fp, -1)\n with open('data/%s.data.pkl' % self.file_name,'wb') as fp:\n pickle.dump((X,Y),fp,-1)\n \n def get_idx(self, vocab, vocabcount):\n \"\"\"\n DOCSTRING\n \"\"\"\n word2idx = dict((word, idx + self.start_idx) for idx, word in enumerate(vocab))\n word2idx[''] = self.empty\n word2idx[''] = self.eos\n self.idx2word = dict((idx, word) for word, idx in word2idx.items())\n return word2idx, self.idx2word\n\n def get_vocab(self, lst):\n \"\"\"\n DOCSTRING\n \"\"\"\n vocabcount = collections.Counter(w for txt in lst for w in txt.split())\n vocab = map(lambda x:x[0], sorted(vocabcount.items(), key=lambda x:-x[1]))\n return vocab, vocabcount\n","sub_path":"text_summarizer_demo/text_summarizer_demo.py","file_name":"text_summarizer_demo.py","file_ext":"py","file_size_in_byte":28071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"219078878","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom backend.forms.article import ArticleForm\nfrom backend.forms.article import EditArticleForm\nfrom backend.forms.category import CategoryForm\nfrom backend import models\nfrom django.db import transaction\nfrom backend.auth.auth import check_login\nimport json\nimport os\nfrom d3 import settings\nimport hashlib\n# Create your views here.\n\n\n@check_login\ndef index(request):\n if request.method == 'GET':\n return render(request, 'backend/backend-index.html')\n\n\n@check_login\ndef user_info(request, **kwargs):\n user_id = request.session.get('user_info')['id']\n user_obj = models.UserInfo.objects.filter(id=user_id).first()\n if request.method == 'GET':\n return render(request, 'backend/user-info.html', {'nav_id': int(kwargs['nav_id']),\n 'user_obj': user_obj\n })\n\n\n@check_login\ndef surprise(request):\n return render(request, 'backend/surprise.html')\n\n\n@check_login\ndef article(request, **kwargs):\n if request.method == 'GET':\n article_obj = models.Article.objects.all()\n return render(request, 'backend/backend-article.html', {'article_obj': article_obj,\n 'nav_id': int(kwargs['nav_id']),\n })\n\n\n@check_login\ndef add_article(request):\n if request.method == 'GET':\n form = ArticleForm()\n return render(request, 'backend/add-article.html', {'form': form})\n elif request.method == 'POST':\n form = ArticleForm(request.POST)\n if form.is_valid():\n with transaction.atomic():\n content = form.cleaned_data['content']\n tags = form.cleaned_data.pop('tag_id')\n article_detail = models.ArticleDetail.objects.create(content=content)\n content_id = article_detail.id\n form.cleaned_data['content_id'] = content_id\n form.cleaned_data['author_id'] = 1 # 由于没有用户,临时添加的用户id\n form.cleaned_data.pop('content')\n article_obj = models.Article.objects.create(**form.cleaned_data)\n article_obj.tag.add(*tags)\n else:\n return render(request, 'backend/add-article.html', {'form': form})\n return redirect('/backend/article/1') # 为后台管理中心导航栏的id, 1为文章管理的id\n\n\n@check_login\ndef del_article(request, **kwargs):\n article_id = int(kwargs['article_id'])\n article_obj = models.Article.objects.filter(id=article_id).first()\n if article_obj:\n article_obj.delete()\n return redirect('/backend/article/1')\n else:\n return HttpResponse(\"文章不存在\")\n\n\n@check_login\ndef edit_article(request, **kwargs):\n article_id = int(kwargs['article_id'])\n if request.method == 'GET':\n article_obj = models.Article.objects.filter(id=article_id).first()\n content_obj = article_obj.content.content\n if article_obj:\n article_form = EditArticleForm(instance=article_obj)\n return render(request, 'backend/edit-article.html', {'article_form': article_form,\n 'content_obj': content_obj,\n 'article_id': article_id\n })\n else:\n return HttpResponse(\"错误,文章不存在\")\n elif request.method == 'POST':\n article_obj = models.Article.objects.filter(id=article_id)\n article_form = ArticleForm(request.POST)\n if article_form.is_valid():\n with transaction.atomic():\n content = article_form.cleaned_data['content']\n models.ArticleDetail.objects.filter(id=article_id).update(content=content)\n tags = article_form.cleaned_data['tag_id']\n article_form.cleaned_data.pop('content')\n article_form.cleaned_data.pop('tag_id')\n article_obj.update(**article_form.cleaned_data)\n obj = models.Article.objects.get(id=article_id)\n obj.tag.set(*tags)\n return redirect('/backend/article/1')\n else:\n return render(request, 'backend/edit-article.html', {'article_form': article_form,\n 'article_id': article_id\n })\n\n\n@check_login\ndef upload_img(request):\n if request.method == 'POST':\n ret = {'errno': 1, 'data': None}\n m = hashlib.md5()\n file_type = request.FILES.get('myfile').name.split('.')[-1]\n m.update(request.FILES.get('myfile').name.encode('utf-8'))\n filename = m.hexdigest() + '.' + file_type\n file_path = os.path.join(settings.MEDIA_ROOT, filename)\n with open(file_path, 'wb+') as f:\n for chunk in request.FILES.get('myfile'):\n f.write(chunk)\n\n url = settings.MEDIA_URL + filename\n print(url)\n ret['errno'] = 0\n ret['data'] = [url]\n return HttpResponse(json.dumps(ret))\n\n\n# newbackend\ndef base(request):\n return render(request, 'newbackend/base.html')\n\n\n@check_login\ndef my_article(request):\n if request.method == 'GET':\n article_obj = models.Article.objects.all()\n return render(request, 'newbackend/my-article.html', {'article_obj': article_obj})\n\n\n@check_login\ndef addd_article(request):\n if request.method == 'GET':\n form = ArticleForm()\n return render(request, 'newbackend/add-article.html', {'form': form})\n if request.method == 'POST':\n ret = {'status': False}\n user_id = request.session.get('user_info')['id']\n form = ArticleForm(request.POST)\n if form.is_valid():\n article_status = form.cleaned_data['status'] # 判断文章的状态,1发布,0保存为草稿\n if article_status == '0':\n status = False\n else:\n status = True\n with transaction.atomic():\n content = form.cleaned_data['content']\n form.cleaned_data['status'] = status\n tags = form.cleaned_data.pop('tag_id')\n article_detail = models.ArticleDetail.objects.create(content=content)\n content_id = article_detail.id\n form.cleaned_data['content_id'] = content_id\n form.cleaned_data['author_id'] = user_id\n form.cleaned_data.pop('content')\n article_obj = models.Article.objects.create(**form.cleaned_data)\n if tags:\n article_obj.tag.add(*tags)\n ret['status'] = True\n else:\n return render(request, 'newbackend/add-article.html', {'form': form})\n return HttpResponse(json.dumps(ret))\n\n\n@check_login\ndef my_category(request):\n if request.method == 'GET':\n category_obj = models.Category.objects.all()\n return render(request, 'newbackend/my-category.html', {'category_obj': category_obj})\n if request.method == 'POST':\n pass\n\n\n@check_login\ndef add_category(request):\n if request.method == 'GET':\n form = CategoryForm()\n return render(request, 'newbackend/add-category.html', {'form': form})\n if request.method == 'POST':\n form = CategoryForm(request.POST)\n if form.is_valid():\n category_obj = models.Category.objects.create(**form.cleaned_data)\n else:\n return render(request, 'newbackend/add-category.html', {'form': form})\n\n return redirect('/backend/my-category.html')\n\n\n@check_login\ndef edit_category(request):\n if request.method == 'GET':\n category_id = request.GET.get('category_id')\n category_obj = models.Category.objects.filter(id=category_id).first()\n if not category_obj:\n return HttpResponse('修改的目录不存在')\n dic = {'id': category_id, 'name': category_obj.name}\n form = CategoryForm(initial=dic)\n return render(request, 'newbackend/edit-category.html', {'form': form})\n if request.method == 'POST':\n form = CategoryForm(request.POST)\n if form.is_valid():\n category_id = form.cleaned_data.get('id')\n name = form.cleaned_data.get('name')\n category_obj = models.Category.objects.filter(id=category_id)\n if not category_obj:\n return HttpResponse('非法操作')\n category_obj.update(name=name)\n return redirect('/backend/my-category.html')\n else:\n return render(request, 'newbackend/edit-category.html', {'form': form})\n\n\n@check_login\ndef add_comment(request):\n ret = {\"status\": False, \"error\": None}\n data = {}\n if request.method == 'POST':\n data['content'] = request.POST.get('text')\n data['article_id'] = request.POST.get('article_id')\n data['reply_id'] = request.POST.get('comment_id')\n data['username_id'] = request.POST.get('user_id')\n # print(data)\n if not (data['content'] and data['article_id'] and data['username_id']):\n ret['error'] = \"Invalid operation\"\n return HttpResponse(json.dumps(ret))\n models.Comment.objects.create(**data)\n ret['status'] = True\n return HttpResponse(json.dumps(ret))","sub_path":"backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"574785931","text":"import json\nimport os\nimport uuid\nimport contextlib\nimport csv\nimport multiprocessing\n\nfrom threading import current_thread\nfrom rx import Observable\nfrom rx.concurrency import ThreadPoolScheduler\n\nfrom io import StringIO\n\nfrom flask import Response\nfrom flask_restful import Resource, request\n\nfrom api.common.decorators import jwt_required, log, role_required\n\nfrom api.services.client_products.client_products import send_product, check_header_file, investments\nimport pandas as pd\nimport requests\nimport os\n\n\nclass CsvFileUpload(Resource):\n @jwt_required\n @role_required('Admin', 'GestorProduto')\n @log('Upload de produtos com sucesso!')\n def post(self):\n try:\n from server import app\n\n files = request.files\n if not request.files:\n return {'message': 'Arquivo não enviado'}, 400\n\n csv_type = request.form['csv_type']\n if not csv_type:\n return {'message': 'Tipo do arquivo não enviado'}, 500\n\n if not os.path.exists(app.config['UPLOAD_FOLDER']):\n os.makedirs(app.config['UPLOAD_FOLDER'],\n mode=0o777, exist_ok=True)\n\n key_csv = list(files.keys())[0]\n data = pd.read_csv(files[key_csv], delimiter=';')\n header = list(data)\n\n if files[key_csv] and self.allowed_file(files[key_csv].filename):\n\n optimal_thread_count = multiprocessing.cpu_count()\n pool_scheduler = ThreadPoolScheduler(optimal_thread_count)\n\n extension = os.path.splitext(files[key_csv].filename)[1]\n\n if not check_header_file(header, csv_type):\n return Response(json.dumps({'message': 'O arquivo está incompatível com o tipo selecionado'}), 500, content_type=\"application/json\")\n\n headers = {\n 'content-type': 'application/json',\n 'X-API-Key': os.environ.get('API_KEY_ALLGOO'),\n 'X-TYK-TOKEN-Allg00-clients': 'andbank'\n }\n url = os.environ.get('API_GATEWAY_URL') + \\\n '/clients/products/' + investments[csv_type][\"slug\"]\n\n r = requests.delete(url, headers=headers)\n if r and (r.status_code != 200 and r.status_code != 201):\n return Response(json.dumps({'message': r.reason}), 500, content_type=\"application/json\")\n\n Observable.from_(data.values.tolist()) \\\n .map(lambda row, csv_type=csv_type: send_product(row, csv_type, headers)) \\\n .subscribe_on(pool_scheduler) \\\n .subscribe(\n on_next=lambda s: print(\n \"PROCESS 1: {0} {1}\".format(current_thread().name, s)),\n on_error=lambda e: print(e),\n on_completed=lambda: print(\"PROCESS 1 done!\"))\n\n return Response(json.dumps({'message': 'Processando os produtos'}), 201, content_type=\"application/json\")\n except Exception as e:\n print(e)\n return {'message': str(e)}, 500\n\n def allowed_file(self, filename):\n from server import app\n\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in set(['csv', 'txt'])\n","sub_path":"Allgoo/api-andbank/api/resources/upload_csv.py","file_name":"upload_csv.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"199909690","text":"from .Sound import Sound, PreloadSounds\nfrom .Devices import queryDevices\n\nPlayers = []\npreload = {}\nplayback_device, feedback_device = (\"\", \"\")\n\ndef _delete_finished_players():\n for player in Players:\n if player.finished:\n Players.remove(player)\n\ndef _stop_players():\n for player in Players:\n player.stop()\n\n\ndef Init(module_config):\n global preload, playback_device, feedback_device\n\n print(\"Soundboard: Retreiving playback & feedback config...\")\n playback_device, playback_volume, feedback_device, feedback_volume = queryDevices(module_config)\n print(\"Soundboard: Playback on %s with volume %d\" % (playback_device, playback_volume))\n print(\"Soundboard: Feedback on %s with volume %d\" % (feedback_device, feedback_volume))\n\n print(\"Soundboard: Preloading...\")\n preload = PreloadSounds(module_config, playback_volume, feedback_volume)\n print(\"Soundboard: Preload ok.\")\n\n captured_keys = list(module_config[\"sounds\"].keys()) + list(module_config[\"actions\"].keys())\n\n return True, captured_keys\n\ndef Update(module_config, key):\n\n _delete_finished_players()\n\n if key in module_config[\"sounds\"]:\n Players.append(Sound(samplerate=44100, device=playback_device).play(preload[key][0]))\n Players.append(Sound(samplerate=44100, device=feedback_device).play(preload[key][1]))\n return True\n\n elif key in module_config[\"actions\"]:\n if module_config[\"actions\"][key] == \"\":\n _stop_players()\n return True\n\n return False\n\ndef Finish(module_config):\n _stop_players()\n _delete_finished_players()\n return True\n","sub_path":"Soundboard/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"529910975","text":"import copy\nimport pandas as pd\nimport numpy as np\nimport random\nimport time\nfrom ClusterUtils.SuperCluster import SuperCluster\nfrom ClusterUtils.ClusterPlotter import _plot_kmeans_\n\n# https://en.wikipedia.org/wiki/K-means_clustering#Algorithms\n# Pretty much using for pseudocode sections\ndebug = False\n\ndef distance(point, centroid):\n # Euclidean distance. No root because it will always be the same.\n dist = 0\n for val in range(len(point)):\n dist += (point[val] - centroid[val]) ** 2\n return dist\n\ndef get_closest_centroid(point, centroids):\n #return an int from 0 to len(centroids)\n minimum = [-1,None]\n for cent in range(len(centroids)):\n #calculate the distance in easiest way\n dist = distance(point, centroids[cent])\n if minimum[0] == -1 or dist < minimum[0]:\n minimum[0] = dist\n minimum[1] = cent\n return minimum[1]\n\ndef get_min_and_max(X):\n # Finds the ranges for all the data. Helpful for generating random centroids\n to_return = [None] * X.shape[1]\n\n for point in X:\n for minmax in range(X.shape[1]):\n if to_return[minmax] == None:\n to_return[minmax] = [point[minmax], point[minmax]]\n else:\n to_return[minmax][0] = min(to_return[minmax][0], point[minmax])\n to_return[minmax][1] = max(to_return[minmax][0], point[minmax])\n print(to_return)\n return to_return\n\ndef silhouette(X, centroids, labels):\n to_return = 0 # Where we will be putting the distance\n # s = (b – a) / max(a,b)\n # a is avg distance to in-cluster\n # Extraordinarily inefficient because of being O(N^2)\n # Considering only working off a sample of the data to cut down on time.\n\n for point1 in range(X.shape[0]):\n a = 0\n a_count = 0\n b_list = [0] * centroids\n b_counts = [0] * centroids #gotta count the number of points per outgroup yo\n for point2 in range(X.shape[0]):\n if labels[point1] == labels[point2]:\n a += distance(X[point1],X[point2])\n a_count += 1\n else:\n b_list[labels[point2]] += distance(X[point1],X[point2])\n b_counts[labels[point2]] += 1\n a = a/a_count\n b_list.pop(labels[point1]) # Avoid the 0/0 from ingroup\n b_counts.pop(labels[point1])\n\n b = min([b_list[x] / (b_counts[x] + 1) for x in range(len(b_list))])\n\n s = (b - a) / max(a,b)\n to_return += s\n to_return = to_return / X.shape[0]\n return to_return\n\ndef k_means(X, n_clusters=3, init='random', algorithm='lloyds', n_init=1, max_iter=300, verbose=False):\n\n # Implement.\n\n # Input: np.darray of samples\n\n # Return the following:\n #\n # 1. labels: An array or list-type object corresponding to the predicted\n # cluster numbers,e.g., [0, 0, 0, 1, 1, 1, 2, 2, 2]\n # 2. centroids: An array or list-type object corresponding to the vectors\n # of the centroids, e.g., [[0.5, 0.5], [-1, -1], [3, 3]]\n # 3. inertia: A number corresponding to some measure of fitness,\n # generally the best of the results from executing the algorithm n_init times.\n # You will want to return the 'best' labels and centroids by this measure.\n\n labels = [None] * X.shape[0]\n centroids = [] #List of essentially points\n inertia = -1 # measure of fitness\n\n for loop in range(n_init): # Do a bunch of times and take 'best' by some measure\n #Initialize the centroids etc for current iteration\n cur_centroids = [] * n_clusters\n ranges = get_min_and_max(X) #So we know where centroids can appear\n i = 0\n while i < n_clusters:\n i += 1\n #Gotta make that uniform distribution yo.\n location = [random.uniform(ranges[item][0], ranges[item][1]) for item in range(X.shape[1])]\n cur_centroids.append(location)\n if debug: print(cur_centroids)\n cur_labels = [None] * X.shape[0]\n cur_inertia = 0 # measure of fitness\n\n x = 0\n last_centroids = None\n while x < max_iter and cur_centroids != last_centroids:\n last_centroids = copy.deepcopy(cur_centroids) #Gotta be deep\n x += 1\n #Assignment Step\n # Assign each observation to the cluster whose mean has the least squared Euclidean distance,\n counts = [0] * n_clusters # keep track of number in each cluster\n sums = [[0] * X.shape[1] for c in range(n_clusters)] # For an average of the next set of centroids\n for sample in range(X.shape[0]):\n min_centroid = get_closest_centroid(X[sample], cur_centroids)\n cur_labels[sample] = min_centroid\n #Update sums for this centroid\n counts[min_centroid] += 1\n for dimension in range(X.shape[1]):\n sums[min_centroid][dimension] += X[sample][dimension]\n\n #Reset centroid step\n\n for centroid in range(len(cur_centroids)):\n if counts[centroid] == 0:\n #Reassign centroid to new random point\n cur_centroids[centroid] = []\n location = [random.uniform(ranges[item][0], ranges[item][1]) for item in range(X.shape[1])]\n cur_centroids[centroid] = location\n else:\n for dimension in range(X.shape[1]):\n cur_centroids[centroid][dimension] = sums[centroid][dimension] / counts[centroid]\n\n cur_inertia = silhouette(X, len(cur_centroids), cur_labels)\n if inertia == -1 or cur_inertia < inertia:\n inertia = cur_inertia\n labels = cur_labels\n centroids = cur_centroids\n\n return labels, centroids, inertia\n\n\n# The code below is completed for you.\n# You may modify it as long as changes are noted in the comments.\n\nclass KMeans(SuperCluster):\n \"\"\"\n Parameters\n ----------\n n_clusters : int, optional, default: 8\n The number of clusters to form as well as the number of\n centroids to generate.\n init : {'random', 'k-means++', 'global'}\n Method for initialization, defaults to 'random'.\n algorithm : {'lloyds', 'hartigans'}\n Method for determing algorithm, defaults to 'lloyds'.\n n_init : int, default: 1\n Number of time the k-means algorithm will be run with different\n centroid seeds. The final results will be the best output of\n n_init consecutive runs in terms of inertia.\n max_iter : int, default: 300\n Maximum number of iterations of the k-means algorithm for a\n single run.\n csv_path : str, default: None\n Path to file for dataset csv\n keep_dataframe : bool, default: True\n Hold on the results pandas DataFrame generated after each run.\n Also determines whether to use pandas DataFrame as primary internal data state\n keep_X : bool, default: True\n Hold on the results generated after each run in a more generic array-type format\n Use these values if keep_dataframe is False\n verbose: bool, default: False\n Optional log level\n \"\"\"\n\n def __init__(self, n_clusters=3, init='random', algorithm='lloyds', n_init=1, max_iter=300,\n csv_path=None, keep_dataframe=True, keep_X=True, verbose=False):\n self.n_clusters = n_clusters\n self.init = init\n self.algorithm = algorithm\n self.n_init = n_init\n self.max_iter = max_iter\n self.csv_path = csv_path\n self.keep_dataframe = keep_dataframe\n self.keep_X = keep_X\n self.verbose = verbose\n\n # X is an array of shape (n_samples, n_features)\n def fit(self, X):\n if self.keep_X:\n self.X = X\n start_time = time.time()\n self.labels, self.centroids, self.inertia = \\\n k_means(X, n_clusters=self.n_clusters, init=self.init, algorithm=self.algorithm,\n n_init=self.n_init, max_iter=self.max_iter, verbose=self.verbose)\n print(self.init + \" k-means finished in %s seconds\" % (time.time() - start_time))\n return self\n\n def show_plot(self):\n if self.keep_dataframe and hasattr(self, 'DF'):\n _plot_kmeans_(df=self.DF)\n elif self.keep_X:\n _plot_kmeans_(X=self.X, labels=self.labels, centroids=self.centroids)\n else:\n print('No data to plot.')\n\n def save_plot(self, name = 'kmeans_plot'):\n if self.keep_dataframe and hasattr(self, 'DF'):\n _plot_kmeans_(df=self.DF, save=True, n=name)\n elif self.keep_X:\n _plot_kmeans_(X=self.X, labels=self.labels,\n centroids=self.centroids, save=True, n=name)\n else:\n print('No data to plot.')\n","sub_path":"ClusterUtils/KMeans.py","file_name":"KMeans.py","file_ext":"py","file_size_in_byte":8796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"130478244","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.11-x86_64/egg/pytrack_analysis/profile.py\n# Compiled at: 2017-07-25 14:07:28\n# Size of source mod 2**32: 8150 bytes\nimport os, sys\nfrom datetime import datetime as date\nfrom functools import wraps\nimport tkinter as tk\nfrom tkinter import messagebox, filedialog\nfrom ._globals import *\nPROFILE, NAME, OS = get_globals()\n\ndef get_profile(_name, _user, script=''):\n \"\"\"\n Returns profile as dictionary. If the given project name or user name is not in the profile, it will create new entries.\n\n Arguments:\n * _name: project name or 'all' (all projects)\n * _user: username\n * script: scriptname\n \"\"\"\n tk.Tk().withdraw()\n nowdate = date.now().strftime('%Y-%m-%d %H:%M:%S')\n with open(PROFILE, 'r') as (stream):\n profile = yaml.load(stream)\n if _name == 'all':\n return profile\n if _name in profile['$PROJECTS']:\n NEW_PROJ = True\n project = profile[_name]\n project['last active'] = nowdate\n profile['active'] = _name\n try:\n systems = project['systems']\n if NAME not in systems.keys():\n if query_yn(\"System '{:}' does not seem to exist in the profile. DO you want to set up a new systems profile? (Opens TKinter GUI)\".format(NAME)):\n profile['activesys'] = NAME\n systems[NAME] = {}\n system = systems[NAME]\n system['os'] = OS\n system['python'] = sys.version\n dbfile, viddir = set_database(forced=True)\n if dbfile is not None:\n if viddir is not None:\n system['database'] = dbfile\n system['videos'] = viddir\n out, log, plot = set_output(forced=True)\n if out is not None:\n system['output'] = out\n system['log'] = log\n system['plot'] = plot\n else:\n profile['activesys'] = NAME\n system = systems[NAME]\n system['python'] = sys.version\n except (AttributeError, TypeError):\n project['systems'] = {}\n\n else:\n NEW_PROJ = query_yn('DO you want to create a new project: {:}?'.format(_name))\n if NEW_PROJ:\n profile['$PROJECTS'].append(_name)\n profile[_name] = {}\n project = profile[_name]\n project['users'] = []\n project['users'].append(_user)\n project['created'] = nowdate\n project['last active'] = nowdate\n profile['active'] = _name\n project['systems'] = {}\n systems = project['systems']\n systems[NAME] = {}\n system = systems[NAME]\n system['os'] = OS\n system['python'] = sys.version\n dbfile, viddir = set_database(forced=True)\n if dbfile is not None:\n if viddir is not None:\n system['database'] = dbfile\n system['videos'] = viddir\n out, log, plot = set_output(forced=True)\n if out is not None:\n system['output'] = out\n system['log'] = log\n system['plot'] = plot\n print('Created [PROJECT] {:}.'.format(_name))\n if NEW_PROJ:\n profile['activeuser'] = _user\n users = profile['$USERS']\n if _user not in users:\n if query_yn('DO you want to create a new user: {:}?'.format(_user)):\n users.append(_user)\n if _user not in project['users']:\n if query_yn('DO you want to add user to project: {:}?'.format(_name)):\n project['users'].append(_user)\n print('Loaded [PROJECT] {:}'.format(_name))\n with io.open(PROFILE, 'w+', encoding='utf8') as (outfile):\n yaml.dump(profile, outfile, default_flow_style=False, allow_unicode=True)\n return profile\n\n\ndef get_db(profile):\n \"\"\" Returns active system's database file location \"\"\"\n return profile[profile['active']]['systems'][NAME]['database']\n\n\ndef get_out(profile):\n \"\"\" Returns active system's output path \"\"\"\n return profile[profile['active']]['systems'][NAME]['output']\n\n\ndef get_log(profile):\n \"\"\" Returns active system's logfile location \"\"\"\n return profile[profile['active']]['systems'][NAME]['log']\n\n\ndef get_plot(profile):\n \"\"\" Returns active system's plot path \"\"\"\n return profile[profile['active']]['systems'][NAME]['plot']\n\n\ndef set_database(forced=False):\n \"\"\" Returns database file location and video directory chosen from TKinter filedialog GUI \"\"\"\n if not forced:\n asksave = messagebox.askquestion('Set database path', 'Are you sure you want to set a new path for the database?', icon='warning')\n if asksave == 'no':\n return (None, None)\n print('Set database...')\n dbfile = filedialog.askopenfilename(title='Load database')\n print('Set raw videos location...')\n viddir = filedialog.askdirectory(title='Load directory with raw video files')\n return (dbfile, viddir)\n\n\ndef set_output(forced=False):\n \"\"\" Returns output, log and plot path chosen from TKinter filedialog GUI \"\"\"\n if not forced:\n asksave = messagebox.askquestion('Set output path', 'Are you sure you want to set a new path for the output/logging?', icon='warning')\n if asksave == 'no':\n return (None, None, None)\n else:\n print('Set output location...')\n outfolder = filedialog.askdirectory(title='Load directory for output')\n if len(outfolder) > 0:\n out = outfolder\n log = os.path.join(outfolder, 'main.log')\n plot = os.path.join(outfolder, 'plots')\n else:\n out = os.path.join(USER_DATA_DIR, 'output')\n log = os.path.join(out, 'main.log')\n plot = os.path.join(out, 'plots')\n for each in [out, plot]:\n check_folder(each)\n\n return (out, log, plot)\n\n\ndef show_profile(profile):\n \"\"\" Command-line output of profile with colored formatting (active project is bold green) \"\"\"\n RED = '\\x1b[1;31m'\n CYAN = '\\x1b[1;36m'\n MAGENTA = '\\x1b[1;35m'\n RESET = '\\x1b[0;0m'\n print()\n if profile is None:\n profile_dump = yaml.dump(profile, default_flow_style=False, allow_unicode=True)\n thisstr = profile_dump.split('\\n')\n sys.stdout.write(RED)\n for lines in thisstr:\n if lines == '$PROJECTS:' or lines == '$USERS:':\n sys.stdout.write(RED)\n else:\n if lines.startswith('-'):\n sys.stdout.write(CYAN)\n else:\n sys.stdout.write(RESET)\n print(lines)\n\n sys.stdout.write(RESET)\n else:\n current = profile['active']\n profile_dump = yaml.dump(profile, default_flow_style=False, allow_unicode=True)\n thisstr = profile_dump.split('\\n')\n sys.stdout.write(RED)\n for lines in thisstr:\n if lines == '$PROJECTS:' or lines == '$USERS:':\n sys.stdout.write(RED)\n else:\n if lines.startswith('-'):\n sys.stdout.write(CYAN)\n elif current in lines:\n if 'active' not in lines:\n print()\n sys.stdout.write(MAGENTA)\n else:\n sys.stdout.write(RESET)\n print(lines)\n\n sys.stdout.write(RESET)","sub_path":"pycfiles/pytrack_analysis-0.0.3-py3.6/profile.cpython-36.py","file_name":"profile.cpython-36.py","file_ext":"py","file_size_in_byte":7714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"257727016","text":"import cv2\nfrom base64 import b64encode\n\n\"\"\" read/write utilities \"\"\"\n\ndef read_image(filename):\n return cv2.imread(filename)\n\ndef save_image(filename, im):\n\tcv2.imwrite(filename, im)\n\ndef read_image_base64(filename):\n\twith open(filename, 'rb') as f:\n\t\treturn b64encode(f.read())\n\n\n\"\"\" OpenCV drawing utilities \"\"\"\n\ndef draw_face(im, annotations):\n\tfor a in annotations:\n\t\ttl ,br = draw_box(im, a['boundingPoly']['vertices'])\n\t\ttl_,br_ = draw_box(im, a['fdBoundingPoly']['vertices'])\n\t\tdraw_angle(im, a['panAngle'], a['tiltAngle'], pt=tl_, size=br_[0]-tl_[0])\n\t\tfor landmark in a['landmarks']:\n\t\t\tdraw_point(im, landmark['position'])\n\t\t\ndef draw_angle(im, pan, tilt, pt, size):\n\tx_delta = np.interp(pan, [-180,180], [-size,size])\n\ty_delta = np.interp(tilt, [-180,180], [-size,size])\n\tpt2 = (pt[0] + int(x_delta), pt[1] + int(y_delta))\n\tcv2.arrowedLine(im, pt, pt2, (0,255,0))\n\n\ndef extract_vertices(vertices):\n\t\"\"\" Extract two opposite vertices from a list of 4 (assumption: rectangle) \"\"\"\n\n\tmin_x,max_x,min_y,max_y = float(\"inf\"),float(\"-inf\"),float(\"inf\"),float(\"-inf\")\n\n\tfor v in vertices:\n\t\tif v.get('x',min_y) < min_x:\n\t\t\tmin_x = v.get('x')\n\t\tif v.get('x',max_y) > max_x:\n\t\t\tmax_x = v.get('x')\n\t\tif v.get('y',min_y) < min_y:\n\t\t\tmin_y = v.get('y')\n\t\tif v.get('y',max_y) > max_y:\n\t\t\tmax_y = v.get('y')\n\n\tv1 = next(v for v in vertices if v.get('x') == min_x and v.get('y') == min_y)\n\tv2 = next(v for v in vertices if v.get('x') == max_x and v.get('y') == max_y)\n\n\treturn v1,v2\n\n\ndef draw_box(im, vertices):\n\tv1,v2 = extract_vertices(vertices)\n\tpt1 = (v1.get('x',0), v1.get('y',0))\n\tpt2 = (v2.get('x',0), v2.get('y',0))\n\tcv2.rectangle(im, pt1, pt2, (0,0,255))\n\treturn pt1, pt2\n\ndef draw_point(im, position):\n\tpt = (int(position.get('x',0)), int(position.get('y',0)))\n\tcv2.circle(im, pt, 3, (0,0,255))\n\treturn pt\n\ndef draw_text(im, text):\n\tfont_face = cv2.FONT_HERSHEY_SIMPLEX\n\tthickness = 1\n\tfor scale in np.arange(2,0,-0.2):\n\t\t(w,h),baseline = cv2.getTextSize(text, font_face, scale, thickness)\n\t\tif w <= im.shape[1]:\n\t\t\tnew_img = cv2.copyMakeBorder(im, 0, baseline*4, 0, 0, cv2.BORDER_CONSTANT, value=0)\n\t\t\tcv2.putText(new_img, text, (baseline*2,new_img.shape[0]-baseline), font_face, scale, (255,255,255), thickness)\n\t\t\treturn new_img\n\n","sub_path":"sandbox/utils_image.py","file_name":"utils_image.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"650857843","text":"from vkviewer.python.models.Meta import Base\nfrom vkviewer.python.models.messtischblatt.Messtischblatt import Messtischblatt\nfrom vkviewer.python.models.messtischblatt.MdCore import MdCore\nfrom webhelpers.paginate import PageURL_WebOb, Page\n\n\n''' Specific query operations '''\ndef getWmsUrlForMtb(mtbid, session):\n query = 'SELECT webmappingservice.onlineressource FROM webmappingservice, refmtbwms WHERE \\\n refmtbwms.messtischblatt = :mtbid AND webmappingservice.servicename = \\\n refmtbwms.webmappingservice;'\n result = session.execute(query,{'mtbid':mtbid}).fetchone()\n return result['onlineressource']\n\n\"\"\" This function computes via a SQL Query the total number of messtischblaetter, which\n are right now published for georeferencing\n @parma session - {SQLAlchemy.SessionObject} \n\"\"\"\n\ndef getCountOfPublishedMesstischblaetter(session):\n query = 'SELECT count(istaktiv) FROM messtischblatt WHERE istaktiv = True'\n result = session.execute(query).fetchone()\n return result['count'] \n\n\"\"\" This function computes via a SQL Query the occurrence of georeferenced \n messtischblaetter. \n \n @param session - {SQLAlchemy.SessionObject}\n\"\"\"\ndef getCountOfGeorefMesstischblaetter(session):\n query = 'SELECT count(isttransformiert) FROM messtischblatt WHERE isttransformiert = True'\n result = session.execute(query).fetchone()\n return result['count']\n\n\"\"\" This function creates a paginator object, which represents a list of messtischblaett objects \n plus information over his zoomify representation for a given blattnumber. It will only choose\n such messtischblaetter which are not georeferenced yet.\n \n @param request - {Pyramid.Request}\n @param blattnr - {Messtischblatt.blattnr}\n @param session - {SQLAlchemy.SessionObject}\n @param page - {Integer}\n @return {Paginator} \n\"\"\"\ndef getZoomifyCollectionForBlattnr(request, blattnr, session, page=1):\n coll = []\n mtbs = Messtischblatt.allForBlattnr(blattnr, session)\n for mtb in mtbs:\n metadata = MdCore.by_id(mtb.id, session)\n if mtb.mdtype == 'M' and mtb.istaktiv and not mtb.isttransformiert and mtb.hasgeorefparams == 0:\n item = {'mtbid':mtb.id,'layername':mtb.dateiname,'titel':metadata.titel,'titel_short':metadata.titel_short,\n 'zoomify_prop':mtb.zoomify_properties,'zoomify_width':mtb.zoomify_width,'zoomify_height':mtb.zoomify_height}\n coll.append(item)\n # create paginator\n page_url = PageURL_WebOb(request)\n return Page(coll, page, url=page_url, items_per_page=10)\n\ndef getCollectionForBlattnr(blattnr, session):\n coll =[]\n mtbs = Messtischblatt.allForBlattnr(blattnr, session)\n for mtb in mtbs:\n wms_url = getWmsUrlForMtb(mtb.id, session)\n metadata = MdCore.by_id(mtb.id, session)\n item = {'wms_url':wms_url,'mtbid':mtb.id,'layername':mtb.dateiname,'titel':metadata.titel,\n 'zoomify_prop':mtb.zoomify_properties,'zoomify_width':mtb.zoomify_width,\n 'zoomify_height':mtb.zoomify_height}\n coll.append(item)\n return coll\n\ndef getPaginatorForBlattnr(request, blattnr, session, page=1):\n page_url = PageURL_WebOb(request)\n \n # get the collection for the paginator\n pageinateColl = getCollectionForBlattnr(blattnr, session)\n return Page(pageinateColl, page, url=page_url, items_per_page=10)","sub_path":"vkviewer/python/models/messtischblatt/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"508615025","text":"from sage.all import EllipticCurve, Integer, QQ, Set, magma, prime_range, factorial, mwrank_get_precision, mwrank_set_precision, srange, pari\n\nfrom sage.databases.cremona import parse_cremona_label, class_to_int\ntry:\n from sage.databases.cremona import cmp_code\nexcept:\n pass\n\nmwrank_saturation_precision = 300\nmwrank_saturation_maxprime = 200000\nGP = '/usr/local/bin/gp'\n\ndef print_data(outfile, code, ainvs, r, t):\n print(\"Code = {}\".format(code))\n print(\"Curve = {}\".format(EllipticCurve(ainvs)))\n print(\"rank = {}\".format(r))\n print(\"torsion = {}\".format(t))\n\ndef put_allcurves_line(outfile, N, cl, num, ainvs, r, t):\n line = ' '.join([str(N),cl,str(num),str(ainvs).replace(' ',''),str(r),str(t)])\n outfile.write(line+'\\n')\n\ndef make_allcurves_lines(outfile, code, ainvs, r, t):\n E = EllipticCurve(ainvs)\n N, cl, n = parse_cremona_label(code)\n for i, F in enumerate(E.isogeny_class().curves):\n put_allcurves_line(outfile,N,cl,str(i+1),list(F.ainvs()),r,F.torsion_order())\n outfile.flush()\n\ndef process_curve_file(infilename, outfilename, use):\n infile = open(infilename)\n outfile = open(outfilename, mode='a')\n for L in infile.readlines():\n N, iso, num, ainvs, r, tor, d = L.split()\n code = N+iso+num\n N = int(N)\n num = int(num)\n r = int(r)\n tor = int(tor)\n ainvs = eval(ainvs)\n use(outfile, code, ainvs, r, tor)\n infile.close()\n outfile.close()\n\ndef liststr(l):\n return str(l).replace(' ','')\n\ndef shortstr(E):\n return liststr(list(E.ainvs()))\n\ndef shortstrlist(Elist):\n return str([list(F.ainvs()) for F in Elist]).replace(' ','')\n\ndef pointstr(P):\n P = list(P)\n z = P[1].denominator()\n P = [z*c for c in P]\n return '['+':'.join([str(c) for c in P])+']'\n# return str(P).replace('(','[').replace(')',']').replace(' ','')\n\n# convert '[x:y:z]' to '[x/z,y/z]'\ndef pointPtoA(P):\n x,y,z = [Integer(c) for c in P[1:-1].split(\":\")]\n return [x/z,y/z]\n\n\ndef matstr(m):\n return str(list(m)).replace('(','[').replace(')',']').replace(' ','')\n\n# Assuming that E is known to have rank 1, returns a point on E\n# computed by Magma's HeegnerPoint command\ndef magma_rank1_gen(E):\n mP = magma(E).HeegnerPoint(nvals=2)[1]\n P = E([mP[i].sage() for i in [1,2,3]])\n return P\n\n# Assuming that E is known to have rank 1, returns a point on E\n# computed by GP's ellheegner() command\ndef pari_rank1_gen_old(E, stacksize=1024000000):\n from os import system, getpid, unlink\n f = 'tempfile-'+str(getpid())\n comm = \"LD_LIBRARY_PATH=/usr/local/lib; echo `echo 'ellheegner(ellinit(\"+str(list(E.ainvs()))+\"))' | %s -q -f -s %s` > %s;\" % (GP,stacksize,f)\n system(comm)\n P = open(f).read()\n #print(P)\n P = open(f).read().partition(\"[\")[2].partition(\"]\")[0]\n P = P.replace(\"\\xb1\",\"\") # needed for 497805u1\n #print(P)\n unlink(f)\n P = E([QQ(c) for c in P.split(',')])\n #print(P)\n return P\n\ndef pari_rank1_gen(E):\n return E(pari(E).ellheegner().sage())\n\n# Given a matrix of isogenies and a list of points on the initial\n# curve returns a# list of their images on each other curve. The\n# complication is that the isogenies will only exist when they have\n# prime degree.\ndef map_points(maps, Plist):\n ncurves = len(maps)\n if len(Plist)==0:\n return [[] for _ in range(ncurves)]\n if ncurves==1:\n return [Plist]\n Qlists = [Plist] + [[]]*(ncurves-1)\n nfill = 1\n for i in range(ncurves):\n if nfill==ncurves:\n return Qlists\n for j in range(1,ncurves):\n if not (maps[i][j] == 0) and Qlists[j]==[]:\n Qlists[j] = [maps[i][j](P) for P in Qlists[i]]\n nfill += 1\n\n\n# Find integral points in a fail-safe way uing both Sage and Magma,\n# comparing, returning the union in all cases and outputting a warning\n# message if they disagree.\ndef get_integral_points_with_sage(E, gens):\n return [P[0] for P in E.integral_points(mw_base=gens)]\n\ndef get_integral_points_with_magma(E, gens):\n magma.eval('E:=EllipticCurve({});'.format(list(E.ainvs())))\n magma.eval('pts:=[];')\n for P in gens:\n magma.eval('Append(~pts,E!{});'.format(list(P)))\n res = magma.eval('IntegralPoints(E : FBasis:=pts);')\n return [p[0] for p in eval(res.split(\"\\n\")[0].replace(\":\",\",\"))]\n\ndef get_integral_points(E, gens, verbose=True):\n x_list_magma = get_integral_points_with_magma(E, gens)\n x_list_sage = get_integral_points_with_sage(E, gens)\n if x_list_magma != x_list_sage:\n if verbose:\n print(\"Curve {} = {}: \\n\".format(E.ainvs))\n print(\"Integral points via Magma: {}\".format(x_list_magma))\n print(\"Integral points via Sage: {}\".format(x_list_sage))\n x_list = list(Set(x_list_sage)+Set(x_list_magma))\n x_list.sort()\n return x_list\n\n# Sage's E.aplist(100) returns a list of the Fourier coefficients for\n# p<100. We want to replace the coefficient for p|N with the\n# W-eigenvalue (the root number) and append the W-eigenvalues for p|N,\n# p>100.\n\ndef wstr(n,w): # str(n) with enough spaces prepended to give width w\n a = str(n)\n if len(a)23:\n return ' +'\n return ' +'\n if p>23:\n return ' -'\n return ' -'\n if p>23: \n return wstr(E.ap(p),3)\n return wstr(E.ap(p),2)\n\ndef my_aplist(E):\n D = E.discriminant()\n ap = [my_ap_str(E,D,p) for p in prime_range(100)]\n qlist = D.support()\n for q in qlist:\n if q>100:\n if E.root_number(q)==1:\n ap.append('+('+str(q)+')')\n else:\n ap.append('-('+str(q)+')')\n return ' '.join(ap)\n\n# Given a filename like curves.000-999, read the data in the file,\n# compute the isogeny class for each curve, and output (1)\n# allcurves.000-999, (2) allisog.000-999 (with the same suffix).\n\ndef make_allcurves_and_allisog(infilename, mode='w'):\n infile = open(infilename)\n pre, suf = infilename.split(\".\")\n allcurvefile = open(\"tallcurves.\"+suf, mode=mode)\n allisogfile = open(\"tallisog.\"+suf, mode=mode)\n for L in infile.readlines():\n N, cl, num, ainvs, r, tor, d = L.split()\n E = EllipticCurve(eval(ainvs))\n Cl = E.isogeny_class()\n Elist = Cl.curves\n mat = Cl.matrix()\n torlist = [F.torsion_order() for F in Elist]\n for i in range(len(Elist)):\n line = ' '.join([N,cl,str(i+1),shortstr(Elist[i]),r,str(torlist[i])])\n allcurvefile.write(line+'\\n')\n print(\"allcurvefile: {}\".format(line))\n line = ' '.join([str(N),cl,str(1),ainvs,shortstrlist(Elist),matstr(mat)])\n allisogfile.write(line+'\\n')\n print(\"allisogfile: {}\".format(line))\n infile.close()\n allcurvefile.close()\n allisogfile.close()\n \n# Version using David Roe's new Isogeny Class class (trac #12768)\ndef make_allcurves_and_allisog_new(infilename, mode='w', verbose=False):\n infile = open(infilename)\n pre, suf = infilename.split(\".\")\n allcurvefile = open(\"tallcurves.\"+suf, mode=mode)\n allisogfile = open(\"tallisog.\"+suf, mode=mode)\n count=0\n for L in infile.readlines():\n count +=1\n if count%1000==0:\n print(L)\n N, cl, num, ainvs, r, tor, d = L.split()\n E = EllipticCurve(eval(ainvs))\n Cl = E.isogeny_class(order=\"database\")\n Elist = Cl.curves\n torlist = [F.torsion_order() for F in Elist]\n for i in range(len(Elist)):\n line = ' '.join([N,cl,str(i+1),shortstr(Elist[i]),r,str(torlist[i])])\n allcurvefile.write(line+'\\n')\n if verbose:\n print(\"allcurvefile: {}\".format(line))\n mat = Cl.matrix()\n line = ' '.join([str(N),cl,str(1),ainvs,shortstrlist(Elist),matstr(mat)])\n allisogfile.write(line+'\\n')\n if verbose:\n print(\"allisogfile: {}\".format(line))\n infile.close()\n allcurvefile.close()\n allisogfile.close()\n \n# Given a filename like curves.000-999, read the data in the file,\n# compute the isogeny class for each curve, and output (1)\n# allcurves.000-999, (2) allisog.000-999 (with the same suffix). Also\n# compute the bsd data for each curve and output (3) allbsd.000-999,\n# (4) allgens.000-999 (with the same suffix), (5) degphi.000-999, (6)\n# intpts.000-999, (7) alldegphi.000-999\n\n# Version to compute gens & torsion gens too\ndef make_datafiles(infilename, mode='w', verbose=False, prefix=\"t\"):\n infile = open(infilename)\n pre, suf = infilename.split(\".\")\n allcurvefile = open(prefix+\"allcurves.\"+suf, mode=mode)\n allisogfile = open(prefix+\"allisog.\"+suf, mode=mode)\n allbsdfile = open(prefix+\"allbsd.\"+suf, mode=mode)\n allgensfile = open(prefix+\"allgens.\"+suf, mode=mode)\n degphifile = open(prefix+\"degphi.\"+suf, mode=mode)\n alldegphifile = open(prefix+\"alldegphi.\"+suf, mode=mode)\n apfile = open(prefix+\"aplist.\"+suf, mode=mode)\n intptsfile = open(prefix+\"intpts.\"+suf, mode=mode)\n for L in infile.readlines():\n if verbose: print(\"=\"*72)\n N, cl, num, ainvs, r, tor, d = L.split()\n E = EllipticCurve(eval(ainvs))\n r=int(r)\n # Compute the isogeny class\n Cl = E.isogeny_class()\n Elist = Cl.curves\n mat = Cl.matrix()\n maps = Cl.isogenies()\n ncurves = len(Elist)\n print(\"class {} (rank {}) has {} curve(s)\".format(N+cl,r,ncurves))\n line = ' '.join([str(N),cl,str(1),ainvs,shortstrlist(Elist),matstr(mat)])\n allisogfile.write(line+'\\n')\n if verbose: print(\"allisogfile: {}\".format(line))\n # compute BSD data for each curve\n torgroups = [F.torsion_subgroup() for F in Elist]\n torlist = [G.order() for G in torgroups]\n torstruct = [list(G.invariants()) for G in torgroups]\n torgens = [[P.element() for P in G.gens()] for G in torgroups]\n cplist = [F.tamagawa_product() for F in Elist]\n omlist = [F.real_components()*F.period_lattice().real_period() for F in Elist]\n\n Lr1 = E.pari_curve().ellanalyticrank()[1].sage() / factorial(r)\n # LE = E.lseries()\n # LEdok = LE.dokchitser(100) # bits precision (default is 53)\n if r==0:\n genlist = [[] for F in Elist]\n reglist = [1 for F in Elist]\n # Lr1 = LEdok(1)\n else:\n # Lr1 = LEdok.derivative(1,r) / factorial(r)\n # #Lr1 = E.lseries().dokchitser().derivative(1,r)/factorial(r)\n if r==1:\n Plist = E.point_search(15)\n if len(Plist)==0:\n try:\n #Plist = [magma_rank1_gen(E)]\n print(\"using GP's ellheegner() to find generator\")\n Plist = [pari_rank1_gen(E)]\n print(\"P = {}\".format(Plist[0]))\n except: # Magma/pari bug or something\n Plist = E.gens()\n else:\n if torlist[0]%2==1:\n if N+cl==\"322074i\":\n P1 = E(QQ(95209997)/361, QQ(-796563345544)/6859)\n P2 = E(QQ(67511363092960062552491477869533612821)/167548532744324594465910917052304,\n QQ(-546962755962107290021339666753477014846325372323086316509)/2168757247628325524167944948382918905481652710592)\n Plist = [P1,P2]\n print(\"Special case gens for {}{}: {}\".format(N,cl,Plist))\n else:\n try:\n s = E.simon_two_descent(lim3=5000)\n Plist = E.gens()\n except:\n print(\"Simon failed, using mwrank: \")\n Plist = E.gens()\n else:\n Plist = E.gens()\n genlist = map_points(maps,Plist)\n prec0=mwrank_get_precision()\n mwrank_set_precision(mwrank_saturation_precision)\n# genlist = [Elist[i].saturation(genlist[i], max_prime=mwrank_saturation_maxprime)[0] for i in range(ncurves)]\n if verbose: print(\"genlist (before saturation) = {}\".format(genlist))\n genlist = [Elist[i].saturation(genlist[i])[0] for i in range(ncurves)]\n if verbose: print(\"genlist (before reduction) = {}\".format(genlist))\n genlist = [Elist[i].lll_reduce(genlist[i])[0] for i in range(ncurves)]\n mwrank_set_precision(prec0)\n if verbose: print(\"genlist (after reduction)= {}\".format(genlist))\n reglist = [Elist[i].regulator_of_points(genlist[i]) for i in range(ncurves)]\n shalist = [Lr1*torlist[i]**2/(cplist[i]*omlist[i]*reglist[i]) for i in range(ncurves)]\n squares = [n*n for n in srange(1,100)]\n for i,s in enumerate(shalist):\n if not round(s) in squares:\n print(\"bad sha value %s for %s\" % (s,str(N)+cl+str(i+1)))\n print(\"Lr1 = %s\" % Lr1)\n print(\"#t = %s\" % torlist[i])\n print(\"cp = %s\" % cplist[i])\n print(\"om = %s\" % omlist[i])\n print(\"reg = %s\" % reglist[i])\n return Elist[i]\n if verbose: print(\"shalist = {}\".format(shalist))\n\n # compute modular degrees\n # degphilist = [e.modular_degree(algorithm='magma') for e in Elist]\n # degphi = degphilist[0]\n # NB The correctness of the following relies on E being optimal!\n try:\n degphi = E.modular_degree(algorithm='magma')\n except RuntimeError:\n degphi = 0\n degphilist1 = [degphi*mat[0,j] for j in range(ncurves)]\n degphilist = degphilist1\n if verbose: print(\"degphilist = {}\".format(degphilist))\n\n # compute aplist for optimal curve only\n aplist = my_aplist(E)\n if verbose: print(\"aplist = {}\".format(aplist))\n\n # Compute integral points (x-coordinates)\n intpts = [get_integral_points(Elist[i],genlist[i]) for i in range(ncurves)]\n #if verbose: print(\"intpts = {}\".format(intpts))\n for i, Ei, xs in zip(range(ncurves),Elist,intpts):\n print(\"{}{}{} = {}: intpts = {}\".format(N,cl,(i+1),Ei.ainvs(),xs))\n\n # Output data for optimal curves\n\n # aplist\n line = ' '.join([N,cl,aplist])\n if verbose: print(\"aplist: {}\".format(line))\n apfile.write(line+'\\n')\n\n # degphi\n line = ' '.join([N,cl,'1',str(degphi),str(Set(degphi.prime_factors())).replace(' ',''),shortstr(E)])\n if verbose: print(\"degphifile: {}\".format(line))\n degphifile.write(line+'\\n')\n\n # Output data for each curve\n for i in range(ncurves):\n # allcurves\n line = ' '.join([N,cl,str(i+1),shortstr(Elist[i]),str(r),str(torlist[i])])\n allcurvefile.write(line+'\\n')\n if verbose: print(\"allcurvefile: {}\".format(line))\n\n # allbsd\n line = ' '.join([N,cl,str(i+1),shortstr(Elist[i]),str(r),str(torlist[i]),str(cplist[i]),str(omlist[i]),str(Lr1),str(reglist[i]),str(shalist[i])])\n allbsdfile.write(line+'\\n')\n if verbose: print(\"allbsdfile: {}\".format(line))\n\n # allgens (including torsion gens, listed last)\n line = ' '.join([str(N),cl,str(i+1),shortstr(Elist[i]),str(r)]\n + [liststr(torstruct[i])]\n + [pointstr(P) for P in genlist[i]]\n + [pointstr(P) for P in torgens[i]]\n )\n allgensfile.write(line+'\\n')\n if verbose:\n print(\"allgensfile: {}\".format(line))\n # intpts\n line = ''.join([str(N),cl,str(i+1)]) + ' ' + shortstr(Elist[i]) + ' ' + liststr(intpts[i])\n intptsfile.write(line+'\\n')\n if verbose: print(\"intptsfile: {}\".format(line))\n\n # alldegphi\n line = ' '.join([str(N),cl,str(i+1),shortstr(Elist[i]),liststr(degphilist[i])])\n alldegphifile.write(line+'\\n')\n if verbose: print(\"alldegphifile: {}\".format(line))\n\n infile.close()\n allbsdfile.close()\n allgensfile.close()\n allcurvefile.close()\n allisogfile.close()\n degphifile.close()\n intptsfile.close()\n apfile.close()\n\n#\n# Compute torsion gens only from allcurves file\n#\ndef make_rank0_torsion(infilename, mode='w', verbose=False, prefix=\"t\"):\n infile = open(infilename)\n pre, suf = infilename.split(\".\")\n allgensfile = open(prefix+\"allgens0.\"+suf, mode=mode)\n for L in infile.readlines():\n N, cl, num, ainvs, r, tor = L.split()\n if int(r)==0:\n E = EllipticCurve(eval(ainvs))\n\n # compute torsion data\n T = E.torsion_subgroup()\n torstruct = list(T.invariants())\n torgens = [P.element() for P in T.gens()]\n gens = []\n\n # Output data\n line = ' '.join([str(N),cl,num,ainvs,r]\n + [liststr(torstruct)]\n + [pointstr(P) for P in gens]\n + [pointstr(P) for P in torgens]\n )\n allgensfile.write(line+'\\n')\n if verbose: \n print(\"allgensfile: {}\".format(line))\n\n infile.close()\n allgensfile.close()\n\n# Read allgens file without torsion and output allgens file with torsion\n#\n\ndef add_torsion(infilename, mode='w', verbose=False, prefix=\"t\"):\n infile = open(infilename)\n pre, suf = infilename.split(\".\")\n allgensfile = open(prefix+\"allgens.\"+suf, mode=mode)\n for L in infile.readlines():\n N, cl, num, ainvs, r, gens = L.split(' ',5)\n gens = gens.split()\n E = EllipticCurve(eval(ainvs))\n T = E.torsion_subgroup()\n torstruct = list(T.invariants())\n torgens = [P.element() for P in T.smith_gens()]\n \n # allgens (including torsion gens, listed last)\n line = ' '.join([N,cl,num,ainvs,r]\n + [liststr(torstruct)]\n + gens #[pointstr(P) for P in gens]\n + [pointstr(P) for P in torgens]\n )\n if verbose: print(line)\n allgensfile.write(line+'\\n')\n\n infile.close()\n allgensfile.close()\n\n# Read allgens file and for curves with non-cyclic torsion, make sure\n# that the gens are in the same order as the group structure\n# invariants:\n\ndef fix_torsion(infilename, mode='w', verbose=False, prefix=\"t\"):\n infile = open(infilename)\n pre, suf = infilename.split(\".\")\n allgensfile = open(prefix+\"allgens.\"+suf, mode=mode)\n for L in infile.readlines():\n if verbose: \n print(\"old line\")\n print(L)\n N, cl, num, ainvs, r, gens = L.split(' ',5)\n gens = gens.split()\n tor_invs = gens[0]\n inf_gens = gens[1:int(r)+1]\n tor_gens = gens[int(r)+1:]\n if verbose: \n print(\"old line rank = %s, gens=%s\"%(r,gens))\n print(tor_invs, inf_gens, tor_gens)\n if len(tor_gens)<2:\n allgensfile.write(L)\n else:\n if verbose: \n print(\"old line\")\n print(L)\n E = EllipticCurve(eval(ainvs))\n T = E.torsion_subgroup()\n tor_struct = list(T.invariants())\n tor_gens = [P.element() for P in T.smith_form_gens()]\n assert all([P.order()==n for P,n in zip(tor_gens,tor_struct)])\n\n # allgens (including torsion gens, listed last)\n line = ' '.join([N,cl,num,ainvs,r]\n + [liststr(tor_struct)]\n + inf_gens #[pointstr(P) for P in gens]\n + [pointstr(P) for P in tor_gens]\n )\n if verbose: \n print(\"new line\")\n print(line)\n allgensfile.write(line+'\\n')\n\n infile.close()\n allgensfile.close()\n\ndef fix_all_torsion():\n for n in range(23):\n ns=str(n)\n filename = \"allgens.\"+ns+\"0000-\"+ns+\"9999\"\n print(filename)\n fix_torsion(filename)\n\n\n# Read allgens file (with torsion) and output paricurves file\n#\ndef make_paricurves(infilename, mode='w', verbose=False, prefix=\"t\"):\n infile = open(infilename)\n pre, suf = infilename.split(\".\")\n paricurvesfile = open(prefix+\"paricurves.\"+suf, mode=mode)\n for L in infile.readlines():\n N, cl, num, ainvs, r, gens = L.split(' ',5)\n if int(r)==0:\n gens = []\n else:\n gens = gens.split()[1:1+int(r)] # ignore torsion struct and gens\n gens = [pointPtoA(P) for P in gens]\n\n line = '[' + ', '.join(['\"'+N+cl+num+'\"',ainvs,str(gens).replace(' ','')]) + ']'\n paricurvesfile.write(line+'\\n')\n infile.close()\n paricurvesfile.close()\n\ndef compare(Ncc1,Ncc2):\n d = Integer(Ncc1[0])-Integer(Ncc2[0])\n if d!=0:\n return d\n code1 = Ncc1[1]+Ncc1[2]\n code2 = Ncc2[1]+Ncc2[2]\n d = cmp_code(code1,code2)\n return d\n\ndef merge_gens(infile1, infile2):\n pre, suf = infile1.split(\".\")\n infile1 = open(infile1)\n infile2 = open(infile2)\n allgensfile = open(\"mallgens.\"+suf, mode='w')\n L1 = infile1.readline()\n L2 = infile2.readline()\n while len(L1)>0 and len(L2)>0:\n N1,cl1,cu1,rest = L1.split(' ',3)\n N2,cl2,cu2,rest = L2.split(' ',3)\n if compare([N1,cl1,cu1],[N2,cl2,cu2])<0:\n allgensfile.write(L1)\n L1 = infile1.readline()\n else:\n allgensfile.write(L2)\n L2 = infile2.readline()\n while len(L1)>0:\n allgensfile.write(L1)\n L1 = infile1.readline()\n while len(L2)>0:\n allgensfile.write(L2)\n L2 = infile2.readline()\n\n infile1.close()\n infile2.close()\n allgensfile.close()\n\n# Create alldegphi files from allcurves files:\n\ndef make_alldegphi(infilename, mode='w', verbose=False, prefix=\"t\"):\n infile = open(infilename)\n pre, suf = infilename.split(\".\")\n alldegphifile = open(prefix+\"alldegphi.\"+suf, mode=mode)\n for L in infile.readlines():\n if verbose: print(L)\n N, cl, num, ainvs, rest = L.split(' ',4)\n if verbose: print(ainvs)\n E = EllipticCurve(eval(ainvs))\n try:\n degphi = E.modular_degree()\n except RuntimeError:\n degphi = 0\n\n # alldegphi\n line = ' '.join([str(N),cl,str(num),shortstr(E),liststr(degphi)])\n alldegphifile.write(line+'\\n')\n if verbose: print(\"alldegphifile: {}\".format(line))\n infile.close()\n alldegphifile.close()\n\ndef check_degphi(infilename):\n infile = open(infilename)\n for L in infile.readlines():\n N, cl, num, ainvs, d = L.split()\n if int(N)==990 and cl=='h':\n continue\n d=int(d)\n if int(num)==1:\n d1=d\n else:\n if d1 which includes what can be deduced about optimality\n# (without a full check) and also outputs Manin constants conditional\n# on the optimal curve being #1.\n\n# The infilename should be an allcurves file, e.g. run in an ecdata\n# directory and use infilename=allcurves/allcurves.250000-259999. The\n# part after the \".\" (here 250000-259999) will be used as suffix to\n# the output file.\n\n# Some classes may be output as \"special\": two curves in the class\n# linked by a 2-isogeny with the first lattice having positive\n# discriminant and the second Manin constant=2. In several cases this\n# has been an indication that the wrong curve has been tagged as\n# optimal.\n\ndef make_manin(infilename, mode='w', verbose=False, prefix=\"\"):\n infile = open(infilename)\n pre, suf = infilename.split(\".\")\n allmaninfile = open(prefix+\"opt_man.\"+suf, mode=mode)\n allisogfile = open(\"allisog/allisog.\"+suf)\n last_class = \"\"\n manins = []\n area0 = 0 # else pyflakes objects\n degrees = [] # else pyflakes objects\n for L in infile.readlines():\n N, cl, num, ainvs, rest = L.split(' ',4)\n this_class = N+cl\n num = int(num)\n E = EllipticCurve(eval(ainvs))\n lattice1 = None\n if this_class == last_class:\n deg = degrees[int(num)-1]\n #assert ideg==deg\n area = E.period_lattice().complex_area()\n mc = round((deg*area/area0).sqrt())\n # print(\"{}{}{}: \".format(N,cl,num))\n # print(\"degree = {}\".format(deg))\n # print(\"area = {}\".format(area))\n # print(\"area ratio = {}\".format(area/area0))\n # print(\"c^2 = {}\".format(deg*area/area0))\n manins.append(mc)\n if num==3:\n lattice1 = None\n elif not (num==2 and deg==2 and mc==2):\n lattice1 = None\n if lattice1:\n print(\"Class {} is special\".format(lattice1))\n else: # start a new class\n if manins and verbose: # else we're at the start\n print(\"class {} has Manin constants {}\".format(last_class,manins))\n isogmat = allisogfile.readline().split()[-1]\n isogmat = eval(isogmat)\n degrees = isogmat[0]\n if verbose:\n print(\"class {}\".format(this_class))\n print(\"isogmat: {}\".format(isogmat))\n print(\"degrees: {}\".format(isogmat))\n area0 = E.period_lattice().complex_area()\n manins = [1]\n if num==1 and len(isogmat)==2 and isogmat[0][1]==2 and E.discriminant()>0:\n lattice1 = this_class\n last_class = this_class\n\n # construct output line for this curve\n #\n # SPECIAL CASE 990h\n #\n if N==90 and cl=='h':\n opt = str(int(num==3))\n manins = [1,1,1,1]\n else:\n opt = str(int(num==1))\n mc = str(manins[-1])\n line = ' '.join([str(N),cl,str(num),shortstr(E),opt,mc])\n\n allmaninfile.write(line+'\\n')\n if verbose: print(\"allmaninfile: {}\".format(line))\n # if int(N)>100:\n # break\n if manins and verbose: # else we're at the start\n # This output line is the only reason we keep the list of all m.c.s\n print(\"class {} has Manin constants {}\".format(last_class,manins))\n infile.close()\n allmaninfile.close()\n\ndef make_opt_input(N):\n \"\"\"Parse a file in optimality/ and produce an input file for\n runh1firstx1 which runs h1first1.\n\n Find lines containing \"possible optimal curves\", extract the\n isogeny class label, convert iso class code to a number, and\n output. One line is output for each level N, of the form\n\n N i_1 i_2 ... i_k 0\n\n where N is the level and i_1,...,i_k are the numbers (from 1) of\n the newforms / isogeny classes where we do not know which curve is\n optimal.\n\n For example the input lines starting with 250010 are\n\n 250010b: c=1; optimal curve is E1\n 250010d: c=1; 3 possible optimal curves: E1 E2 E3\n\n and produce the output line\n\n 250010 2 4 0\n\n while the lines starting with 250020 are\n\n 250020b: c=1; optimal curve is E1\n 250020d: c=1; optimal curve is E1\n\n and produce no output\n \"\"\"\n outfile = \"optx.{0:02d}\".format(N)\n o = open(outfile, 'w')\n n = 0\n lastN = 0\n for L in open(\"optimality/optimality.{0:02d}\".format(N)):\n if \"possible\" in L:\n N, c, i = parse_cremona_label(L.split()[0][:-1])\n if N==lastN:\n o.write(\" {}\".format(1+class_to_int(c)))\n else:\n if lastN!=0:\n o.write(\" 0\\n\")\n o.write(\"{} {}\".format(N, 1+class_to_int(c)))\n lastN = N\n n += 1\n o.write(\" 0\\n\")\n n += 1\n o.close()\n print(\"wrote {} lines to {}\".format(n,outfile))\n\ndef check_sagedb(N1, N2, a4a6bound=100):\n \"\"\"Sanity check that Sage's elliptic curve database contains all\n curves [a1,a2,a3,a4,a6] with a1,a3 in [0,1], a2 in [-1,0,1], a4,a6\n in [-100..100] and conductor in the given range.\n\n Borrowed from Bill Allombert (who found a missing curve of\n conductor 406598 this way).\n \"\"\"\n CDB = CremonaDatabase()\n def CDB_curves(N):\n return [c[0] for c in CDB.allcurves(N).values()]\n Nrange = srange(N1,N2+1)\n ncurves = 12*(2*a4a6bound+1)**2\n print(\"Testing {} curves\".format(ncurves))\n n=0\n for a1 in xrange(2):\n for a2 in xrange(-1,2):\n for a3 in xrange(2):\n for a4 in xrange(-a4a6bound,a4a6bound+1):\n for a6 in xrange(-a4a6bound,a4a6bound+1):\n ai = [a1,a2,a3,a4,a6]\n n += 1\n if n%1000==0:\n print(\"test #{}/{}\".format(n,ncurves))\n try:\n E = EllipticCurve(ai).minimal_model()\n except ArithmeticError: #singular curve\n continue\n N = E.conductor()\n if not N in Nrange:\n continue\n if not list(E.ainvs()) in CDB_curves(N):\n print(\"Missing N={}, ai={}\".format(N,ai))\n","sub_path":"scripts/ecdb.py","file_name":"ecdb.py","file_ext":"py","file_size_in_byte":29746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"398908943","text":"import json\nfrom os import utime\nimport socket\nfrom threading import Thread\nimport time\n\n#create a class that extends/inherits from Thread class\nclass MyThread(Thread):\n #create a constructor for our class,\n # aurguments for our thread\n utf8 = \"utf-8\"\n Authurized_users = []\n def __init__(self, client):\n #class the parent constructor that will make sure\n # a separate thread is created, when called\n Thread.__init__(self)\n #save the counter parameter, so that we can use\n #it later\n self.client=client\n #override the run function of the Thread class\n\n \n def run(self):\n #Receiving data from client what client wants \n data = self.client.recv(1024)\n data = data.decode(self.utf8)\n #function will call server 4 for authentication of user\n def request_for_authentications(client):\n data = client.recv(1024)\n address = \"localhost\"\n port = 5054\n\n c = socket.socket()\n\n c.connect((address,port))\n print(\"Connected with server4 for authentication service\")\n c.send(data)\n data = c.recv(1024)\n data = data.decode(self.utf8)\n if data == \"0\":\n client.send(\"0\".encode(self.utf8))\n else:\n self.Authurized_users.append(data)\n client.send(data.encode(self.utf8)) \n #fucntion will verify token and will send service1 info to client\n def request_for_echo_service(client):\n data = client.recv(1024)\n data = data.decode(self.utf8)\n print(data)\n count = self.Authurized_users.count(data)\n if count > 0:\n service1_details = []\n address = \"localhost\"\n port = 5051\n service1_details.append(address)\n service1_details.append(port)\n service1_details = json.dumps(service1_details)\n client.send(service1_details.encode(self.utf8))\n else:\n client.send(\"0\".encode(self.utf8))\n\n #fucntion will call service2 from server2\n def request_for_palindrome_service(client):\n data = client.recv(1024)\n data = data.decode(self.utf8)\n print(data)\n count = self.Authurized_users.count(data)\n if count > 0:\n service2_details = []\n address = \"localhost\"\n port = 5052\n service2_details.append(address)\n service2_details.append(port)\n service2_details = json.dumps(service2_details)\n client.send(service2_details.encode(self.utf8))\n else:\n client.send(\"0\".encode(self.utf8))\n \n \n\n #fucntion will call service3 from server3\n def request_for_checking_length_service(client):\n data = client.recv(1024)\n data = data.decode(self.utf8)\n print(data)\n count = self.Authurized_users.count(data)\n if count > 0:\n service1_details = []\n address = \"localhost\"\n port = 5053\n service1_details.append(address)\n service1_details.append(port)\n service1_details = json.dumps(service1_details)\n client.send(service1_details.encode(self.utf8))\n else:\n client.send(\"0\".encode(self.utf8)) \n #function will logout the user\n def Logout_user(client):\n data = client.recv(1024)\n data = data.decode(self.utf8)\n count = self.Authurized_users.count(data)\n if count > 0:\n self.Authurized_users.remove(data)\n client.send(\"1\".encode(self.utf8))\n else:\n client.send(\"0\".encode(self.utf8)) \n #If data == 1 tha call server 4 for authentications\n if data == \"1\":\n request_for_authentications(self.client)\n #if data == 2 than call server 1 for services\n elif data == \"2\":\n request_for_echo_service(self.client)\n \n #if data == 3 than call server 2 for services\n elif data == \"3\":\n request_for_palindrome_service(self.client)\n \n #if data == 4 than call server 3 for services\n elif data == \"4\":\n request_for_checking_length_service(self.client)\n #if data == 5 than logout \n elif data == \"5\":\n Logout_user(self.client)\n\n\ndef main():\n Address = \"localhost\"\n\n port = 5050\n\n s = socket.socket()\n\n s.bind((Address,port))\n\n s.listen(5)\n print(\"Main server listening for client\")\n while True:\n c,addr = s.accept()\n #Create object for our thread class\n thread=MyThread(c)\n #thread.run()\n #if you start the thread using run() function, it\n #will be executed on the main thread as normal\n #function. Never use the run() function your self\n #rather call the start(), it will create a separate\n # thread, and there it will call the run function\n thread.start()\nif __name__=='__main__':\n main()","sub_path":"main_server.py","file_name":"main_server.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"439044585","text":"\"\"\"\nSome of the functions have a bit cumbersome behavior when we deal with\npositional and keyword arguments.\nWrite a function that accept any iterable of unique values and then\nit behaves as range function:\nimport string\nassert = custom_range(string.ascii_lowercase, 'g') == ['a', 'b', 'c', 'd', 'e', 'f']\nassert = custom_range(string.ascii_lowercase, 'g', 'p') == ['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']\nassert = custom_range(string.ascii_lowercase, 'p', 'g', -2) == ['p', 'n', 'l', 'j', 'h']\n\"\"\"\nfrom typing import List\n\n\ndef custom_range(collection, *args) -> List:\n defaults = [collection[0], collection[-1], 1]\n if len(args) == 3:\n defaults = list(args)\n elif len(args) == 2:\n defaults[0], defaults[1] = args[0], args[1]\n else:\n defaults[1] = args[0]\n start, stop, step = defaults\n answer = []\n if step < 1:\n collection = collection[::-1]\n step_start = collection.find(start)\n for i, elem in enumerate(collection):\n if i >= step_start:\n if elem != stop:\n if (i - step_start) % step == 0:\n answer.append(elem)\n else:\n break\n return answer\n","sub_path":"homework2/task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"586149940","text":"import os\nfrom decouple import config\nfrom django import forms\nfrom django.core.mail import EmailMultiAlternatives\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import From, To, Personalization, Mail\n\n\ntry:\n # Python 3\n import urllib.request as urllib\nexcept ImportError:\n # Python 2\n import urllib2 as urllib\n\n\nclass ContactForm(forms.Form):\n\n fname = forms.CharField(\n widget=forms.TextInput(\n attrs={\n 'id': False,\n }\n ),\n max_length=80,\n required=True,\n error_messages={'required': 'Please enter your first name'},\n )\n\n lname = forms.CharField(\n widget=forms.TextInput(\n attrs={\n 'id': False,\n }\n ),\n max_length=80,\n required=True,\n error_messages={'required': 'Please enter your last name'},\n )\n\n email = forms.EmailField(\n widget=forms.TextInput(\n attrs={\n 'id': False,\n }\n ),\n label='',\n max_length=80,\n required=True,\n error_messages={\n 'required': 'Please enter your email address',\n 'invalid': 'Please enter a valid email address'\n },\n )\n\n phone = forms.CharField(\n widget=forms.TextInput(\n attrs={\n 'id': False,\n }\n ),\n label='',\n max_length=80,\n required=True,\n error_messages={'required': 'Please enter your contact number'},\n )\n\n message = forms.CharField(\n widget=forms.Textarea(\n attrs={\n 'rows': '3',\n 'cols': '40',\n 'id': False,\n 'autofocus': True\n }\n ),\n label='',\n required=False,\n )\n\n def send_email(self):\n\n # send email using the self.cleaned_data dictionary\n first_name = self.cleaned_data.get(\"fname\")\n last_name = self.cleaned_data.get(\"lname\")\n email = self.cleaned_data.get(\"email\")\n phone = self.cleaned_data.get(\"phone\")\n message = self.cleaned_data.get(\"message\")\n\n # Issue response to client via sendgrid API\n sendgrid_client = SendGridAPIClient(config('SENDGRID_API_KEY'))\n mail = Mail()\n mail.from_email = From(config('EMAIL_FROM'))\n mail.to_email = To(email)\n mail.subject = \"Your Enquiry with Mayan Web Studio\"\n mail.template_id = config('SENDGRID_TEMPLATE_ID')\n p = Personalization()\n p.add_to(To(email))\n p.dynamic_template_data = {\n \"firstName\": first_name,\n \"lastName\": last_name,\n \"phone\": phone\n }\n mail.add_personalization(p)\n\n response = sendgrid_client.client.mail.send.post(\n request_body=mail.get())\n print(response.status_code)\n print(response.body)\n print(response.headers)\n\n # Send notification email to Mayan\n subject, from_email, to = 'New Enquiry for Mayan Web Studio', config(\n 'EMAIL_FROM'), 'mike@mayanwebstudio.co.uk'\n text_content = 'This is an important message.'\n html_content = '''\n

New Enquiry from

\n
    \n
  • First Name: $(first_name)
  • \n
  • Last Name: $(last_name)
  • \n
  • Email: $(email)
  • \n
  • Phone: $(phone)
  • \n
  • Message: $(message)
  • \n
\n '''\n\n html_content = html_content.replace(\"$(first_name)\", first_name)\n html_content = html_content.replace(\"$(last_name)\", last_name)\n html_content = html_content.replace(\"$(email)\", email)\n html_content = html_content.replace(\"$(phone)\", phone)\n html_content = html_content.replace(\"$(message)\", message)\n\n msg = EmailMultiAlternatives(subject, text_content, from_email, [to])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n\n # from_email = Email(config('EMAIL_FROM'), 'Mayan Web Studio')\n # to_email = email\n\n # mail = Mail(from_email, to_email)\n # mail.personalizations[0].add_substitution(\n # Substitution(\"-firstName-\", first_name))\n # mail.personalizations[0].add_substitution(\n # Substitution(\"-lastName-\", last_name))\n # mail.personalizations[0].add_substitution(\n # Substitution(\"-phone-\", phone))\n # mail.template_id = config('SENDGRID_TEMPLATE_ID')\n\n # data = {\n # \"asm\": {\n # \"group_id\": 13815,\n # },\n # \"content\": [\n # {\n # \"type\": \"text/html\",\n # \"value\": \"

Hello from Mayan

\"\n # }\n # ],\n # \"from\": {\n # \"email\": config('EMAIL_FROM'),\n # \"name\": \"Mayan Web Studio\"\n # },\n # \"personalizations\": [\n # {\n # \"headers\": {\n # \"X-Accept-Language\": \"en\",\n # \"X-Mailer\": \"MyApp\"\n # },\n # \"subject\": \"Your Enquiry with Mayan Web Studio\",\n # \"substitutions\": {\n # \"firstName\": first_name,\n # \"lastName\": last_name,\n # \"phone\": phone\n # },\n # \"to\": [\n # {\n # \"email\": email,\n # \"name\": \"Mayan Web Studio\"\n # }\n # ]\n # }\n # ],\n # \"reply_to\": {\n # \"email\": \"hello@mayanwebstudio.co.uk\",\n # \"name\": \"Mayan Web Studio\"\n # },\n # \"template_id\": config('SENDGRID_TEMPLATE_ID')\n # }\n\n # message = Mail(\n # from_email=config('EMAIL_FROM'),\n # to_emails=config('EMAIL_TO'),\n # html_content=)\n\n # try:\n # sendgrid_client = SendGridAPIClient(config('SENDGRID_API_KEY'))\n # response = sendgrid_client.send(message)\n # print(response.status_code)\n # print(response.body)\n # print(response.headers)\n # except Exception as e:\n # print(e)\n","sub_path":"mayan/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"242744289","text":"from django.shortcuts import render\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom views_db import db_open, db_set\nfrom views_routes import direction\nfrom views_mod1 import kiosk_lastpart_find, kiosk_email_initial, find_current_date\nfrom trakberry.forms import kiosk_dispForm1,kiosk_dispForm2,kiosk_dispForm3,kiosk_dispForm4, sup_downForm,login_Form\nimport MySQLdb\nimport time\nfrom django.core.context_processors import csrf\nimport datetime as dt \nfrom views_vacation import vacation_temp, vacation_set_current7, vacation_set_current6, vacation_set_current5\nimport smtplib\nfrom smtplib import SMTP\n\ndef hrly_display(request): # This will return a tuple with hourly prod summary on last hour for each p_cell\n \n hourly = ['' for x in range(0)]\n hourly_var = ['' for x in range(0)]\n ert = ['' for x in range(0)]\n xx = ['' for x in range(0)]\n hourly_all = ['' for x in range(0)]\n\n red_block = '#ff0000'\n green_block = '#62c12e'\n yellow_block = '#faff2b'\n grey_block = '#a5a4a4'\n hhh = 3\n \n\n email_hour_check2(request)\n\n\n\n current_first, shift1, shift2, shift3, hour_curr = vacation_set_current7()\n db, cur = db_set(request) \n s1 = \"SELECT p_cell FROM sc_prod_hr_target\" # Set the p_cell value we'll use to iterate through for each cell\n cur.execute(s1)\n tmp = cur.fetchall()\n p_cell = tmp[0]\n row_ctr = 1\n for i in tmp:\n c1 = 0\n c2 = 0\n pc = i[0]\n try:\n aql = \"SELECT MAX(id) FROM sc_prod_hour where p_cell = '%s'\" %(pc) # Set the max_id to get p_cell latest entry\n cur.execute(aql)\n tmp3 = cur.fetchall()\n tmp4 = tmp3[0]\n max_id = tmp4[0]\n \n except:\n route = 'Filed'\n try:\n bql = \"Select * From sc_prod_hour where id = '%s'\" %(max_id) # Get latest entry for p_cell\n cur.execute(bql)\n tmp3 = cur.fetchall()\n tmp4 = tmp3[0]\n ert.append(tmp4)\n c1 = int((float(tmp4[8])/float(tmp4[7]))*100) # Calculate the % for Hourly\n c2 = int((float(tmp4[10])/float(tmp4[9]))*100) # Calculate the % for Shift Total\n if c1 > 84: # Below determins d1 and d2 to signify colour red, yellow, green\n d1 = green_block\n elif c1 > 69:\n d1 = yellow_block\n else:\n d1 = red_block\n if c2 > 84:\n d2 = green_block\n elif c2 > 69:\n d2 = yellow_block\n else:\n d2 = red_block\n ctr = 0\n s1 = 1\n s2 = 2\n s3 = 0\n s4 = 4\n d11 = 99\n hourly_var.append(str(tmp4[4]))\n if int(tmp4[6]) != (hour_curr-1):\n d1 = grey_block \n c1 = '---'\n if (str(tmp4[4])) != str(current_first):\n d2 = grey_block\n d1 = grey_block\n c1 = '---'\n c2 = '---'\n elif (tmp4[5]) != shift1:\n if (tmp4[5]) != shift2:\n if (tmp4[5]) != shift3:\n d2 = grey_block\n d1 = grey_block\n c1 = '---'\n c2 = '---'\n\n new_line = row_ctr % hhh # uses Mod of hhh to determine how many on a line. hhh is the number on a line\n\n #yyt = vacation_set_current6(tmp[4])\n\n # new code\n lst = list(tmp4)\n d3 = d2 + ' 60%,' + d1 + ' 40%' # combines the two colors together to d3 format \n lst.extend((c2,d2,c1,d1,d3,new_line,tmp[4]))\n mst=tuple(lst)\n xx.append(mst)\n row_ctr = row_ctr + 1\n\n except:\n dummy = 1\n\n db.close()\n\n current_first, shift1, shift2, shift3, hour_curr = vacation_set_current7()\n request.session[\"variableA\"] = current_first\n request.session[\"variableB\"] = shift1\n request.session[\"variableC\"] = shift2\n request.session[\"variableD\"] = hourly_var\n request.session[\"variableE\"] = hour_curr\n\n # This is where you return the value 'hourly' which has all the data needed in tuple form\n return render(request,'production/hrly_display.html', {'tmpp':xx})\t\n\n\ndef butter(request):\n email_hour_check2(request)\n return render(request,'done_test.html')\n\ndef email_hour_check2(request):\n\n h1 = 7\n h2 = 15\n h3 = 23\n h4 = 17\n m1 = 15\n m2 = 30\n m3 = 45\n ch = 0\n t=int(time.time())\n tm = time.localtime(t)\n mn = tm[4]\n hour = tm[3]\n if hour == h1:\n if mn > m1 and mn < m2:\n ch = 1\n if hour == h2:\n if mn > m1 and mn < m2:\n ch = 1\n if hour == h3:\n if mn > m1 and mn < m2:\n ch = 1\n if hour == h4:\n if mn > m2 and mn < m3:\n ch = 1\n \n if ch != 1:\n return\n\n # Define Variables\n production_check = 2\n manual_check = 0\n manual_set = 1\n production_set = 1\n reason1 = \"Missed Kiosk Entries\"\n reason2 = \"Low Production\"\n db, cursor = db_set(request)\n # db, cursor = kiosk_email_initial(request) # This Check will ensure the new columns are in and if not will add them\n # sql = \"SELECT * FROM sc_production1 where low_production = '%d'\" %(production_check)\n # cursor.execute(sql)\n # tmp = cursor.fetchall()\n # tmp2 = tmp[0]\n # email_manual1(tmp,reason1)\n try:\n zql = \"SELECT * FROM sc_production1 where low_production = '%d'\" %(production_check)\n cursor.execute(zql)\n zmp = cursor.fetchall()\n tmp2 = zmp[0]\n email_manual1(zmp,reason2)\n zql = ('update sc_production1 SET low_production = \"%d\" WHERE low_production = \"%d\"' % (production_set, production_check))\n cursor.execute(zql)\n db.commit()\n except:\n dummy = 0\n try:\n sql = \"SELECT * FROM sc_production1 where manual_sent = '%d'\" %(manual_check)\n cursor.execute(sql)\n tmp = cursor.fetchall()\n tmp2 = tmp[0]\n email_manual1(tmp,reason1)\n sql = ('update sc_production1 SET manual_sent = \"%d\" WHERE manual_sent = \"%d\"' % (manual_set, manual_check))\n cursor.execute(sql)\n db.commit()\n except:\n dummy = 0\n\n db.close()\n return \n\ndef email_manual1(tmp,reason):\n db, cursor = db_open()\n b = \"\\r\\n\"\n ctr = 0\n message_subject = reason\n message = \"\"\n #toaddrs = [\"sbrownlee@stackpole.com,jmcmaster@stackpole.com\",\"dmiller@stackpole.com\",\"dclark@stackpole.com\",\"sherman@stackpole.com\",\"pmurphy@stackpole.com\",\"ghundt@stackpole.com\",\"kfrey@stackpole.com\",\"asmith@stackpole.com\",\"smcmahon@stackpole.com\",\"mclarke@stackpole.com\",\"gharvey@stackpole.com\",\"rstanley@stackpole.com\",\"nkleingeltink@stackpole.com\"]\n toaddrs = [\"dclark@stackpole.com\"]\n \n fromaddr = 'stackpole@stackpole.com'\n frname = 'Dave'\n server = SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n server.login('StackpolePMDS@gmail.com', 'stacktest6161')\n message = \"From: %s\\r\\n\" % frname + \"To: %s\\r\\n\" % ', '.join(toaddrs) + \"Subject: %s\\r\\n\" % message_subject + \"\\r\\n\" \n message = message + message_subject + \"\\r\\n\\r\\n\" + \"\\r\\n\\r\\n\"\n # message = message + \"Name\" + \" || \" + \"Job\" + \" || \" + \"Count\" + \" || \" + \"Target\" + \" || \" + \"Date \" + \" || \" + \"Shift\" + b + b\n # message = message + \" --------------------------------------------------------------------------------\" + b\n # message = message + str(tmp)\n # h = 6 / 0\n for x in tmp:\n nm = (str(x[9]))\n # nm = int(nm)\n try:\n zql = \"SELECT * FROM tkb_users where Clock = '%s'\" %(nm)\n cursor.execute(zql)\n zmp = cursor.fetchall()\n zzmp = zmp[0]\n nm = zzmp[2]\n except:\n nm = \"Clock \" + str(x[9])\n\n\n a1 = \"Name:\"+nm\n a2 = \"Job:\"+str(x[1])\n a3 = \"Count:\"+str(x[4])\n a4 = \"Target:\"+str(x[13])\n a5 = \"Date:\"+str(x[10])\n a6 = \"Shift:\"+str(x[11])\n\n # a1 = string_make(str(x[9]),7)\n # a2 = str(x[1])\n # a3 = string_make(str(x[4]),7)\n # a4 = string_make(str(x[13]),8)\n # a5 = str(x[10])\n # a6 = str(x[11])\n # a7 = str(ctr)\n ctr = ctr + 1\n b = \"\\r\\n\"\n message = message + a1 + \" \" + a2 + \" \" + a3 + \" \" + a4 + \" \" + a5 + \" \" + a6 + b + b\n # message = message + x[8] + \" \" + x[1] + \" \" + x[4] + \":\" + x[3] + \" \" + \"\\r\\n\\r\\n\"\n m_ctr = 4\n\n server.sendmail(fromaddr, toaddrs, message)\n server.quit()\n db.close()\n return\n\ndef string_make(x,n):\n while True:\n if len(x) >= n:\n break\n x = x + \" \"\n return x\n\n \n\n","sub_path":"trakberry/views_mod2.py","file_name":"views_mod2.py","file_ext":"py","file_size_in_byte":9126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"499164351","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Author: David BEAL Copyright 2014 Akretion\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import orm, fields\nfrom openerp.tools.translate import _\nfrom openerp.addons.connector.event import (\n on_record_write,\n on_record_create)\nfrom openerp.addons.connector.unit.mapper import (\n mapping,\n ImportMapChild,\n ImportMapper,\n ExportMapper)\nfrom openerp.addons.magentoerpconnect.unit.binder import MagentoModelBinder\nimport openerp.addons.magentoerpconnect.consumer as magentoerpconnect\nfrom openerp.addons.magentoerpconnect.backend import magento\nfrom openerp.addons.magentoerpconnect.unit.export_synchronizer import (\n MagentoExporter)\nfrom openerp.addons.magentoerpconnect import sale\n\nimport nltk\n\n\nclass mail_message(orm.Model):\n _inherit = \"mail.message\"\n\n _columns = {\n 'magento_sale_bind_ids': fields.one2many(\n 'magento.sale.comment',\n 'openerp_id',\n string=\"Magento Bindings\"),\n }\n\n\n@on_record_create(model_names='mail.message')\ndef create_mail_message(session, model_name, record_id, vals):\n if session.context.get('connector_no_export'):\n return\n if vals.get('model') == 'sale.order' and vals.get('subtype_id'):\n order = session.browse('sale.order', vals['res_id'])\n for mag_sale in order.magento_bind_ids:\n store = mag_sale.storeview_id.store_id\n session.create('magento.sale.comment', {\n 'openerp_id': record_id,\n 'subject': _('Sent to Magento'),\n 'is_visible_on_front': True,\n 'is_customer_notified': store.send_sale_comment_mail,\n 'magento_sale_order_id': mag_sale.id,\n })\n\n\nclass magento_sale_order(orm.Model):\n \"\"\"Allow to have a relation between\n magento.sale.order and magento.sale.comment\n like you have a relation between\n magento.sale.order and magento.sale.order.line\n see in magentoerpconnect/sale.py\n \"\"\"\n _inherit = 'magento.sale.order'\n\n _columns = {\n 'magento_order_comment_ids': fields.one2many(\n 'magento.sale.comment',\n 'magento_sale_order_id',\n 'Magento Sale comments'),\n }\n\n\nclass magento_sale_comment(orm.Model):\n _name = 'magento.sale.comment'\n _inherit = 'magento.binding'\n _description = 'Magento Sale Comment'\n _inherits = {'mail.message': 'openerp_id'}\n\n MAGENTO_HELP = \"This field is a technical / configuration field for the \" \\\n \"sale comment on Magento. \\nPlease refer to the Magento \" \\\n \"documentation for details. \"\n\n def _get_comments_from_order(self, cr, uid, ids, context=None):\n return self.pool['magento.sale.comment'].search(\n cr, uid, [('magento_sale_order_id', 'in', ids)], context=context)\n\n _columns = {\n 'openerp_id': fields.many2one(\n 'mail.message',\n string='Sale Comment',\n required=True,\n ondelete='cascade'),\n 'magento_sale_order_id': fields.many2one(\n 'magento.sale.order',\n 'Magento Sale Order',\n required=True,\n ondelete='cascade',\n select=True),\n 'is_customer_notified': fields.boolean(\n 'Customer notified',\n help=MAGENTO_HELP),\n 'is_visible_on_front': fields.boolean(\n 'Visible on front',\n help=MAGENTO_HELP),\n 'status': fields.char(\n 'Order status',\n size=64,\n help=MAGENTO_HELP),\n 'backend_id': fields.related(\n 'magento_sale_order_id', 'backend_id',\n type='many2one',\n relation='magento.backend',\n string='Magento Backend',\n store={\n 'magento.sale.comment': (\n lambda self, cr, uid, ids, c=None:\n ids,\n ['magento_sale_order_id'],\n 10),\n 'magento.sale.order': (\n _get_comments_from_order,\n ['backend_id'],\n 20),\n },\n readonly=True),\n 'storeid': fields.char(\n 'Store id',\n help=MAGENTO_HELP),\n }\n\n def create(self, cr, uid, vals, context=None):\n if not 'res_id' in vals:\n info = self.pool['magento.sale.order'].read(\n cr, uid, vals['magento_sale_order_id'],\n ['openerp_id'],\n context=context)\n vals.update({\n 'res_id': info['openerp_id'][0],\n 'model': 'sale.order',\n })\n return super(magento_sale_comment, self).create(\n cr, uid, vals, context=context)\n\n\n@magento(replacing=sale.SaleOrderCommentImportMapper)\nclass SaleOrderImportMapper(sale.SaleOrderCommentImportMapper):\n \"Sales order has got an 'status_history' list which all magento comments\"\n _model_name = 'magento.sale.order'\n\n children = sale.SaleOrderCommentImportMapper.children + [\n ('status_history',\n 'magento_order_comment_ids',\n 'magento.sale.comment')]\n\n\n@magento\nclass SaleCommentImportMapper(ImportMapper):\n _model_name = 'magento.sale.comment'\n\n direct = [\n ('comment', 'body'),\n ('created_at', 'date'),\n ('status', 'status'),\n ]\n\n @mapping\n def type(self, record):\n return {'type': 'comment'}\n\n @mapping\n def store(self, record):\n if 'store_id' in record:\n return {'storeid': record['store_id']}\n\n @mapping\n def is_customer_notified(self, record):\n res = False\n if record['is_customer_notified'] == '1':\n res = True\n return {'is_customer_notified': res}\n\n @mapping\n def is_visible_on_front(self, record):\n res = False\n if record['is_visible_on_front'] == '1':\n res = True\n return {'is_visible_on_front': res}\n\n @mapping\n def subject(self, record):\n subject = _('Magento comment in %s status') % record['status']\n options = []\n if record.get('is_customer_notified'):\n options.append(_('customer notified'))\n if record.get('is_visible_on_front'):\n options.append(_('visible on front'))\n if options:\n subject += ' (' + ', ' . join(options) + ')'\n return {'subject': subject}\n\n\n@magento\nclass SaleCommentImportMapChild(ImportMapChild):\n _model_name = 'magento.sale.comment'\n\n def skip_item(self, map_record):\n if map_record.source['comment'] is None:\n return True\n\n\n@magento(replacing=sale.SaleOrderMoveComment)\nclass SaleOrderMoveComment(sale.SaleOrderMoveComment):\n _model_name = ['magento.sale.order']\n\n def move(self, binding):\n \"\"\"magento messages from canceled (edit) order\n are moved to the new order\"\"\"\n mag_message_ids = self.session.search('magento.sale.comment', [\n ('model', '=', 'sale.order'),\n ('magento_sale_order_id', '!=', False),\n ('res_id', '=', binding.parent_id)])\n mag_sale_order_ids = self.session.search('magento.sale.order', [\n ('openerp_id', '=', binding.openerp_id.id)])\n vals = {\n 'res_id': binding.openerp_id.id,\n 'magento_id': False,\n 'magento_sale_order_id': mag_sale_order_ids[0]}\n self.session.write('magento.sale.comment', mag_message_ids, vals)\n\n\n@magento\nclass MagentoSaleCommentBinder(MagentoModelBinder):\n _model_name = [\n 'magento.sale.comment',\n ]\n\n\n@magento\nclass MagentoSaleCommentExporter(MagentoExporter):\n \"\"\" Export sale order comments seller to Magento \"\"\"\n _model_name = ['magento.sale.comment']\n\n def _should_import(self):\n return False\n\n def _create(self, data):\n \"\"\" Create the Magento record \"\"\"\n # special check on data before export\n self._validate_data(data) # you may inherit in your own module\n return self.backend_adapter.create(data['order_increment'],\n data['status'],\n data['comment'],\n data['notify'])\n\n\n@magento\nclass SaleCommentExportMapper(ExportMapper):\n _model_name = 'magento.sale.comment'\n direct = [\n ('is_customer_notified', 'notify'),\n ]\n\n @mapping\n def comment(self, record):\n \"clean html tags but keep break lines\"\n comment = record.body\n for elm in ['

', '
', '
', '
']:\n comment = comment.replace(elm, elm + '\\n')\n return {'comment': nltk.clean_html(comment)}\n\n @mapping\n def status(self, record):\n state = record.magento_sale_order_id.openerp_id.state\n return {'status': sale.ORDER_STATUS_MAPPING.get(state, 'pending')}\n\n @mapping\n def order_increment(self, record):\n binder = self.get_binder_for_model('magento.sale.order')\n order_increment = binder.to_backend(\n record.magento_sale_order_id.id)\n return {'order_increment': order_increment}\n\n\n@on_record_create(model_names=['magento.sale.comment'])\n@on_record_write(model_names=['magento.sale.comment'])\ndef delay_export(session, model_name, record_id, vals):\n magentoerpconnect.delay_export(session, model_name, record_id, vals)\n","sub_path":"magentoerpconnect_order_comment/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":10151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"134120175","text":"'''\n@#!/usr/bin/env: Python3.7.6\n@# -*- encoding: utf-8-*-\n@Description: start and config snipaste\n@Author: Allen\n@Date: 2020-04-01 18:34:43\n@LastEditTime: 2020-04-16 17:05:39\n@LastEditors: Allen\n'''\nfrom subprocess import Popen, PIPE\nimport time\nimport os\nimport subprocess\n\n\nclass snipaste(object):\n def __init__(self):\n self.proc = None\n self.proc_name = 'Snipaste.exe'\n self.cur_path = os.path.abspath(os.path.dirname(__file__))\n self.root_path = os.path.join(self.cur_path, 'Snipaste-1.16.2-x64')\n self.exec_path = os.path.join(self.root_path, self.proc_name)\n\n def set_quick_save_path(self, config_path, monitor_path):\n result = list()\n with open('%s' % (config_path), 'r+', encoding='utf-8') as f:\n for line in f.readlines():\n if 'auto_save_dir' in line:\n line = ''.join(['auto_save_dir', '=', monitor_path, '\\n'])\n if 'quick_save_dir' in line:\n line = ''.join(['quick_save_dir', '=', monitor_path, '\\n'])\n result.append(line)\n f.seek(0)\n f.truncate()\n f.write(\"{}\\n\".format(''.join(result)))\n f.close()\n\n def stop_snipaste(self):\n if self.proc:\n # self.proc.kill() # 终止子进程\n # self.proc.communicate()\n # self.proc.terminate()\n # print('test')\n self.end_program()\n self.proc = None\n\n #关闭其他应用程序\n #pro_name:将要关闭的程序\n def end_program(self):\n os.system('%s%s' % (\"taskkill /F /IM \", self.proc_name))\n # stop_cmd = 'snip --exit'\n # ret = subprocess.call([exec_path, stop_cmd],\n # shell=True,\n # stdout=subprocess.PIPE,\n # stderr=subprocess.PIPE,\n # encoding=\"utf-8\",\n # timeout=1)\n\n def start_snipaste(self, monitor_path):\n config_path = os.path.join(self.root_path, 'config.ini')\n self.set_quick_save_path(config_path, monitor_path)\n config_param = '--config=%s' % config_path\n # print(config_param)\n # quick_save_param = 'snip -o quick-save'\n # subprocess.run([exec_path, config_param])\n\n # cmd_line = \" \".join([exec_path, config_param])\n # os.system(cmd_line)\n\n if not self.proc:\n self.proc = subprocess.Popen(\n [self.exec_path, config_param],\n shell=True,\n )\n\n\nsnip = snipaste()\n","sub_path":"snipaste.py","file_name":"snipaste.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"638352214","text":"from functools import wraps\n\nfrom flask import jsonify, session, request\n\nfrom Src.common import status_code\nfrom Src.common.service import LogService\nfrom Src.services.user_service import UserService\nfrom Src.utils import log as logger\n\n\ndef login_required(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n if not (session and session.get(\"user_id\") and session.get(\"token\")):\n return status_code.USER_NO_LOGIN\n try:\n user_service = UserService()\n user = user_service.get_user_by_id(session.get(\"user_id\"))\n if not user:\n return status_code.USER_NOT_EXIST\n if not user.get(\"is_active\"):\n return status_code.USER_IS_NOT_ACTIVE\n if user.get(\"token\") != session.get(\"token\"):\n return status_code.PLEASE_LOGIN\n except Exception as ex:\n print(ex)\n logger.error(\"认证失败,{}\".format(ex))\n return status_code.FAIL\n\n return func(*args, **kwargs)\n return wrapper\n\n\ndef user_is_active(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n try:\n user_service = UserService()\n if not user_service.get_user_active(user_id=session.get(\"user_id\")):\n return jsonify(status_code.USER_IS_NOT_ACTIVE)\n except Exception as ex:\n print(ex)\n return jsonify(status_code.FAIL)\n\n return func(*args, **kwargs)\n return wrapper\n\n\ndef write_operate_log(action_cn=\"\", action_en=\"\"):\n def wrapper(func):\n @wraps(func)\n def inner(*args, **kwargs):\n ip = request.remote_addr\n\n result = func(*args, **kwargs)\n\n if session and session.get(\"user_id\"):\n user_id = session.get(\"user_id\")\n else:\n user_id = None\n\n if result.get(\"code\") == status_code.SUCCESS_CODE:\n result_cn = \"成功\"\n result_en = \"SUCCESS\"\n else:\n result_cn = \"失败\"\n result_en = \"FAIL\"\n # 在这里写操作日志\n try:\n LogService().write_log(client_ip=ip, action_cn=action_cn, action_en=action_en,\n result_cn=result_cn, result_en=result_en,\n reason_cn=result.get(\"msg_cn\"), reason_en=result.get(\"msg_en\"),\n user_id=user_id)\n except Exception as ex:\n print(ex)\n logger.error(\"写操作日志失败,{}\".format(ex))\n return jsonify(result)\n\n return inner\n return wrapper\n","sub_path":"Src/utils/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"521139025","text":"'''\n=> Two Pointer\nDrive by left pointer\n'''\nclass Solution:\n \"\"\"\n @param s: a string\n @return: an integer\n \"\"\"\n def lengthOfLongestSubstring(self, s):\n # write your code here\n r, res, chars = 0, 0, set()\n for l in range(len(s)):\n while r < len(s) and s[r] not in chars:\n chars.add(s[r])\n r += 1\n res = max(res, len(chars))\n chars.remove(s[l])\n \n return res","sub_path":"3_longest-substring-without-repeating-characters/rear-drive.py","file_name":"rear-drive.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"94005044","text":"'''练习1: 使用vi编写一个程序\n写一个求函数运行时间的装饰器\n\n提示 : import time\n\n def fun():\n pass\n\n start = time.time()\n fun()\n end = time.time()\n end - start()\n\nplan : 求 1 到 20 20个整数的乘积结果'''\nimport time\n\ndef timeis(f):\n def wrapper(*args,**kwargs):\n start = time.time()\n res = f(*args,**kwargs)\n end = time.time()\n print(\"函数执行时间:\",end - start)\n return res \n return wrapper \n\n@timeis\ndef fun(n):\n result = 1 \n for i in range(1,n + 1):\n result *= i\n return result\n\nprint(fun(20))","sub_path":"note-month02/01linux1-2/day02/zhuangshiqi.py","file_name":"zhuangshiqi.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"18454556","text":"#!/usr/bin/python\nimport sys\nimport os\nimport re\nfrom sys import argv\n\npath = argv[1] + '/Unity-iPhone.xcodeproj/project.pbxproj'\npathw = '/tmp/Unity-iPhone.xcodeproj-project.pbxproj'\nlogf = open('/tmp/fqlog.txt', 'w')\nsrcf = open(path)\ndstf = open(pathw, 'w')\n\nlogf.write('path = '+path+'\\n')\nlogf.write('pathw = '+pathw+'\\n')\n\np = re.compile(r'(\\s)+\"(\\$\\(SRCROOT.+)\",')\n\nfor i, line in enumerate(srcf):\n m = p.search(line)\n if m:\n logf.write('('+str(i)+') : '+m.group(1)+'\"\\\\\"'+m.group(2)+'\\\\\"\",\\n')\n dstf.write(m.group(1)+'\"\\\\\"'+m.group(2)+'\\\\\"\",\\n')\n\n else:\n dstf.write(line)\n\n\ndstf.close()\nsrcf.close()\nlogf.close()\n\nos.rename(pathw, path)\n\n","sub_path":"Assets/Editor/framework_quoter.py","file_name":"framework_quoter.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"111721432","text":"inputs=open('all.combined.txt','r').read().strip().split('\\n')\noutf=open('all.combined.heatmap.txt','w')\nall_dict=dict()\ngene_set=set([])\npath_set=set([]) \nfor line in inputs:\n tokens=line.split('\\t')\n gene=tokens[0]\n for time in ['earlyg1','lateg1','sg2m']:\n gene_set.add(gene+'.'+time)\n pathways=tokens[2]\n if pathways==\"NA\":\n continue\n pathways=pathways.split('|')\n for pathway in pathways:\n path_set.add(pathway) \n label=tokens[1].split('.')\n time=label[0].lower() \n direction=label[1]\n if direction==\"up\":\n direction=1\n elif direction==\"down\":\n direction=-1\n gene=gene+'.'+time\n if gene not in all_dict:\n all_dict[gene]=dict()\n for pathway in pathways:\n all_dict[gene][pathway]=direction \n\ngene_set=list(gene_set)\ngene_set.sort()\npath_set=list(path_set)\npath_set.sort()\noutf.write('Gene.Time'+'\\t'+'\\t'.join(path_set)+'\\n')\nfor gene in gene_set:\n if gene not in all_dict:\n continue \n #outf.write('\\t0'*len(path_set)+'\\n')\n else:\n outf.write(gene)\n for path in path_set:\n if path in all_dict[gene]:\n outf.write('\\t'+str(all_dict[gene][path]))\n else:\n outf.write('\\t0')\n outf.write('\\n')\n \n","sub_path":"cytoscape_pathways/combined/make_summary_gene_path_heatmap.py","file_name":"make_summary_gene_path_heatmap.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"495309776","text":"from django.shortcuts import render\nfrom .models import All_post_links,Autor,Stats,Top10\nfrom .serializers import AutorSerializer,StatsSerializer,top10Serializer,SubAutorSerializer\nfrom rest_framework import viewsets\nfrom .DatabaseCheck import Links_checker\n\n#-------------------SERIALIZERS-----------------------------\nclass AutorView(viewsets.ModelViewSet):\n queryset = Autor.objects.all()\n serializer_class = AutorSerializer\n lookup_field = \"Subname\"\n\nclass SubAutorView(viewsets.ModelViewSet):\n queryset = Autor.objects.all()\n serializer_class = SubAutorSerializer\n\nclass StatsView(viewsets.ModelViewSet):\n serializer_class = StatsSerializer\n queryset = Stats.objects.all()\n def get_queryset(self):\n qs = super(StatsView, self).get_queryset()\n qs = qs.all().order_by(\"-Count\")[::1][:10]\n return qs\n\nclass Top10View(viewsets.ModelViewSet):\n queryset = Top10.objects.all()\n serializer_class = top10Serializer\n def get_queryset(self):\n qs2 = super(Top10View, self).get_queryset()\n qs2 = qs2.all().order_by(\"-T10Count\")[::1][:10]\n return qs2\n#------------------------------------------------------------\n\n#Check if Database Scrap data\ntry:\n Autor.objects.get(Subname='MartaKoziel')\n\nexcept Autor.DoesNotExist:\n Links_checker()\n","sub_path":"Teonite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"375547566","text":"#!/usr/bin/env python3\r\n\r\nimport sys\r\nfrom .. import Network\r\nfrom electrum_cadex.util import json_encode, print_msg\r\nfrom electrum_cadex import bitcoin\r\n\r\ntry:\r\n addr = sys.argv[1]\r\nexcept Exception:\r\n print(\"usage: get_history \")\r\n sys.exit(1)\r\n\r\nn = Network()\r\nn.start()\r\n_hash = bitcoin.address_to_scripthash(addr)\r\nh = n.get_history_for_scripthash(_hash)\r\nprint_msg(json_encode(h))\r\n","sub_path":"electrum_cadex/scripts/get_history.py","file_name":"get_history.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"438466607","text":"import os\nimport json\n# from .. import config\nfrom warnings import warn\n\n\ndef find_root_dir():\n i = 0\n while os.path.realpath('../' * i) != '/':\n if os.path.exists('../' * i + 'kts_config.py'):\n if i != 0:\n return '../' * i\n else:\n return './'\n i += 1\n return False\n\n\ndef parse(file):\n with open(file) as f:\n return json.load(f)\n\n\ndef get_mode():\n if find_root_dir():\n # config.storage_path = parse(find_root_dir() + '.kts')['storage_path']\n cache_mode = 'disk_and_ram'\n cache_policy = 'everything'\n root_dir = find_root_dir()\n else:\n # warn(\"Couldn't find existing kts project. Setting kaggle-mode\")\n cache_mode = 'ram'\n cache_policy = 'service'\n root_dir = '.'\n return cache_mode, cache_policy, root_dir\n\n\ndef check_structure(paths):\n for path in paths:\n if not os.path.isdir(path):\n return False\n return True\n\n\nIMPORT_ERROR_MESSAGE = \"\"\"\nThis directory doesn't look like kts project.\nUse `kts init` to initialize a project. You can't use kts without its file system.\nThis error could also be raised by importing kts from a directory of existing project other than /notebooks.\n\"\"\"\n\n\ndef check_file_system():\n paths = ['../input', '../notebooks', '../storage/info', '../storage/sources', '../output']\n\n if check_structure(paths):\n return\n\n raise ImportError(IMPORT_ERROR_MESSAGE)\n","sub_path":"kts/environment/file_system.py","file_name":"file_system.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"378704146","text":"from functools import cached_property\nimport pandas\nimport pymc as pm\nimport pymc.math as pmmath\nfrom scipy.special import expit, logit\n\nfrom .pymc_model import PyMCModel\n\n\nclass Elo(PyMCModel):\n model_name = \"elo\"\n weight_key = \"elo\"\n\n @cached_property\n def model_(self):\n with pm.Model() as model:\n elo_logit_scale = pm.HalfNormal(\"elo_logit_scale\", sigma=1.0)\n win_lik = pm.Bernoulli(\n \"win_lik\",\n logit_p=elo_logit_scale * logit(self.data_.elo_estimate),\n observed=self.y_,\n )\n if self.sample_weight_ is not None:\n pm.Potential(\n \"weighted\",\n pmmath.prod(pmmath.stack([self.sample_weight_, win_lik])),\n )\n return model\n\n def p1_win_chance(self, X: pandas.DataFrame):\n elo_logit_scale = float(\n self.inf_data_[\"posterior\"].elo_logit_scale.mean([\"chain\", \"draw\"])\n )\n prob_p1_win = expit(elo_logit_scale * logit(X.elo_estimate))\n return pandas.DataFrame(\n {1: prob_p1_win, 0: 1 - prob_p1_win}, columns=self.classes_\n )\n","sub_path":"src/yomi_skill/models/elo.py","file_name":"elo.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"93159437","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\nimport socket\r\nimport pickle\r\nimport clase_U_Inicio\r\n\r\n\r\nclass Principal():\r\n def Cargar():\r\n\r\n v_user_Inicio = Tk()\r\n\r\n print(\"usuario_Inicio\")\r\n\r\n host = \"localhost\"\r\n\r\n port = 9999\r\n\r\n sock = socket.socket()\r\n\r\n sock.connect((host,port))\r\n\r\n\r\n usuario = \"getusername\"\r\n usuario = pickle.dumps(usuario)\r\n\r\n sock.send(usuario)\r\n\r\n usuario = sock.recv(1024)\r\n usuario = pickle.loads(usuario)\r\n\r\n\r\n sock.close()\r\n\r\n\r\n frm = Frame(v_user_Inicio)\r\n frm.grid(padx=10,pady=10)\r\n\r\n lbl = Label(frm,text=\"Nombre de usuario: \")\r\n lbl.grid(row=0,column=0)\r\n\r\n lbl = Label(frm,text=usuario)\r\n lbl.grid(row=0,column=1)\r\n\r\n lbl = Label(frm,text=\"Cantidad de billetes: \")\r\n lbl.grid(row=1,column=0)\r\n\r\n\r\n varBilletes=StringVar()\r\n lbl = Label(frm,textvariable=varBilletes)\r\n lbl.grid(row=1,column=1)\r\n\r\n print(\"usuario_Inicio\")\r\n\r\n host = \"localhost\"\r\n\r\n port = 9999\r\n\r\n sock = socket.socket()\r\n\r\n sock.connect((host,port))\r\n clase=clase_U_Inicio.clase_U_Inicio(sock)\r\n\r\n\r\n clase.varDefault(usuario,varBilletes)\r\n\r\n frmBtn=Frame(v_user_Inicio)\r\n frmBtn.grid(row=1)\r\n\r\n clase.crearFrame(frmBtn)\r\n\r\n\r\n\r\n frmPaquete=LabelFrame(v_user_Inicio,text=\"Paquete\")\r\n frmPaquete.grid(row=1,column=1,padx=10,sticky=\"n\")\r\n\r\n frmVenta = LabelFrame(v_user_Inicio,text=\"Paquete\")\r\n frmVenta.grid(row=0,column=1,padx=10,sticky=\"n\")\r\n\r\n clase.crearPaquete(frmPaquete,frmVenta)\r\n\r\n sock.close()\r\n\r\n\r\n v_user_Inicio.mainloop()\r\n","sub_path":"Proyectos/Album Progra/usuario_Inicio.py","file_name":"usuario_Inicio.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"511976478","text":"\nfrom typing import Union, Optional\n\nimport requests\n\nfrom .base import RQBase, RQError\n\n\nclass DBServerError(Exception):\n pass\n\n\nclass DBServer(RQBase):\n def __init__(self, auth: Union[str, bytes],\n host: str = 'localhost', port: int = 50860):\n\n super().__init__(host, port)\n\n if isinstance(auth, bytes):\n self.auth2(auth)\n elif isinstance(auth, str):\n if ':' not in auth:\n raise DBServerError(\"missing ':' for auth [format: : ]\")\n self.auth(*auth.split(':'))\n else:\n raise DBServerError(f\"auth should be {type(bytes())!r} or {type(str())!r} not {type(auth)!r}\")\n\n def _create_path(self, group: Optional[str], label: Optional[str]) -> str:\n if label and not group:\n raise DBServerError(\"group needed for label\")\n\n return f\"{((group + '/') if group else '')}{label if (group and label) else ''}\"\n\n def get(self, group: str = None, label: str = None) -> requests.Response:\n return requests.get(\n f\"{self.url}/db/{self._create_path(group, label)}\",\n headers=self.headers,\n timeout=self.timeout\n )\n\n def post(self, group: str, label: str, data: bytes,\n _auto_put: bool = False) -> requests.Response:\n\n assert isinstance(data, bytes), f\"data have to be {type(data)!r}\"\n\n headers = {**self.headers, **{'Content-Type': 'data/bytes'}}\n\n r = requests.post(\n f\"{self.url}/db/{self._create_path(group, label)}\",\n data=data,\n headers=headers,\n timeout=self.timeout\n )\n\n if not r and _auto_put:\n if 'use put' in r.text.lower():\n r = self.put(group, label, data)\n\n return r\n\n def put(self, group: str, label: str, data: bytes,\n _auto_post: bool = False) -> requests.Response:\n\n assert isinstance(data, bytes), f\"data have to be {type(data)!r}\"\n\n headers = {**self.headers, **{'Content-Type': 'data/bytes'}}\n\n r = requests.put(\n f\"{self.url}/db/{self._create_path(group, label)}\",\n data=data,\n headers=headers,\n timeout=self.timeout\n )\n\n if not r and _auto_post:\n if 'use post' in r.text.lower():\n r = self.post(group, label, data)\n\n return r\n\n def delete(self, group: str, label: str = None):\n return requests.delete(\n f\"{self.url}/db/{self._create_path(group, label)}\",\n headers=self.headers\n )\n","sub_path":"kwking_helper/rq/dbserver.py","file_name":"dbserver.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"84482906","text":"from django_bootstrap import bootstrap\nbootstrap()\n\nimport sys\nimport json\n\nfrom appl.models import AdmissionProject, AdmissionRound, ProjectApplication, AdmissionResult\n\ndef load_tcas_data(filename):\n lines = open(filename).readlines()\n\n count = len(lines) // 2\n\n tcas_data = {}\n \n for i in range(count):\n nat_id = lines[i*2].strip()\n data = json.loads(lines[i*2+1].strip())\n\n if len(data) == 0:\n tcas_data[nat_id] = { 'status': 'missing' }\n continue\n\n names = data[0]['studenT_NAME'].split()\n tcas_data[nat_id] = {\n 'status': 'found',\n 'prefix': names[0],\n 'first_name': names[1],\n 'last_name': ' '.join(names[2:]), \n }\n \n return tcas_data\n\ndef load_major_map(map_files):\n import csv\n \n major_map = {}\n for f in map_files:\n with open(f) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n project_number = int(row['project'])\n major_number = int(row['number'])\n if project_number not in major_map:\n major_map[project_number] = {}\n if major_number not in major_map[project_number]:\n major_map[project_number][major_number] = []\n\n major_map[project_number][major_number].append(row)\n return major_map\n\ndef print_csv_line(applicant, application, personal_profile, app_date, cupt_major,\n app_type, tcas_id, ranking, interview_status, interview_description,\n header):\n university_id = '002'\n\n data = {\n 'university_id': university_id,\n 'program_id': cupt_major['program_id'],\n 'major_id': cupt_major['major_id'],\n 'project_id': cupt_major['project_id'],\n 'type': app_type,\n 'citizen_id': '',\n 'gnumber': '',\n 'passport': '',\n 'first_name_th': applicant.first_name,\n 'last_name_th': applicant.last_name,\n 'first_name_en': personal_profile.first_name_english,\n 'last_name_en': personal_profile.last_name_english,\n 'priority': 0,\n 'application_id': application.get_number(),\n 'application_date': app_date,\n 'tcas_id': tcas_id,\n 'ranking': ranking,\n 'score': 0,\n 'interview_status': interview_status,\n 'interview_description': interview_description,\n 'status': 0,\n }\n\n if not applicant.has_registered_with_passport():\n data['citizen_id'] = applicant.national_id\n data['first_name_en'] = data['last_name_en'] = ''\n else:\n data['passport'] = applicant.passport_number\n data['first_name_th'] = data['last_name_th'] = ''\n \n print(','.join(['\"'+str(data[h])+'\"' for h in header]))\n\n\ndef get_admission_result(application,\n admission_project,\n admission_round,\n major):\n results = AdmissionResult.objects.filter(application=application,\n admission_project=admission_project,\n admission_round=admission_round,\n major=major).all()\n if len(results) == 0:\n return None\n else:\n return results[0]\n\nMAJOR_MAP = {\n 1:{\n 100: [\n '10020118620101A,A',\n '10020118620101A,B',\n ],\n },\n 2:{\n 40: ['10020107611106A,'],\n },\n}\n \ndef main():\n project_id = sys.argv[1]\n round_id = sys.argv[2]\n\n if (len(sys.argv) >= 4) and (sys.argv[3] != '-'):\n tcas_data_filename = sys.argv[3]\n tcas_data = load_tcas_data(tcas_data_filename)\n else:\n tcas_data = {}\n\n #major_map_files = [f for f in sys.argv[4:] if not f.startswith('--')]\n #major_map = load_major_map(major_map_files)\n\n major_map = MAJOR_MAP\n \n only_accepted = False\n if '--accepted' in sys.argv:\n only_accepted = True\n\n with_interview_status = False\n if '--interview_status' in sys.argv:\n with_interview_status = True\n\n project = AdmissionProject.objects.get(pk=project_id)\n admission_round = AdmissionRound.objects.get(pk=round_id)\n\n project_applications = ProjectApplication.find_for_project_and_round(project,\n admission_round,\n True)\n\n not_found_list = []\n\n header = ['university_id',\n 'program_id',\n 'major_id',\n 'project_id',\n 'type',\n 'citizen_id',\n 'gnumber',\n 'passport',\n 'first_name_th',\n 'last_name_th',\n 'first_name_en',\n 'last_name_en',\n 'priority',\n 'application_id',\n 'application_date',\n 'tcas_id',\n 'ranking',\n 'score',\n 'interview_status',\n 'interview_description',\n 'status',]\n\n print(','.join(header))\n \n app_type = '1_2564'\n \n for app in project_applications:\n if app.has_paid():\n try:\n majors = app.major_selection.get_majors()\n except:\n majors = []\n applicant = app.applicant\n if applicant.has_registered_with_passport():\n nat = applicant.passport_number\n else:\n nat = applicant.national_id\n\n is_found = False\n if nat in tcas_data:\n if tcas_data[nat]['status'] == 'found':\n is_found = True\n \n applicant.prefix = tcas_data[nat]['prefix']\n applicant.first_name = tcas_data[nat]['first_name']\n applicant.last_name = tcas_data[nat]['last_name']\n \n \n profile = applicant.get_personal_profile()\n app_date = '%02d/%02d/%04d' % (app.applied_at.day,\n app.applied_at.month,\n app.applied_at.year + 543)\n \n for m in majors:\n result = None\n \n if only_accepted:\n result = get_admission_result(app, project, admission_round, m)\n if (not result) or (not result.is_accepted):\n continue\n\n \n \n cupt_majors = [{\n 'program_id': m.get_detail_items()[-2],\n 'major_id': m.get_detail_items()[-1],\n 'project_id': project.cupt_code,\n }]\n if (project.id in major_map) and (m.number in major_map[project.id]):\n cupt_majors = []\n for mj in major_map[project.id][m.number]:\n cupt_majors.append({\n 'program_id': mj.split(',')[0],\n 'major_id': mj.split(',')[1],\n 'project_id': project.cupt_code,\n })\n\n interview_status = '0'\n if with_interview_status:\n if not result:\n result = get_admission_result(app, project, admission_round, m)\n\n if result and result.is_accepted:\n interview_status = '1'\n \n for cupt_major in cupt_majors:\n print_csv_line(applicant, app, profile,\n app_date, cupt_major,\n app_type,\n '0','0',\n interview_status,\n '0',\n header)\n\nif __name__ == '__main__':\n main()\n \n","sub_path":"scripts/export_project_applicants_tcas64.py","file_name":"export_project_applicants_tcas64.py","file_ext":"py","file_size_in_byte":8019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"647813803","text":"import tensorflow as tf\n\ndef build_inputs(batch_size, num_steps):\n ''' Define placeholders for inputs, targets, and dropout \n \n Arguments\n ---------\n batch_size: Batch size, number of sequences per batch\n num_steps: Number of sequence steps in a batch\n \n '''\n # Declare placeholders we'll feed into the graph\n inputs = tf.placeholder(dtype=tf.int32, shape=(batch_size, num_steps), name=\"inputs\")\n targets = tf.placeholder(dtype=tf.int32, shape=(batch_size, num_steps), name=\"targets\")\n \n # Keep probability placeholder for drop out layers\n keep_prob = tf.placeholder(dtype=tf.float32, shape=(), name=\"keep_prob\")\n \n return inputs, targets, keep_prob\n\ndef build_cell(num_units, keep_prob):\n lstm = tf.contrib.rnn.BasicLSTMCell(num_units)\n drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)\n\n return drop\n\ndef build_lstm(lstm_size, num_layers, batch_size, keep_prob):\n ''' Build LSTM cell.\n \n Arguments\n ---------\n keep_prob: Scalar tensor (tf.placeholder) for the dropout keep probability\n lstm_size: Size of the hidden layers in the LSTM cells\n num_layers: Number of LSTM layers\n batch_size: Batch size\n\n '''\n lstm_drops = [build_cell(lstm_size, keep_prob) for _ in range(num_layers)]\n \n # Stack up multiple LSTM layers, for deep learning\n cell = tf.contrib.rnn.MultiRNNCell(lstm_drops)\n initial_state = cell.zero_state(batch_size, tf.float32)\n \n return cell, initial_state\n\n\ndef build_output(lstm_output, in_size, out_size):\n ''' Build a softmax layer, return the softmax output and logits.\n \n Arguments\n ---------\n \n lstm_output: List of output tensors from the LSTM layer\n in_size: Size of the input tensor, for example, size of the LSTM cells\n out_size: Size of this softmax layer\n \n '''\n\n # Reshape output so it's a bunch of rows, one row for each step for each sequence.\n # Concatenate lstm_output over axis 1 (the columns)\n seq_output = tf.concat(lstm_output, axis=1)\n # Reshape seq_output to a 2D tensor with lstm_size columns\n x = tf.reshape(seq_output, shape=(-1, in_size))\n \n # Connect the RNN outputs to a softmax layer\n with tf.variable_scope('softmax'):\n # Create the weight and bias variables here\n softmax_w = tf.Variable(tf.truncated_normal((in_size, out_size), stddev=0.1))\n softmax_b = tf.Variable(tf.zeros(out_size))\n \n # Since output is a bunch of rows of RNN cell outputs, logits will be a bunch\n # of rows of logit outputs, one for each step and sequence\n logits = tf.matmul(x, softmax_w) + softmax_b\n \n # Use softmax to get the probabilities for predicted characters\n out = tf.nn.softmax(logits, name='predictions')\n \n return out, logits\n\n\ndef build_loss(logits, targets, lstm_size, num_classes):\n ''' Calculate the loss from the logits and the targets.\n \n Arguments\n ---------\n logits: Logits from final fully connected layer\n targets: Targets for supervised learning\n lstm_size: Number of LSTM hidden units\n num_classes: Number of classes in targets\n \n '''\n \n # One-hot encode targets and reshape to match logits, one row per batch_size per step\n y_one_hot = tf.one_hot(targets, num_classes)\n y_reshaped = tf.reshape(y_one_hot, logits.get_shape())\n \n # Softmax cross entropy loss\n loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_reshaped)\n loss = tf.reduce_mean(loss)\n return loss\n\ndef build_optimizer(loss, learning_rate, grad_clip):\n ''' Build optmizer for training, using gradient clipping.\n \n Arguments:\n loss: Network loss\n learning_rate: Learning rate for optimizer\n \n '''\n \n # Optimizer for training, using gradient clipping to control exploding gradients\n tvars = tf.trainable_variables()\n grads, _ = tf.clip_by_global_norm(tf.gradients(loss, tvars), grad_clip)\n train_op = tf.train.AdamOptimizer(learning_rate)\n optimizer = train_op.apply_gradients(zip(grads, tvars))\n \n return optimizer\n\n\nclass CharRNN:\n \n def __init__(self, num_classes, batch_size=64, num_steps=50, \n lstm_size=128, num_layers=2, learning_rate=0.001, \n grad_clip=5, sampling=False):\n \n # When we're using this network for sampling later, we'll be passing in\n # one character at a time, so providing an option for that\n if sampling == True:\n batch_size, num_steps = 1, 1\n else:\n batch_size, num_steps = batch_size, num_steps\n\n tf.reset_default_graph()\n \n # Build the input placeholder tensors\n self.inputs, self.targets, self.keep_prob = build_inputs(batch_size, num_steps)\n\n # Build the LSTM cell\n cell, self.initial_state = build_lstm(lstm_size, num_layers, batch_size, self.keep_prob)\n\n ### Run the data through the RNN layers\n # First, one-hot encode the input tokens\n x_one_hot = tf.one_hot(self.inputs, num_classes)\n \n # Run each sequence step through the RNN and collect the outputs\n outputs, state = tf.nn.dynamic_rnn(cell, x_one_hot, initial_state=self.initial_state)\n self.final_state = state\n \n # Get softmax predictions and logits\n self.prediction, self.logits = build_output(outputs, lstm_size, num_classes)\n \n # Loss and optimizer (with gradient clipping)\n self.loss = build_loss(self.logits, self.targets, lstm_size, num_classes)\n self.optimizer = build_optimizer(self.loss, learning_rate, grad_clip)","sub_path":"intro-to-rnns/source/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"550633905","text":"import setuptools\nimport os\n\ndef package_files(directory):\n paths = []\n for (path, directories, filenames) in os.walk(directory):\n for filename in filenames:\n paths.append(os.path.join('..', path, filename))\n return paths\n\nextra_files = package_files('ml/sample/components')\n\nsetuptools.setup(\n name='ml-sample',\n version='0.0.1',\n author='Example Author',\n author_email='author@example.com',\n description='Component package generated by azure-ml-component. '\n 'Learn more on reference doc site: https://aka.ms/azure-ml-component-reference.',\n classifiers=[\n \"Intended Audience :: Developers\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3\",\n ],\n install_requires=['azure-ml-component'],\n packages=setuptools.find_packages(),\n python_requires='>=3.6',\n include_package_data=True,\n package_data={'': extra_files},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"56811258","text":"\r\n# victorffs 2019 Victor Fragoso\r\n# https://github.com/victorffs\r\n\r\nfrom SCons.Script import DefaultEnvironment\r\n\r\nenv = DefaultEnvironment()\r\nplatform = \"threadx\"\r\nmodule = platform + \"-\" + env.BoardConfig().get(\"build.core\")\r\nm = __import__(module) \r\nglobals()[module] = m\r\nm.dev_init(env, platform)\r\n#print env.Dump()\r\n","sub_path":"builder/frameworks/threadx.py","file_name":"threadx.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"269910162","text":"## @file SALst.py\n# @author Frank Su\n# @brief SALst module allocates students to departments based on gpa and first choice\n# @date 02/04/2019\n\nfrom StdntAllocTypes import *\nfrom AALst import *\nfrom DCapALst import *\nfrom typing import *\n\n\n## @brief a local type that represents a student as tuple of (macid, info)\nclass StudentT(NamedTuple):\n macid: str\n info: SInfoT\n\n\n## @brief a local function that returns the gpa of a student in SALst\n# @param m a string representing a students macid\n# @param s a set of students of type StudentT\n# @return student[1][3] the gpa of the student\ndef get_gpa(m, s):\n for student in s:\n if m == student[0]:\n return student[1][3]\n\n\n## @brief a class that represents a list of students\nclass SALst:\n s = []\n\n ## @brief initalizes s with empty set\n @staticmethod\n def init():\n SALst.s = []\n\n ## @brief adds a student to the set of students\n # @exception raises KeyError if name of student already in set\n # @param m a string representing a student\n # @param i an object of type SInfoT that stores information for student\n @staticmethod\n def add(m, i):\n for students in SALst.s:\n if m == students[0]:\n raise KeyError\n student = tuple(StudentT(m, i))\n SALst.s.append(student)\n\n ## @brief removes a student from the set of students\n # @exception raises KeyError if student is not in set\n # @param m a student in the set\n @staticmethod\n def remove(m):\n copy = SALst.s.copy()\n for student in copy:\n if m == student[0]:\n SALst.s.remove(student)\n return\n raise KeyError\n\n ## @brief returns true if student is in set\n # @param m a student in the set of students\n # @return true if student m is in set, false otherwise\n @staticmethod\n def elm(m):\n if SALst.s == set():\n return False\n for student in SALst.s:\n if m == student[0]:\n return True\n return False\n\n ## @brief returns the information of a student as a type SInfoT\n # @exception raises ValueError if student is not in the set\n # @param m a student in the set of students\n # @return i information of a student as type SInfoT\n @staticmethod\n def info(m):\n if SALst.s == set():\n raise KeyError\n for student in SALst.s:\n if m == student[0]:\n return student[1]\n raise KeyError\n\n ## @brief returns list of students sorted by GPA highest to lowest\n # @param f a lambda function that determines if freechoice = true and gpa >= 4\n # @return L a sequence of strings representing names of students\n @staticmethod\n def sort(f):\n list = []\n # if student is in SALst.s and student GPA >= 4.0, add student to list\n for student in SALst.s:\n if f(student[1]):\n list.append(student[0])\n # sort based on students GPA using bubble sort\n n = len(list)\n for i in range(n):\n for j in range(0, n - i - 1):\n if get_gpa(list[j], SALst.s) < get_gpa(list[j + 1], SALst.s):\n list[j], list[j + 1] = list[j + 1], list[j]\n return list\n\n ## @brief returns the average gpa\n # @exception raises ValueError if there are no female/male students in set\n # @param f lambda function determines the gender of students\n # @return average a double representing the average gpa of male/female students\n @staticmethod\n def average(f):\n # populate fset with students of specific gender\n fset = []\n for student in SALst.s:\n if f(student[1]):\n fset.append(student)\n # raise ValueError if fset is empty\n if not fset:\n raise ValueError\n # calculate average of gpa for students in fset\n total = 0\n for student in fset:\n total = total + student[1][3]\n average = total / len(fset)\n return average\n\n ## @brief allocates students based on average gpa and first choice selections\n # @exception raises RuntimeError if a student cannot be allocated\n @staticmethod\n def allocate():\n AALst.init()\n f = SALst.sort(lambda t: t.freechoice and t.gpa >= 4.0)\n for m in f:\n ch = SALst.info(m).choices\n AALst.add_stdnt(ch.next(), m)\n s = SALst.sort(lambda t: not t.freechoice and t.gpa >= 4.0)\n for m in s:\n ch = SALst.info(m).choices\n alloc = False\n while not alloc and not ch.end():\n d = ch.next()\n if AALst.num_alloc(d) < DCapALst.capacity(d):\n AALst.add_stdnt(d, m)\n alloc = True\n if not alloc:\n raise RuntimeError\n","sub_path":"A2/src/SALst.py","file_name":"SALst.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"253205253","text":"\"\"\"\nArtificail NN to solve a classification Probelm\nNeed to install Keras Library,Tensor flow and Theano\nIf you install Keras ,Tensorflow will run in background\n\"\"\"\n#Part 1 Data Preprocessing\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndataset = pd.read_csv(r'Churn_Modelling.csv')\n\nX = dataset.iloc[:,3:13].values\ny = dataset.iloc[:,13].values\n\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\nlabelencoder_x_1 = LabelEncoder() #will encode country\nX[:,1] = labelencoder_x_1.fit_transform(X[:,1])\n\nlabelencoder_x_2 = LabelEncoder() #will encode Gender\nX[:,2] = labelencoder_x_2.fit_transform(X[:,2])\n\n#As country has 3 catagorical variable we will prepare the dummy for country\nonehotencoder_x = OneHotEncoder(categorical_features=[1])\nX= onehotencoder_x.fit_transform(X).toarray()\n#Remove first dummy variable colulm to get rid of trap\nX = X[:,1:] #Now we have only two dummy variable for country\n\n#Split Data\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\nscale = StandardScaler()\nX_train = scale.fit_transform(X_train)\nX_test = scale.transform(X_test)\n\n#Part 2 - Make the ANN\n\n#Importing the keras library and \n\n\"\"\"\nimport keras #It will use TensorFlow in backend\nfrom keras.models import Sequential #Intialise the ANN\nfrom keras.layers import Dense #Creating layers in\nGiving error: \nimport tensorflow as tf\nModuleNotFoundError: No module named 'tensor\n\"\"\"\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Flatten\n\n#Intiating the ANN\nclassifier = Sequential()\n\n#Adding the input layer and first hidden layer\n#Follow the 7 steps here\n#relu = Rectifier activation function\n#output_dim = NO f nodes in hidden layer\n#input_dim = input \n#init = intilaises the weight randomly\nclassifier.add(Dense(output_dim=6, init=\"uniform\",activation='relu',input_dim=11))\n\n#Adding the second hidden layer(Actually for our probelm here we dont need 2nd layer)\n#We dont need input layer here\nclassifier.add(Dense(output_dim=6, init=\"uniform\",activation='relu'))\n\n#Adding the output layer\n#output_dim =1 as we have only one output node y\n#activation = We are predicting the people leavig the abnk base on probablistic\n#If more output catagores then choose softmax as activation\nclassifier.add(Dense(output_dim=1, init=\"uniform\",activation='sigmoid'))\n\n#Compiling the ANN (Applying Sochastic Gradient Descent)\n#adam = one of the sochastic function popular one\n#optimizer = selection of algorithm (we are going to use adam sochastic)\n#loss = we are using logarithimic loss as our output is sigmoid\n#binary_crossentropy bcz our output is binary 0 or 1\nclassifier.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\n\n#Fit the ANN to training the set\n#There is no thumb rule to seelct two extra parameretes values\nclassifier.fit(X_train,y_train,batch_size=10,epochs=100)\n\n#Part 3 -Making the prediction and evaluting the model\n\n#Predicting teh Test set results\ny_pred = classifier.predict(X_test) #this returns the probabilites\ny_pred = (y_pred > 0.5) #If probability is graeter than 0.5 threshld then its True(Leave bank) \n\n#confusion matrix\nfrom sklearn.metrics import confusion_matrix\nmatrix = confusion_matrix(y_test,y_pred)\nprint(f\"confusion matrix: {matrix}\")\n\ninput = [[619],\t['France'],\t['Male'],\t[42],\t[2],\t[0.0],\t[1],\t[1],\t[1],\t[101348.88]]\n#input = [619,\t'France',\t'Female',\t42,\t2,\t0.0,\t1,\t1,\t1,\t101348.88]\ninput[1] = labelencoder_x_1.fit_transform(input[1])\ninput[2] = labelencoder_x_2.fit_transform(input[2])\n#input = list(Flatten(input))\nintput = [item for sublist in input for item in sublist]\ninput= onehotencoder_x.fit_transform(input).toarray()#Random prediction\n\n\n","sub_path":"UdemyPractice/18-DeepLearning/ANN/ArtificialNN.py","file_name":"ArtificialNN.py","file_ext":"py","file_size_in_byte":3815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"510345432","text":"from datetime import datetime\nimport os\n\nfrom configobj import ConfigObj\nimport pinhook.plugin\nfrom tvdb_api import Tvdb, tvdb_shownotfound\n\n\nt = Tvdb()\nconf_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tv.conf')\nconfig = ConfigObj(conf_file)\naliases = config[\"aliases\"]\n\n\ndef get_datekey(date):\n dkey = \"%Y-%m-%d\"\n datekey = datetime.strptime(date, dkey).strftime(\"%Y%m%d\")\n datekey = int(datekey)\n return datekey\n\n\ndef remove_bad_dates(show):\n eps = {}\n datelist = []\n if len(show) == 1:\n for e in range(len(show[1])):\n e += 1\n if show[1][e]['firstaired']:\n datekey = get_datekey(show[1][e]['firstaired'])\n eps[datekey] = (1, e)\n datelist.append(datekey)\n elif len(show) > 1:\n for s in range(len(show) + 1):\n s += 1\n try:\n for e in range(len(show[s])):\n e += 1\n if show[s][e]['firstaired']:\n datekey = get_datekey(show[s][e]['firstaired'])\n eps[datekey] = (s, e)\n datelist.append(datekey)\n except:\n pass\n datelist.sort()\n return (eps, datelist)\n\n\ndef next_ep(show, eps, datelist, today):\n scenario = 0\n for t in range(0, len(datelist)):\n if t != len(datelist) - 1:\n if datelist[t] > today:\n future = True\n else:\n future = False\n prev = datelist[t - 1] - today\n if prev > 0:\n prev_ep_in_future = True\n else:\n prev_ep_in_future = False\n if t == len(datelist) - 1:\n if datelist[t] > today:\n future = True\n else:\n future = False\n prev_ep_in_future = False\n\n if future and not prev_ep_in_future:\n s, e = eps[datelist[t]]\n scenario = 1\n break\n elif datelist[t] == today:\n s, e = eps[datelist[t]]\n scenario = 2\n break\n elif not future and not prev_ep_in_future:\n s, e = eps[datelist[t]]\n scenario = 3\n return s, e, scenario\n\n\ndef ep_marker(show, s, e):\n ep = show[s][e]\n if int(ep['seasonnumber']) < 10:\n snum = '0' + ep['seasonnumber']\n else:\n snum = ep['seasonnumber']\n if int(ep['episodenumber']) < 10:\n enum = '0' + ep['episodenumber']\n else:\n enum = ep['episodenumber']\n return 'S' + snum + 'E' + enum\n\n\ndef modify_alias(text):\n try:\n key, alias = text.split(\"=>\")\n key = key.strip().lower()\n alias = alias.strip().lower()\n except:\n return(\"An error occurred adding alias\")\n if key in aliases:\n aliases[key] = alias\n config.write()\n return(\"Successfully modified alias\")\n else:\n aliases[key] = alias\n config.write()\n return(\"Successfully added alias\")\n\n\ndef build_string(show, s, e, scen):\n ep = show[s][e]\n d = ep['firstaired']\n airdate = datetime.strptime(d, \"%Y-%m-%d\").strftime(\"%A, %m-%d-%Y\")\n oldair = datetime.strptime(d, \"%Y-%m-%d\").strftime(\"%m-%d-%Y\")\n status = show['status']\n sname = show['seriesname']\n airtime = show['airs_time']\n network = show['network']\n ename = ' \"' + ep['episodename'] + '\"'\n epmarker = ep_marker(show, s, e)\n if ep['imdb_id']:\n imdb = \"http://www.imdb.com/title/\" + ep['imdb_id'] + \"/\"\n else:\n imdb = \"http://www.imdb.com/title/\" + show['imdb_id'] + \"/\"\n\n if scen == 1:\n showstring = (sname + ' - Next Episode: ' + epmarker + ename +\n ' - Airs: ' + airdate + ' at ' + airtime +\n ' on ' + network + \" - \" + imdb)\n elif scen == 2:\n showstring = (sname + ' - Next Episode: ' + epmarker + ename +\n ' - Airs: Today, ' + airdate + ' at ' + airtime +\n ' on ' + network + \" - \" + imdb)\n elif scen == 3:\n if status == 'Ended':\n showstring = (sname + ' - Last Aired: ' + oldair +\n ' - Show has ended')\n else:\n showstring = (sname + ' - Last Aired: ' + epmarker + ename + \" on \" + airdate +\n ' - No new air dates have been announced')\n else:\n showstring = \"There was an error.\"\n return showstring\n\n\ndef next_up(text):\n message = ''\n try:\n if text.lower() in aliases:\n stext = aliases[text.lower()]\n else:\n stext = text\n show = t[stext]\n print(show[1].__dict__)\n sname = show['seriesname']\n today = int(datetime.now().strftime(\"%Y%m%d\"))\n eps, datelist = remove_bad_dates(show)\n s, e, scenario = next_ep(show, eps, datelist, today)\n showstring = build_string(show, s, e, scenario)\n message = showstring\n except tvdb_shownotfound:\n message = 'Cannot find show \"' + text + '\"'\n except Exception as e:\n message = e\n return message\n\n\ndef alias_show(text):\n return modify_alias(text)\n\n@pinhook.plugin.register('!tv')\n@pinhook.plugin.register('!tvalias')\ndef run(msg):\n if msg.cmd == '!tv':\n return pinhook.plugin.message(next_up(msg.arg))\n elif msg.cmd == '!tvalias':\n return pinhook.plugin.message(alias_show(msg.arg))\n\n","sub_path":"plugins/tv.py","file_name":"tv.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"4518974","text":"import pandas as pd\nimport os\nimport cx_Oracle\nimport pymysql\nimport configparser\nimport datetime as dt\nimport sys\n\n\n#%%\n# 建表:account,task,log\ndef CreateTable():\n db_nickname='sys'\n config = configparser.ConfigParser()\n config.read(os.path.join(os.getcwd(), 'config/dbconfig.conf'))\n uid = config.get(db_nickname, 'uid')\n pwd = config.get(db_nickname, 'pwd')\n host = config.get(db_nickname, 'ip')\n port = config.get(db_nickname, 'port')\n databasename=config.get(db_nickname, 'databasename')\n # service=config.get(databasename,'service')\n # 连接数据库\n tag = 0\n try:\n conn = pymysql.connect(host=host, port=int(port), user=uid, password=pwd, database=databasename, charset='utf8')\n print('连接数据库成功!')\n except Exception as e:\n print(e)\n return(tag)\n cur=conn.cursor()\n # 建用户表 todo 主键,三者分离\n tablename='account'\n sql='''create table %s.%s(\n accountid integer, -- 用户ID \n username varchar(20), -- 账户名\n passwd varchar(20), -- 账户密码\n identity varchar(20), -- 账户身份\n create_time timestamp\n );'''%(databasename,tablename)\n try:\n conn.begin()\n cur.execute(sql)\n conn.commit()\n print('建用户表成功!')\n except Exception as e:\n print(e)\n return(tag)\n # 建任务表\n tablename = 'task'\n sql = '''create table %s.%s(\n task_id integer, -- 任务ID\n task_name varchar(100), -- 任务名称\n project_name varchar(100), -- 项目名称\n model_name varchar(200), -- 模型名称\n ip varchar(50), -- 我方ip地址\n port_num varchar(50), -- 我方端口\n protocol varchar(50), -- 我方协议\n participant_name varchar(100), -- 参与方名称\n participant_ip varchar(50), -- 参与方ip\n participant_port varchar(50), -- 参与方端口\n participant_protocol varchar(50), -- 参与方协议\n dataset_info varchar(200), -- 我方数据集来源信息\n learning_algorithm varchar(50), -- 机器学习算法\n align varchar(50), -- 对齐方式,按照哪个字段对齐\n pretreatment varchar(50), -- 预处理方法概览\n -- encode varchar(50), -- 编码方式\n -- normalization varchar(50), -- 归一化方法\n -- cross_proportion varchar(50), -- 交叉验证比例\n train_proportion varchar(50), -- 训练验证测试集比例\n features varchar(1000), -- 使用的特征\n task_progress varchar(50), -- 任务进度:待审批训练、待加入训练、训练中、训练完、待审批预测、待加入预测、预测中、预测完\n display_location varchar(500), -- 展示结果保存位置\n auc double,\n ks double,\n psi double,\n result_file varchar(200), -- 结果文件保存位置\n result_data varchar(200), -- 数据库结果保存位置\n create_time varchar(200), -- 任务创建时间\n operation_time varchar(200) -- 任务最后操作时间\n );''' % (databasename, tablename)\n try:\n conn.begin()\n cur.execute(sql)\n conn.commit()\n print('建任务表成功!')\n except Exception as e:\n print(e)\n return (tag)\n # 建日志表\n tablename = 'log'\n sql = '''create table %s.%s(\n task_id integer, -- 任务ID\n task_name varchar(100), -- 任务名称\n model_name varchar(200), -- 模型名称\n task_progress varchar(50), -- 任务进度\n operation_time date -- 任务最后操作时间\n );''' % (databasename, tablename)\n try:\n conn.begin()\n cur.execute(sql)\n conn.commit()\n print('建日志表成功!')\n except Exception as e:\n print(e)\n return (tag)\n cur.close()\n conn.close()\n return tag\n\n\n# %%\n# 注册新账号\ndef Register(username,passwd,identity):\n db_nickname='sys'\n tablename='account'\n config = configparser.ConfigParser()\n config.read(os.path.join(os.getcwd(),'config/dbconfig.conf'))\n uid = config.get(db_nickname, 'uid')\n pwd = config.get(db_nickname, 'pwd')\n host = config.get(db_nickname, 'ip')\n port = config.get(db_nickname, 'port')\n databasename = config.get(db_nickname, 'databasename')\n # service=config.get(databasename,'service')\n # 连接数据库\n tag = 0\n try:\n conn = pymysql.connect(host=host, port=int(port), user=uid, password=pwd, database=databasename, charset='utf8')\n print('连接数据库成功!')\n except Exception as e:\n print(e)\n return(tag)\n cur = conn.cursor()\n # 读取当前表,判断用户是否已注册,并确定用户ID\n try:\n cur.execute('select * from %s.%s' % (databasename, tablename))\n user_list = [acc[1] for acc in cur.fetchall()]\n if username not in user_list:\n accountid = len(user_list)+1\n print('账户ID为:%d' % accountid) # todo 用户删除导致listbug\n else:\n print('账户已存在:%s' % username)\n return(tag)\n except Exception as e:\n print(e)\n return(tag)\n # 执行插入和更新\n create_time=dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n sql='insert into %s.%s (accountid,username,passwd,identity,create_time) values (%d,\\'%s\\',\\'%s\\',\\'%s\\',\\'%s\\');' \\\n % (databasename,tablename,accountid,username,passwd,identity,create_time)\n try:\n conn.begin()\n cur.execute(sql)\n conn.commit()\n tag=1\n print('新账户信息写入成功!')\n except Exception as e:\n conn.rollback()\n print(e)\n return(tag)\n cur.close()\n conn.close()\n return tag # 注册成功返回1,否则返回0\n\n","sub_path":"test/client/iAo/initialAndCreate.py","file_name":"initialAndCreate.py","file_ext":"py","file_size_in_byte":5655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"191960303","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport random\nimport pickle\nimport time\n# from Intersection import intersection\nfrom Jiin2 import intersection, checkIntersection\n\n\nclass RoadSegment:\n def __init__(self, backline, frontline, centerline, right_edge, left_edge, isarc=False, radius=0, angle=0, length=0):\n self.backline = backline # [left, center, right]\n self.frontline = frontline # [left, center, right]\n self.centerline = centerline # np.array([x_list, y_list])\n self.right_edge = right_edge # np.array([x_list, y_list])\n self.left_edge = left_edge # np.array([x_list, y_list])\n self.width = math.sqrt((backline[0,0] - backline[0,2])**2 + (backline[1,0] - backline[1,2])**2)\n self.npoints = centerline.shape[1]\n self.isarc = isarc\n self.radius = radius\n self.angle = angle\n self.length = length\n\n def getFront(self):\n return self.frontline\n\n def getBack(self):\n return self.backline\n\n def getCenter(self):\n return self.centerline\n\n def getRight(self):\n return self.right_edge\n\n def getLeft(self):\n return self.left_edge\n\n def drawPlot(self):\n plt.plot(self.backline[0], self.backline[1], color='black')\n plt.plot(self.frontline[0], self.frontline[1], color='black')\n plt.plot(self.left_edge[0], self.left_edge[1], color='black')\n plt.plot(self.right_edge[0], self.right_edge[1], color='black')\n plt.plot(self.centerline[0], self.centerline[1], color='black')\n # plt.plot(self.centerline[0], self.centerline[1], color='black', marker='o')\n\nclass Road:\n def __init__(self, inital_segment):\n self.segmentNumber = 1\n self.path = [inital_segment]\n self.NodeList = []\n self.NodeNum = 0\n\n def clean_NodeList(self):\n self.NodeList = []\n self.NodeNum = 0\n\n def add_NodeList(self, segment_idx):\n self.NodeList.append(segment_idx)\n self.NodeList.sort()\n self.NodeNum = self.NodeNum + 1\n\n def find_ceil_segment(self, segment_idx):\n ceil_idx = 0\n for seg_idx in self.NodeList:\n ceil_idx = seg_idx\n if (seg_idx > segment_idx):\n break\n return ceil_idx\n\n def lastSegment(self):\n return self.path[-1]\n\n def pushRoadSegment(self, new_segment):\n result = None\n if np.array_equal(self.path[-1].getFront(), new_segment.getBack()):\n # print('Successfully connected')\n self.path.append(new_segment)\n self.segmentNumber += 1\n result = self.path[:]\n #else:\n # print('Fail: This road segment cause gap')\n return result\n\n def popRoadSegment(self):\n if self.segmentNumber > 1:\n self.segmentNumber -= 1\n self.path.pop()\n return True\n return False\n \n\n def drawPlot(self):\n for i in range(self.segmentNumber):\n self.path[i].drawPlot()\n\n def getNpoints(self):\n return sum(list(map(lambda x: x.npoints, self.path))) - (self.segmentNumber-1)\n\n def getCenterline(self):\n total_points = sum(list(map(lambda x: x.npoints, self.path))) - (self.segmentNumber-1)\n result = np.zeros((2, total_points), dtype=np.float16)\n result[0, 0] = self.path[0].getCenter()[0,0]\n result[1, 0] = self.path[0].getCenter()[1,0]\n curr = 1\n for i in range(self.segmentNumber):\n curr_segment = self.path[i]\n for j in range(curr_segment.npoints-1):\n result[0, curr] = curr_segment.getCenter()[0, j+1]\n result[1, curr] = curr_segment.getCenter()[1, j+1]\n curr += 1\n return result\n\n def getRightEdge(self):\n total_points = sum(list(map(lambda x: x.npoints, self.path))) - (self.segmentNumber-1)\n result = np.zeros((2, total_points), dtype=np.float16)\n result[0, 0] = self.path[0].getRight()[0,0]\n result[1, 0] = self.path[0].getRight()[1,0]\n curr = 1\n for i in range(self.segmentNumber):\n curr_segment = self.path[i]\n for j in range(curr_segment.npoints-1):\n result[0, curr] = curr_segment.getRight()[0, j+1]\n result[1, curr] = curr_segment.getRight()[1, j+1]\n curr += 1\n return result\n\n def getLeftEdge(self):\n total_points = sum(list(map(lambda x: x.npoints, self.path))) - (self.segmentNumber-1)\n result = np.zeros((2, total_points), dtype=np.float16)\n result[0, 0] = self.path[0].getLeft()[0,0]\n result[1, 0] = self.path[0].getLeft()[1,0]\n curr = 1\n for i in range(self.segmentNumber):\n curr_segment = self.path[i]\n for j in range(curr_segment.npoints-1):\n result[0, curr] = curr_segment.getLeft()[0, j+1]\n result[1, curr] = curr_segment.getLeft()[1, j+1]\n curr += 1\n return result\n\nclass RoadNetwork:\n def __init__(self, x_size, y_size):\n self.roadNumber = 0\n self.roads = []\n self.mapsize = [x_size, y_size]\n self.waypoints = None\n self.path = []\n\n def addRoad(self, new_road):\n self.roads.append(new_road)\n self.roadNumber += 1\n return self.roads[:]\n\n def deleteLastRoad(self):\n self.roads.pop()\n self.roadNumber -= 1\n\n def drawPlot(self):\n for i in range(self.roadNumber):\n self.roads[i].drawPlot()\n\n def saveNetwork(self, path):\n with open(path, 'wb') as f:\n pickle.dump(self, f)\n f.close()\n return True\n\n def loadNetwork(self, path):\n with open(path, 'rb') as f:\n data = pickle.load(f)\n self.roadNumber = data.roadNumber\n self.roads = data.roads\n self.mapsize = data.mapsize\n self.waypoints = data.waypoints\n f.close()\n return True\n\n def getWayPoints(self):\n pass\n\ndef CreateStraigthRoadSegment(backline, length, orient):\n ''' If oreint is True, ratate 90 angle, else -90 angle'''\n angle = -90\n if orient == True:\n angle = 90\n\n ''' Get unit vector of backline '''\n v1 = backline[0][-1] - backline[0][0]\n v2 = backline[1][-1] - backline[1][0]\n vectorLen = math.sqrt(v1**2 + v2**2)\n unitVector = np.array([[v1/vectorLen, v2/vectorLen]], dtype=np.float16).T\n\n ''' Get orthogonal unit vector '''\n theta = np.radians(angle)\n c, s = np.cos(theta), np.sin(theta)\n orthogonal = np.array(((c, -s), (s, c)), dtype=np.float16)\n orthogonalVector = np.dot(orthogonal, unitVector)\n\n ''' Get frontline '''\n frontline = backline + orthogonalVector*length\n\n ''' Get left_edge, centerline, right_edge '''\n n = int(length)\n left_edge = np.zeros((2, n+1), dtype=np.float16)\n for i in range(n+1):\n left_edge[0, i] = backline[0, 0] + (length*i/n)*orthogonalVector[0, 0]\n left_edge[1, i] = backline[1, 0] + (length*i/n)*orthogonalVector[1, 0]\n\n centerline = np.zeros((2, n+1), dtype=np.float16)\n for i in range(n+1):\n centerline[0, i] = backline[0, 1] + (length*i/n)*orthogonalVector[0, 0]\n centerline[1, i] = backline[1, 1] + (length*i/n)*orthogonalVector[1, 0]\n\n right_edge = np.zeros((2, n+1), dtype=np.float16)\n for i in range(n+1):\n right_edge[0, i] = backline[0, 2] + (length*i/n)*orthogonalVector[0, 0]\n right_edge[1, i] = backline[1, 2] + (length*i/n)*orthogonalVector[1, 0]\n\n return RoadSegment(backline, frontline, centerline, right_edge, left_edge, False, 0 ,0, length)\n\ndef CreateArcRoadSegment(backline, radius, angle):\n theta = np.radians(angle)\n length = abs(theta*radius)\n road_width = np.linalg.norm(backline.T[2] - backline.T[1])\n n = max(2, int(length))\n theta_seg = theta/n\n c, s = np.cos(theta_seg), np.sin(theta_seg)\n ''' rotation matrix '''\n rotation = np.array(((c, -s), (s, c)))\n # generating inter-points\n left_edge = np.zeros((2, n), dtype=np.float16)\n centerline = np.zeros((2, n), dtype=np.float16)\n right_edge = np.zeros((2, n), dtype=np.float16)\n templine = backline\n left_edge[0, 0] = backline[0, 0]\n left_edge[1, 0] = backline[1, 0]\n centerline[0, 0] = backline[0, 1]\n centerline[1, 0] = backline[1, 1]\n right_edge[0, 0] = backline[0, 2]\n right_edge[1, 0] = backline[1, 2]\n for i in range(n-1):\n ''' translation matrix '''\n left_point = templine.T[0]\n center_point = templine.T[1]\n right_point = templine.T[2]\n width_vector = right_point - center_point\n # find center of arc\n if angle < 0:\n arc_point = center_point + width_vector * radius / road_width\n else:\n arc_point = center_point - width_vector * radius / road_width\n translation = np.matmul(np.identity(2) - rotation, arc_point)\n lp = np.matmul(rotation, left_point)+translation\n left_edge[0, i+1] = lp[0]\n left_edge[1, i+1] = lp[1]\n cp = np.matmul(rotation, center_point) + translation\n centerline[0, i+1] = cp[0]\n centerline[1, i+1] = cp[1]\n rp = np.matmul(rotation, right_point) + translation\n right_edge[0, i+1] = rp[0]\n right_edge[1, i+1] = rp[1]\n templine = np.concatenate([lp, cp, rp]).reshape(3,2).T\n frontline = templine\n return RoadSegment(backline, frontline, centerline, right_edge, left_edge, True, radius, angle)\n\ndef CreateRandomRoadSegment(backline, map_x, map_y):\n avg_map_size = (map_x + map_y)//2\n ''' Randomly select the road type - Straight road vs Arc road => percentage = 2: 1'''\n road_type = random.choice([0, 1])\n if road_type == 0:\n ''' Generate Straight Road '''\n length = random.randint(3, 6)*avg_map_size//100\n segment = CreateStraigthRoadSegment(backline, length, True)\n else:\n ''' Generate Arc Road '''\n angle_bound = [40, 60]\n width = math.sqrt((backline[0,0] - backline[0,1])**2 + (backline[1,0] - backline[1,1])**2)\n radius = random.uniform(7, 9)*width\n angle = random.choice([-1,1])*random.uniform(angle_bound[0], angle_bound[1])\n segment = CreateArcRoadSegment(backline, radius, angle)\n\n return segment\n\ndef CreateRandomRoad(map_x, map_y, width):\n ''' Get random start point from map size '''\n width = width/2\n map_size = [map_x, map_y]\n x_bound = [0, map_size[0]]\n y_bound = [0, map_size[1]]\n start_axis = random.choice([0, 1])\n start_point = [0, 0]\n if start_axis == 0:\n start_point = [random.uniform(width*2, map_size[0]-width*2), 0]\n backline = np.array(([start_point[0]-width, start_point[0], start_point[0]+width], [start_point[1], start_point[1], start_point[1]]), dtype=np.float16)\n else:\n start_point = [0, random.uniform(width*2, map_size[1]-width*2)]\n backline = np.array(([start_point[0], start_point[0], start_point[0]], [start_point[1]+width, start_point[1], start_point[1]-width]), dtype=np.float16)\n\n ''' Create first straight road segment '''\n start_len = map_size[start_axis]//20 # Len of first straight road = map size / 20 (5%)\n result_road = Road(CreateStraigthRoadSegment(backline, start_len, True))\n\n ''' Autonomously generate road segment until reach the edge of map '''\n backline = result_road.lastSegment().getFront()\n invalid_count = 0\n success = True\n while not checkOutOfMap(result_road, x_bound, y_bound):\n #print(backline)\n new_segment = CreateRandomRoadSegment(backline, map_x, map_y)\n result_road.pushRoadSegment(new_segment)\n\n ''' Check whether road is a valid road '''\n if not isValidRoad(result_road):\n # print('Invalid road segement')\n result_road.popRoadSegment() # remove last segment\n #result_road.popRoadSegment() # remove last segment\n #result_road.popRoadSegment() # remove last segment\n #result_road.popRoadSegment() # remove last segment\n #result_road.popRoadSegment() # remove last segment\n invalid_count += 1\n else:\n invalid_count = 0\n\n if invalid_count > 5:\n #print('Road Generation Failed')\n return False, None\n\n ''' Update the next backline'''\n backline = result_road.lastSegment().getFront()\n\n #print('Road Generation success')\n return success, result_road\n\ndef CreateRandomRoadNetwork(map_x, map_y, width):\n ''' Randomly choice the number of road in road network '''\n road_number = random.choice([2,3])\n #road_number = 1\n \n print(f'Generate {road_number} roads')\n result_network = RoadNetwork(map_x, map_y)\n i = 0\n while i < road_number:\n print(f'road {i}')\n start = time.time()\n sucess, new_road = CreateRandomRoad(map_x, map_y, width)\n exe_time = time.time() - start\n print(f'CreateRandomRoad time : {exe_time}')\n if sucess == False:\n continue\n road_len = new_road.getCenterline().shape[1]\n if road_len < (map_x + map_y)//3:\n #print('Too much short road')\n continue\n # ''' Check new road is valid '''\n # if not isValidRoad(new_road):\n # print(f'[{i}] Not valid road')\n # continue\n result_network.addRoad(new_road)\n\n ''' Check network is valid '''\n if not isValidNetworkLast(result_network):\n result_network.deleteLastRoad()\n continue\n i += 1\n #print('done')\n return result_network\n\ndef isValidRoad(road):\n return not checkSelfIntersect(road)\n\ndef checkSelfIntersect(road):\n for i in range(road.segmentNumber-1):\n curr_segment = road.path[i]\n curr_right, curr_left = curr_segment.getRight(), curr_segment.getLeft()\n for j in range(i+1, road.segmentNumber):\n target_segment = road.path[j]\n target_right, target_left = target_segment.getRight(), target_segment.getLeft()\n ''' Test right_edge & right_edge, left_edge & right_edge, right_edge & left_edge, left_edge & left_edge '''\n test_list = [(curr_right, target_right), (curr_left, target_right), (curr_right, target_left), (curr_left, target_left)]\n for test in test_list:\n ''' Check there are some intersection between two segments '''\n # intersects, _ = intersection(test[0][0, 1:], test[0][1, 1:], test[1][0, 1:], test[1][1, 1:])\n # if len(intersects) > 0:\n # return True\n if checkIntersection(test[0][0, 1:], test[0][1, 1:], test[1][0, 1:], test[1][1, 1:]):\n return True\n return False\n\ndef checkOutOfMap(road, x_bound, y_bound):\n last_segment = road.lastSegment()\n frontline = last_segment.getFront()\n result = False\n for i in range(3):\n if frontline[0, i] < x_bound[0] or frontline[0, i] > x_bound[1]:\n result = True\n break\n if frontline[1, i] < y_bound[0] or frontline[1, i] > y_bound[1]:\n result = True\n break\n return result\n\ndef isValidNetworkLast(road_network: RoadNetwork):\n print(\"isValidNetworkLast\")\n road_number = road_network.roadNumber\n ''' Road network that have only one road is valid '''\n if road_number < 2:\n return True\n intersect_count = 0\n start = time.time()\n for i in range(0, road_number-1):\n partial_result, intersects = checkPartialOverlap(road_network.roads[-1], road_network.roads[i])\n intersect_count += len(intersects[0])\n ''' if partial overlap, return False '''\n if partial_result:\n return False\n exe_time = time.time() - start\n print(f'isValidNetworkLast time : {exe_time}')\n #print(f'No intersect test: {intersect_count == 0}')\n ''' if partial overlap, return False '''\n if intersect_count == 0:\n return False\n return True\n\ndef isValidNetwork(road_network: RoadNetwork):\n print(\"isValidNetwork\")\n road_number = road_network.roadNumber\n ''' Road network that have only one road is valid '''\n if road_number < 2:\n return True\n for i in range(road_number):\n intersect_count = 0\n for j in range(road_number):\n if i == j:\n continue\n partial_result, intersects = checkPartialOverlap(road_network.roads[i], road_network.roads[j])\n intersect_count += len(intersects[0])\n ''' if partial overlap, return False '''\n if partial_result:\n return False\n #print(f'No intersect test: {intersect_count == 0}')\n ''' if partial overlap, return False '''\n if intersect_count == 0:\n return False\n return True\n\ndef checkPartialOverlap(road1, road2):\n ''' Get each road element (Left Edge, Center Line, Right Edge)'''\n road1_lines = [road1.getLeftEdge(), road1.getCenterline(), road1.getRightEdge()]\n road2_lines = [road2.getLeftEdge(), road2.getCenterline(), road2.getRightEdge()]\n\n intersects = [[], [], []]\n for r in range(3):\n road_len = road1_lines[r].shape[1]\n for i in range(road_len-1):\n for j in range(3):\n ''' Get intersection point between two line element '''\n curr_intersect = intersection(road1_lines[r][0, i:i+2], road1_lines[r][1, i:i+2], road2_lines[j][0, :], road2_lines[j][1, :])\n if len(curr_intersect[0]) > 0:\n if len(intersects[r]) > 0:\n road_type, prev_intersect = intersects[r][-1]\n try:\n ''' if detect the same intersection point, ignore it '''\n if road_type == j and getDistance(prev_intersect, curr_intersect) < 0.5:\n #print(f'invalid intersect [{i}] \\n{curr_intersect}')\n continue\n except:\n return True, [[], [], []]\n ''' Save (line type, intersection point) '''\n intersects[r].append((j, curr_intersect))\n break\n ''' Remain only line type '''\n for i in range(3):\n intersects[i] = list(map(lambda x: x[0], intersects[i]))\n\n #print(intersects)\n #print(f'Partial overlap test: {not (intersects[0] == intersects[1] and intersects[1] == intersects[2])}')\n\n ''' Determine whether partial overlap occur '''\n result = not (intersects[0] == intersects[1] and intersects[1] == intersects[2])\n return result, intersects\n\ndef getDistance(v1, v2):\n x1, y1 = v1[0], v1[1]\n x2, y2 = v2[0], v2[1]\n return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)\n","sub_path":"KDAsFault/Road.py","file_name":"Road.py","file_ext":"py","file_size_in_byte":18740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"10817931","text":"\"\"\"\nParser for the xliff translation format.\n\"\"\"\nfrom lxml import etree\nfrom translate.storage import xliff\n\nfrom pontoon.sync.exceptions import ParseError\nfrom pontoon.sync.formats.base import ParsedResource\nfrom pontoon.sync.vcs.models import VCSTranslation\n\n\nclass XLIFFEntity(VCSTranslation):\n \"\"\"\n Interface for modifying a single entity in an xliff file.\n \"\"\"\n\n def __init__(self, order, unit):\n self.order = order\n self.unit = unit\n self.strings = {None: self.target_string} if self.target_string else {}\n\n @property\n def key(self):\n return self.unit.getid()\n\n @property\n def context(self):\n return self.unit.xmlelement.get(\"id\") or \"\"\n\n @property\n def source_string(self):\n return str(self.unit.rich_source[0])\n\n @property\n def source_string_plural(self):\n return \"\"\n\n @property\n def comments(self):\n notes = self.unit.getnotes()\n return notes.split(\"\\n\") if notes else []\n\n @property\n def fuzzy(self):\n return False\n\n @fuzzy.setter\n def fuzzy(self, fuzzy):\n pass # We don't use fuzzy in XLIFF\n\n @property\n def source(self):\n return []\n\n @property\n def target_string(self):\n return str(self.unit.get_rich_target()[0])\n\n @target_string.setter\n def target_string(self, value):\n self.unit.settarget(value)\n\n def sync_changes(self):\n \"\"\"\n Apply any changes made to this object to the backing unit in the\n xliff file.\n \"\"\"\n if None in self.strings:\n self.target_string = self.strings[None]\n # Store updated nodes\n xml = self.unit.xmlelement\n target = xml.find(self.unit.namespaced(\"target\"))\n\n else:\n # Read stored nodes\n xml = self.unit.xmlelement\n target = xml.find(self.unit.namespaced(\"target\"))\n if target is not None:\n xml.remove(target)\n\n # Clear unused approved tag\n if \"approved\" in xml.attrib:\n del xml.attrib[\"approved\"]\n\n # Clear unused state tag\n if target is not None and \"state\" in target.attrib:\n del target.attrib[\"state\"]\n\n\nclass XLIFFResource(ParsedResource):\n def __init__(self, path, xliff_file):\n self.path = path\n self.xliff_file = xliff_file\n self.entities = [\n XLIFFEntity(order, unit) for order, unit in enumerate(self.xliff_file.units)\n ]\n\n @property\n def translations(self):\n return self.entities\n\n def save(self, locale):\n for entity in self.entities:\n entity.sync_changes()\n\n locale_code = locale.code\n\n # TODO: should be made iOS specific\n # Map locale codes for iOS: http://www.ibabbleon.com/iOS-Language-Codes-ISO-639.html\n locale_mapping = {\n \"bn-IN\": \"bn\",\n \"ga-IE\": \"ga\",\n \"nb-NO\": \"nb\",\n \"nn-NO\": \"nn\",\n \"sv-SE\": \"sv\",\n }\n\n if locale_code in locale_mapping:\n locale_code = locale_mapping[locale_code]\n\n # Set target-language if not set\n file_node = self.xliff_file.namespaced(\"file\")\n for node in self.xliff_file.document.getroot().iterchildren(file_node):\n if not node.get(\"target-language\"):\n node.set(\"target-language\", locale_code)\n\n with open(self.path, \"wb\") as f:\n f.write(bytes(self.xliff_file))\n\n\ndef parse(path, source_path=None, locale=None):\n with open(path) as f:\n xml = f.read().encode(\"utf-8\")\n\n try:\n xliff_file = xliff.xlifffile(xml)\n except etree.XMLSyntaxError as err:\n raise ParseError(f\"Failed to parse {path}: {err}\")\n\n return XLIFFResource(path, xliff_file)\n","sub_path":"pontoon/sync/formats/xliff.py","file_name":"xliff.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"241909716","text":"import torch\nimport torch.nn as nn\nfrom collections import OrderedDict\nfrom ptsemseg.utils import initialize_weights\n\nclass _DenseLayer(nn.Sequential):\n def __init__(self, num_input_features, growth_rate, bn_size, drop_rate):\n super(_DenseLayer, self).__init__()\n if bn_size is not None:\n self.add_module('norm.1', nn.BatchNorm2d(num_input_features))\n self.add_module('relu.1', nn.ReLU(inplace=True))\n self.add_module('conv.1', nn.Conv2d(num_input_features, bn_size *\n growth_rate, kernel_size=1, stride=1, bias=False))\n\n self.add_module('norm.2', nn.BatchNorm2d(bn_size * growth_rate))\n self.add_module('relu.2', nn.ReLU(inplace=True))\n self.add_module('conv.2', nn.Conv2d(bn_size * growth_rate, growth_rate,\n kernel_size=3, stride=1, padding=1, bias=False))\n else:\n self.add_module('norm.1', nn.BatchNorm2d(num_input_features))\n self.add_module('relu.1', nn.ReLU(inplace=True))\n self.add_module('conv.1', nn.Conv2d(num_input_features, growth_rate,\n kernel_size=3, stride=1, padding=1, bias=False))\n self.drop_rate = drop_rate\n\n def forward(self, x):\n new_features = super(_DenseLayer, self).forward(x)\n if self.drop_rate > 0:\n new_features = F.dropout(new_features, p=self.drop_rate, training=self.training)\n return torch.cat([x, new_features], 1)\n\nclass _TransitionDown(nn.Sequential):\n def __init__(self, num_input_features, num_output_features, drop_rate):\n super(_TransitionDown, self).__init__()\n self.add_module('norm', nn.BatchNorm2d(num_input_features))\n self.add_module('relu', nn.ReLU(inplace=True))\n self.add_module('conv', nn.Conv2d(num_input_features, num_output_features,\n kernel_size=1, stride=1, bias=False))\n self.add_module('dropout', nn.Dropout2d(p=drop_rate))\n self.add_module('pool', nn.MaxPool2d(kernel_size=2, stride=2))\n\nclass _TransitionUp(nn.Sequential):\n def __init__(self, num_input_features, num_output_features):\n super(_TransitionUp, self).__init__()\n self.add_module('norm', nn.BatchNorm2d(num_input_features))\n self.add_module('relu', nn.ReLU(inplace=True))\n self.add_module('upconv', nn.ConvTranspose2d(num_input_features, num_output_features,\n kernel_size=4, stride=2, bias=False))\n\nclass _DenseBlock(nn.Sequential):\n def __init__(self, num_layers, num_input_features, growth_rate, drop_rate, bn_size=None):\n super(_DenseBlock, self).__init__()\n for i in range(num_layers):\n layer = _DenseLayer(num_input_features + i * growth_rate, growth_rate, bn_size, drop_rate)\n self.add_module('denselayer%d' % (i + 1), layer)\n\nclass tiramisu(nn.Module):\n def __init__(self, n_classes, num_init_features, growth_rate, encoder_cf, bottleneck_cf, decoder_cf):\n super(tiramisu, self).__init__()\n\n encoder_cf_parts = encoder_cf.split('-')\n decoder_cf_parts = decoder_cf.split('-')\n\n encoder_cf = [int(x) for x in encoder_cf_parts]\n decoder_cf = [int(x) for x in decoder_cf_parts]\n\n compression = 1\n bn_size = 1\n drop_rate = 0.2\n num_features = num_init_features\n self.num_encoder_blocks = len(encoder_cf)\n self.growth_rate = growth_rate\n self.n_classes = n_classes\n\n #First convolution (our backbone is same as a pure densenet)\n self.features = nn.Sequential(OrderedDict([\n ('conv0', nn.Conv2d(3, num_features, kernel_size=3, stride=1, padding=1, bias=False)),\n ]))\n\n #Encoder denseblocks\n for i, num_layers in enumerate(encoder_cf):\n block = _DenseBlock(num_layers=num_layers,\n num_input_features=num_features,\n growth_rate=growth_rate,\n drop_rate=drop_rate,\n )\n self.features.add_module('denseblock%d' % (i + 1), block)\n num_features = num_features + num_layers * growth_rate\n# if i != len(encoder_cf) - 1:\n block = _TransitionDown(num_input_features=num_features,\n num_output_features=int(num_features * compression), drop_rate=drop_rate)\n self.features.add_module('transition-down%d' % (i + 1), block)\n num_features = int(num_features * compression)\n\n #Bottleneck in the middle\n block = _DenseBlock(num_layers=bottleneck_cf,\n num_input_features=num_features,\n growth_rate=growth_rate,\n drop_rate=drop_rate)\n self.features.add_module('bottleneck', block)\n\n num_features = bottleneck_cf * growth_rate\n\n #The first transposed convolution\n block = _TransitionUp(num_input_features=num_features,\n num_output_features=num_features)\n self.features.add_module('transition-up1', block)\n\n total = 0\n sums = []\n for v in encoder_cf:\n total+=v\n sums.append(total)\n num_features_shortcuts = [num_init_features + x * growth_rate for x in sums]\n num_features_shortcuts = num_features_shortcuts[::-1]\n temp = [bottleneck_cf] + decoder_cf\n temp = temp[:-1]\n num_features_from_below = [x * growth_rate for x in temp]\n\n #number of layers to be fed to each layer in decoder\n num_features_dec = [sum(x) for x in zip(num_features_shortcuts, num_features_from_below)]\n num_features_from_below = num_features_from_below[1:]\n\n #Decoder denseblocks\n for i, num_layers in enumerate(decoder_cf):\n block = _DenseBlock(num_layers=num_layers,\n num_input_features=num_features_dec[i],\n growth_rate=growth_rate,\n drop_rate=drop_rate)\n self.features.add_module('denseblock-up%d' % (i + 1), block)\n if i != len(decoder_cf) - 1:\n block = _TransitionUp(num_input_features=num_features_from_below[i],\n num_output_features=num_features_from_below[i])\n self.features.add_module('transition-up%d' % (i + 2), block)\n filters = num_features_from_below[-1] + num_features_shortcuts[-1] + decoder_cf[-1] * growth_rate\n block = nn.Conv2d(filters, n_classes, 1)\n self.features.add_module('predictionlayer', block)\n initialize_weights(self.features)\n\n def forward(self, x):\n x = self.features[0](x) # Very first convolution\n\n keep_shortcuts = []\n\n x = self.features[1](x) # Denseblock-down1\n keep_shortcuts.append(x)\n x = self.features[2](x) # Transition-down1\n\n x = self.features[3](x) # Denseblock-down2\n keep_shortcuts.append(x)\n x = self.features[4](x) # Transition-down2\n\n x = self.features[5](x) # Denseblock-down3\n keep_shortcuts.append(x)\n x = self.features[6](x) # Transition-down3\n\n x = self.features[7](x) # Denseblock-down4\n keep_shortcuts.append(x)\n x = self.features[8](x) # Transition-down4\n\n x = self.features[9](x) # Denseblock-down5\n keep_shortcuts.append(x)\n x = self.features[10](x) # Transition-down5\n\n keep_shortcuts = keep_shortcuts[::-1]\n\n keep = []\n for name, layer in self.features[11].named_children():\n x = layer(x)\n keep.append(x.narrow(1,0, self.growth_rate))\n\n x = self.features[12](torch.cat(keep,1)) # Transition-up1\n x = torch.cat((x[:,:,1:-1,1:-1], keep_shortcuts[0]),1)\n\n del keep[:]\n for name, layer in self.features[13].named_children():\n x = layer(x)\n keep.append(x.narrow(1,0, self.growth_rate))\n\n x = self.features[14](torch.cat(keep,1)) # Transition-up2)\n x = torch.cat((x[:,:,1:-1,1:-1], keep_shortcuts[1]),1)\n\n del keep[:]\n for name, layer in self.features[15].named_children():\n x = layer(x)\n keep.append(x.narrow(1,0, self.growth_rate))\n\n x = self.features[16](torch.cat(keep,1)) # Transition-up3\n x = torch.cat((x[:,:,1:-1,1:-1], keep_shortcuts[2]),1)\n\n del keep[:]\n for name, layer in self.features[17].named_children():\n x = layer(x)\n keep.append(x.narrow(1,0, self.growth_rate))\n\n x = self.features[18](torch.cat(keep,1)) # Transition-up4\n x = torch.cat((x[:,:,1:-1,1:-1], keep_shortcuts[3]),1)\n\n del keep[:]\n for name, layer in self.features[19].named_children():\n x = layer(x)\n keep.append(x.narrow(1,0, self.growth_rate))\n\n x = self.features[20](torch.cat(keep,1)) # Transition-up5\n x = torch.cat((x[:,:,1:-1,1:-1], keep_shortcuts[4]),1)\n x = self.features[21](x)\n x = self.features[22](x) # Final layer 1x1 conv\n\n #x = x.permute(0, 2, 3, 1).contiguous().view(-1, self.n_classes)\n\n# out = nn.functional.log_softmax(x)\n out = x\n return out\n","sub_path":"ptsemseg/models/tiramisu.py","file_name":"tiramisu.py","file_ext":"py","file_size_in_byte":9298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"89696760","text":"from otree.api import Currency as c, currency_range\nfrom ._builtin import Page, WaitPage\nfrom .models import Constants\n\n\nclass Smoker(Page):\n form_model = 'player'\n form_fields = [\n 'sm_1',\n 'sm_2',\n 'sm_2_op',\n 'sm_3_times',\n 'sm_3_mins',\n 'sm_3_1_1',\n 'sm_3_1_2',\n 'sm_4_1',\n 'sm_4_2',\n 'sm_4_3_years',\n 'sm_4_3_months',\n 'sm_4_3_days',\n 'sm_4_4',\n 'sm_4_4_op',\n 'sm_4_5',\n 'sm_4_6',\n 'sm_4_6_op',\n 'sm_5_1',\n 'sm_5_2',\n 'sm_5_3',\n 'sm_5_4',\n 'sm_5_5',\n 'sm_5_6',\n # 'sm_6_1_1',\n # 'sm_6_1_2',\n 'sm_6_2_1',\n 'sm_6_2_2',\n 'sm_6_2_3',\n 'sm_6_3',\n # 'sm_transfer_will',\n # 'sm_transfer_will_yn',\n # 'sm_transfer_will_alt',\n # 'sm_transfer_will_alt_yn',\n ]\n\npage_sequence = [Smoker]\n","sub_path":"smoker/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"645400825","text":"import json\nimport os\n\nfrom mongoengine import EmbeddedDocument\nfrom mongoengine import Document\nfrom mongoengine import StringField, EmbeddedDocumentListField\nfrom .scenario import Scenario\nfrom .result import Result\n\n\nclass TestSuite(Document):\n name = StringField(max_length=128, required=True)\n scenarios = EmbeddedDocumentListField(Scenario)\n\n def run(self):\n data = []\n result = True\n for scenario in self.scenarios:\n scenario.run()\n result = scenario.result.result\n if result is False:\n data.append(scenario.result.data)\n\n if data:\n result = False\n\n response_result = Result(result=result, data=data)\n return response_result\n\n def from_folder(self, directory):\n file_names = os.listdir(directory)\n\n for file_name in file_names:\n file_path = os.path.join(directory, file_name)\n with open(file_path, \"r\") as file:\n scenario = Scenario.from_json(file.read())\n self.scenarios.append(scenario)\n\n\n","sub_path":"TestingTool/testsuite.py","file_name":"testsuite.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"366332641","text":"# -*- coding: utf-8 -*-\n#\n# XChat-DeaDBeeF - XChat/HexChat script for DeaDBeeF integration\n# Python 3 version\n#\n# Unless indicated otherwise, files from the XChat-DeaDBeeF project\n# are licensed under the WTFPL version 2. Full license information\n# for the WTFPL version 2 can be found in the LICENSE.txt file.\n#\n\n__module_name__ = \"XChat-DeaDBeeF\"\n__module_author__ = \"iceTwy\"\n__module_description__ = \"DeaDBeeF integration in XChat and HexChat.\"\n__module_version__ = \"1.0.1\"\n\nimport xchat\nimport subprocess\nfrom threading import Thread\nfrom time import sleep\n\ndef execute_db():\n print(\"DeaDBeeF launched.\")\n calldb = subprocess.call(\"deadbeef\")\n if calldb == 0 or calldb == 1:\n print(\"DeaDBeeF closed.\")\n\ndef exit_db_user(word, word_eol, userdata):\n check_pid = subprocess.call([\"pgrep\", \"-f\", \"deadbeef\"])\n if check_pid == 1:\n print(\"DeaDBeeF isn't running.\")\n else:\n db_pid = subprocess.check_output([\"pgrep\", \"-f\", \"deadbeef\"])\n exit_db = subprocess.call([\"kill\", str(db_pid).strip('\\n')])\n\n return xchat.EAT_ALL\n\ndef call_db_user(word, word_eol, userdata):\n db_pid = subprocess.call([\"pgrep\", \"-f\", \"deadbeef\"])\n if db_pid == 1:\n calldb_user_thread = Thread(target=execute_db)\n calldb_user_thread.start()\n else:\n print(\"DeaDBeeF is already running.\")\n\n return xchat.EAT_ALL\n\ndef is_db_running():\n check_db_pid = subprocess.call([\"pgrep\", \"-f\", \"deadbeef\"])\n if check_db_pid == 1:\n print(\"DeaDBeeF is not running. Launching...\")\n call_db_thread = Thread(target=execute_db)\n call_db_thread.start()\n\ndef is_track_loaded():\n np_track = subprocess.check_output([\"deadbeef\", \"--nowplaying\", \"%e\"])\n if \"nothing\" in str(np_track):\n print(\"Track loaded!\")\n else:\n print(\"Track resumed/reset!\")\n\ndef track_info_script():\n track = subprocess.check_output([\"deadbeef\", \"--nowplaying\", \"%t by %a\"])\n print(\"You're listening to: {}\".format(str(track)))\n\ndef track_info_user(word, word_eol, userdata):\n track = subprocess.check_output([\"deadbeef\", \"--nowplaying\", \"%t by %a // %@:BITRATE@kbps\"])\n print(\"You're listening to: {}\".format(str(track)))\n\n return xchat.EAT_ALL\n\ndef db_current_track(word, word_eol, userdata):\n is_db_running()\n track = subprocess.check_output([\"deadbeef\", \"--nowplaying\", \"%t by %a\"])\n xchat.command(\"me is listening to: {}\".format(str(track)))\n\n return xchat.EAT_ALL\n\ndef db_next_track(word, word_eol, userdata):\n is_db_running()\n next_track = subprocess.call([\"deadbeef\", \"--next\"])\n print(\"Next track loaded!\")\n sleep(0.05) # Give some time to DeaDBeeF to update accurately\n track_info_script()\n\n return xchat.EAT_ALL\n\ndef db_previous_track(word, word_eol, userdata):\n is_db_running()\n prev_track = subprocess.call([\"deadbeef\", \"--prev\"])\n print(\"Previous track loaded!\")\n sleep(0.05) # Give some time to DeaDBeeF to update accurately\n track_info_script()\n\n return xchat.EAT_ALL\n\ndef db_play_track(word, word_eol, userdata):\n is_db_running()\n is_track_loaded()\n play_track = subprocess.call([\"deadbeef\", \"--play\"])\n sleep(0.05) # Give some time to DeaDBeeF to update accurately\n track_info_script()\n\n return xchat.EAT_ALL\n\ndef db_pause_track(word, word_eol, userdata):\n is_db_running()\n pause_track = subprocess.call([\"deadbeef\", \"--pause\"])\n track_time = subprocess.check_output([\"deadbeef\", \"--nowplaying\", \"%e/%l\"])\n print(\"Current track paused at {}.\".format(str(track_time)))\n\n return xchat.EAT_ALL\n\ndef db_stop_track(word, word_eol, userdata):\n is_db_running()\n stop_track = subprocess.call([\"deadbeef\", \"--stop\"])\n print(\"Current track stopped!\")\n\n return xchat.EAT_ALL\n\ndef unload(userdata):\n print(\"XChat-DeaDBeeF {} unloaded!\".format(__module_version__))\n\n return xchat.EAT_ALL\n\nif __name__ == '__main__':\n print(\"XChat-DeaDBeeF {} loaded successfully! - by {}\".format(__module_version__,__module_author__))\n print(\"Protip: using /dbplay when the track is playing resets the track.\")\n\n #Launch/close DeaDBeeF\n xchat.hook_command('deadbeef',call_db_user) #=> execute_db() in a new thread.\n xchat.hook_command('dbexit',exit_db_user)\n\n #Display the current track\n xchat.hook_command('dbshow',track_info_user)\n xchat.hook_command('np',db_current_track)\n\n #Play, pause, stop track\n xchat.hook_command('dbplay',db_play_track)\n xchat.hook_command('dbpause',db_pause_track)\n xchat.hook_command('dbstop',db_stop_track)\n\n #Skip to next or previous track\n xchat.hook_command('dbnext',db_next_track)\n xchat.hook_command('dbprev',db_previous_track)\n\n #Unload XChat-DeaDBeeF\n xchat.hook_unload(unload)\n\n","sub_path":"python2/XChat-DeaDBeeF.py","file_name":"XChat-DeaDBeeF.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"354003657","text":"# -*- coding: utf-8 -*-\r\n# python中的类属性和实例属性 https://www.cnblogs.com/scolia/p/5582268.html\r\n# 属性就是属于一个对象的数据或者函数,我们可以通过句点(.)来访问属性,同时 python 还支持在运作中添加和修改属性。\r\n# 而数据变量,类似于: name = 'scolia' 这样的形式,会称其为字段;\r\n# 而类里面的函数,又称为方法。\r\n# 而方法又分为实例方法,类方法和静态方法\r\nclass Test(object):\r\n name = 'scolia'\r\n\r\n\r\ndef normal():\r\n a = Test()\r\n print(Test.name) # 通过类进行访问\r\n print(a.name) # 通过实例进行访问\r\n\r\n\r\n# 通过类进行修改\r\ndef modify_prop1():\r\n a = Test()\r\n Test.name = 'scolia good' # 通过类进行修改\r\n print(Test.name)\r\n print(a.name)\r\n\r\n\r\n# 通过实例进行修改\r\ndef modify_prop2():\r\n a = Test()\r\n a.name = 'scolia good' # 通过实例进行修改\r\n print(Test.name)\r\n print(a.name)\r\n\r\n\r\n# 函数 dir() 就能查看对象的属性\r\ndef list_prop():\r\n a = Test()\r\n a.abc = 123\r\n print(dir(Test))\r\n print(dir(a))\r\n\r\n\r\nif __name__ == '__main__':\r\n print(\"------normal-----\")\r\n normal()\r\n print(\"------modify_prop1-----\")\r\n modify_prop1()\r\n print(\"------modify_prop2-----\")\r\n modify_prop2()\r\n print(\"------list_prop-----\")\r\n list_prop()\r\n","sub_path":"src/8/creating_a_new_kind_of_class_or_instance_attribute/attribute_ex1.py","file_name":"attribute_ex1.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"161614496","text":"from layer import Layer\nfrom math import exp, sqrt\n\nLEARNING_RATE = 0.01\nNO_LABELS = 3\n\n\nclass Network:\n def __init__(self, noInputs, hiddens, noOutputs):\n self.__noInputs = noInputs\n self.__noOutputs = noOutputs\n self.__noHL = len(hiddens)\n layers = [Layer(noInputs, 1)] # input layer\n layers += [Layer(hiddens[0], noInputs)] # first hidden layer\n for i in range(1, self.__noHL): # additional hidden layers\n layers.append(Layer(hiddens[i], hiddens[i - 1]))\n layers.append(Layer(noOutputs, hiddens[-1])) # output layer\n self.__layers = layers\n\n def activate(self, input):\n for i in range(self.__noInputs):\n self.__layers[0].neurons[i].output = input[i]\n for l in range(1, self.__noHL + 2):\n for n in self.__layers[l].neurons:\n info = [self.__layers[l - 1].neurons[i].output for i in range(self.__layers[l - 1].noNeurons)]\n n.activate(info)\n\n def backPropagate(self, error):\n for l in range(self.__noHL + 1, 0, -1):\n i = 0\n for n1 in self.__layers[l].neurons:\n if l == self.__noHL + 1:\n n1.setErrorLin(-n1.output + error[i])\n else:\n sumError = 0.0\n for n2 in self.__layers[l + 1].neurons:\n sumError += n2.weights[i] * n2.error\n n1.setErrorSig(sumError)\n for j in range(len(n1.weights)):\n netWeight = n1.weights[j] + LEARNING_RATE * n1.error * self.__layers[l - 1].neurons[j].output\n n1.setWeight(j, netWeight)\n i += 1\n\n def errorComputeClass(self, target, noLabels):\n aux = [n.output for n in self.__layers[self.__noHL + 1].neurons]\n m = max(aux)\n aux = [exp(x - m) for x in aux]\n s = sum(aux)\n transfOutput = [x / s for x in aux]\n m = transfOutput[0]\n computeLabel = 1\n for i in range(noLabels):\n if transfOutput[i] > m:\n m = transfOutput[i]\n computeLabel = i + 1\n if target == computeLabel:\n return 0\n else:\n return 1\n\n def checkGlobalError(self, error):\n errors = sum(error)\n error = errors / len(error)\n if error < 0.05:\n return True\n return False\n\n def learn(self, inData, outData, epochLimit):\n stop = False\n epoch = 0\n errors = []\n while not stop and epoch < epochLimit:\n globalError = []\n for d in range(len(inData)):\n self.activate(inData[d])\n err = [0 for _ in range(self.__noOutputs)]\n err[outData[d] - 1] = 1\n globalError.append(self.errorComputeClass(outData[d], NO_LABELS))\n self.backPropagate(err)\n errors += [sum(globalError)]\n epoch += 1\n return errors\n\n def getLayers(self):\n return self.__layers\n\n def normalizeData(self, n, noLabels, data):\n for j in range(noLabels):\n summ = 0.0\n for i in range(n):\n summ += data[i][j]\n mean = summ / n\n squareSum = 0.0\n for i in range(n):\n squareSum += (data[i][j] - mean) ** 2\n deviation = sqrt(squareSum / n)\n for i in range(n):\n data[i][j] = (data[i][j] - mean) / deviation\n","sub_path":"Classification/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"361602469","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\n\r\n# 模版匹配\r\ndef template_image():\r\n tpl = cv.imread(\"C://bg1.jpg\")\r\n target = cv.imread(\"C://bg.jpg\")\r\n cv.imshow(\"模板\", tpl)\r\n cv.imshow(\"原图\", target)\r\n methods = [cv.TM_SQDIFF_NORMED, cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED]\r\n th, tw = tpl.shape[:2]\r\n for md in methods:\r\n print(md)\r\n result = cv.matchTemplate(target, tpl, md)\r\n min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)\r\n if md == cv.TM_SQDIFF_NORMED:\r\n tl = min_loc\r\n else:\r\n tl = max_loc\r\n br = (tl[0] + tw, tl[1] + th)\r\n cv.rectangle(target, tl, br, (0, 0, 255), 2)\r\n cv.imshow(\"匹配\" + np.str(md), target)\r\n # cv.imshow(\"匹配\" + np.str(md), result)\r\n\r\n\r\n\r\ntemplate_image()\r\ncv.waitKey(0)\r\ncv.destroyAllWindows()\r\n\r\n","sub_path":"OpenCV学习/10.1.py","file_name":"10.1.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"553582205","text":"from . import views\nfrom django.urls import path\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('shop_login/', views.shop_login, name='shop_login'),\n path('admin_login/', views.admin_login, name='admin_login'),\n path('login/', views.user_login, name='user_login'),\n path('logout/', views.logout_view, name='user_logout'),\n path('admin_dashboard/', views.admin_dashboard, name='admin_dashboard'),\n path('tenant_dashboard/', views.tenant_dashboard, name='tenant_dashboard'),\n]","sub_path":"portal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"123048323","text":"import serial\nimport socketio\nimport asyncio\nfrom dataclasses import dataclass\nfrom .area.game_areas import GameArea\nfrom .area.area_methods import inside_area_effect, distance_to_border\n\n\n\"\"\"\nGeneral:\n - Python version 3.7\n - Socketio version 4.6.1\n - use python-socketio's async client for the communication:\n https://python-socketio.readthedocs.io/en/latest/api.html#asyncclient-class\n https://github.com/miguelgrinberg/python-socketio\n -pyserial\n (if i2c is better use that)\n https://github.com/pyserial/pyserial-asyncio\n -Shapely 1.7\n\"\"\"\n\n\n@dataclass\nclass GPSData:\n \"\"\"Represents data form the sensors\n\n Can include also speed, acceleration, angles etc.\n This is just for position\n \"\"\"\n\n lon: float\n lat: float\n alt: float\n\n\nclass GPSSocket:\n\n sio = socketio.AsyncClient()\n\n def __init__(self, url, robot_id, game_id):\n self.url = url\n self.robot_id = robot_id\n self.game_id = game_id\n self.game_areas = []\n\n @sio.event(namespace=\"/robot\")\n def boundary_data(self, data):\n # if area id exists, update\n print(\"Received single data: \", data)\n for area in self.game_areas:\n if area.area_id == data[\"uuid\"]:\n print(\"Override old area: \", area.area_id)\n self.game_areas.remove(area)\n self.game_areas.append(GameArea(data))\n\n @sio.event(namespace=\"/robot\")\n def all_boundary_data(self, data):\n print(\"Received data: \", data)\n for area in data:\n self.game_areas.append(GameArea(area))\n\n @sio.event(namespace=\"/robot\")\n def remove_boundary(self, id):\n for area in self.game_areas:\n if area.area_id == id:\n print(\n \"Remove area: \", area.area_id, \" and label: \", area.label\n )\n self.game_areas.remove(area)\n break\n\n # Not used\n @sio.event(namespace=\"/robot\")\n def distance_to_area(self, id):\n for area in self.game_areas:\n if area.area_id == id:\n print(\"Distance to area!\")\n dist = distance_to_border(area, self.latest_loc)\n self.sio.emit(\"distance_to_area\", dist, namespace=\"/robot\")\n break\n\n # Not used\n @sio.event(namespace=\"/robot\")\n def inside_area(self, id):\n for area in self.game_areas:\n if area.area_id == id:\n print(\"Inside an area!\")\n effect = inside_area_effect(area, self.latest_loc)\n self.sio.emit(\"inside_area\", effect, namespace=\"/robot\")\n break\n\n def get_query_url(self, url):\n self.url += f\"?token={self.token}\"\n\n async def send_data(self, data):\n x = {\n \"robot_id\": self.robot_id,\n \"alt\": data.alt,\n \"long\": data.lon,\n \"lat\": data.lat,\n }\n await self.sio.emit(\"location_data\", x, namespace=\"/robot\")\n\n async def connect(self):\n # Link the handler to the GPSSocket class, allows the use of 'self'\n self.sio.on(\"boundary_data\", self.boundary_data, namespace=\"/robot\")\n self.sio.on(\n \"all_boundary_data\", self.all_boundary_data, namespace=\"/robot\"\n )\n self.sio.on(\n \"remove_boundary\", self.remove_boundary, namespace=\"/robot\"\n )\n self.sio.on(\n \"distance_to_area\", self.distance_to_area, namespace=\"/robot\"\n )\n self.sio.on(\"inside_area\", self.inside_area, namespace=\"/robot\")\n\n # For testing locally\n if \"localhost\" not in self.url:\n self.get_query_url(self.url)\n\n await self.sio.connect(self.url, namespaces=[\"/robot\"])\n\n async def disconnect(self):\n await self.sio.disconnect()\n\n\nclass GPSSensor:\n \"\"\"Do not implement __init__, as this is more convenient for the users\"\"\"\n\n testing = False\n gps_fix_lost = False\n num_of_errors = 0\n latest_loc = GPSData(1000, 1000, 1000)\n\n async def connect(self, pins=\"SOME_DEFAULT_PINS\"):\n \"\"\"Connect and start polling data from the sensor to on_location method\n\n Any required parameters can be passed to __init__ also (pins, etc.).\n Optionally allow specifying the polling rate to some appropriate value\n\n \"\"\"\n\n self.ser = serial.Serial(\n port=\"/dev/ttyS0\",\n baudrate=9600,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS,\n timeout=1,\n )\n\n def get_data(self):\n \"\"\"Returns a GPSData object\n\n After connect, this method should be called\n according to the polling rate (can be async def if needed)\n \"\"\"\n if self.testing:\n return GPSData(5, 15, -10000)\n\n while True:\n # TEST what happens when you remove gps module during game.\n gpsData = str(self.ser.readline())\n if len(gpsData) < 5:\n print(\"GPS Problem\")\n raise RuntimeError(\"GPS Problem\")\n if \"$GPGGA\" in gpsData:\n try:\n\n \"\"\"Parse the data from the sensor and convert the elements\n to a correct format\"\"\"\n gpsList = gpsData.split(\",\")\n\n latitude = gpsList[2]\n latChar = gpsList[3]\n degreeLat = int(float(latitude) / 100)\n secondLat = float(latitude) - degreeLat * 100\n latDec = degreeLat + secondLat / 60\n if latChar == \"S\":\n latDec = -latDec\n\n longitude = gpsList[4]\n longChar = gpsList[5]\n degreeLong = int(float(longitude) / 100)\n secondLong = float(longitude) - degreeLong * 100\n longDec = degreeLong + secondLong / 60\n if longChar == \"W\":\n longDec = -longDec\n\n alt = gpsList[9]\n self.latest_loc = GPSData(latDec, longDec, alt)\n self.num_of_errors = 0\n\n return GPSData(latDec, longDec, alt)\n except (ValueError, IndexError):\n self.num_of_errors += 1\n if self.num_of_errors < 5 and self.latest_loc:\n return self.latest_loc\n else:\n return GPSData(1000, 1000, 1000)\n\n async def on_data(self, data):\n \"\"\"Users should override this method to keep up with changes\n\n For example they could pass the GPSData to GPSArea.in_valid_area\n \"\"\"\n pass\n\n async def disconnect(self):\n \"\"\"Stop polling, connections, release resources\"\"\"\n pass\n\n\nif __name__ == \"__main__\":\n # Example usage:\n\n # create custom gps sensor\n class MyGPSSensor(GPSSensor):\n def __init__(self, socket):\n self.socket = socket\n\n async def pre_run(self):\n self.testing = True\n await self.socket.connect()\n\n async def post_run(self):\n await self.socket.disconnect()\n\n async def run(self, polling_rate):\n await self.pre_run()\n while True:\n loc = self.get_data()\n await self.socket.send_data(loc)\n await asyncio.sleep(polling_rate)\n\n async def main():\n print(\"running\")\n # Create SocketIO and GPSSensor\n # \"http://localhost:9090\"\n\n socket = GPSSocket(\"https://gps.surrogate.tv:3002\", 123456, \"0\")\n gps_sensor = MyGPSSensor(socket)\n\n # Create new task and add it to the event loop\n event_loop = asyncio.get_event_loop()\n event_loop.create_task(gps_sensor.run(1))\n\n # get GPS updates for 30s according to the set polling rate\n await asyncio.sleep(10)\n await gps_sensor.post_run()\n print(\"main loop ended\")\n\n await gps_sensor.disconnect()\n\n asyncio.run(main())\n","sub_path":"games/gps_car/gps.py","file_name":"gps.py","file_ext":"py","file_size_in_byte":7996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"602420122","text":"import httpx\nimport bs4 as soup\nimport googlesearch as google\nfrom typing import Set\nimport sys\nimport json\nimport logging\nimport aiosqlite\nimport datetime\nimport asyncio\n\n\nwith open(\"deadlinks.csv\", \"w\") as f:\n f.write(\"\")\n\nlogging.basicConfig(level=logging.WARN, format=\"%(levelname)-8s %(message)s\", handlers=[\n logging.StreamHandler(sys.stdout),\n logging.FileHandler(\"deadlinks.csv\")])\n\n\ndef get_base_url(url: str) -> str:\n return \"/\".join(url.split(\"/\")[:3])\n\n\nasync def google_domain_search(domain: str) -> Set[str]:\n print(f\"Expanding {domain}\")\n result = set((get_base_url(i) for i in google.search(\n f\"site:{domain}\", tld=\"no\", lang=\"no\", pause=5) if domain in i))\n return result\n\n\ndef handle_url(url: str, current) -> (str, str):\n https = 's' if \"https\" in str(current.url) else ''\n\n if url.startswith(\"http\"):\n if https:\n return (url, url.replace(\"s\", '', 1))\n else:\n return (url[:4] + 's' + url[4:], url)\n\n elif url.startswith(\"#\"):\n output = (str(current.url) + url,\n str(current.url).replace('s', '', 1) + url)\n if str(current.url)[4].lower() == 's':\n return output\n else:\n return (output[1], output[0])\n\n elif url.startswith(\"//\"):\n return (\"https:\" + url, \"http:\" + url)\n elif url.startswith(\"/\"):\n return (\"https://\" + current.url.host + url, \"http://\" + current.url.host + url)\n else:\n return (\"https://\" + current.url.host + \"/\" + url, \"http://\" + current.url.host + \"/\" + url)\n\n\nasync def search_domain(domain: str, visited: Set[str], database_queue) -> None:\n async with httpx.AsyncClient(timeout=30) as client:\n try:\n resp = await client.get(\"https://\" + domain)\n except httpx.ConnectError as e:\n print(f\"Got an ssl error in {domain}\")\n return\n except Exception:\n try:\n resp = await client.get(\"http://\" + domain)\n except httpx.ConnectError as e:\n print(f\"Got a connection error in {domain}\")\n return\n else:\n await database_queue.put((str(resp.url), resp.url.host, str(resp.url), \"557\", str(datetime.datetime.today())))\n\n to_search = set([resp])\n while to_search:\n current = to_search.pop()\n\n if not current.url.host.endswith(domain):\n continue\n if str(current.url) in visited:\n continue\n visited.add(str(current.url))\n\n # Get all the URLs in the current page\n try:\n text = soup.BeautifulSoup(current.text, \"html.parser\")\n except:\n print(current)\n continue\n hrefs = {i.get(\"href\") for i in text.find_all(\n href=True)}\n srcs = {i.get(\"src\") for i in text.find_all(\n src=True)}\n\n # Loop over the URLs in the current page\n for url in hrefs | srcs:\n if any(url.startswith(i) for i in [\"mailto:\", \"tel:\", \"javascript:\", \"#content-middle\", \"about:blank\", \"skype:\"]):\n continue\n if url == \"#\" or \"linkedin\" in url or \"\\\\\" in url:\n continue\n\n try: # getting the content of the URL we're checking currently\n full_urls = handle_url(str(url), current)\n #TODO: add the full url, so it actually skips already searched \n if full_urls[0] in visited or full_urls[1] in visited:\n continue\n resp = await client.get(full_urls[0])\n await asyncio.sleep(0.5)\n\n if resp.status_code == 403:\n pass\n\n if 200 <= resp.status_code < 300 or resp.status_code == 301 or resp.status_code == 302:\n if \".js\" not in full_urls[0] and resp.url.host.endswith(domain):\n to_search.add(resp)\n\n logging.debug(\n f\"{full_urls[0]},{url},{str(current.url)},{resp.status_code}\")\n\n else: # Got an HTTP error\n await database_queue.put((str(current.url), current.url.host, full_urls[0], str(resp.status_code), str(datetime.datetime.today())))\n # await cur.execute(\"\"\"INSERT INTO errors VALUES (?,?,?,?)\"\"\", (str(current.url), full_url, str(resp.status_code), str(datetime.date.today())))\n # await cur.commit()\n # await con.commit()\n logging.error(\n f\"{full_urls[0]},{url},{str(current.url)},{resp.status_code}\")\n\n except httpx.ConnectError as e: # SSL errors and such?\n if not e.args[0].startswith(\"[SSL: WRONG_VERSION_NUMBER]\"):\n continue\n\n try:\n resp_https = await client.get(full_urls[1])\n except Exception as e:\n print(\"130\".e.args)\n else:\n if 200 <= resp_https.status_code < 300 or resp_https.status_code == 301 or resp_https.status_code == 302:\n await database_queue.put((str(current.url), current.url.host, full_urls[1], \"557\", str(datetime.datetime.today())))\n logging.error(\n f\"{full_urls[1]},{url},{str(current.url)},{e.args}\")\n\n except httpx.ConnectTimeout as e:\n # TODO: what do we do on a timeout\n #print(\"139\",\" timeout \",e)\n continue\n\n except httpx.TooManyRedirects as e:\n # TODO: edit redirect maximum?\n #print(\"144\",\" redirects \",e)\n continue\n\n except OSError:\n await database_queue.put((str(current.url), current.url.host, full_urls[1], \"5\", str(datetime.datetime.today())))\n\n except httpx.ConnectError as e: # Semaphore error?\n await database_queue.put((str(current.url), current.url.host, full_urls[0], \"0\", str(datetime.datetime.today())))\n # await cur.execute(\"\"\"INSERT INTO errors VALUES (?,?,?,?)\"\"\", (str(current.url), full_url, str(e.args), str(datetime.date.today())))\n # await cur.commit()\n # await con.commit()\n logging.error(\n f\"{full_urls[0]},{url},{str(current.url)},{e.args}\")\n except httpx.RemoteProtocolError:\n print(\"protocol error\")\n\n\nasync def database_worker(data_queue, insert_length) -> None:\n try:\n async with aiosqlite.connect(DATABASE_NAME) as con:\n cursor = await con.cursor()\n stored_data = []\n try:\n while True:\n await asyncio.sleep(1)\n # (source,target,code,timestamp) = await data_queue.get()\n data = await data_queue.get()\n stored_data.append(data)\n if len(stored_data) >= insert_length:\n await cursor.executemany(\n \"INSERT INTO errors VALUES (?,?,?,?,?)\", stored_data)\n stored_data = []\n await con.commit()\n data_queue.task_done()\n except asyncio.CancelledError:\n print(\"storing final data\")\n if len(stored_data) != 0:\n await cursor.executemany(\n \"INSERT INTO errors VALUES (?,?,?,?,?)\", stored_data)\n await con.commit()\n print(\"stored final data\")\n finally:\n print(\"trying to close\")\n print(\"closing\")\n return\n except Exception as e:\n print(\"185\",e.args)\n\n\nDATABASE_NAME = \"data.db\"\n\n\nasync def main() -> None:\n visited = set()\n # domains = set(['https://www.uia.no', 'https://cair.uia.no', 'https://home.uia.no', 'https://kompetansetorget.uia.no', 'https://icnp.uia.no', 'http://friluft.uia.no', 'https://passord.uia.no', 'https://windplan.uia.no', 'https://appsanywhere.uia.no', 'https://shift.uia.no', 'https://insitu.uia.no', 'https://lyingpen.uia.no', 'https://platinum.uia.no', 'https://dekomp.uia.no', 'https://naturblogg.uia.no', 'https://enters.uia.no', 'https://wisenet.uia.no', 'https://libguides.uia.no', 'http://ciem.uia.no']) \n con = await aiosqlite.connect(DATABASE_NAME)\n cur = await con.cursor()\n domains = set()\n try:\n rows = await cur.execute(\"SELECT domain FROM subdomains where should_search=1\")\n for (i,) in await rows.fetchall():\n #print(i)\n domains.add(i)\n except Exception as e:\n print(e.args)\n with open(\"config.json\") as file:\n data = json.loads(file.read())\n domains = set(filter(lambda x: data[x], data.keys()))\n await cur.close()\n if not domains:\n print(\"No domains to search\")\n return\n # _ = await asyncio.wait([search_domain(domain, visited) for domain in domains],return_when=asyncio.ALL_COMPLETED)\n # worker_amount = 6\n # task_queue = asyncio.Queue()\n insert_length = 1\n database_queue = asyncio.Queue()\n # result_queue = asyncio.Queue()\n data_worker = asyncio.create_task(\n database_worker(database_queue, insert_length))\n workers = []\n\n #print(domains)\n for domain in domains:\n workers.append(asyncio.create_task(search_domain(\n domain, visited, database_queue), name=domain))\n # await asyncio.gather(*workers, return_exceptions=True)\n (done, running) = await asyncio.wait(workers, return_when=asyncio.FIRST_COMPLETED)\n #print(f\"{done=}\")\n #print(f\"{running=}\")\n while running:\n (done_new, running_new) = await asyncio.wait(workers, return_when=asyncio.FIRST_COMPLETED)\n if done_new != done:\n print(f\"{len(done_new)}/{len(done_new)+len(running_new)} workers done\")\n done, running = done_new, running_new\n await asyncio.sleep(1)\n await database_queue.join()\n data_worker.cancel()\n await data_worker\n for task in done:\n await task\n del done\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n # asyncio.get_event_loop().run_until_complete(main())\n","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":10494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"238565776","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom odoo import fields, http, _, SUPERUSER_ID\nfrom odoo.http import request\nimport json\nimport base64\n\n_logger = logging.getLogger(__name__)\n\nclass WebFormulier(http.Controller):\n\n @http.route(['/web/video/'], type='http', auth=\"user\", website=True)\n def video_url(self, video_id, **kw):\n \"\"\" video binary data return \"\"\"\n\n if video_id:\n order_video = request.env['order.video'].browse(video_id)\n video = base64.b64decode(order_video.video)\n return video\n return False\n\n @http.route(['/country_infos/'], type='json', auth=\"user\", website=True)\n def get_state_id(self, country_id, **kw):\n \"\"\" State show on Web Form \"\"\"\n\n state_ids = request.env['res.country.state'].search_read(\n [('country_id','=',country_id)],['name'])\n return state_ids\n\n @http.route(['/question/formulier/submit//'], type='http',\n auth='user', methods=['POST'], website=True)\n def question_formulier_submit(self,question_frm_id,model_name, **kwargs):\n \"\"\" Project Formulier web form submit \"\"\"\n if question_frm_id:\n if kwargs.get('product_id'):\n kwargs.pop('product_id')\n if kwargs.get('product_qty'):\n kwargs.pop('product_qty')\n if kwargs.get('state_id'):\n kwargs.pop('state_id')\n if kwargs.get('country_id'):\n kwargs.pop('country_id')\n if kwargs.get('que_id'):\n kwargs.pop('que_id')\n question_frm_id = request.env['question.formulier'].sudo().browse(question_frm_id)\n if question_frm_id.state == 'opportunity':\n question_frm_id.state = 'opportunity_output'\n elif question_frm_id.state == 'quotation':\n question_frm_id.state = 'quotation_output'\n elif question_frm_id.state == 'task':\n question_frm_id.state = 'task_output'\n if kwargs.get('question_image_upload_input[0]'):\n del kwargs['question_image_upload_input[0]']\n if kwargs.get('question_video_upload_input[0]'):\n del kwargs['question_video_upload_input[0]']\n if kwargs.get('question_document_upload_input[0]'):\n del kwargs['question_document_upload_input[0]']\n question_frm_id.write(kwargs)\n return json.dumps({'id': question_frm_id.id})\n\n @http.route(['/question/formulier/'], type='http', auth=\"user\", website=True)\n def question_formulier_page(self, question_frm_id, **kw):\n \"\"\" Project Formulier view on web form \"\"\"\n\n question_frm_id = request.env['question.formulier'].sudo().browse(question_frm_id)\n user = request.env.user\n if question_frm_id and question_frm_id.partner_id:\n if user.has_group('base.group_user') or user.partner_id.id == question_frm_id.partner_id.id:\n values = question_frm_id.sudo().online_pf_dictionary()\n return request.render('quotation_images_feedback.question_formulier_template', values)\n else:\n return request.redirect('/my')\n else:\n return request.redirect('/my')\n\n @http.route('/question/form/image/upload',auth=\"user\", website=True, type=\"json\", csrf=False)\n def question_form_image_upload_file(self, image, fileName, file_type, que_id, is_task):\n \"\"\" Project Formulier web form -> extra images directly create new record \"\"\"\n\n OrderImage = request.env['order.image'].create({\n 'name': fileName,\n 'image': image,\n 'file_type': file_type or 'application/png',\n 'question_frm_id': int(que_id),\n 'is_task': is_task,\n })\n return OrderImage.id\n\n @http.route('/question/form/video/upload',auth=\"user\", website=True, type=\"json\", csrf=False)\n def question_form_video_upload_file(self, video, fileName, file_type, que_id, is_task):\n \"\"\" Project Formulier web form -> extra videos directly create new record \"\"\"\n OrderVideo = request.env['order.video'].create({\n 'name': fileName,\n 'video': video,\n 'file_type': file_type or 'application/mp4',\n 'question_frm_id': int(que_id),\n 'is_task': is_task,\n })\n return OrderVideo.id\n\n @http.route('/question/form/document/upload',auth=\"user\", website=True, type=\"json\", csrf=False)\n def question_form_document_upload_file(self, document, fileName, file_type, que_id):\n \"\"\" Project Formulier web form -> extra document directly create new record \"\"\"\n OrderDocument = request.env['order.document'].create({\n 'name': fileName,\n 'file': document,\n 'file_type': file_type or 'application/pdf',\n 'question_frm_id': int(que_id),\n })\n return OrderDocument.id,OrderDocument.name\n\n @http.route(['/sale_order/project_formulier/get'], type='json', auth=\"public\", website=True)\n def get_images(self, order_id, res_model, **kw):\n \"\"\" quotation image tab on quotation preview\"\"\" \n\n data = {'formulier_id': '', 'data':[], 'image_ids':[], 'document_ids': [], 'video_ids': []}\n if res_model == 'sale.order':\n order_id = request.env['sale.order'].browse(order_id)\n if order_id and order_id.question_frm_id:\n que_id = order_id.question_frm_id\n data.update({'formulier_id': que_id.id, 'data':[]})\n if que_id.image_ids:\n data['image_ids'].append(que_id.image_ids.ids)\n for doc in que_id.document_ids:\n data['document_ids'].append([doc.id, doc.name])\n for video in que_id.video_ids:\n data['video_ids'].append([video.id, video.name])\n formulerModelId = request.env['ir.model'].search([('model', '=', 'question.formulier')])\n fields = request.env['ir.model.fields'].search([('ttype', '=', 'binary'),\n ('model_id', '=', formulerModelId.id)])\n for field in fields:\n imageData = request.env['question.formulier'].search_read(\n [('id', '=', que_id.id)], [field.name])\n if imageData[0].get(field.name):\n data['data'].append(field.name)\n if res_model == 'sale.order.template':\n template_id = request.env['sale.order.template'].browse(order_id)\n if template_id:\n for video in template_id.template_video_ids:\n data['video_ids'].append([video.id, video.name])\n return data\n","sub_path":"quotation_images_feedback/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"569437618","text":"from typing import Callable, Any, Optional\nimport functools\nimport logging\nimport datetime\nfrom ogr.abstract import PullRequest, PRComment, PRStatus, GitProject\nfrom ogr.constant import DEFAULT_RO_PREFIX_STRING\n\n\ndef log_output(\n text: str, default_prefix: str = DEFAULT_RO_PREFIX_STRING, namespace: str = __name__\n) -> None:\n logger = logging.getLogger(namespace)\n logger.warning(f\"{default_prefix} {text}\")\n\n\ndef readonly(\n *,\n return_value: Optional[Any] = None,\n return_function: Optional[Callable] = None,\n log_message: str = \"\",\n) -> Any:\n \"\"\"\n Decorator to log function and ovewrite return value of object methods\n Ignore function name as first parameter and ignore every other parameters\n\n :param return_value: returned Any value if given, return_function has higher prio if set\n :param return_function: return function and give there parameters also\n original caller object return_function(self, *args, **kwargs)\n :param log_message: str string to put to logger output\n :return: Any type what is expected that function or return value returns\n \"\"\"\n\n def decorator_readonly(func):\n @functools.wraps(func)\n def readonly_func(self, *args, **kwargs):\n if not self.read_only:\n return func(self, *args, **kwargs)\n else:\n args_str = str(args)[1:-1]\n kwargs_str = \", \".join(f\"{k}={v!r}\" for k, v in kwargs.items())\n # add , in case there are also args, what has to be separated\n if args and kwargs:\n kwargs_str = \", \" + kwargs_str\n log_output(\n f\"{log_message} {self.__class__.__name__}.\"\n f\"{func.__name__}({args_str}{kwargs_str})\"\n )\n if return_function:\n return return_function(self, *args, **kwargs)\n else:\n return return_value\n\n return readonly_func\n\n return decorator_readonly\n\n\nclass GitProjectReadOnly:\n id = 1\n author = \"ReadOnlyAuthor\"\n url = \"url://ReadOnlyURL\"\n\n @classmethod\n def pr_create(\n cls,\n original_object: Any,\n title: str,\n body: str,\n target_branch: str,\n source_branch: str,\n ) -> \"PullRequest\":\n output = PullRequest(\n title=title,\n description=body,\n target_branch=target_branch,\n source_branch=source_branch,\n id=cls.id,\n status=PRStatus.open,\n url=cls.url,\n author=cls.author,\n created=datetime.datetime.now(),\n )\n return output\n\n @classmethod\n def pr_comment(\n cls,\n original_object: Any,\n pr_id: int,\n body: str,\n commit: str = None,\n filename: str = None,\n row: int = None,\n ) -> \"PRComment\":\n pull_request = original_object.get_pr_info(pr_id)\n log_output(pull_request)\n output = PRComment(\n comment=body,\n author=cls.author,\n created=datetime.datetime.now(),\n edited=datetime.datetime.now(),\n )\n return output\n\n @classmethod\n def pr_close(cls, original_object: Any, pr_id: int) -> \"PullRequest\":\n pull_request = original_object.get_pr_info(pr_id)\n pull_request.status = PRStatus.closed\n return pull_request\n\n @classmethod\n def pr_merge(cls, original_object: Any, pr_id: int) -> \"PullRequest\":\n pull_request = original_object.get_pr_info(pr_id)\n pull_request.status = PRStatus.merged\n return pull_request\n\n @classmethod\n def fork_create(cls, original_object: Any) -> \"GitProject\":\n return original_object\n","sub_path":"ogr/mock_core.py","file_name":"mock_core.py","file_ext":"py","file_size_in_byte":3757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"649361910","text":"# Solution for Day 29 Bitwise AND\n\n# Taken from the editorial; the approach described in the example is too slow\n# in Python and the test cases fail due time restriction.\n\n# !/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\nif __name__ == '__main__':\n t = int(input())\n\n for t_itr in range(t):\n nk = input().split()\n n = int(nk[0])\n k = int(nk[1])\n\n a = k - 1\n b = ~a & -~a\n if a | b > n:\n print(a - 1)\n else:\n print(a)\n","sub_path":"Python/30 Days of Code/Day 29 Bitwise AND.py","file_name":"Day 29 Bitwise AND.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"104707241","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('hostels', '0012_auto_20150131_2259'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='hostel',\n name='symbol_code',\n field=models.CharField(default=b'hostelm', unique=True, max_length=30, verbose_name=b'\\xd0\\xa1\\xd0\\xb8\\xd0\\xbc\\xd0\\xb2\\xd0\\xbe\\xd0\\xbb\\xd1\\x8c\\xd0\\xbd\\xd1\\x8b\\xd0\\xb9 \\xd0\\xba\\xd0\\xbe\\xd0\\xb4 (\\xd1\\x82\\xd0\\xbe\\xd0\\xbb\\xd1\\x8c\\xd0\\xba\\xd0\\xbe \\xd0\\xbb\\xd0\\xb0\\xd1\\x82\\xd0\\xb8\\xd0\\xbd\\xd0\\xb8\\xd1\\x86\\xd0\\xb0)'),\n preserve_default=True,\n ),\n ]\n","sub_path":"hostels/migrations/0013_hostel_symbol_code.py","file_name":"0013_hostel_symbol_code.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"347596725","text":"import json\nimport os\nfrom pprint import pprint\nimport item\n\n__db_location__ = \"db/order\"\n__order_folder__ = f\"{__db_location__}/order\"\n__order_detail_folder__ = f\"{__db_location__}/order_detail\"\n__order_last_id__ = f\"{__db_location__}/order_id.db\"\n__order_detail_last_id__ = f\"{__db_location__}/order_detail_id.db\"\n\n\ndef init():\n db()\n\n\ndef db():\n os.makedirs(__order_folder__)\n os.makedirs(__order_detail_folder__)\n\n\ndef set_command_and_params(command, params):\n if command == \"init\":\n init()\n elif command == \"add\":\n __add_order__()\n pass\n elif command == \"find\":\n order_id = input(\"Enter the order number you want to see : \")\n __find_order__(order_id)\n pass\n elif command == \"findAll\":\n __find_all_order__()\n pass\n elif command == \"search\":\n __order_search__(*params)\n pass\n\n\ndef __add_order__():\n print(\"Enter order details\")\n o = Order()\n o.order_id = o.last_order_id + 1\n o.customer_id = input(\"customer id : \")\n total_price = 0\n\n items = item.get_items()\n for i in items:\n details = Detail()\n status = input(i.name + \" \" + i.price + \" plz enter add or skip item : \")\n if status == \"add\":\n details.order_id = o.order_id\n details.item_id = i.item_id\n details.item_price = int(i.price)\n details.item_qty = int(input(\"The number of items you take : \"))\n details.item_total_price = int(i.price) * int(details.item_qty)\n total_price += int(details.item_total_price)\n details.save()\n else:\n pass\n\n o.total_price = total_price\n o.save()\n print(\"Success added\")\n\n\ndef __find_all_order__():\n order = Order()\n orders = order.all()\n for order in orders:\n print(order.order_id, order.customer_id, order.total_price)\n\n\ndef __find_order__(order_id):\n order = Order()\n detail = Detail()\n order.find(order_id)\n print(order.order_id, order.customer_id, order.total_price)\n print(order_id, \" id order details list :\")\n details = detail.search(order_id)\n for data in details:\n print(\" \\t\", data.order_detail_id, data.order_id, data.item_id, data.item_price, data.item_price,\n data.item_total_price)\n\n\ndef __order_search__(key, value):\n pass\n\n\ndef __add_order_details__(order_id, item_id, item_qty, item_price, total_price):\n pass\n\n\ndef __find_order_detail_by_order_id(order_id):\n pass\n\n\nclass Order:\n def __init__(self):\n self.order_id = None\n self.total_price = int\n self.customer_id = None\n if os.path.exists(__order_last_id__):\n with open(__order_last_id__, \"r\") as last_order_id_f:\n self.last_order_id = int(last_order_id_f.readline())\n else:\n self.last_order_id = 0\n\n def save(self):\n _data_ = {\n \"orderId\": self.order_id,\n \"customerId\": self.customer_id,\n \"totalPrice\": self.total_price,\n }\n with open(f\"{__order_folder__}/{self.order_id}.db\", \"w\") as order_file:\n json.dump(_data_, order_file)\n\n self.last_order_id += 1\n with open(__order_last_id__, \"w\") as f:\n f.write(str(self.last_order_id))\n\n @staticmethod\n def all():\n order_file_names = os.listdir(__order_folder__)\n orders = []\n for order_file_name in order_file_names:\n order = Order()\n Order.__get_order_by_path(\n order, f\"{__order_folder__}/{order_file_name}\")\n orders.append(order)\n return orders\n\n def __get_order_by_path(self, path):\n with open(path, \"r\") as order_file:\n _data_ = json.load(order_file)\n self.order_id = int(_data_[\"orderId\"])\n self.customer_id = _data_[\"customerId\"]\n self.total_price = _data_[\"totalPrice\"]\n\n def find(self, order_id):\n Order.__get_order_by_path(self, f\"{__order_folder__}/{order_id}.db\")\n\n\nclass Detail:\n def __init__(self):\n self.order_detail_id = None\n self.order_id = None\n self.item_total_price = None\n self.item_price = None\n self.item_qty = None\n self.item_id = None\n if os.path.exists(__order_detail_last_id__):\n with open(__order_detail_last_id__, \"r\") as last_order_detail_id_f:\n self.last_order_detail_id = int(last_order_detail_id_f.readline())\n else:\n self.last_order_detail_id = 0\n\n def save(self):\n self.order_detail_id = self.last_order_detail_id + 1\n _data_ = {\n \"orderDetailsId\": self.order_detail_id,\n \"orderId\": self.order_id,\n \"itemId\": self.item_id,\n \"itemQty\": self.item_qty,\n \"itemPrice\": self.item_price,\n \"itemTotalPrice\": self.item_total_price\n }\n with open(f\"{__order_detail_folder__}/{self.last_order_detail_id + 1}.db\", \"w\") as order_details_file:\n json.dump(_data_, order_details_file)\n\n self.last_order_detail_id += 1\n with open(__order_detail_last_id__, \"w\") as f:\n f.write(str(self.last_order_detail_id))\n\n @staticmethod\n def all():\n order_details_file_names = os.listdir(__order_detail_folder__)\n details = []\n for order_details_file_name in order_details_file_names:\n detail = Detail()\n Detail.__get_order_details_by_path(\n detail, f\"{__order_detail_folder__}/{order_details_file_name}\")\n details.append(detail)\n return details\n\n def __get_order_details_by_path(self, path):\n with open(path, \"r\") as order_details_file:\n _data_ = json.load(order_details_file)\n self.order_detail_id = int(_data_[\"orderDetailsId\"])\n self.order_id = _data_[\"orderId\"]\n self.item_id = _data_[\"itemId\"]\n self.item_qty = _data_[\"itemQty\"]\n self.item_price = _data_[\"itemPrice\"]\n self.item_total_price = _data_[\"itemTotalPrice\"]\n\n def search(self, value):\n key = \"order_id\"\n details = self.all()\n result_details = []\n for detail in details:\n details_value = str(getattr(detail, key))\n if details_value == value:\n result_details.append(detail)\n return result_details\n\n def __str__(self):\n return f\"orderDetailsId:{self.order_detail_id},orderId:{self.order_id},itemId:{self.item_id},itemQty:{self.item_qty},itemPrice:{self.item_price},itemTotalPrice:{self.item_total_price}\"\n","sub_path":"order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":6581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"419481099","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/3/9 18:48\nfrom flask import request, render_template, url_for, current_app\n\nfrom app.models import Tag, Article\nfrom app import db\nfrom . import main\n\n\n@main.route('/')\ndef index():\n page = request.args.get('page', 1, type=int)\n articles = Article.get_articles(page, current_app.config['ARTICLE_PER_PAGE'])\n\n if articles.total == 0:\n return render_template('base.html')\n\n all_tags = Tag.get_tags_dict()\n\n next_url = url_for('main.index', page=articles.next_num) if articles.has_next else None\n prev_url = url_for('main.index', page=articles.prev_num) if articles.has_prev else None\n page_number = articles.page\n page_total = articles.pages\n\n return render_template('index.html', items=articles.items, next_url=next_url, prev_url=prev_url,\n all_tags=all_tags, search=False, page=page_number, pages=page_total)\n\n\n@main.route('/detail')\ndef detail():\n article_id = request.args.get('id', type=int)\n single = Article.query.get(article_id)\n single.views += 1\n db.session.add(single)\n db.session.commit()\n return render_template('detail.html', article=single)\n\n\n@main.route('/tag')\ndef tag():\n tag_title = request.args.get('tag_title')\n page = request.args.get('page', 1, type=int)\n searchs = Article.get_search(tag_title, page, current_app.config['ARTICLE_PER_PAGE'])\n next_url = url_for('main.tag', tag_title=tag_title, page=searchs.next_num) if searchs.has_next else None\n prev_url = url_for('main.tag', tag_title=tag_title, page=searchs.prev_num) if searchs.has_prev else None\n page_number = searchs.page\n page_total = searchs.pages\n all_tags = Tag.get_tags_dict()\n\n return render_template('index.html', items=searchs.items, next_url=next_url, prev_url=prev_url,\n all_tags=all_tags, search=True, tag_title=tag_title, article_number=searchs.total,\n page=page_number, pages=page_total)\n\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"417244207","text":"import os\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Sequential\nfrom keras.layers import Embedding, Flatten, Dense\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport json\nimport sys\n\nprint(sys.getdefaultencoding())\nwith open('train-v2.0.json', 'r') as f:\n json_file = json.load(f)\nquestion_context_list = []\n# answer_start_list_of_lists = []\n# answer_end_list_of_lists = []\nanswer_start_end_list_of_lists = []\nfor title_paragraphs in json_file['data']:\n for qas_context in title_paragraphs['paragraphs']:\n for qas in qas_context['qas']:\n question_context = qas['question'] + \" : \" + qas_context['context']\n question_context_list.append(qas['question'] + \":\" + qas_context['context'])\n if len(qas['answers']) == 0:\n # answer_start_list_of_lists.append([])\n # answer_end_list_of_lists.append([])\n answer_start_end_list_of_lists.append([-1, -1])\n else:\n # answers_start = []\n # answers_end = []\n answers_start_end = []\n for answer in qas['answers']:\n # answers_start.append(answer['answer_start'])\n answers_start_end.append(answer['answer_start'])\n answers_start_end.append(answer['answer_start'] + len(answer['text']) - 1)\n # if answer['answer_start'] > max:\n # max = answer['answer_start']\n # answers_end.append(answer['answer_start'] + len(answer['text']) - 1)\n # answer_start_list_of_lists.append(answers_start)\n # answer_end_list_of_lists.append(answers_end)\n answer_start_end_list_of_lists.append(answers_start_end)\nprint(max)\ntraining_samples = 100000\ntokenizer = Tokenizer()\ntokenizer.fit_on_texts(question_context_list)\nsequences = tokenizer.texts_to_sequences(question_context_list)\n\nword_index = tokenizer.word_index\nprint('Found %s unique tokens.' % len(word_index))\ndata = pad_sequences(sequences)\n# data = np.asarray(sequences)\n# answers_start = np.asarray(answer_start_list_of_lists)\n# answers_end = np.asarray(answer_end_list_of_lists)\nanswers_start_end = np.asarray(answer_start_end_list_of_lists)\nprint('Shape of data tensor:', data.shape) # Shape of data tensor: (130319,)\nprint(data.shape[1])\nprint('Shape of answers tensor:', answers_start_end.shape) # Shape of answers tensor: (130319,)\n# print(data_np)\n# print(answers)\n\n# Split the data into a training set and a validation set\n# But first, shuffle the data\nindices = np.arange(data.shape[0])\n# print(indices.shape)\nnp.random.shuffle(indices)\ndata = data[indices]\nanswers_start_end = answers_start_end[indices]\n# answers_start = answers_start[indices]\n# answers_end = answers_end[indices]\n\nx_train = data[:training_samples]\ny_train = answers_start_end[:training_samples]\nx_val = data[training_samples:]\ny_val = answers_start_end[training_samples:]\nprint(x_train.shape)\nprint(y_train.shape)\nprint(x_val.shape)\nprint(y_val.shape)\n\nglove_dir = '../glove.6B'\n\nembeddings_index = {}\nf = open(os.path.join(glove_dir, 'glove.6B.100d.txt'), encoding=\"utf8\")\nfor line in f:\n values = line.split()\n word = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n embeddings_index[word] = coefs\nf.close()\nprint('Found %s word vectors.' % len(embeddings_index))\n\nembedding_dim = 100\nembedding_matrix = np.zeros((len(word_index) + 1, embedding_dim))\nfor word, i in word_index.items():\n # print(word)\n # print(i)\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n # Words not found in embedding index will be all-zeros.\n embedding_matrix[i] = embedding_vector\nmodel = Sequential()\nmodel.add(Embedding(len(word_index) + 1, embedding_dim, input_length=data.shape[1]))\nmodel.add(Flatten())\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(2, activation='relu'))\nmodel.summary()\n\nmodel.layers[0].set_weights([embedding_matrix])\nmodel.layers[0].trainable = False\n\nmodel.compile(optimizer='adam',\n loss='mean_squared_error',\n metrics=['acc'])\nhistory = model.fit(x_train, y_train,\n epochs=10,\n batch_size=32,\n validation_data=(x_val, y_val))\nmodel.save_weights('pre_trained_glove_model.h5')\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n","sub_path":"Question Answering Bot/SQuADProjekt/SQuADProblem/SolveSquadWithNNsModel.py","file_name":"SolveSquadWithNNsModel.py","file_ext":"py","file_size_in_byte":4945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"394904854","text":"#\n# Copyright 2016, 2017, 2018 Guenter Bartsch, 2021 Florian Quirin\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n#\n# adapt an existing kaldi model to a new language model\n#\n\nimport os\nimport sys\nimport logging\n\nfrom optparse import OptionParser\nfrom kaldi_adapt_lm import kaldi_adapt_lm\n\nDEFAULT_KALDI_ROOT = '/opt/kaldi'\nDEFAULT_WORK_DIR = 'work'\n\n# commandline parsing\nparser = OptionParser(\"usage: %prog [options] src_model_dir lm.arpa dst_model_name\")\n\nparser.add_option (\"-f\", \"--force\", action=\"store_true\", dest=\"force\",\n help=\"overwrite work dir if it exists\")\n\nparser.add_option (\"-k\", \"--kaldi-root\", dest=\"kaldi_root\", type = \"str\", default=DEFAULT_KALDI_ROOT,\n help=\"kaldi root dir (default: %s)\" % DEFAULT_KALDI_ROOT)\n\nparser.add_option (\"-v\", \"--verbose\", action=\"store_true\", dest=\"verbose\",\n help=\"enable verbose logging\")\n\nparser.add_option (\"-w\", \"--work-dir\", dest=\"work_dir\", type = \"str\", default=DEFAULT_WORK_DIR,\n help=\"work dir (default: %s)\" % DEFAULT_WORK_DIR)\n\n(options, args) = parser.parse_args()\n\nif options.verbose:\n logging.basicConfig(level=logging.DEBUG)\nelse:\n logging.basicConfig(level=logging.INFO)\n\nif len(args) != 3:\n parser.print_usage()\n sys.exit(1)\n\nsrc_model_dir = args[0]\nlm_fn = args[1]\ndst_model_name = args[2]\nwork_dir = options.work_dir\n\nif os.path.exists(work_dir):\n if options.force:\n # cleanup leftovers from previous runs\n cmd = 'rm -rf %s' % work_dir\n logging.info(cmd)\n os.system(cmd)\n else:\n logging.error(\"work dir %s already exists.\" % work_dir)\n sys.exit(1)\n\nkaldi_root = options.kaldi_root\n\n# main\nkaldi_adapt_lm (kaldi_root, src_model_dir, lm_fn, work_dir, dst_model_name)\n\nlogging.info (\"All done.\")\n","sub_path":"adapt.py","file_name":"adapt.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"71490842","text":"#------------- Daniel Han-Chen 2017\n#------------- https://github.com/danielhanchen/sciblox\n#------------- SciBlox v0.2.8\n#-------------\n\nmaxcats = 15\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ntrue = True; TRUE = True\nfalse = False; FALSE = False\n\n#-----------------------------\nimport pandas as pd, numpy as np, scipy, sklearn as sk, seaborn as sb\nfrom copy import copy\nimport matplotlib.pyplot as plt\ntry:\n from jupyterthemes import jtplot;\n jtplot.style()\nexcept: pass;\n#-----------------------------\nnp.set_printoptions(suppress = True)\npd.set_option('display.max_rows', 10)\npd_colour = '#302f2f'\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ DATAFRAME METHODS ------------------------------------#\n#-------------------- Display options and pandas methods --------------------#\ndef maxrows(x = 10): pd.set_option('display.max_rows', x)\ndef maxcat(x = 15): maxcats = x\ndef tabcolour(x = '#302f2f'): pd_colour = x\n#-----------------------------\ndef percent(x):\n if x <= 1: return x\n else: return x/100\n#-----------------------------\ndef table(x): \n try: return pd.DataFrame(x)\n except: return pd.DataFrame(list(x.items()))\ndef series(x): \n try: return pd.Series(x)\n except:\n first = pd.Series(x[0])\n if len(first)!=len(x): return pd.Series(T(x)[0])\n else: return first\n#-----------------------------\ndef istable(x): return (type(x) in [pd.DataFrame,pd.Series])*1\ndef isarray(x): return (type(x) in [np.array,np.ndarray,np.matrix])*1\n#-----------------------------\ndef shape(x):\n try: return x.shape\n except: return len(x)\n#----------------------------- \ndef head(x, n = 5):\n if istable(x)==1: return x.head(n)\n else:\n if len(x) > n: return x[:n]\n else: return x\n \ndef tail(x, n = 5):\n if istable(x)==1: return x.tail(n)\n else:\n if len(x) > n: return x[-n:]\n else: return x\n#----------------------------- \ndef sample(x, n = 5, ordered = False):\n if n > len(x): g = len(x)\n else: g = n\n \n if istable(x)==1:\n if ordered == False: return x.sample(g)\n else: return x.iloc[[int(y*(len(x)/g)) for y in range(g)]]\n else:\n if ordered == False: return np.random.choice(x, g)\n else: return np.array(x)[[int(y*(len(x)/g)) for y in range(g)]]\n#----------------------------- \ndef columns(x):\n try: return x.columns.tolist()\n except: pass;\n \ndef index(x):\n try: return x.index.tolist()\n except: pass;\n#----------------------------- \ndef reset(x, index = True, column = False, string = False, drop = False):\n if index == True and column == False: \n if drop == False: return x.reset_index()\n else: return x.reset_index()[columns(x)]\n else:\n y = copy(x)\n if type(x)==pd.Series: ss = 0\n else: ss = shape(x)[1]\n if string == True: y.columns = [\"col\"+str(y) for y in range(ss)]\n else: y.columns = [y for y in range(ss)]\n return y\n#----------------------------- \ndef hcat(*args):\n a = args[0]\n if type(a)==pd.Series: a = table(a)\n for b in args[1:]:\n if type(a)==list:\n if type(b)!=list: b = list(b)\n a = a + b\n elif isarray(a)==1:\n if isarray(b)==0: b = array(b)\n a = np.hstack((a,b))\n else:\n if type(b)!=pd.DataFrame: b = table(b)\n a = pd.concat([a,b],1)\n del b\n return a\n\ndef vcat(*args):\n a = args[0]\n if type(a)==pd.Series: a = table(a)\n elif type(a)==list: a = array(a)\n for b in args[1:]:\n if isarray(a)==1:\n if isarray(b)==0: b = array(b)\n a = np.vstack((a,b))\n else:\n if type(b)!=pd.DataFrame: b = table(b)\n a = pd.concat([a,b],0)\n del b\n return a\n#-----------------------------\ndef dtypes(x):\n if type(x)==pd.Series:\n types = x.dtype\n if types==('O' or \"string\" or \"unicode\"): return 'obj'\n elif types==(\"int64\" or \"uint8\" or \"uint16\" or \"uint32\" or \"uint64\" or \"int8\" or \"int32\" or \"int16\"): return 'int'\n elif types==('float64' or 'float16' or 'float32' or 'float128'): return 'float'\n elif types=='bool': return 'bool'\n else: return 'date'\n else:\n dfs = x.dtypes\n for f in (dfs.index.tolist()):\n dfs[f] = str(dfs[f])\n if \"int\" in dfs[f]: dfs[f] = 'int'\n elif \"float\" in dfs[f]: dfs[f] = \"float\"\n elif \"bool\" in dfs[f]: dfs[f] = \"bool\"\n elif \"O\" in dfs[f] or \"obj\" in dfs[f]: dfs[f] = \"obj\"\n elif \"date\" in dfs[f]: dfs[f] = \"date\"\n else: dfs[f] = \"obj\"\n return dfs\ndef dtype(x): return dtypes(x)\n\ndef contcol(x): \n try: return ((dtypes(x)==\"int\")|(dtypes(x)==\"float\")).index[(dtypes(x)==\"int\")|(dtypes(x)==\"float\")].tolist()\n except: return np.nan\ndef conts(x):\n if type(x) == pd.Series:\n if dtype(x) in [\"int\",\"float\"]: return x\n else: return np.nan\n else: return x[contcol(x)]\n\ndef objcol(x): \n try: return (dtypes(x)==\"obj\").index[dtypes(x)==\"obj\"].tolist()\n except: return np.nan\ndef objects(x):\n if type(x) == pd.Series:\n if dtype(x) == \"obj\": return x\n else: return np.nan\n else: return x[objcol(x)]\ndef objs(x): return objects(x)\ndef notobj(x): return exc(x, objcol(x))\n\ndef catcol(x):\n if type(x) == pd.Series:\n if iscat(x) == True: return x\n else: return np.nan\n else: return (iscat(x).index[iscat(x)]).tolist()\ndef classcol(x): return cats(x)\ndef cats(x): return x[catcol(x)]\ndef classes(x): return x[catcol(x)]\n\ndef iscat(x, cat = maxcats):\n return ((dtypes(x)!='float')|(dtypes(x)!='int'))&(nunique(x)<=cat)\n#-----------------------------\ndef nullcol(x): return (count(x)!=len(x)).index[count(x)!=len(x)].tolist()\ndef nacol(x): return nullcol(x)\ndef missingcol(x): return nullcol(x)\n\ndef notnull(x, row = 1, keep = None, col = 0):\n if row!=1: axis = 1\n elif col!=0: axis = 0\n else: axis = 0\n if keep is None: \n try: return x.dropna(axis = axis)\n except: return x.dropna()\n else:\n if keep < 1: \n if axis==1: keep = len(x)*keep\n else: keep = shape(x)[1]*keep\n return x.dropna(axis = axis, thresh = keep)\n \ndef isnull(x, row = 1, keep = None, col = 0):\n if row!=1 or col!=0: axis = 0\n else: axis = 1\n if keep is None: miss = missing(x, row = axis)!=0\n else:\n if axis == 1:\n if keep < 1: miss = missing(x, row = axis)<=shape(x)[1]*keep\n else: miss = missing(x, row = axis)<=keep\n else:\n if keep < 1: miss = missing(x, row = axis)<=len(x)*keep\n else: miss = missing(x, row = axis)<=keep\n try: return x.iloc[miss.index[miss]]\n except: return x[pd.isnull(x)==True]\n \ndef dropna(x, col = None):\n if col is None: return x.dropna()\n else:\n if type(col)!=list: col = list(col)\n return x.dropna(subset = col)\n \n#-----------------------------\ndef diff(want, rem):\n w = copy(want)\n for j in w:\n if j in rem: w.remove(j)\n for j in rem:\n if j in w: w.remove(j)\n return w\n\ndef exc(x, l):\n if type(l) == str: l = [l]\n return x[diff(columns(x),l)]\n\ndef drop(x, l): return exc(x, l), x[l]\ndef pop(x, l): return exc(x, l), x[l]\n\ndef append(l, r):\n g = copy(l);\n if type(g)!= list: g = [g]\n if type(r) == list:\n for a in r: g.append(a)\n else: g.append(r)\n return g\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ OTHER ANALYTICAL METHODS ------------------------------------#\n#-------------------- Uniques and counting and sorting --------------------#\ndef count(x):\n try: return x.count()\n except: return len(x)\n \ndef missing(x, row = 0, col = 1):\n if row!=0 or col!=1: x = x.T \n try: return (pd.isnull(x)).sum()\n except: return (np.isnan(x)).sum()\n#----------------------------- \ndef unique(x, dropna = False):\n if dropna == True: x = notnull(x)\n if type(x) == pd.Series: return list(x.unique())\n elif type(x) == pd.DataFrame: return {col:list(x[col].unique()) for col in columns(x)}\n else:\n u = []\n for a in x:\n if dropna == True: \n if a not in u and a!=np.nan: u.append(a)\n else: \n if a not in u: u.append(a)\n del a\n return u\n \ndef nunique(x, dropna = False):\n if istable(x)==True: return x.nunique()\n else:\n u = []; n = 0\n for a in x:\n if dropna == True: \n if a not in u and a!=np.nan: u.append(a); n += 1\n else: \n if a not in u: u.append(a); n += 1\n del u,a\n return n\n \ndef cunique(x, dropna = False):\n if type(x) == pd.Series: return x.value_counts(dropna = dropna)\n elif type(x) == pd.DataFrame: return {col:x[col].value_counts() for col in columns(x)}\n else:\n u = {}\n for a in x:\n if dropna == True: \n if a not in u and a!=np.nan: u[a]=1\n else: u[a]+=1\n else: \n if a not in u: u[a]=1\n else: u[a]+=1\n del a\n return u\n \ndef punique(x, dropna = False): \n return round(nunique(x, dropna = dropna)/(count(x)+missing(x)*(dropna==False)*1)*100,4)\n#-----------------------------\ndef reverse(x):\n if type(x) == pd.Series and dtype(x) == 'bool': return x == False\n elif istable(x)==1: return x.iloc[::-1]\n elif type(x) == list: return x[::-1]\n elif type(x) == dict: return {i[1]:i[0] for i in x.items()}\n#-----------------------------\ndef sort(x, by = None, asc = True, ascending = True, des = False, descending = False):\n if type(x) == list:\n if asc == ascending == True and des == descending == False: return sorted(x)\n else: return reverse(sorted(x))\n else:\n if type(x) == pd.Series:\n if asc == ascending == True and des == descending == False: return x.sort_values(ascending = True)\n else: return x.sort_values(ascending = False)\n else:\n if by is None: col = columns(x)\n else: col = by\n if asc == ascending == True and des == descending == False: return x.sort_values(ascending = True, by = col)\n else: return x.sort_values(ascending = False, by = col)\n \ndef fsort(x, by = None, keep = False, asc = True, ascending = True, des = False, descending = False):\n if type(x)==pd.Series: x = table(x); x = reset(x, column = True, string = True); by = columns(x)[0];\n if type(by)==list: by = by[0]\n if type(x) == list:\n from collections import Counter\n c = copy(x)\n if asc == ascending == True and des == descending == False: c.sort(key=Counter(sort(c, asc = True)).get, reverse = True); return c\n else: c.sort(key=Counter(sort(c, asc = False)).get, reverse = False); return c\n elif by is None: print(\"Please specify column to sort by: fsort(x, by = 'Name')\")\n else:\n f = by; fg = reset(table(x[f].value_counts()))\n ff = f+\"_Freq\"; fg.columns = [f,ff]\n del ff\n try: fg[f+\"_Length\"] = fg[f].str.len()\n except: fg[f+\"_Length\"] = fg[f]\n \n df = x.merge(fg, how = \"outer\")\n if asc == ascending == True and des == descending == False: df = sort(df, [f+\"_Freq\",f+\"_Length\"], asc = True)\n else: df = sort(df, [f+\"_Freq\",f+\"_Length\"], asc = False)\n \n if keep == True: return df\n else: l = columns(df); l.remove(f+\"_Freq\"); l.remove(f+\"_Length\")\n return df[l]\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ BASIC ANALYSIS METHODS ------------------------------------#\n#-------------------- Ratios and detections --------------------#\ndef freqratio(x):\n counted = cunique(x)\n if type(x) == pd.Series:\n try: return counted[0]/counted[1]\n except: return 1\n else:\n empty = []\n for col in columns(x):\n try: empty.append(counted[col].iloc[0]/counted[col].iloc[1])\n except: empty.append(1)\n tab = table(empty); tab.index = columns(x); return tab[0]\n\ndef isid(x):\n for col in columns(x):\n if (nunique(x[col]) == len(x)) or \"id\" in col.lower() or \"index\" in col.lower(): return col\n else: return ''\n \ndef pzero(x): return sum(x==0, axis = 0)/count(x)*100\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ MATHEMATICAL METHODS ------------------------------------#\n#-------------------- Statistical methods --------------------#\ndef var(x, axis = 0, dof = 1):\n try: return x.var(axis = axis, ddof = dof)\n except: return np.nanvar(x, axis = axis, ddof = dof)\n \ndef std(x, axis = 0, dof = 1):\n try: return x.std(axis = axis, ddof = dof)\n except: return np.nanstd(x, axis = axis, ddof = dof)\n\n#------------- \ndef mean(x, axis = 0):\n try: return x.mean(axis = axis)\n except: return np.nanmean(x, axis = axis)\n \ndef median(x, axis = 0):\n try: return x.median(axis = axis)\n except: return np.nanmedian(x, axis = axis)\n \ndef mode(x, axis = 0):\n try: return series(x).mode()[0]\n except: return x.mode(axis = axis).iloc[0]\n \ndef rng(x, axis = 0):\n try: return conts(x).max(axis = axis) - conts(x).min(axis = axis)\n except: \n try: return max(x)-min(x)\n except: return np.nan\n#-------------\ndef percentile(x, p, axis = 0):\n if p > 1: p = p/100\n try: return x.quantile(p, axis = axis)\n except: return np.nanpercentile(x, p, axis = axis)\n\ndef iqr(x, axis = 0):\n return percentile(x, 0.75, axis = axis) - percentile(x, 0.25, axis = axis)\n#-------------\ndef skewness(x, axis = 0):\n try: return x.skew(axis = axis)\n except: return scipy.stats.skew(x, axis = axis, nan_policy='omit')\ndef skew(x, axis = 0): return skewness(x, axis)\n \ndef kurtosis(x, axis = 0):\n try: return scipy.stats.kurtosis(x, axis = axis, nan_policy='omit')\n except: return x.kurt(axis = axis)\n \ndef kurt(x, axis = 0): return kurtosis(x, axis)\n#-------------\ndef pnorm(p, mean = 0, var = 1):\n if p > 1: p = p/100\n return scipy.stats.norm.cdf(p, loc=mean, scale=var)\n\ndef qnorm(q, mean = 0, var = 1):\n if q > 1: q = q/100\n return scipy.stats.norm.ppf(q, loc=mean, scale=var)\n\ndef CI(q, data, method = \"mean\",U = True, L = True):\n if q > 1: q = q/100\n norms = qnorm(q+(1-q)/2)*(std(data) / sqrt(len(data)) )\n if method == \"mean\": u = mean(data) + norms; l = mean(data) - norms\n if U == L == True: return (l,u)\n elif U == True: return u\n else: return l\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ TYPES METHODS ------------------------------------#\n#-------------------- Changing case --------------------#\ndef lower(x):\n j = copy(x)\n if type(x) == list:\n for k in range(len(j)):\n try: j[k] = j[k].lower()\n except: pass;\n return j\n\ndef upper(x):\n j = copy(x)\n if type(x) == list:\n for k in range(len(j)):\n try: j[k] = j[k].upper()\n except: pass;\n return j\n#-------------------- Other types and conversions --------------------#\ndef int(df, *args):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = x[y].astype(\"int64\")\n except: \n try: x[y] = np.floor(x[y])\n except: pass\n return x\n else: \n try: return np.int64(df)\n except: \n try: return np.floor(df)\n except: return df\n \ndef float(df, *args):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = x[y].astype(\"float64\")\n except: pass\n return x\n else: \n try: return np.float64(df)\n except: return df\n#------------- \ndef max(x, axis = 0):\n if istable(x)==1: return conts(x).max()\n else:\n if shape(matrix(x))[0] == 1: return np.amax(x,axis=axis)\n else: return np.amax(x)\n \ndef min(x, axis = 0):\n if istable(x)==1: return conts(x).min()\n else:\n if shape(matrix(x))[0] == 1: return np.amin(x)\n else: return np.amin(x,axis=axis)\n#------------- \ndef argcheck(df, args):\n if len(args)==0: col = columns(df)\n elif type(args[0])!=list: col = list(args)\n else: col = args[0]\n return copy(df), col\n#-------------\ndef abs(df, *args):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = np.abs(x[y])\n except: pass\n return x\n else: \n try: return np.abs(df)\n except: return df\n#------------- \ndef log(df, *args, shift = 0):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = np.log(x[y]+shift)\n except: pass;\n return x\n else: \n try: return np.log(df+shift)\n except: return df\n#------------- \ndef exp(df, *args, shift = 0):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = np.exp(x[y])+shift\n except: pass;\n return x\n else: \n try: return np.exp(df)+shift\n except: return df\n#------------- \ndef sin(df, *args):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = np.sin(x[y])\n except: pass;\n return x\n else: \n try: return np.sin(df)\n except: return df\n#-------------\ndef cos(df, *args):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = np.cos(x[y])\n except: pass;\n return x\n else: \n try: return np.cos(df)\n except: return df\n#------------- \ndef tan(df, *args):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = np.tan(x[y])\n except: pass;\n return x\n else: \n try: return np.tan(df)\n except: return df\n#------------- \ndef sqrt(df, *args):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = np.sqrt(x[y])\n except: pass;\n return x\n else: \n try: return np.sqrt(df)\n except: return df\n#------------- \ndef floor(df, *args):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = np.floor(x[y])\n except: pass;\n return x\n else: \n try: return np.floor(df)\n except: return df\n#------------- \ndef ceiling(df, *args):\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n try: x[y] = np.ceil(x[y])\n except: pass;\n return x\n else: \n try: return np.ceil(df)\n except: return df\n\ndef ceil(df, *args): return ceiling(df, args)\n#-------------\ndef sum(x, axis = 1): \n try: return x.sum(axis = axis)\n except: return np.nansum(x, axis = 0)\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ MATHEMATICAL METHODS ------------------------------------#\n#-------------------- Linear Algebra --------------------#\nfrom numpy import dot, multiply, multiply as mult\ndef array(*args):\n if len(args)==1: \n arrs = np.array(args[0])\n try:\n if shape(arrs)[1]==1: arrs = arrs.T[0]\n except: pass;\n return arrs\n else:\n try: return np.array(args)\n except: return np.array([args])\n\ndef matrix(*args): return np.matrix(array(args))\n\ndef T(x):\n if type(x)==np.array: return matrix(x).T\n else: \n try: return x.T\n except: return array(x).T\n \ndef inv(x):\n try: return np.linalg.inv(x)\n except: print(\"Either det(x)=0 or not square matrix\")\n \ndef det(x):\n try: return np.linalg.det(x)\n except: print(\"Not square matrix\")\n#------------- \ndef eye(x): return np.eye(x)\ndef I(x): return np.eye(x)\n#------------- \ndef ones(x, s = 1):\n if s == 1: return np.ones((x,x))\n else: return np.ones(x)\n \ndef J(x, s = 1): return ones(x, s)\n#------------- \ndef zeros(x, s = 1):\n if s == 1: return np.zeros((x,x))\n else: return np.zeros(x)\n \ndef zeroes(x, s = 1): return zeros(x, s)\ndef Z(x, s = 1): return zeros(x, s)\n#------------- \ndef triu(matrix): return np.triu(matrix)\ndef tril(matrix): return np.tril(matrix)\n#------------- \ndef trace(A): return np.trace(A)\ndef tr(A): return trace(A)\ndef diag(A): return np.diagonal(A)\n#------------- \ndef repmat(A, *args):\n if len(args) == 2: return np.tile(A, (args[0],args[1]))\n elif len(args) == 1: return np.tile(A, args[0])\n else: print(\"Error\")\n\ndef tile(A, *args): return repmat(A, args)\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ TABLE METHODS ------------------------------------#\n#-------------------- Opening and editing --------------------#\ndef read(x):\n if type(x) == list:\n for y in x: \n if \"csv\" in y: return clean(pd.read_csv(y))\n else: \n if \"csv\" in x: return clean(pd.read_csv(x))\n#------------- \ndef string(dfx, *args):\n x = copy(dfx); df = copy(dfx)\n if type(df) == pd.DataFrame:\n x, col = argcheck(df, args)\n for y in col:\n x[y] = x[y].astype(\"str\")+\"*\"\n return x\n elif type(df) == pd.Series: \n df = df.astype(\"str\")+\"*\"\n return df\n else: return str(df)\n#------------- \ndef clean(x, *args):\n def cleancol(x):\n if dtypes(x) == 'obj': \n c = x.str.replace(\",\",\"\").str.replace(\" \",\"\").str.replace(\"-\",\"\").str.replace(\"%\",\"\").str.replace(\"#\",\"\")\n else: c = x\n \n try: \n if ((sum(int(c)) - sum(float(c)) == 0) or sum(int(c)-float(c))==0) and count(c) == len(c): return int(c)\n else: return float(c)\n except: \n return x\n \n x = x.replace(np.inf, np.nan).replace(-np.inf, np.nan).replace(\"NaN\",np.nan)\n \n df = copy(x)\n if type(x) == pd.Series: return cleancol(x)\n else:\n if len(args)==0: col = columns(df)\n elif type(args[0]) != list: col = list(args)\n else: col = args[0]\n for y in col: df[y] = cleancol(df[y])\n return df\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ DATA ANALYTICS ------------------------------------#\n#-------------------- Analyse --------------------#\ndef analyse(c, y = None, extra = [\"skew\"], dec = 2, colour = True, limit = True, graph = True):\n x = copy(c)\n if y is not None:\n if type(y) == str: x, y = drop(x, y)\n first = describe(x, extra = extra, clean = False); cols = columns(first)\n df = hcat(guess_importance(x,y), first)\n df.columns = append(\"Importance\", cols)\n df = round(sort(df, by = [\"Importance\",\"FreqRatio\",\"%Unique\"], des = True),dec)\n if limit == True: df = df[df[\"Importance\"]>0]\n if graph == True: plot(x = index(df)[0], y = index(df)[1], z = index(df)[2], hue = y, data = c)\n if colour == True: df = df.style.bar(align='mid', color=pd_colour, width = 80).set_properties(**{'max-width': '90px'})\n return df\n\ndef describe(x, extra = [\"skew\"], clean = True):\n normal = hcat(mean(x), median(x), rng(x), freqratio(x), mode(x), punique(x))\n normal.columns = [\"Mean\",\"Median\",\"Range\", \"FreqRatio\", \"Mode\",\"%Unique\"]\n if type(extra)!=list: extra = [extra];extra = lower(extra); \n for j in extra:\n before = columns(normal)\n if \"skew\" in j: normal = hcat(normal, skew(x)); normal.columns = append(before, \"Skewness\")\n elif \"cat\" in j: normal = hcat(normal, iscat(x)); normal.columns = append(before, \"IsCategorical\")\n elif \"iqr\" in j: normal = hcat(normal, iqr(x)); normal.columns = append(before, \"InterQuartileRng\")\n elif \"var\" in j: normal = hcat(normal, var(x)); normal.columns = append(before, \"Variance\")\n elif \"std\" in j or \"sd\" in j: normal = hcat(normal, std(x)); normal.columns = append(before, \"SD\")\n elif \"min\" in j: normal = hcat(normal, np.min(x)); normal.columns = append(before, \"Min\")\n elif \"kurt\" in j: normal = hcat(normal, kurtosis(x)); normal.columns = append(before, \"Kurt\")\n elif \"max\" in j: normal = hcat(normal, np.max(x)); normal.columns = append(before, \"Max\")\n elif \"punq\" in j: normal = hcat(normal, punique(x)); normal.columns = append(before, \"%Unique\")\n elif \"nunq\" in j: normal = hcat(normal, nunique(x)); normal.columns = append(before, \"No.Unique\")\n df = sort(normal, by = \"FreqRatio\")\n if clean == True: return df.replace(np.nan,\"\")\n else: return df\n#-------------------- Var-Check and FreqRatio Check --------------------# \ndef varcheck(x, freq = \"mean\", unq = 0.1, colour = True, limit = True, output = False):\n freqs = freqratio(x); unqs = punique(x)\n if freq == \"mean\": fd = (freqs>=CI(q=0.99,data =freqs,L=False))*1\n else: fd = (freqs>freq)*1\n df = hcat(freqs,fd,unqs,(unqs<=unq)*1,var(x))\n df.columns = [\"FreqRatio\",\"BadFreq?\",\"%Unique\",\"BadUnq?\",\"Var\"]\n df[\"BadVar?\"] = (df[\"Var\"].fillna(1000)<=0.1)*1\n df[\"BAD?\"] = (df[\"BadFreq?\"]+df[\"BadUnq?\"]+df[\"BadVar?\"])>0\n df = round(sort(df, by =[\"BAD?\",\"BadVar?\",\"BadFreq?\",\"BadUnq?\",\"FreqRatio\",\"%Unique\",\"Var\"], des = True),2)\n \n if limit == True: df = T(T(df)[((df[\"BAD?\"]==True).index[df[\"BAD?\"]==True]).tolist()])\n if colour == True: \n df = df.style.bar(align='zero', color=pd_colour, width = 80, subset=[\"FreqRatio\",\"%Unique\",\"Var\"])\n df = df.apply(highlight_one, subset = [\"BadFreq?\",\"BadUnq?\",\"BadVar?\"]).apply(highlight_true, subset=[\"BAD?\"])\n df = df.set_properties(**{'max-width': '90px'})\n if output == True: return exc(x, index(df))\n else: return df\n \n#-------------------- Correlations --------------------# \ndef corr(x, table = False, limit = 20):\n if table == False:\n corrs = round(x.corr()*100)\n sortby = sort(sum(abs(corrs)-100),des=False)\n corrs = corrs[index(sortby)]\n corrs = T(T(corrs)[index(sortby)])\n if shape(corrs)[0]>limit: corrs = T(T(corrs.iloc[0:limit]).iloc[0:limit])\n corrs = T(reverse(T(reverse(corrs))))\n cmap = sb.light_palette(\"black\", as_cmap=True)\n show = abs(corrs).style.background_gradient(cmap).set_properties(**{'max-width': '50px', 'font-size': '8pt'\n ,'color':'black'})\n return show\n else:\n try: return conts(x).corr()\n except: print(\"Error. No continuous data\")\n \ndef correlation(x, table = False): return corr(x, table)\ndef correlation_matrix(x, table = False): return corr(x, table)\ndef cor(x, table = False): return corr(x, table)\n\n#-------------------- Feature Importance --------------------#\ndef guess_importance(df, y):\n x = copy(df)\n if type(y) == str:\n try: y = x[y]\n except: \n print(\"No column for y\")\n x = dummies(x)\n x_train, x_test, y_train, y_test = holdout(x, y, info = False);\n \n def lightmodel(x_train, x_test, y_train, y_test, reg, seed = 1234):\n try: import lightgbm as lgb\n except: print(\"Cannot install\"); raise\n x_train = array(x_train); y_train = array(y_train); x_test = array(x_test); y_test = array(y_test)\n if reg == True:\n model = lgb.LGBMRegressor(objective='regression', num_leaves = 5, learning_rate = 0.1, n_estimators = 100, seed = seed)\n model.fit(x_train, y_train, early_stopping_rounds = 10, eval_metric='l2', eval_set=[(x_test, y_test)],verbose=False)\n return model\n \n imps = lightmodel(x_train, x_test, y_train, y_test, reg = True).feature_importances_\n tab = table(imps); tab.index = columns(x)\n imps = dict(tab)[0]*100; cols = columns(df)\n\n imp = {k:0 for k in cols}\n for j in imps.keys():\n for c in cols:\n if c in j: imp[c] += imps[j]\n return series(imp)\n\ndef guess_imp(df, y): return guess_importance(df, y)\n\n#-------------------- Data Reduction --------------------#\n## https://stackoverflow.com/questions/29294983/how-to-calculate-correlation-between-all-columns-and-remove-highly-correlated-on\ndef remcor(x, limit = 0.9):\n dataset = copy(x)\n col_corr = set(); corr_matrix = dataset.corr()\n for i in range(len(corr_matrix.columns)):\n for j in range(i):\n if corr_matrix.iloc[i, j] >= limit:\n colname = corr_matrix.columns[i]\n col_corr.add(colname)\n if colname in dataset.columns: del dataset[colname]\n return dataset\ndef remcorr(x,limit=0.9): return remcor(x,limit)\n#-------------\n#https://stackoverflow.com/questions/28816627/how-to-find-linearly-independent-rows-from-a-matrix\ndef independent(A):\n try: import sympy\n except: \n print(\"Please install SYMPY: pip install sympy\"); raise\n _, inds = sympy.Matrix(A).T.rref()\n print(\"Lin Indp rows are: \"+str(inds))\n return A[list(inds)]\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ DUMMIFICATION ------------------------------------#\n#-------------------- Dummies method --------------------#\ndef dummies(x, dummies = True, codes = False, freq = True, na = \"inplace\", nanew = True, col = None, ascending = True, cat = True, drop = True,\n ids = False):\n try:\n if dtypes(x)[0]==('int' or 'float') and type(x)==pd.Series: return x\n except:\n if dtypes(x)==('int' or 'float') and type(x)==pd.Series: return x\n if type(x)!=pd.DataFrame: x = table(x)\n df = copy(x)\n if ids == False: df = exc(df, isid(df))\n if col is None: \n if cat == True: col = catcol(df)\n else: col = objcol(df)\n elif type(col)!=list: col = [col]\n if dummies == True:\n if \"in\" in na:\n for j in col:\n dummified = pd.get_dummies(x[j], dummy_na = nanew)\n dummified.columns = [str(j)+\"_\"+str(c) for c in columns(dummified)]\n if j in nacol(x): dummified.iloc[isnull(x[j]).index]=np.nan\n df = hcat(df, dummified)\n else: df = pd.get_dummies(x, dummy_na = nanew, columns = col)\n if drop == True: return notobj(zerodrop(df))\n else: return zerodrop(df)\n else:\n if freq == True:\n code = {}\n for j in col:\n part = {}; \n try: i = min(df[j]);\n except: i = 0;\n if dtype(df[j])!=('int'or'float'): d = fsort(df, by = j)[j]\n else: d = sort(df, by = j)[j]\n for k in d:\n if pd.isnull(k)==False:\n try: part[k]\n except: part[k] = i; i+=1\n code[j] = part\n df[j]=df[j].replace(part)\n del part,i,d,k\n else:\n code = {}\n for j in col: \n code[j] = reverse(dict(enumerate(df[j].astype(\"category\").cat.categories)))\n df[j]=df[j].replace(code[j])\n if drop == True: df = notobj(df)\n if shape(df)[1]==1: df = df[columns(df)[0]]\n if codes == True: return df,code\n else: return df\n#-------------------- Quantile conversion --------------------#\ndef discretise(x, n = 4, smooth = True, codes = False):\n if codes == False: codes = None\n else: codes = False\n if smooth == True:\n try: return pd.qcut(x, q = n, duplicates = 'drop', labels = codes)\n except: return pd.cut(x, q = n, labels = codes)\n else:\n return pd.cut(x, bins = n, labels = codes)\n \ndef qcut(x, n = 4, smooth = True, codes = False): return discretise(x, n, smooth, codes)\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ ADVANCED DATA ANALYTICS ------------------------------------#\n#-------------------- Skewness Analysis --------------------#\ndef topositive(y, info = False):\n x = copy(y); d = conts(x)\n notgood = ((np.min(d)<=0).index[np.min(d)<=0]).tolist()\n add = np.abs(np.min(d[notgood]))+1\n d[notgood] = d[notgood]+add\n x[columns(d)] = d\n if info == False: return x\n else: return x,add\n#------------- \ndef boxcox(x):\n if type(x) == pd.Series: \n k = (conts(x)+abs(min(conts(x)))+1)\n lm = scipy.stats.boxcox(k)[1]\n if lm == 0: return log(x), lm\n else: return ((k**lm)-1)/lm, lm\n else:\n df = []; lms = []\n for col in contcol(x):\n k = (x[col]+abs(min(x[col]))+1)\n lm = scipy.stats.boxcox(k)[1]\n if lm == 0: df.append(log(x[col])); lms.append(lm)\n else: df.append(((k**lm)-1)/lm); lms.append(lm)\n return T(table(df)), array(lms)\n#------------- \ndef unskew(x, info = False):\n def show(q, df):\n if q == 0: return (df, \"normal\")\n elif q == 1: return (sqrt(df), \"sqrt\")\n else: return (boxcox(df)[0], \"boxcox\")\n original = copy(x)\n df = topositive(conts(x))\n skews = np.abs(skew(df))\n sqrted = sqrt(df)\n boxcoxed = boxcox(df)[0]\n comp = hcat(skew(df),skew(sqrted),skew(boxcoxed)); comp.columns = [\"norm\",\"sqrt\",\"box\"]\n res = np.abs(comp.T)\n r = []; out = []\n for col in res:\n p = 0\n for i in res[col]:\n if i == np.min(res[col]):\n f = show(p, df[col]); r.append(f[1]); out.append(f[0]); break\n else: p += 1\n first = out[0]\n for c in out[1:]: first = hcat(first, c)\n \n del c, out, res, comp, sqrted, skews, boxcoxed, show\n original[columns(first)] = first\n res = table(r); res.index = columns(first)\n \n if info == True: return original, res[0]\n else: return original\n#------------- \ndef outlier(df, method = \"forest\", poutlier = 0.025, sd = 3.5, iqr = 1.5, indicate = True, n_estimators = 100):\n x = copy(df)\n if \"for\" in method or \"tree\" in method:\n from sklearn.ensemble import IsolationForest\n df = dummies(x, na = \"clear\"); df = df.fillna(df[nullcol].median())\n model = IsolationForest(n_estimators = n_estimators, n_jobs=-1, bootstrap = True, contamination = poutlier)\n model.fit(df); preds = model.predict(df)\n res = x.iloc[np.where(preds==-1)[0]]\n else:\n f = dummies(x, na = \"clear\"); df = topositive(f.fillna(f.median()))\n if \"std\" in method or \"sd\" in method:\n #https://stackoverflow.com/questions/22354094/pythonic-way-of-detecting-outliers-in-one-dimensional-observation-data\n if len(shape(df)) == 1: df = df[:,None]\n df = unskew(df)\n meds = median(df, axis=0)\n diff = sum((df - meds)**2, axis=1)\n diff = sqrt(diff); mad = median(diff)\n z = 0.6745 * diff / mad\n out = (z>sd)==True\n where = out.index[out].tolist()\n res = x.iloc[where]\n\n elif \"iqr\" in method:\n first = percentile(df, p = 0.25)\n last = percentile(df, p = 0.75)\n iqrred = first-last\n where = sum((df>(last+iqr*last))|(df<(first-iqr*first)))!=0\n res = x.iloc[where.index[where].tolist()]\n \n print(\"No. outliers = \"+str(len(res)))\n if indicate == True:\n x[\"IsOutlier\"] = 0\n try: x[\"IsOutlier\"].iloc[[res.index.tolist()]] = 1\n except: pass;\n return x\n else: return res\n \ndef isoutlier(df, method = \"forest\", poutlier = 0.025, sd = 3.5, iqr = 1.5, indicate = False, n_estimators = 100):\n d = outlier(df, method = method, poutlier = poutlier, sd = sd, iqr = iqr, indicate = True, n_estimators = n_estimators)\n if indicate == False: return exc(d.iloc[(d[\"IsOutlier\"]==1).index[d[\"IsOutlier\"]==1]], \"IsOutlier\")\n else: return d.iloc[(d[\"IsOutlier\"]==1).index[d[\"IsOutlier\"]==1]]\n\ndef notoutlier(df, method = \"forest\", poutlier = 0.025, sd = 3.5, iqr = 1.5, indicate = False, n_estimators = 100):\n d = outlier(df, method = method, poutlier = poutlier, sd = sd, iqr = iqr, indicate = True, n_estimators = n_estimators)\n if indicate == False: return exc(d.iloc[(d[\"IsOutlier\"]==0).index[d[\"IsOutlier\"]==0]], \"IsOutlier\")\n else: return d.iloc[(d[\"IsOutlier\"]==0).index[d[\"IsOutlier\"]==0]]\n#-------------\ndef zerodrop(x): return exc(x, (pzero(x)==100).index[pzero(x)==100].tolist())\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ DATA CLEANING AND CONVERSION ------------------------------------#\n#-------------------- Normal statistic filling --------------------#\ndef fillobj(x, method):\n data = copy(clean(x))\n missed = nacol(data[objcol(data)]); missdf = data[missed]\n if method in [\"mode\",\"freq\",\"frequency\"]: data[missed] = data[missed].fillna(mode(missdf))\n elif method in [\"zero\",\"missing\",\"none\"]: data[missed] = data[missed].fillna(\"Missing_Data\")\n elif method in [\"mix\",\"half\",\"halved\"]:\n ins = (count(x)<0.75*len(x)).index[count(x)<0.75*len(x)]\n data[ins] = data[ins].fillna(\"Missing_Data\")\n other = diff(columns(x), ins)\n data[other] = data[other].fillna(mode(x[other]))\n return data\n#-------------\ndef fillcont(x, method):\n data = copy(clean(x))\n missed = nacol(conts(data)); missdf = data[missed]\n if method in [\"mean\",\"avg\",\"average\"]: data[missed] = data[missed].fillna(mean(missdf))\n elif method in [\"median\"]: data[missed] = data[missed].fillna(median(missdf))\n elif method in [\"mode\",\"freq\",\"frequency\"]: data[missed] = data[missed].fillna(mode(missdf))\n return data\n#-------------------- Full methods --------------------#\ndef complete(df, method = None, objects = None, continuous = None, knn = 5, max_unique = 20, epoch = 100, mice = \"forest\", ids = False):\n x = copy(df); imputation = [\"bpca\",\"pca\",\"knn\",\"mice\",\"svd\"]; imped = 0\n if ids == False: x = exc(x, isid(x))\n if method is not None: meth = method.lower()\n else: meth = \"a\"\n if method is None and objects is None and continuous is None: meth = 'knn'\n \n if meth in imputation or objects in imputation or continuous in imputation:\n imped = 1\n try: import fancyimpute\n except: \n print(\"Please install fancyimpute for KNN,SVD. MICE,Forest,BPCA is allowed without it.\\nPip install fancyimpute\\nIf there are errors, please use Anaconda or install C++ build tools or MingW C++\\nSorry\"); raise\n \n def matching(method, objects, continuous, thingo):\n if method is not None:\n if thingo in method: return 1\n else: return 0\n else:\n if thingo in objects or thingo in continuous: return 1\n else: return 0\n \n res,codes = dummies(x, codes = True, dummies = False)\n intcols = (dtypes(res)=='int').index[dtypes(res)=='int'].tolist()\n\n if matching(meth, objects, continuous, \"knn\") == 1: dfilled = fancyimpute.KNN(k=knn, verbose = 0).complete(res)\n elif matching(meth, objects, continuous, \"svd\") == 1: dfilled = fancyimpute.SoftImpute(verbose = 0).complete(res)\n elif matching(meth, objects, continuous, \"mice\") == 1: \n print(\"Please wait...\")\n dfilled = mice_complete(res, epochs = int(epoch/10), impute_method = mice, strings = objcol(x))\n print(\"Done\")\n else: \n print(\"Please wait...\")\n dfilled = bpca_complete(res, epochs = epoch)\n print(\"Done\")\n\n dfilled = table(dfilled); dfilled.columns = columns(res)\n\n for col in codes: x[col] = squeeze(series(int(round(dfilled[col],0))), upper = len(codes[col])-1, lower = 0).replace(reverse(codes[col]))\n for col in contcol(x): x[col] = dfilled[col]\n for col in contcol(x): x[col] = squeeze(x[col], lower = np.min(df[col]), upper = np.max(df[col]))\n\n if (missingcol(x) != [] and objects in imputation) or meth in imputation: x = fillobj(x, \"mix\")\n elif objects is not None: x[objcol(x)] = fillobj(df[objcol(df)], objects)\n\n if continuous not in imputation and continuous is not None: x[contcol(x)] = fillcont(df[contcol(df)], continuous)\n\n x = round(x, 4)\n x[intcols] = int(round(x[intcols]))\n return x\n\n#-------------------- BPCA --------------------#\n#http://ishiilab.jp/member/oba/tools/BPCAFill.html\ndef bpca_complete(x, epochs = 100):\n decimals = 4\n y = copy(x); cols = y.columns.tolist()\n maximum = np.int(np.max(y.max())*999)\n means = round(y.mean(),decimals); sd = round(y.std(),decimals); y = round((y-means)/sd,decimals)\n y[missingcol(y)] = y[missingcol(y)].fillna(maximum)\n mat = float(np.matrix(y))\n\n N,d = mat.shape; q = d-1\n yest = np.copy(mat); yest[yest==maximum]=0\n\n missidx = {}; bad = np.where(mat==maximum)\n for a in bad[0]: missidx[a] = []\n for a in range(len(bad[0])): missidx[bad[0][a]].append(bad[1][a])\n\n nomissidx = {}; good = np.where(mat!=maximum)\n for a in good[0]: nomissidx[a] = []\n for a in range(len(good[0])): nomissidx[good[0][a]].append(good[1][a])\n\n gmiss = list(set(bad[0]))\n gnomiss = list(set(good[0]))\n\n covy = np.cov(yest.T)\n U, S, V = np.linalg.svd(np.matrix(covy))\n U = (U.T[0:q]).T; S = S[0:q]*np.eye(q); V = (V.T[0:q]).T\n\n mu = np.copy(mat); mu[mu==maximum]=np.nan; mu = np.nanmean(mu, 0)\n W = U*np.sqrt(S); tau = 1/ (np.trace(covy)-np.trace(S)); taumax = 1e20; taumin = 1e-20; tau = np.amax([np.amin([tau,taumax]),taumin])\n\n galpha0 = 1e-10; balpha0 = 1; alpha = (2*galpha0 + d)/(tau*np.diag(W.T*W)+2*galpha0/balpha0)\n gmu0 = 0.001; btau0 = 1; gtau0 = 1e-10; SigW = eye(q)\n tauold = 1000\n\n for epoch in range(epochs):\n Rx = np.eye(q)+tau*W.T*W+SigW; Rxinv = np.linalg.inv(Rx)\n idx = gnomiss; n = len(idx) \n dy = mat[idx,:] - np.tile(mu,(n,1)); x = tau * Rxinv * W.T * dy.T\n\n Td = dy.T*x.T; trS = np.sum(np.multiply(dy,dy))\n for n in range(len(gmiss)):\n i = gmiss[n]\n dyo = np.copy(mat)[i,nomissidx[i]] - mu[nomissidx[i]]\n Wm = W[missidx[i],:]; Wo = W[nomissidx[i],:]\n Rxinv = np.linalg.inv( Rx - tau*Wm.T*Wm ); ex = tau * Wo.T * np.matrix(dyo).T; x = Rxinv * ex\n dym = Wm * x; dy = np.copy(mat)[i,:]\n dy[nomissidx[i]] = dyo; dy[missidx[i]] = dym.T\n yest[i,:] = dy + mu\n Td = Td + np.matrix(dy).T*x.T; Td[missidx[i],:] = Td[missidx[i],:] + Wm * Rxinv\n trS = trS + dy*np.matrix(dy).T + len(missidx[i])/tau + np.trace( Wm * Rxinv * Wm.T )\n\n Td = Td/N; trS = trS/N; Rxinv = np.linalg.inv(Rx); \n Dw = Rxinv + tau*Td.T*W*Rxinv + np.diag(alpha)/N; Dwinv = np.linalg.inv(Dw);\n W = Td * Dwinv;\n\n tau = (d+2*gtau0/N)/(trS-np.trace(Td.T*W) + (mu*np.matrix(mu).T*gmu0+2*gtau0/btau0)/N)[0,0];\n SigW = Dwinv*(d/N);\n alpha = (2*galpha0 + d)/ (tau*np.diag(W.T*W)+np.diag(SigW)+2*galpha0/balpha0).T\n\n if np.abs(np.log10(tau)-np.log10(tauold)) < 1e-4: break;\n tauold = tau\n out = table(yest)\n out.columns = cols\n out = (out*sd)+means\n return out\n#-------------------- MICE --------------------#\n#https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3074241/\ndef mice_complete(res, strings, epochs = 10, impute_method = \"forest\"):\n x = copy(clean(res)); original = copy(x)\n filled = fillcont(original, method = \"median\")\n from sklearn.cross_validation import train_test_split\n \n for epoch in range(epochs):\n for missing_col in missingcol(original):\n null_data = isnull(original[missing_col]).index\n\n not_null = filled.iloc[notnull(original[missing_col]).index]\n y = not_null.pop(missing_col)\n \n if \"forest\" in impute_method or \"tree\" in impute_method or \"bag\" in impute_method:\n from sklearn.ensemble import RandomForestRegressor as rfr\n from sklearn.ensemble import RandomForestClassifier as rfc\n if missing_col in strings: model = rfc(n_jobs = -1, n_estimators=epochs*4)\n else: model = rfr(n_jobs = -1, n_estimators=epochs*4)\n \n elif \"linear\" in impute_method or \"log\" in impute_method:\n from sklearn.linear_model import LinearRegression as linreg\n from sklearn.linear_model import LogisticRegression as logreg\n if missing_col in strings: model = logreg(n_jobs = -1, solver = 'sag', multi_class = \"multinomial\")\n else: model = linreg(n_jobs = -1)\n \n elif \"boost\" in impute_method:\n from lightgbm import LGBMRegressor as xgbr\n from lightgbm import LGBMClassifier as xgbc\n if missing_col in strings: model = xgbc(learning_rate = 10/epochs, n_estimators=epochs*4, nthread =-1)\n else: model = xgbr(learning_rate = 10/epochs, n_estimators=epochs*4, nthread=-1)\n \n train_x, test_x, train_y, test_y = train_test_split(not_null, y, test_size=0.33, random_state=42)\n model.fit(train_x, train_y)\n\n filled[missing_col].iloc[null_data] = model.predict(exc(filled.iloc[null_data], missing_col))\n return filled\n#-------------------- Squeeze or round functions --------------------#\ndef squeeze(df, lower = 0, upper = 1):\n x = copy(df)\n x[xupper] = upper\n return x\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ MACHINE LEARNING ------------------------------------#\n#-------------------- Boosting --------------------#\ndef lightgbm(x_train, x_test, y_train, y_test, noclass = None, lr = 0.05, method = \"dart\", gpu = False, trees = 100, metric = None, \n depth = -1, splits=2, leaves=31.123, min_weight=20.123, features=1, bins=5.123, impurity=1e-3+0.000001, jobs=-1, state=None, bagging = 0.1, \n stop = 10, l1 = 0, l2 = 1, dropout = 0.1, skipdrop = 0.5, verbose = False, info = True):\n \n if noclass is None: \n try: noclass = nunique(array(hcat(y_train,y_test)))\n except: noclass = nunique(array(vcat(y_train,y_test)))\n\n if gpu == True: gpu = \"gpu\"\n else: gpu = \"cpu\"\n if min_weight <1: min_weight = int(min_weight*(len(vcat(x_train,y_train))))\n if bagging != False: bagged = 1;\n else: bagged = 0;\n if verbose == True: verbose = 1;\n else: verbose = 0;\n leaves = int(leaves); min_weight = int(min_weight); bins = int(bins)\n \n try: import lightgbm as lgb\n except:\n print(\"Cannot import\"); raise\n\n x_train = array(x_train); y_train = array(y_train); x_test = array(x_test); y_test = array(y_test)\n train_data = lgb.Dataset(x_train,label=y_train)\n\n mets = metrics(noclass,\"lightgbm\")\n param = {'num_leaves':leaves, 'application':mets[0],'max_depth':depth,'learning_rate':lr,'num_iterations':trees, 'device':gpu,\n 'max_depth':depth, 'metric':mets[1],'min_sum_hessian_in_leaf':impurity,'feature_fraction':features,\n 'min_data_in_bin':bins,'bagging_fraction':bagging,'bagging_freq':bagged,'early_stopping_round':stop,'lambda_l1':l1,\n 'lambda_l2':l2,'verbose':verbose,'nthread':jobs}\n \n if method == \"dart\": param['drop_rate'] = dropout; param['skip_drop'] = skipdrop\n elif mets[1] == 'multiclass': param['num_class'] = noclass\n \n print(\"--------------------------------\\nLightGBM: Training...\")\n modeller=lgb.train(param,train_data,trees)\n print(\"Finished\")\n \n if info == True:\n if mets[0] == ('binary' or 'multiclass'): preds = toclasses(modeller.predict(x_test), unique(hcat(y_train,y_test)))\n else: preds = modeller.predict(x_test)\n for k in list(mets[2].keys()): \n if k != 'rmse': print(\"Score = \"+str(k)+\" = \"+str(mets[2][k](y_test, preds)))\n else: print(\"Score = \"+str(k)+\" = \"+str(mets[2][k](y_test, preds)**0.5))\n \n return modeller\n\n#-------------------- RF --------------------#\ndef randomforest(x_train, x_test, y_train, y_test, noclass = None, lr = 0.05, method = \"dart\", gpu = False, trees = 100, metric = None, \n depth = -1, splits=2, leaves=31.123, min_weight=20, features=1, bins=5.123, impurity=1e-3+0.000001, jobs=-1, state=None, bagging = 0.1, \n stop = 10, l1 = 0, l2 = 1, dropout = 0.1, skipdrop = 0.5, verbose = False, info = True, addon = False):\n \n from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\n if noclass is None: \n try: noclass = nunique(array(hcat(y_train,y_test)))\n except: noclass = nunique(array(vcat(y_train,y_test)))\n \n if depth == -1: depth = None;\n if method not in [\"gini\",\"entropy\"]: method = \"gini\";\n if features == 1: features = \"auto\";\n if impurity == (1e-3+0.000001): impurity = 1e-07;\n if leaves == 31.123: leaves = None;\n if min_weight == 20.123: min_weight = 0;\n if bins == 5.123: bins = 1;\n\n leaves = int(leaves); bins = int(bins)\n \n x_train = array(x_train); y_train = array(y_train); x_test = array(x_test); y_test = array(y_test)\n mets = metrics(noclass,\"randomforest\")\n \n if mets[0] != 'regression':\n modeller = RandomForestClassifier(n_estimators=trees, criterion=method, max_depth=depth, min_samples_split=splits, min_samples_leaf=bins, \n min_weight_fraction_leaf=0.0, max_features=features, max_leaf_nodes=leaves, min_impurity_split=impurity, \n bootstrap=True, oob_score=info, n_jobs=jobs, random_state=state, verbose=verbose, warm_start=addon)\n else:\n modeller = RandomForestRegressor(n_estimators=trees, criterion=\"mse\", max_depth=depth, min_samples_split=splits, min_samples_leaf=bins, \n min_weight_fraction_leaf=0.0, max_features=features, max_leaf_nodes=leaves, min_impurity_split=impurity, \n bootstrap=True, oob_score=info, n_jobs=jobs, random_state=state, verbose=verbose, warm_start=addon)\n \n print(\"--------------------------------\\nRandomForest: Training...\")\n modeller.fit(x_train,y_train)\n print(\"Finished\")\n \n if info == True:\n preds = modeller.predict(x_test)\n for k in list(mets[1].keys()): \n if k != 'rmse': print(\"Score = \"+str(k)+\" = \"+str(mets[1][k](y_test, preds)))\n else: print(\"Score = \"+str(k)+\" = \"+str(mets[1][k](y_test, preds)**0.5))\n print(\"Score = \"+\"OOB\"+\" = \"+str(modeller.oob_score_))\n return modeller\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ SCALING AND NORMALISING ------------------------------------#\n#-------------------- Standardise --------------------#\ndef standardise(data, output = True, method = \"robust\"):\n if method == \"robust\": from sklearn.preprocessing import RobustScaler as scaler\n elif method == \"standard\": from sklearn.preprocessing import StandardScaler as scaler\n elif \"min\" in method or \"max\" in method: from sklearn.preprocessing import MinMaxScaler as scaler\n elif \"abs\" in method: from sklearn.preprocessing import MaxAbsScaler as scaler\n \n if type(data)==pd.DataFrame: cols = columns(data)\n scaler = scaler()\n res = scaler.fit(data)\n res = scaler.transform(data)\n if type(data)==pd.DataFrame: \n res = table(res)\n res.columns = cols\n if output == True: return res, scaler\n else: return res\n \n#-------------------- Normalise --------------------# \ndef normalise(data, output = True, method = \"l2\"):\n from sklearn.preprocessing import Normalizer\n \n if type(data)==pd.DataFrame: cols = columns(data)\n scaler = Normalizer(norm=method).fit(data)\n res = scaler.transform(data)\n if type(data)==pd.DataFrame: \n res = table(res)\n res.columns = cols\n if output == True: return res, scaler\n else: return res\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ PREPROCESS FUNCTION ------------------------------------#\n#-------------------- :) --------------------#\n\ndef preprocess(train, target, hold = 0.2, dummy = True, impute = \"bpca\", mice = \"boost\",remove_outlier = 0, scale = \"robust\", transform = 0,\n norm = False, output = True):\n \n processor = {'dummies':-1, 'impute':-1, 'scale':-1, 'transform':-1, 'norm':-1, 'columns':-1}\n \n if remove_outlier == 1: train = notoutlier(train)\n \n if type(target)==str: x = exc(train, target); y = train[target]\n if nunique(y)<=15: processor['target'] = unique(y)\n else: processor['target'] = -1\n \n x = complete(x, method = impute, mice = mice)\n \n if transform == (1 or True): x, unskewer = unskew(x, info = True)\n \n if dummy == False: x, codes = dummies(x, dummies = dummy, codes = True, ids = True)\n else: x = dummies(x, dummies = dummy, ids = True); codes = -2\n \n x = conts(x)\n if scale is not None and scale != False: \n if scale == True: x, scaler = standardise(x, method = \"robust\")\n else: x, scaler = standardise(x, method = scale)\n \n if norm is not None and norm != False: \n if norm == True: x, normer = normalise(x, method = \"l2\")\n else: x, normer = normalise(x, method = norm)\n \n if hold != (0 or False) and hold is not None: x_train, x_test, y_train, y_test = holdout(x, y = y)\n \n print(\"Processing finished :)\")\n if output == True:\n try: processor['dummies'] = codes\n except: pass;\n try: processor['impute'] = [impute,train,mice]\n except: pass;\n try: processor['scale'] = scaler\n except: pass;\n try: processor['norm'] = normer\n except: pass;\n try: processor['transform'] = unskewer\n except: pass;\n processor['columns'] = columns(x_train)\n return x_train, x_test, y_train, y_test, processor\n \n else: return x_train, x_test, y_train, y_test\n\n#-------------------- :) Transform the test data --------------------#\ndef prefit(test, processor):\n alldf = reset(vcat(processor['impute'][1],test), drop = True)\n df = complete(alldf, method = processor['impute'][0], ids = True, mice = processor['impute'][2])\n\n test = df[len(processor['impute'][1]):]\n if processor['dummies'] == -2: test = dummies(test, dummies = True, ids = True)\n a = set(processor['columns'])\n b = set(columns(test))\n matching = set.intersection(a,b)\n not_matching = a.symmetric_difference(matching)\n test = test[list(matching)]\n \n if processor['dummies'] == -2: \n try: \n tabs = int(table(np.zeros((len(test),len(not_matching)))))\n tabs.columns = list(not_matching)\n test[columns(tabs)] = tabs\n except: pass;\n test = test[processor['columns']]\n else:\n for key in list(processor['dummies'].keys()):\n try: test[key] = test[key].replace(processor['dummies'][key])\n except: pass;\n test = conts(test)\n\n if processor['scale']!=-1: test = processor['scale'].transform(test)\n if processor['norm']!=-1: test = processor['norm'].transform(test)\n \n df = table(test)\n df.columns = processor['columns']\n return df\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ METRICS AND HOLDOUT ------------------------------------#\n\ndef holdout(x, y, test = 0.2, seed = 1234, info = True):\n from sklearn.model_selection import train_test_split\n if info == True: print(\"--------------------------------\\nx_train, x_test, y_train, y_test\")\n return train_test_split(x, y, test_size = test, random_state = seed)\n#--------------------\ndef metrics(noclass, model = \"lightgbm\"):\n from sklearn.metrics import mean_squared_error, cohen_kappa_score, r2_score\n \n if model == \"lightgbm\":\n if noclass == 2: return ['binary', ['binary_logloss','auc'], {'kappa':cohen_kappa_score,'rmse':mean_squared_error}]\n elif noclass < 15: return ['multiclass', ['multi_logloss','multi_error'], {'kappa':cohen_kappa_score,'rmse':mean_squared_error}]\n else: return ['regression_l2', ['l2_root'], {'r2':r2_score,'rmse':mean_squared_error}]\n \n elif model == \"randomforest\":\n if noclass == 2: return ['binary', {'kappa':cohen_kappa_score,'rmse':mean_squared_error}]\n elif noclass < 15: return ['multiclass', {'kappa':cohen_kappa_score,'rmse':mean_squared_error}]\n else: return ['regression', {'r2':r2_score,'rmse':mean_squared_error}]\n#-------------------- \ndef toclasses(preds, classes):\n preds = np.round(preds)\n preds = int(squeeze(preds, lower = min(classes), upper = max(classes)))\n return preds\n#--------------------\ndef predict(test, model, processor):\n preds = model.predict(array(test))\n if processor['target'] != -1: return toclasses(preds, classes = processor['target'])\n else: return preds\n\n#-------------\n#-------------\n#-------------\n#-------------\n#------------------------------------ GRAPHING ------------------------------------#\ndef plot(x = None, y = None, z = None, hue = None, size = 8, data = None, color = 'afmhot', smooth = True, n = 4):\n dfdf = copy(data)\n import matplotlib.pyplot as plt\n if data is None and x is not None: print(\"Need to specify data\"); return\n try:\n if type(x)==str: xlabel = x; x = dfdf[xlabel]; x = dummies(x, dummies = False)\n except: pass;\n try: \n if type(y)==str: ylabel = y; y = dfdf[ylabel]; y = dummies(y, dummies = False)\n except: pass;\n try: \n if type(z)==str: zlabel = z; z = dfdf[zlabel]; z = dummies(z, dummies = False)\n except: pass;\n try: \n if type(hue)==str: huelabel = hue; hue = dfdf[huelabel]; hue = dummies(hue, dummies = False)\n except: pass;\n try: \n xlabel = columns(x)[0]; \n if xlabel is None: xlabel = \"X\"\n except: pass;\n try:\n ylabel = columns(y)[0]; \n if ylabel is None: ylabel = \"Y\"\n except: pass;\n try: \n zlabel = columns(z)[0];\n if zlabel is None: zlabel = \"Z\"\n except: pass;\n try: \n huelabel = columns(hue)[0]; \n if huelabel is None: huelabel = \"Hue\"\n except: pass;\n\n if x is not None and y is not None and z is not None:\n from mpl_toolkits.mplot3d import Axes3D\n import matplotlib\n fig = plt.figure(figsize=(size,size))\n ax = Axes3D(fig)\n if hue is not None:\n cm = plt.get_cmap(color)\n try: cNorm = matplotlib.colors.Normalize(vmin=np.min(hue)[0], vmax=np.max(hue)[0])\n except: cNorm = matplotlib.colors.Normalize(vmin=np.min(hue), vmax=np.max(hue))\n scalarMap = matplotlib.cm.ScalarMappable(norm=cNorm, cmap=cm)\n ax.scatter(array(x),array(y),array(z),c=scalarMap.to_rgba(array(hue)),s=size*5)\n ax.set_xlabel(xlabel); ax.set_ylabel(ylabel); ax.set_zlabel(zlabel)\n scalarMap.set_array(hue)\n fig.colorbar(scalarMap, pad=0, orientation = \"h\", shrink = .8)\n plt.show()\n else:\n import matplotlib\n ax.scatter(x,y,z,s=size*5)\n ax.set_xlabel(xlabel); ax.set_ylabel(ylabel); ax.set_zlabel(zlabel)\n plt.show()\n \n else:\n import seaborn as sb\n try: \n if check_type(dfdf[xlabel]) == 'cat': dfdf[xlabel] = string(dfdf[xlabel])\n except: pass;\n try: \n if check_type(dfdf[ylabel]) == 'cat': dfdf[ylabel] = string(dfdf[ylabel])\n except: pass;\n try: \n if check_type(dfdf[huelabel]) == 'cat': dfdf[huelabel] = string(dfdf[huelabel])\n except: pass;\n\n if y is None and hue is None:\n fig = plt.figure(figsize=(size,size))\n\n if check_type(dfdf[xlabel]) == 'cont':\n fig = sb.kdeplot(data = dfdf[xlabel], linewidth = 3,clip = [min(dfdf[xlabel]),max(dfdf[xlabel])])\n mean_line(dfdf[xlabel])\n plt.ylabel(\"Frequency\"); plt.xlabel(xlabel); plt.title(\"Kernel Density graph\"); plt.show()\n\n elif check_type(dfdf[xlabel]) == 'cat':\n fig = sb.countplot(dfdf[xlabel].fillna(\"Missing\"))\n plt.title(\"Count graph for \"+xlabel); plt.show()\n\n elif y is None:\n if check_type(dfdf[xlabel]) == 'cont': sort_by = xlabel\n else: sort_by = huelabel\n\n if dtypes(dfdf[huelabel])[0] != 'obj':\n df = sort(dfdf, by = sort_by)\n dfdf[sort_by+\"_Q\"] = qcut(dfdf[sort_by], smooth = smooth, n = n)\n dfdf[sort_by+\"_Q\"] = string(dfdf[sort_by+\"_Q\"])\n\n fig = plt.figure(figsize=(size,size))\n if check_type(dfdf[xlabel]) == 'cont':\n\n if check_type(dfdf[huelabel]) == \"cont\":\n fig = sb.violinplot(x=xlabel+\"_Q\", y=huelabel, bw='scott' ,scale=\"width\",\n cut=min(dfdf[huelabel]), inner = None, linewidth =4, data = dfdf)\n plt.setp(fig.get_xticklabels(), rotation=45); plt.title(\"Violin graph for \"+xlabel+\" & \"+huelabel)\n plt.show()\n\n elif check_type(dfdf[huelabel]) == 'cat':\n fig = sb.countplot(x = xlabel+\"_Q\", hue = huelabel, data = dfdf)\n plt.title(\"Count graph for \"+xlabel+\" & \"+huelabel); plt.setp(fig.get_xticklabels(), rotation=45)\n plt.show()\n\n elif check_type(dfdf[xlabel]) == 'cat':\n if check_type(dfdf[huelabel]) == \"cont\":\n fig = sb.countplot(x = xlabel, hue = huelabel+\"_Q\", data = dfdf)\n plt.title(\"Count graph for \"+xlabel+\" & \"+huelabel); plt.setp(fig.get_xticklabels(), rotation=45)\n plt.show()\n\n if check_type(dfdf[huelabel]) == \"cat\":\n fig = sb.countplot(x = xlabel, hue = huelabel, data = dfdf)\n plt.title(\"Count graph for \"+xlabel+\" & \"+huelabel); plt.setp(fig.get_xticklabels(), rotation=45)\n plt.show()\n\n elif hue is None:\n if check_type(dfdf[xlabel]) == 'cont':\n\n if check_type(dfdf[ylabel]) == 'cont':\n fig = plt.figure(figsize=(size,size))\n dfdf = notnull(dfdf)\n dfdf[xlabel+\"_Q\"] = qcut(dfdf[xlabel], n = 30, smooth = True)\n dfdf = (dfdf.groupby(by = xlabel+\"_Q\").median()+dfdf.groupby(by = xlabel+\"_Q\").mean())/2\n sb.regplot(x = xlabel, y = ylabel, data = dfdf, ci = None, truncate=True, order=2, color = 'black')\n plt.title(\"Regression graph for \"+xlabel+\" & \"+ylabel); plt.show()\n\n elif check_type(dfdf[ylabel]) == 'cat':\n fig, (ax1,ax2) = plt.subplots(1,2, sharey = True, figsize = (size*1.5,size))\n sb.boxplot(x = xlabel, y = ylabel, data = dfdf, palette=\"Set3\", linewidth = 3, whis = 1, ax = ax1)\n sb.pointplot(x = xlabel, y = ylabel, data = dfdf, lw=5, ax = ax2, ci = 50, capsize = .1, palette = 'Set1')\n plt.title(\"Mean PointPlot graph for \"+xlabel+\" & \"+ylabel); plt.show()\n\n elif check_type(dfdf[xlabel]) == 'cat':\n\n if check_type(dfdf[ylabel]) == 'cont':\n fig, (ax1,ax2) = plt.subplots(1,2, sharey = False, figsize = (size*1.5,size))\n sb.boxplot(x = xlabel, y = ylabel, data = dfdf, palette=\"Set3\", linewidth = 3, whis = 1, ax = ax1)\n plt.setp(ax1.get_xticklabels(), rotation=45)\n plt.setp(ax2.get_xticklabels(), rotation=45)\n sb.pointplot(x = xlabel, y = ylabel, data = dfdf, lw=5, ax = ax2, ci = 50, capsize = .1, palette = 'Set1')\n plt.title(\"Mean PointPlot graph for \"+xlabel+\" & \"+ylabel); plt.show()\n\n elif check_type(dfdf[ylabel]) == 'cat':\n fig = sb.factorplot(x = xlabel, col = ylabel, data = dfdf, size = 5, palette=\"Set2\", col_wrap = 4, kind = \"count\")\n plt.show() \n else:\n if check_type(dfdf[huelabel]) == 'cont':\n dfdf = notnull(sort(dfdf, by = huelabel))\n dfdf[huelabel] = string(qcut(dfdf[huelabel], smooth = False, n = 4))\n\n elif check_type(dfdf[huelabel]) == 'cat':\n dfdf = notnull(dfdf)\n\n if check_type(dfdf[xlabel]) == 'cat':\n\n if check_type(dfdf[ylabel]) == 'cont':\n try: \n fig = plt.figure(figsize=(size,size))\n fig = sb.barplot(x = xlabel, y = ylabel, hue = huelabel, data = dfdf)\n plt.setp(fig.get_xticklabels(), rotation=45)\n plt.show()\n except:\n fig = sb.factorplot(x = xlabel, y = ylabel, data = dfdf, col = huelabel, size = 5, capsize=.1, palette=\"Set2\", ci = 70)\n plt.show()\n\n elif check_type(dfdf[ylabel]) == 'cat':\n fig = sb.factorplot(x = xlabel, hue = ylabel, data = dfdf, col = huelabel, kind = \"count\", size = 5)\n plt.show()\n\n elif check_type(dfdf[xlabel]) == 'cont':\n\n if check_type(dfdf[ylabel]) == 'cont':\n fig = plt.figure(figsize=(size,size))\n fig = sb.lmplot(x = xlabel, y = ylabel, hue = huelabel, data = dfdf,robust = True, n_boot = 50, scatter = False, ci = None)\n plt.show()\n\n elif check_type(dfdf[ylabel]) == 'cat':\n fig = sb.factorplot(x = xlabel, y = ylabel, col = huelabel, data = dfdf, palette = \"Set3\", dodge=True, ci = 70, \n estimator = special_statistic, capsize=.2, n_boot = 100, size = 5)\n plt.show()\n \ndef highlight_larger(s):\n is_max = s > CI(99,s,L=False); return ['background-color: '+pd_colour if v else '' for v in is_max]\ndef highlight_smaller(s):\n is_min = s < CI(99,s,U=False); return ['background-color: '+pd_colour if v else '' for v in is_min]\ndef highlight_one(s):\n is_true = s == 1; return ['background-color: '+pd_colour if v else '' for v in is_true]\ndef highlight_true(s):\n is_true = s == True; return ['background-color: '+pd_colour if v else '' for v in is_true]\n\n#------------- \ndef mean_line(x, **kwargs):\n ls = {\"0\":\"--\"}\n plt.axvline(mean(x), linestyle =ls[kwargs.get(\"label\",\"0\")], \n color = kwargs.get(\"color\", \"brown\"), linewidth=2)\n txkw = dict(size=12, color = kwargs.get(\"color\", \"brown\"))\n plt.text(mean(x),0.03, \"MEAN\", **txkw)\n#------------- \ndef special_statistic(x): return (2*np.nanmedian(x)+np.nanmean(x))/3\n#-------------\ndef check_type(x):\n ctd = nunique(x); parts = (((ctd<=15)&(len(x)>15))|((ctd\",'\"',\"'\",\"/\",\"<\",\">\",\"%\"]:\n now = now.str.replace(j,\"\")\n elif \"symbol\" in args[c]: now = now.replace(r'[^\\w]','')\n else: now = now.str.replace(args[c][0], \"\")\n elif \"len\" in c: \n if args[c] == 1: now = now.str.len()\n elif \"low\" in c:\n if args[c] == 1: now = now.str.lower()\n elif \"up\" in c:\n if args[c] == 1: now = now.str.upper()\n elif \"count\" in c: \n if args[c] == \".\": now = now.str.count(r\"(\\.)\")\n elif args[c] == \"(\": now = now.str.count(r\"(\\()\")\n elif args[c] == \")\": now = now.str.count(r\"(\\))\")\n elif args[c] == \"[\": now = now.str.count(r\"(\\[)\")\n elif args[c] == \"]\": now = now.str.count(r\"(\\])\")\n elif args[c] == \"{\": now = now.str.count(r\"(\\{)\")\n elif args[c] == \"}\": now = now.str.count(r\"(\\})\")\n elif 'symbol' in args[c]: now = now.str.count(r'[^\\w]')\n elif 'sym' in args[c]: now = now.str.count(r'[\\w]')\n elif 'num' in args[c] or 'dig' in args[c]: now = now.str.count(r'[\\d]')\n else: now = now.str.count(args[c]) \n elif \"df\" in c or \"table\" in c or \"series\" in c: now = now.apply(pd.Series)\n return now\n \ndef get(x, **args):\n import re\n now = copy(x)\n for c in args:\n now = getfunction(c, args, now)\n return now\n\ndef extract(x, **args): return get(x, args)\n#-------------------- Word Frequency --------------------#\ndef flatten(y, split = \" \", dropna = True, symbols = False, lower = True):\n \n def col_split(x,split,dropna,symbols,lower):\n if split is not None: \n if symbols == False: \n if lower == True: f = list(get(x, lower = True, rem = \"all\", splitex = split).fillna(np.nan).values.flatten())\n else: f = list(get(x, rem = \"all\", splitex = split).fillna(np.nan).values.flatten())\n else: f = list(get(x, splitex = split).fillna(np.nan).values.flatten())\n else: f = list(x.fillna(np.nan).values.flatten())\n return f\n \n if type(y)==pd.Series: flattened = col_split(y,split,dropna,symbols,lower)\n else:\n flattened = []\n for col in strs(y): \n flattened += col_split(y[col],split,dropna,symbols,lower)\n if dropna == True: return list(array(flattened)[array(flattened)!='nan'])\n else: return flattened\n#------------- \ndef wordfreq(x, hist = True, first = 15, separate = True):\n if separate == False or type(x) == pd.Series:\n df = reset(table(cunique(flatten(x))))[0:first]\n df.columns = [\"Word\",\"Count\"]\n \n else:\n first = int(first/len(strs(x)))\n df = reset(table(cunique(flatten(x[strs(x)[0]]))))[0:first]\n df.columns = [\"Word\",\"Count\"]\n df[\"Column\"] = objcol(x)[0]\n for col in objcol(x)[1:]:\n dfx = reset(table(cunique(flatten(x[col]))))[0:first]\n dfx.columns = [\"Word\",\"Count\"]\n dfx[\"Column\"] = col\n df = vcat(df,dfx)\n \n if hist == True: \n \n if separate == True and type(x) != pd.Series:\n k = first*1.25\n if k < 10: k = 8\n fig = plt.figure(figsize=(k,k))\n fig = sb.barplot(x = \"Word\", y = \"Count\", hue = \"Column\", data = df)\n plt.setp(fig.get_xticklabels(), rotation=45, size = 16)\n else: \n fig = plt.figure(figsize=(first*0.5,first*0.35))\n fig = sb.barplot(x = \"Word\", y = \"Count\", data = df)\n plt.setp(fig.get_xticklabels(), rotation=45, size = 16)\n plt.show() \n else:\n return df\n#------------- \ndef getwords(y, first = 10):\n x = copy(y)\n df = wordfreq(x, first = first, hist = False)\n for col in objcol(x):\n cols = get(x[col], lower = True, rem = \"all\", table = True)\n for j in df[df[\"Column\"]==col][\"Word\"]:\n x[\"Count=\"+str(j)] = get(cols[0], count = j)\n return x\n\n#-------------\n\n#------------- Daniel Han-Chen 2017\n#------------- https://github.com/danielhanchen/sciblox\n#------------- SciBlox v0.2.8\n#-------------\n","sub_path":"sciblox/sciblox.py","file_name":"sciblox.py","file_ext":"py","file_size_in_byte":73696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"55780906","text":"# -*- coding:utf-8 -*-\r\nimport numpy as np\r\n\r\n\"\"\"\r\n给定一个二维数组,每行都是递增,每列也是递增,给定一个数字,查找是否在mat中\r\n\"\"\"\r\n\r\n\r\nclass Solution:\r\n\r\n def Find(self, mat, num):\r\n # write code here\r\n found = False\r\n m, n = np.shape(mat)\r\n if mat is not None and m > 0 and n > 0:\r\n row = 0\r\n colum = n - 1\r\n while row < m and colum >= 0:\r\n if mat[row][colum] == num:\r\n found = True\r\n break\r\n elif mat[row][colum] > num:\r\n colum -= 1\r\n else:\r\n row += 1\r\n return found\r\n\r\n\r\nif __name__ == '__main__':\r\n mat = [[1, 2, 8, 9], [2, 4, 9, 12], [4, 7, 10, 13], [6, 8, 11, 15]]\r\n num = 7\r\n print(Solution().Find(mat, num))\r\n # print(dups)\r\n # print(arr)\r\n","sub_path":"CodeOffer/1FindMat.py","file_name":"1FindMat.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"567715141","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport re\nimport random\n\n\nbase_url = \"https://zh.wikipedia.org\"\nhis = [\"/wiki/%E7%B6%B2%E8%B7%AF%E7%88%AC%E8%9F%B2\"]\nfor i in range(20):\n url = base_url + his[-1]\n html = urlopen(url).read().decode('utf-8')\n soup = BeautifulSoup(html, 'lxml')\n print(soup.find('h1').get_text(), 'url:', his[-1])\n\n sub_urls = soup.find_all(\"a\", {\"href\": re.compile('/wiki/(%.{2})+$')})\n # print(sub_urls)\n if len(sub_urls) != 0:\n his.append(random.sample(sub_urls, 1)[0]['href'])\n else:\n # no valid sub link found\n his.pop()\n\n\n\n","sub_path":"scrapingPC.py","file_name":"scrapingPC.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"399028009","text":"class Status(object):\n\n \"\"\"\n The Status class is a parental class to the Player and Monster class, holding their Status\n\n Attributes:\n default_stats class dictionary int Holds defaults stats of specific instances of Status\n self.stats dictionary int Holds current stats\n \"\"\"\n\n default_stats = {\n 'player': (None, 1000, 200, 1, None),\n 'monster': (None, 400, 100, 0, None)\n }\n\n stat_names = ('name', 'health', 'strength', 'food', 'coord')\n\n def __init__(self, creature, name, coord = None):\n \"\"\"\n Initialize self.stats dictionary by fetching desired default stats from the defaults_stats dictionary.\n Self.coord is optional\n \"\"\"\n\n self.stats = dict(zip(Status.stat_names, Status.default_stats.get(creature, None)))\n self.stats['name'] = name\n self.stats['coord'] = coord","sub_path":"classes/creatures/class_Status.py","file_name":"class_Status.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"115328512","text":"import os\nimport unittest\nfrom uuid import uuid4\n\nimport pytest\nfrom dotenv import load_dotenv\n\nfrom runningbox_api_python import __version__\nfrom runningbox_api_python.client import Client\nfrom runningbox_api_python.constants import Service\nfrom runningbox_api_python.resources import Order\n\n\nclass OrdersTest(unittest.TestCase):\n order_data_for_estimate = {\n \"ubigeo\": \"150131\",\n \"servicio\": \"EXPRESS\",\n \"peso\": \"43.00\",\n }\n order_data_for_create = {\n # Cliente de envio\n \"cliente\": \"Customer Inc.\",\n \"cliente_ruc\": \"20601826535\",\n \"piezas\": \"10\",\n \"imp_seguro\": \"\",\n \"descripcion\": \"Sample description\",\n \"peso\": \"10.0\",\n \"cod\": \"\",\n \"dd\": \"\",\n \"importe_cod\": \"0.00\",\n \"servicio\": Service.EXPRESS,\n # Cliente final\n \"cliente_final\": \"Jhon Doe\",\n \"tipo_doc\": \"1\",\n \"numero_doc\": \"123456789\",\n # \"documento1\": \"\",\n # \"nrodoc1\":\"\",\n # \"documento2\":\"\",\n # \"nrodoc2\":\"\",\n # \"documento3\":\"\",\n # \"nrodoc3\":\"\",\n # \"documento4\":\"\",\n # \"nrodoc4\":\"\",\n # Entrega\n \"ubigeo\": \"150101\",\n \"departamento\": \"Lima\",\n \"provincia\": \"Lima\",\n \"distrito\": \"Lima\",\n \"direccion\": \"jr la mar 1000\",\n \"observacion\": \"\",\n \"mail\": \"jhon.doe@example.com\",\n \"telefono\": \"999999999\",\n \"contacto\": \"Margery Doe (999999998)\",\n # Recojo\n \"nombre_resp_almacen\": \"Donnald Doe (999999997)\",\n \"dni_resp_almacen\": \"123456788\",\n \"telefono_resp_almacen\": \"999999997\",\n \"arco_resp_almacen\": \"8:00 - 19:00\",\n \"direccion_almacen\": \"Sample Address 777, No where.\",\n \"ubigeo_almacen\": \"150132\",\n \"flag_inversa\": 0,\n \"flag_canal\": 1,\n \"notas\": \"\",\n \"productos\": [\n {\n \"nombre\": \"delirium/bvd hombre addiction/talla:xl/color:azul y negro\",\n \"descripcion\": \"delirium-bvd-hombre-addiction-1-018171\",\n \"sku\": \"dbh-add-blrj-xl\",\n \"peso\": 10,\n }\n ],\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n load_dotenv()\n self.version = __version__\n\n self.api_key = os.environ.get(\"API_KEY\", \"sample_api_key\")\n self.broker_tax_id = os.environ.get(\"BROKER_TAX_ID\", \"sample_api_secret\")\n\n self.request_number = \"CUSTOMER-{0}\".format(uuid4().hex)\n self.order_number = None\n self.client = Client(self.api_key, self.broker_tax_id)\n self.order = Order(client=self.client)\n\n def test_order_attribute_type(self):\n order = getattr(self.client, \"order\", None)\n assert isinstance(order, Order)\n\n def test_order_client(self):\n order = getattr(self.client, \"order\", None)\n assert order.client == self.client\n\n @pytest.mark.vcr()\n def test_order_estimate_status_code(self):\n response = self.order.estimate(self.order_data_for_estimate)\n assert response[\"status\"] == 200\n\n @pytest.mark.vcr()\n def test_order_create_status_code(self):\n self.order_data_for_create.update({\"nro_pedido\": self.request_number})\n response = self.order.create(self.order_data_for_create)\n assert response[\"status\"] == 200\n self.order_number = response[\"data\"][\"NRO_ORDEN\"]\n\n @pytest.mark.vcr()\n def test_order_tracking_status_code_with_request_number(self):\n response = self.order.tracking(self.request_number)\n assert response[\"status\"] == 200\n\n @pytest.mark.vcr()\n def test_order_tracking_status_code_with_order_number(self):\n response = self.order.tracking(self.order_number)\n assert response[\"status\"] == 200\n\n @pytest.mark.vcr()\n def test_order_trackin_compare_order_number_and_request_number(self):\n request_number_response = self.order.tracking(self.request_number)\n order_number_response = self.order.tracking(self.order_number)\n\n assert request_number_response == order_number_response\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_orders.py","file_name":"test_orders.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"393940555","text":"\"\"\"\nmav_dynamics\n - this file implements the dynamic equations of motion for MAV\n - use unit quaternion for the attitude state\n\n\"\"\"\n\n'''\nQuestions:\nFinal Vg, gamma, chi calculations\n'''\n\n\nimport sys\nsys.path.append('..')\nimport numpy as np\nfrom math import sqrt,cos,sin,pi,atan2,asin\n\n# load message types\nfrom message_types.msg_state import msg_state\nfrom message_types.msg_sensors import msg_sensors\n\nimport parameters.aerosonde_parameters as MAV\nimport parameters.sensor_parameters as SENSOR\nfrom tools.tools import Quaternion2Euler, RotationVehicle2Body, RotationBody2Vehicle\n\nclass mav_dynamics:\n def __init__(self, Ts, initial_position):\n self._ts_simulation = Ts\n # set initial states based on parameter file\n # _state is the 13x1 internal state of the aircraft that is being propagated:\n # _state = [pn, pe, pd, u, v, w, e0, e1, e2, e3, p, q, r]\n # We will also need a variety of other elements that are functions of the _state and the wind.\n # self.true_state is a 19x1 vector that is estimated and used by the autopilot to control the aircraft:\n # true_state = [pn, pe, h, Va, alpha, beta, phi, theta, chi, p, q, r, Vg, wn, we, psi, gyro_bx, gyro_by, gyro_bz]\n self._state = np.array([[initial_position[0]], # (0)\n [initial_position[1]], # (1)\n [initial_position[2]], # (2)\n [MAV.u0], # (3)\n [MAV.v0], # (4)\n [MAV.w0], # (5)\n [MAV.e0], # (6)\n [MAV.e1], # (7)\n [MAV.e2], # (8)\n [MAV.e3], # (9)\n [MAV.p0], # (10)\n [MAV.q0], # (11)\n [MAV.r0]]) # (12)\n # store wind data for fast recall since it is used at various points in simulation\n self._wind = np.array([[0.], [0.], [0.]]) # wind in NED frame in meters/sec\n #self.chi_prev = 0.\n\n # store forces to avoid recalculation in the sensors function\n self._forces = np.array([[0.], [0.], [0.]])\n self._Va = MAV.u0\n self._alpha = 0.0\n self._beta = 0.0\n self._update_velocity_data()\n\n # initialize true_state message\n self.msg_true_state = msg_state()\n self._update_msg_true_state()\n\n # initialize the sensors message\n self.sensors = msg_sensors()\n # random walk parameters for GPS\n self._gps_eta_n = 0.\n self._gps_eta_e = 0.\n self._gps_eta_h = 0.\n # timer so that gps only updates every ts_gps seconds\n self._t_gps = 999. # large value ensures gps updates at initial time.\n\n ###################################\n # public functions\n def update(self,delta,wind):\n self.update_state(delta,wind)\n self.update_sensors()\n\n\n def update_state(self, delta, wind):\n '''\n Integrate the differential equations defining dynamics, update sensors\n delta = (delta_a, delta_e, delta_r, delta_t) are the control inputs\n wind is the wind vector in inertial coordinates\n Ts is the time step between function calls.\n '''\n # get forces and moments acting on rigid bod\n forces_moments = self._forces_moments(delta)\n\n # Integrate ODE using Runge-Kutta RK4 algorithm\n time_step = self._ts_simulation\n k1 = self._derivatives(self._state, forces_moments)\n k2 = self._derivatives(self._state + time_step/2.*k1, forces_moments)\n k3 = self._derivatives(self._state + time_step/2.*k2, forces_moments)\n k4 = self._derivatives(self._state + time_step*k3, forces_moments)\n self._state += time_step/6. * (k1 + 2.*k2 + 2.*k3 + k4)\n\n # normalize the quaternion\n e0 = self._state.item(6)\n e1 = self._state.item(7)\n e2 = self._state.item(8)\n e3 = self._state.item(9)\n normE = np.sqrt(e0**2+e1**2+e2**2+e3**2)\n self._state[6][0] = self._state.item(6)/normE\n self._state[7][0] = self._state.item(7)/normE\n self._state[8][0] = self._state.item(8)/normE\n self._state[9][0] = self._state.item(9)/normE\n\n # update the airspeed, angle of attack, and side slip angles using new state\n self._update_velocity_data(wind)\n\n # update the message class for the true state\n self._update_msg_true_state()\n\n\n\n ###################################\n # private functions\n def _derivatives(self, state, forces_moments):\n \"\"\"\n for the dynamics xdot = f(x, u), returns f(x, u)\n \"\"\"\n # extract the states\n u = state.item(3)\n v = state.item(4)\n w = state.item(5)\n\n e0 = state.item(6)\n e1 = state.item(7)\n e2 = state.item(8)\n e3 = state.item(9)\n\n\n p = state.item(10)\n q = state.item(11)\n r = state.item(12)\n # extract forces/moments\n fx = forces_moments.item(0)\n fy = forces_moments.item(1)\n fz = forces_moments.item(2)\n l = forces_moments.item(3)\n m = forces_moments.item(4)\n n = forces_moments.item(5)\n\n # position kinematics\n pn_dot = (e1**2+e0**2-e2**2-e3**2)*u + 2*(e1*e2-e3*e0)*v + 2*(e1*e3+e2*e0)*w\n pe_dot = 2*(e1*e2+e3*e0)*u + (e2**2+e0**2-e1**2-e3**2)*v + 2*(e2*e3-e1*e0)*w\n pd_dot = 2*(e1*e3-e2*e0)*u + 2*(e2*e3+e1*e0)*v + (e3**2+e0**2-e1**2-e2**2)*w\n\n # position dynamics\n u_dot = r*v-q*w + fx/MAV.mass\n v_dot = p*w-r*u + fy/MAV.mass\n w_dot = q*u-p*v + fz/MAV.mass\n\n # rotational kinematics\n e0_dot = 0.5*(-p*e1-q*e2-r*e3)\n e1_dot = 0.5*(p*e0+r*e2-q*e3)\n e2_dot = 0.5*(q*e0-r*e1+p*e3)\n e3_dot = 0.5*(r*e0+q*e1-p*e2)\n\n # rotatonal dynamics\n p_dot = MAV.gamma1*p*q - MAV.gamma2*q*r + MAV.gamma3*l + MAV.gamma4*n\n q_dot = MAV.gamma5*p*r - MAV.gamma6*(p**2-r**2) + m/MAV.Jy\n r_dot = MAV.gamma7*p*q - MAV.gamma1*q*r + MAV.gamma4*l + MAV.gamma8*n\n\n # collect the derivative of the states\n x_dot = np.array([[pn_dot, pe_dot, pd_dot, u_dot, v_dot, w_dot,\n e0_dot, e1_dot, e2_dot, e3_dot, p_dot, q_dot, r_dot]]).T\n return x_dot\n\n def _update_velocity_data(self, wind=np.zeros((6,1))):\n # compute airspeed\n\n e0 = self._state.item(6)\n e1 = self._state.item(7)\n e2 = self._state.item(8)\n e3 = self._state.item(9)\n #print(\"EEEES=\",e0,e1,e2,e3)\n\n\n phi, theta, psi = Quaternion2Euler(np.array([e0,e1,e2,e3]))\n #print(\"angles=\",phi,theta,psi)\n Rv2b = RotationVehicle2Body(phi, theta, psi)\n wind_result = np.matmul(Rv2b,wind[0:3]) + wind[3:6]\n self._wind = np.matmul(Rv2b,wind_result)\n\n uw = wind_result.item(0)\n vw = wind_result.item(1)\n ww = wind_result.item(2)\n\n ur = self._state[3] - uw\n vr = self._state[4] - vw\n wr = self._state[5] - ww\n\n ur = ur.item(0)\n vr = vr.item(0)\n wr = wr.item(0)\n\n\n self._Va = sqrt(ur**2+vr**2+wr**2)\n #print(\"update_velocities =\",self._Va)\n # compute angle of attack\n self._alpha = atan2(wr,ur)\n # compute sideslip angle\n self._beta = np.arcsin(vr/self._Va)\n # Vg, chi, gamma\n\n\n Rb2v = RotationBody2Vehicle(phi, theta, psi)\n\n Vg_result = np.matmul(Rb2v,self._state[3:6])\n Vg_n = Vg_result.item(0)\n Vg_e = Vg_result.item(1)\n Vg_d = Vg_result.item(2)\n self._Vg = sqrt(Vg_n**2+Vg_e**2+Vg_d**2)\n self.gamma = atan2(-Vg_d,sqrt(Vg_n**2 + Vg_e**2))\n self.chi = atan2(Vg_e,Vg_n)\n\n def _forces_moments(self, delta):\n \"\"\"\n return the forces on the UAV based on the state, wind, and control surfaces\n :param delta: np.array(delta_a, delta_e, delta_r, delta_t)\n :return: Forces and Moments on the UAV np.array(Fx, Fy, Fz, Ml, Mn, Mm)\n \"\"\"\n # pull out neeed inputs\n e0 = self._state.item(6)\n e1 = self._state.item(7)\n e2 = self._state.item(8)\n e3 = self._state.item(9)\n p = self._state.item(10)\n q = self._state.item(11)\n r = self._state.item(12)\n delta_a = delta.item(0)\n delta_e = delta.item(1)\n delta_r = delta.item(2)\n delta_t = delta.item(3)\n\n M1 = np.array([[2.*(e1*e3-e2*e0)],\n [2.*(e2*e3+e1*e0)],\n [e3**2+e0**2-e1**2-e2**2]])\n\n M1 *= MAV.mass*MAV.gravity\n\n Tp = self.propThrust(delta_t,self._Va)\n\n M2 = np.array([[Tp],\n [0.],\n [0.]])\n\n\n Cx = -self.CD(self._alpha)*cos(self._alpha) + self.CL(self._alpha)*sin(self._alpha)\n Cxq = -MAV.C_D_q*cos(self._alpha) + MAV.C_L_q*sin(self._alpha)\n Cxde = -MAV.C_D_delta_e*cos(self._alpha) + MAV.C_L_delta_e*sin(self._alpha)\n Cz = -self.CD(self._alpha)*sin(self._alpha) - self.CL(self._alpha)*cos(self._alpha)\n Czq = -MAV.C_D_q*sin(self._alpha) - MAV.C_L_q*cos(self._alpha)\n Czde = -MAV.C_D_delta_e*sin(self._alpha) - MAV.C_L_delta_e*cos(self._alpha)\n\n M3 = np.array([[Cx+Cxq*MAV.c*q/(2.*self._Va)],\n [MAV.C_Y_0 + MAV.C_Y_beta*self._beta + MAV.C_Y_p*MAV.b*p/(2.*self._Va) + MAV.C_Y_r*MAV.b*r/(2*self._Va)],\n [Cz + Czq*MAV.c*q/(2.*self._Va)]])\n\n M4 = np.array([[Cxde*delta_e],\n [MAV.C_Y_delta_a*delta_a + MAV.C_Y_delta_r*delta_r],\n [Czde*delta_e]])\n\n k1 = 0.5*MAV.rho*self._Va**2*MAV.S_wing\n\n force_result = M1 + M2 + k1*M3 + k1*M4\n\n fx = force_result.item(0)\n fy = force_result.item(1)\n fz = force_result.item(2)\n self._forces[0] = fx\n self._forces[1] = fy\n self._forces[2] = fz\n\n\n M5 = np.array([[MAV.b*(MAV.C_ell_0 + MAV.C_ell_beta*self._beta + MAV.C_ell_p*MAV.b*p/(2.*self._Va) + MAV.C_ell_r*MAV.b*r/(2.*self._Va))],\n [MAV.c*(MAV.C_m_0 + MAV.C_m_alpha*self._alpha + MAV.C_m_q*MAV.c*q/(2.*self._Va))],\n [MAV.b*(MAV.C_n_0 + MAV.C_n_beta*self._beta + MAV.C_n_p*MAV.b*p/(2.*self._Va) + MAV.C_n_r*MAV.b*r/(2.*self._Va))]])\n\n M6 = np.array([[MAV.b*(MAV.C_ell_delta_a*delta_a + MAV.C_ell_delta_r*delta_r)],\n [MAV.c*(MAV.C_m_delta_e*delta_e)],\n [MAV.b*(MAV.C_n_delta_a*delta_a + MAV.C_n_delta_r*delta_r)]])\n\n Qp = self.propTorque(delta_t,self._Va)\n\n M7 = np.array([[-Qp],\n [0.],\n [0.]])\n\n moment_result = k1*M5 + k1*M6 + M7\n\n Mx = moment_result.item(0)\n My = moment_result.item(1)\n Mz = moment_result.item(2)\n\n return np.array([[fx, fy, fz, Mx, My, Mz]]).T\n\n def CD(self,alpha):\n '''\n UAV book equation 4.11\n '''\n result = MAV.C_D_p + ((MAV.C_L_0+alpha*MAV.C_L_alpha)**2)/(pi*MAV.e*MAV.AR)\n #result = (1-self.calcSigma(alpha))*(MAV.C_D_0 + MAV.C_D_alpha*alpha)+self.calcSigma(alpha)*(2.0*np.sign(alpha)*sin(alpha)**2*cos(alpha))\n return result\n\n def CL(self,alpha):\n '''\n This is a linear coefficient model that is not valid over a wide\n range of angles of attack. UAV Book equation 4.13\n '''\n result = (1-self.calcSigma(alpha))*(MAV.C_L_0 + MAV.C_L_alpha*alpha)+self.calcSigma(alpha)*(2.0*np.sign(alpha)*sin(alpha)**2*cos(alpha))\n return result\n\n def calcSigma(self,alpha):\n # blending function according to ch 4 UAV book slides\n nom = 1.0 + np.exp(-MAV.M*(alpha-MAV.alpha0))+np.exp(MAV.M*(alpha+MAV.alpha0))\n den = (1.0 + np.exp(-MAV.M*(alpha-MAV.alpha0)))*(1+np.exp(MAV.M*(alpha+MAV.alpha0)))\n result = nom/den\n return result\n\n def propThrust(self,delta_t,V_a):\n\n Omega_op = self.propOperatingSpeed(delta_t,V_a)\n\n J_op = 2.*pi*V_a/(Omega_op*MAV.D_prop)\n Ct_op = MAV.C_T2*J_op**2 + MAV.C_T1*J_op + MAV.C_T0\n\n result = Ct_op*MAV.rho*(Omega_op**2)*(MAV.D_prop**4)/((2.*pi)**2)\n return result\n\n def propOperatingSpeed(self,delta_t,V_a):\n a = MAV.rho*MAV.D_prop**5*MAV.C_Q0/(2.*pi)**2\n b = MAV.rho*MAV.D_prop**4*MAV.C_Q1*V_a/(2.*pi) + MAV.KQ**2/MAV.R_motor\n c = MAV.rho*MAV.D_prop**3*MAV.C_Q2*V_a**2 - MAV.KQ*MAV.V_max*delta_t/MAV.R_motor + MAV.KQ*MAV.i0\n #print(\"V_a=\",V_a)\n if (b**2-4*a*c) > 0:\n result = (-b + sqrt(b**2 - 4.*a*c))/(2.*a)\n else:\n result = -b/(2*a)\n return result\n\n def propTorque(self,delta_t,V_a):\n Vin = MAV.V_max*delta_t\n Omega_op = self.propOperatingSpeed(delta_t,V_a)\n result = MAV.KQ*((Vin - MAV.KQ*Omega_op)/MAV.R_motor - MAV.i0)\n return result\n\n def _update_msg_true_state(self):\n # update the class structure for the true state:\n # [pn, pe, h, Va, alpha, beta, phi, theta, chi, p, q, r, Vg, wn, we, psi, gyro_bx, gyro_by, gyro_bz]\n\n phi, theta, psi = Quaternion2Euler(self._state[6:10])\n self.msg_true_state.pn = self._state.item(0)\n self.msg_true_state.pe = self._state.item(1)\n self.msg_true_state.h = -self._state.item(2)\n self.msg_true_state.Va = self._Va\n self.msg_true_state.alpha = self._alpha\n self.msg_true_state.beta = self._beta\n self.msg_true_state.phi = phi\n self.msg_true_state.theta = theta\n self.msg_true_state.psi = psi\n self.msg_true_state.Vg = self._Vg\n self.msg_true_state.gamma = self.gamma\n self.msg_true_state.chi = self.chi\n self.msg_true_state.p = self._state.item(10)\n self.msg_true_state.q = self._state.item(11)\n self.msg_true_state.r = self._state.item(12)\n self.msg_true_state.wn = self._wind.item(0)\n self.msg_true_state.we = self._wind.item(1)\n\n def update_sensors(self):\n \"Return value of sensors on MAV: gyros, accels, static_pressure, dynamic_pressure, GPS\"\n\n pn = self._state.item(0)\n pe = self._state.item(1)\n h = -self._state.item(2)\n e0 = self._state.item(6)\n e1 = self._state.item(7)\n e2 = self._state.item(8)\n e3 = self._state.item(9)\n phi, theta, psi = Quaternion2Euler(np.array([e0,e1,e2,e3]))\n p = self._state.item(10)\n q = self._state.item(11)\n r = self._state.item(12)\n Va = self._Va\n wn = self._wind.item(0)\n we = self._wind.item(1)\n\n self.sensors.gyro_x = p + SENSOR.gyro_sigma*np.random.randn()\n self.sensors.gyro_y = q + SENSOR.gyro_sigma*np.random.randn()\n self.sensors.gyro_z = r + SENSOR.gyro_sigma*np.random.randn()\n self.sensors.accel_x = float(self._forces[0]/MAV.mass + MAV.gravity*np.sin(theta) + SENSOR.accel_sigma*np.random.randn())\n self.sensors.accel_y = float(self._forces[1]/MAV.mass - MAV.gravity*np.cos(theta)*np.sin(phi) + SENSOR.accel_sigma*np.random.randn())\n self.sensors.accel_z = float(self._forces[2]/MAV.mass - MAV.gravity*np.cos(theta)*np.cos(phi) + SENSOR.accel_sigma*np.random.randn())\n self.sensors.static_pressure = MAV.rho*MAV.gravity*h + SENSOR.static_pres_sigma*np.random.randn()\n self.sensors.diff_pressure = MAV.rho*Va**2/2. + SENSOR.diff_pres_sigma*np.random.randn()\n if self._t_gps >= SENSOR.ts_gps:\n kGPS = 1.0/16000.\n self._gps_eta_n = np.exp(-kGPS*SENSOR.ts_gps)*self._gps_eta_n + SENSOR.gps_n_sigma*np.random.randn()\n self._gps_eta_e = np.exp(-kGPS*SENSOR.ts_gps)*self._gps_eta_e + SENSOR.gps_e_sigma*np.random.randn()\n self._gps_eta_h = np.exp(-kGPS*SENSOR.ts_gps)*self._gps_eta_h + SENSOR.gps_h_sigma*np.random.randn()\n self.sensors.gps_n = pn + self._gps_eta_n\n self.sensors.gps_e = pe + self._gps_eta_e\n self.sensors.gps_h = h + self._gps_eta_h\n self.sensors.gps_Vg = np.sqrt((Va*np.cos(psi)+wn)**2 + (Va*np.sin(psi)+we)**2) + SENSOR.gps_Vg_sigma*np.random.randn()\n self.sensors.gps_course = np.arctan2(Va*np.sin(psi)+we,Va*np.cos(psi)+wn) + SENSOR.gps_course_sigma*np.random.randn()\n self._t_gps = 0.\n else:\n self._t_gps += self._ts_simulation\n","sub_path":"chap7/mav_dynamics.py","file_name":"mav_dynamics.py","file_ext":"py","file_size_in_byte":16385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"352672662","text":"# LSST Data Management System\n# Copyright 2015 AURA/LSST.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n\n\"\"\"\nCommons functions for Qserv administration tools\n\n@author Fabrice Jammes, IN2P3\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\n# --------------------------------\n# Imports of standard modules --\n# -------------------------------\ntry:\n import configparser\nexcept ImportError:\n import ConfigParser as configparser # python2\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\n\n# ----------------------------\n# Imports for other modules --\n# ----------------------------\n\n# ---------------------------------\n# Local non-exported definitions --\n# ---------------------------------\n_LOG = logging.getLogger(__name__)\n\n# -----------------------\n# Exported definitions --\n# -----------------------\n\n# Qserv service states\nNO_STATUS_SCRIPT = -1\nDOWN = 127\nUP = 0\n\nconfig = dict()\n\n\ndef read_user_config():\n config_file = os.path.join(os.getenv(\"HOME\"), \".lsst\", \"qserv.conf\")\n _LOG.debug(\"Read user config file: %r\", config_file)\n config = read_config(config_file)\n return config\n\n\ndef read_config(config_file):\n\n _LOG.debug('Reading config file %r' % config_file)\n if not os.path.isfile(config_file):\n _LOG.fatal(\"qserv configuration file not found: %r\" % config_file)\n exit(1)\n\n parser = configparser.SafeConfigParser()\n # TODO: add unicode support for passwords: see DM-5985\n parser.read(config_file)\n\n _LOG.debug(\"Build configuration : \")\n for section in parser.sections():\n _LOG.debug(\"===\")\n _LOG.debug(\"[%r]\" % section)\n _LOG.debug(\"===\")\n config[section] = dict()\n for option in parser.options(section):\n _LOG.debug(\"%r = %r\" % (option, parser.get(section, option)))\n config[section][option] = parser.get(section, option)\n\n # normalize directories names\n for section in config:\n for option in config[section]:\n if re.match(\".*_dir\", option):\n config[section][option] = os.path.normpath(\n config[section][option])\n\n if parser.has_option('mysqld', 'port'):\n config['mysqld']['port'] = parser.getint('mysqld', 'port')\n\n config['mysql_proxy']['port'] = parser.getint('mysql_proxy', 'port')\n\n return config\n\n\ndef getConfig():\n return config\n\n\ndef restart(service_name):\n config = getConfig()\n if len(config) == 0:\n raise RuntimeError(\"Qserv configuration is empty\")\n initd_path = os.path.join(config['qserv']['qserv_run_dir'], 'etc', 'init.d')\n daemon_script = os.path.join(initd_path, service_name)\n out = os.system(\"%s stop\" % daemon_script)\n out = os.system(\"%s start\" % daemon_script)\n\n\ndef status(qserv_run_dir):\n \"\"\"\n Check if Qserv services are up\n @param qserv_run_dir: Qserv run directory of Qserv instance to ckeck\n @return: the exit code of qserv-status.sh, i.e.:\n id status file doesn't exists: -1 (NO_STATUS_SCRIPT)\n if all Qserv services are up: 0 (UP)\n if all Qserv services are down: 255 (DOWN)\n else the number of stopped Qserv services\n \"\"\"\n script_path = os.path.join(qserv_run_dir, 'bin', 'qserv-status.sh')\n if not os.path.exists(script_path):\n return NO_STATUS_SCRIPT\n with open(os.devnull, \"w\") as fnull:\n retcode = subprocess.call([script_path], stdout=fnull, stderr=fnull, shell=False)\n return retcode\n\n\ndef run_command(cmd_args, stdin_file=None, stdout=None, stderr=None,\n loglevel=logging.INFO):\n \"\"\"\n Run a shell command\n @cmdargs command arguments\n @stdin can be a filename, or None\n @stdout can be sys.stdout, a filename, or None\n which redirect to current processus output\n @stderr same as stdout\n @loglevel print stdin, stdout and stderr if current module logger\n verbosity is greater than loglevel\n \"\"\"\n\n cmd_str = ' '.join(cmd_args)\n _LOG.log(loglevel, \"Run shell command: {0}\".format(cmd_str))\n\n sin = None\n if stdin_file:\n _LOG.log(loglevel, \"stdin file: %r\" % stdin_file)\n sin = open(stdin_file, \"r\")\n\n sout = None\n if stdout == sys.stdout:\n sout = sys.stdout\n elif stdout:\n _LOG.log(loglevel, \"stdout file: %r\" % stdout)\n sout = open(stdout, \"w\")\n else:\n sout = subprocess.PIPE\n\n serr = None\n if stderr == sys.stderr:\n serr = sys.stderr\n elif stderr:\n _LOG.log(loglevel, \"stderr file: %r\" % stderr)\n serr = open(stderr, \"w\")\n else:\n serr = subprocess.PIPE\n\n try:\n process = subprocess.Popen(\n cmd_args, stdin=sin, stdout=sout, stderr=serr\n )\n\n (stdoutdata, stderrdata) = process.communicate()\n\n if stdoutdata != None and len(stdoutdata) > 0:\n _LOG.info(\"\\tstdout :\\n--\\n%s--\", stdoutdata.decode(errors='replace'))\n if stderrdata != None and len(stderrdata) > 0:\n _LOG.info(\"\\tstderr :\\n--\\n%s--\", stderrdata.decode(errors='replace'))\n\n if process.returncode != 0:\n _LOG.fatal(\n \"Error code returned by command : {0} \".format(cmd_str))\n sys.exit(1)\n\n except OSError as e:\n _LOG.fatal(\"Error: %r while running command: %r\" %\n (e, cmd_str))\n sys.exit(1)\n except ValueError as e:\n _LOG.fatal(\"Invalid parameter: %r for command: %r\" %\n (e, cmd_str))\n sys.exit(1)\n","sub_path":"admin/python/lsst/qserv/admin/commons.py","file_name":"commons.py","file_ext":"py","file_size_in_byte":6229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"546869015","text":"import json\nimport os\n\nfrom dotenv import load_dotenv\nfrom google.cloud import dialogflow\nfrom google.api_core.exceptions import InvalidArgument\n\n\ndef create_intent(project_id, display_name, training_phrases_parts, message_texts):\n\n intents_client = dialogflow.IntentsClient()\n\n parent = dialogflow.AgentsClient.agent_path(project_id)\n training_phrases = []\n for training_phrases_part in training_phrases_parts:\n part = dialogflow.Intent.TrainingPhrase.Part(text=training_phrases_part)\n\n training_phrase = dialogflow.Intent.TrainingPhrase(parts=[part])\n training_phrases.append(training_phrase)\n\n text = dialogflow.Intent.Message.Text(text=message_texts)\n message = dialogflow.Intent.Message(text=text)\n\n intent = dialogflow.Intent(\n display_name=display_name, training_phrases=training_phrases, messages=[message]\n )\n\n response = intents_client.create_intent(\n request={\"parent\": parent, \"intent\": intent}\n )\n\n\ndef main():\n load_dotenv()\n project_id = os.environ['PROJECT_ID']\n training_file = os.environ['TRAINING']\n\n with open(training_file, 'r') as f:\n training_phrases = json.load(f)\n \n for display_name, phrases in training_phrases.items():\n questions = phrases['questions']\n answers = [phrases['answer']]\n try:\n create_intent(project_id, display_name, questions, answers)\n except InvalidArgument:\n continue\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"create_intent.py","file_name":"create_intent.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"123084907","text":"from django.shortcuts import render\nfrom .forms import UploadFileForm\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport sys\nfrom PIL import Image\nimport cv2\nimport numpy as np\nimport os\nfrom django.shortcuts import render, redirect\n#from .models import IMG\nfrom .forms import ImageForm\nimport pyocr\nimport pyocr.builders\n#objsize\nimport imutils\nfrom imutils import perspective\nfrom imutils import contours\nfrom scipy.spatial import distance as dist\ndef index(request):\n return HttpResponse(\"Hello Django world!\")\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n# ------------------------------------------------------------------\n@csrf_exempt\ndef file_upload(request):\n form = UploadFileForm(request.POST, request.FILES)\n sys.stderr.write(\"*** file_uploaded *** start ***\\n\")\n if request.method == 'POST':\n imgSave(request)\n return success(request)\n else:\n form = UploadFileForm()\n return render(request, 'file_upload/upload.html', {'form': form})\n \ndef imgSave(request):\n form = UploadFileForm(request.POST, request.FILES)\n \n #sys.stderr.write(request.FILES['file'].name + \"\\n\")\n #sys.stderr.write(request.POST['id'] + \"\\n\")\n if form.is_valid():\n sys.stderr.write(\"*** file_upload *** aaa ***\\n\")\n handle_uploaded_file(request.FILES['file'])\n file_obj = request.FILES['file']\n sys.stderr.write(file_obj.name + \"\\n\")\n sys.stderr.write(request.POST['id'] + \"\\n\")\n#\n# ------------------------------------------------------------------\ndef handle_uploaded_file(file_obj):\n sys.stderr.write(\"*** handle_uploaded_file *** aaa ***\\n\")\n sys.stderr.write(file_obj.name + \"\\n\")\n file_path = BASE_DIR + '/img/' + file_obj.name \n sys.stderr.write(file_path + \"\\n\")\n with open(file_path, 'wb+') as destination:\n for chunk in file_obj.chunks():\n sys.stderr.write(\"*** handle_uploaded_file *** ccc ***\\n\")\n destination.write(chunk)\n sys.stderr.write(\"*** handle_uploaded_file *** eee ***\\n\")\n#\n# ------------------------------------------------------------------\ndef success(request):\n path=BASE_DIR + '/img/'\n file_obj = request.FILES['file']\n res = imgOCR(path,file_obj.name)\n str_out = \"{'message':'\"+res+\"'}\"\n sys.stderr.write(str_out+'\\n')\n return HttpResponse(str_out)\n\ndef tmp():\n #file_obj = request.FILES['file']\n response = HttpResponse(content_type=\"image/png\")\n path=BASE_DIR + '/img/'\n\n #res = imgChange(path,file_obj.name)\n return HttpResponse(\"res\")\n #res=imgChange(path,file_obj.name)\n #res.save(response,'png')\n #return response\n# ------------------------------------------------------------------\ndef imgOCR(path,filename):\n # 1.インストール済みのTesseractのパスを通す\n path_tesseract = \"C:\\\\Program Files\\\\Tesseract-OCR\"\n if path_tesseract not in os.environ[\"PATH\"].split(os.pathsep):\n os.environ[\"PATH\"] += os.pathsep + path_tesseract\n \n # 2.OCRエンジンの取得\n tools = pyocr.get_available_tools()\n tool = tools[0]\n \n # 3.原稿画像の読み込み\n img_org = Image.open(path+filename)\n \n # 4.OCR実行\n builder = pyocr.builders.TextBuilder()\n result = tool.image_to_string(img_org, lang=\"jpn\", builder=builder)\n if result==\"\":\n result=\"nothing\"\n sys.stderr.write(result+'\\n')\n return result\n \ndef imgChange(path,imgPth):\n # 入力画像とテンプレート画像をで取得\n img = np.array(Image.open(path+imgPth))\n temp = np.array(Image.open(path+\"temp.jpg\"))\n \n # グレースケール変換\n gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)\n temp = cv2.cvtColor(temp,cv2.COLOR_RGB2GRAY)\n\n # テンプレート画像の高さ・幅\n h, w = temp.shape\n\n # テンプ��ートマッチング(OpenCVで実装)\n match = cv2.matchTemplate(gray, temp, cv2.TM_SQDIFF_NORMED)\n min_value, max_value, min_pt, max_pt = cv2.minMaxLoc(match)\n pt = min_pt\n\n # テンプレートマッチングの結果を出力\n cv2.rectangle(img, (pt[0], pt[1]), (pt[0] + w, pt[1] + h), (0, 0, 200), 3)\n cv2.imwrite(path+\"res.jpg\",img)\n return Image.fromarray(np.uint8(img))\n\ndef upload(request):\n if request.method == \"POST\":\n form = ImageForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('showall')\n else:\n form = ImageForm()\n\n context = {'form':form}\n return render(request, 'album/upload.html', context)\n\n\ndef showall(request):\n images = Image.objects.all()\n context = {'images':images}\n return render(request, 'album/showall.html', context)\n\n@csrf_exempt\ndef login(request):\n if request.method == \"POST\":\n try:\n id=request.POST['id']\n ps=request.POST['pass']\n sys.stderr.write(\"id:\" + id + \"\\n\")\n sys.stderr.write(\"pass:\" + ps + \"\\n\")\n if(id==\"1\" and ps==\"password\"):\n str_out = \"{'message':'welcome \"+id+\"'}\"\n else:\n str_out = \"{'message':'NO'}\"\n except:\n str_out = \"{'message':'ERR'}\"\n return HttpResponse(str_out)\n else:\n return render(request, 'login/login.html')\n \ndef midpoint(ptA, ptB):\n\treturn ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)\n\n@csrf_exempt\ndef showimg(request):\n imgpath=BASE_DIR + '/img/res.jpg'\n img = Image.open(imgpath)\n response = HttpResponse(content_type='image/jpg')\n img.save(response, \"JPEG\")\n return response\n \n@csrf_exempt\ndef objsize(request):\n if request.method == \"POST\":\n try:\n objsize_do(request)\n str_out=\"{'message':'OK'}\" \n return HttpResponse(str_out)\n \n except:\n str_out = \"{'message':'ERR'}\"\n return HttpResponse(str_out)\n else:\n return render(request, 'login/login.html')\n\ndef objsize_do(request):\n path=BASE_DIR + '/img/'\n imgfile = path + request.FILES['file'].name\n imgSave(request)\n # load the image, convert it to grayscale, and blur it slightly\n image = np.array(Image.open(imgfile))\n sys.stderr.write(\"*** file_objsize_do *** start ***\\n\")\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (7, 7), 0)\n\n # perform edge detection, then perform a dilation + erosion to\n # close gaps in between object edges\n edged = cv2.Canny(gray, 50, 100)\n edged = cv2.dilate(edged, None, iterations=1)\n edged = cv2.erode(edged, None, iterations=1)\n\n # find contours in the edge map\n cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n\n # sort the contours from left-to-right and initialize the\n # 'pixels per metric' calibration variable\n (cnts, _) = contours.sort_contours(cnts)\n pixelsPerMetric = None\n \n orig = image.copy()\n \n # loop over the contours individually\n for c in cnts:\n # if the contour is not sufficiently large, ignore it\n if cv2.contourArea(c) < 100:\n continue\n\n # compute the rotated bounding box of the contour\n box = cv2.minAreaRect(c)\n box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)\n box = np.array(box, dtype=\"int\")\n\n # order the points in the contour such that they appear\n # in top-left, top-right, bottom-right, and bottom-left\n # order, then draw the outline of the rotated bounding\n # box\n box = perspective.order_points(box)\n cv2.drawContours(orig, [box.astype(\"int\")], -1, (0, 255, 0), 2)\n\n # loop over the original points and draw them\n for (x, y) in box:\n cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)\n\n # unpack the ordered bounding box, then compute the midpoint\n # between the top-left and top-right coordinates, followed by\n # the midpoint between bottom-left and bottom-right coordinates\n (tl, tr, br, bl) = box\n (tltrX, tltrY) = midpoint(tl, tr)\n (blbrX, blbrY) = midpoint(bl, br)\n\n # compute the midpoint between the top-left and top-right points,\n # followed by the midpoint between the top-righ and bottom-right\n (tlblX, tlblY) = midpoint(tl, bl)\n (trbrX, trbrY) = midpoint(tr, br)\n\n # draw the midpoints on the image\n cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)\n cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)\n cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)\n cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)\n\n # draw lines between the midpoints\n cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)),\n (255, 0, 255), 2)\n cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)),\n (255, 0, 255), 2)\n\n # compute the Euclidean distance between the midpoints\n dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))\n dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))\n\n # if the pixels per metric has not been initialized, then\n # compute it as the ratio of pixels to supplied metric\n # (in this case, inches)\n if pixelsPerMetric is None:\n pixelsPerMetric = dB\n\n # compute the size of the object\n dimA = dA / pixelsPerMetric\n dimB = dB / pixelsPerMetric\n\n # draw the object sizes on the image\n cv2.putText(orig, \"{:.1f}in\".format(dimA),\n (int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,\n 0.65, (255, 255, 255), 2)\n cv2.putText(orig, \"{:.1f}in\".format(dimB),\n (int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,\n 0.65, (255, 255, 255), 2)\n sys.stderr.write(\"*** file_obj *** end ***\\n\")\n res=Image.fromarray(np.uint8(orig))\n res.save(path + \"res.jpg\")\n\nfrom google.cloud import speech_v1\nfrom google.cloud.speech_v1 import enums\nimport io\n \n@csrf_exempt\ndef speachToText(request):\n if request.method == \"POST\":\n try: \n text = speachToTextdo(request)\n str_out=\"[{'message':'\"+text+\"'}]\" \n return HttpResponse(str_out)\n \n except:\n str_out = \"[{'message':'ERR'}]\"\n return HttpResponse(str_out)\n else:\n return render(request, 'login/login.html')\n \ndef speachToTextdo(request):\n client = speech_v1.SpeechClient()\n language_code = \"ja-JP\"\n sample_rate_hertz = 44100\n encoding = enums.RecognitionConfig.AudioEncoding.LINEAR16\n config = {\n \"language_code\": language_code,\n \"sample_rate_hertz\": sample_rate_hertz,\n \"encoding\": encoding,\n }\n \n file = request.FILES['file']\n \n file_path = BASE_DIR + '/img/' + file.name\n \n sys.stderr.write(file_path + \"\\n\")\n \n with open(os.path.join(file_path), 'wb+') as destination:\n for chunk in file.chunks():\n sys.stderr.write(\"*** handle_uploaded_file *** ccc ***\\n\")\n destination.write(chunk)\n sys.stderr.write(\"*** handle_uploaded_file *** eee ***\\n\")\n \n wav = wave.open(file_path)\n \n save_wav_channel(file_path, wav, 0)\n \n with io.open(file_path, \"rb\") as f:\n content = f.read()\n \n audio = {\"content\": content}\n\n response = client.recognize(config, audio)\n \n return response.results[0].alternatives[0].transcript\n\nimport wave\n\ndef save_wav_channel(fn, wav, channel):\n '''\n Take Wave_read object as an input and save one of its\n channels into a separate .wav file.\n '''\n # Read data\n nch = wav.getnchannels()\n depth = wav.getsampwidth()\n wav.setpos(0)\n sdata = wav.readframes(wav.getnframes())\n\n # Extract channel data (24-bit data not supported)\n typ = { 1: np.uint8, 2: np.uint16, 4: np.uint32 }.get(depth)\n if not typ:\n raise ValueError(\"sample width {} not supported\".format(depth))\n if channel >= nch:\n raise ValueError(\"cannot extract channel {} out of {}\".format(channel+1, nch))\n print (\"Extracting channel {} out of {} channels, {}-bit depth\".format(channel+1, nch, depth*8))\n data = np.fromstring(sdata, dtype=typ)\n ch_data = data[channel::nch]\n\n # Save channel to a separate file\n outwav = wave.open(fn, 'w')\n outwav.setparams(wav.getparams())\n outwav.setnchannels(1)\n outwav.writeframes(ch_data.tostring())\n outwav.close()\n \n@csrf_exempt\ndef objdis(request):\n if request.method == \"POST\":\n try:\n objdis_do(request)\n str_out=\"{'message':'OK'}\" \n return HttpResponse(str_out)\n \n except:\n str_out = \"{'message':'ERR'}\"\n return HttpResponse(str_out)\n else:\n return render(request, 'login/login.html')\n\ndef objdis_do(request):\n path=BASE_DIR + '/img/'\n imgfile = path + request.FILES['file'].name\n imgSave(request)\n # load the image, convert it to grayscale, and blur it slightly\n image = np.array(Image.open(imgfile))\n sys.stderr.write(\"*** file_objdis_do *** start ***\\n\")\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (7, 7), 0)\n\n # perform edge detection, then perform a dilation + erosion to\n # close gaps in between object edges\n edged = cv2.Canny(gray, 50, 100)\n edged = cv2.dilate(edged, None, iterations=1)\n edged = cv2.erode(edged, None, iterations=1)\n\n # find contours in the edge map\n cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n\n # sort the contours from left-to-right and, then initialize the\n # distance colors and reference object\n (cnts, _) = contours.sort_contours(cnts)\n colors = ((0, 0, 255), (240, 0, 159), (0, 165, 255), (255, 255, 0),\n (255, 0, 255))\n refObj = None\n\n # loop over the contours individually\n for c in cnts:\n # if the contour is not sufficiently large, ignore it\n if cv2.contourArea(c) < 100:\n continue\n\n # compute the rotated bounding box of the contour\n box = cv2.minAreaRect(c)\n box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)\n box = np.array(box, dtype=\"int\")\n\n # order the points in the contour such that they appear\n # in top-left, top-right, bottom-right, and bottom-left\n # order, then draw the outline of the rotated bounding\n # box\n box = perspective.order_points(box)\n\n # compute the center of the bounding box\n cX = np.average(box[:, 0])\n cY = np.average(box[:, 1])\n\n # if this is the first contour we are examining (i.e.,\n # the left-most contour), we presume this is the\n # reference object\n if refObj is None:\n # unpack the ordered bounding box, then compute the\n # midpoint between the top-left and top-right points,\n # followed by the midpoint between the top-right and\n # bottom-right\n (tl, tr, br, bl) = box\n (tlblX, tlblY) = midpoint(tl, bl)\n (trbrX, trbrY) = midpoint(tr, br)\n\n # compute the Euclidean distance between the midpoints,\n # then construct the reference object\n D = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))\n refObj = (box, (cX, cY), D)\n continue\n\n \n orig = image.copy()\n \n # draw the contours on the image\n cv2.drawContours(orig, [box.astype(\"int\")], -1, (0, 255, 0), 2)\n cv2.drawContours(orig, [refObj[0].astype(\"int\")], -1, (0, 255, 0), 2)\n\n # stack the reference coordinates and the object coordinates\n # to include the object center\n refCoords = np.vstack([refObj[0], refObj[1]])\n objCoords = np.vstack([box, (cX, cY)])\n\n # loop over the original points\n for ((xA, yA), (xB, yB), color) in zip(refCoords, objCoords, colors):\n # draw circles corresponding to the current points and\n # connect them with a line\n cv2.circle(orig, (int(xA), int(yA)), 5, color, -1)\n cv2.circle(orig, (int(xB), int(yB)), 5, color, -1)\n cv2.line(orig, (int(xA), int(yA)), (int(xB), int(yB)),\n color, 2)\n\n # compute the Euclidean distance between the coordinates,\n # and then convert the distance in pixels to distance in\n # units\n D = dist.euclidean((xA, yA), (xB, yB)) / refObj[2]\n (mX, mY) = midpoint((xA, yA), (xB, yB))\n cv2.putText(orig, \"{:.1f}in\".format(D), (int(mX), int(mY - 10)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.55, color, 2)\n \n sys.stderr.write(\"*** file_obj *** end ***\\n\")\n res=Image.fromarray(np.uint8(orig))\n res.save(path + \"res.jpg\")","sub_path":"20200929/pyapi/fileapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"186126545","text":"import pandas as pd\nimport streamlit as st\nfrom pathlib import Path\nimport base64\n\ndef img_to_bytes(img_path):\n img_bytes = Path(img_path).read_bytes()\n encoded = base64.b64encode(img_bytes).decode()\n return encoded\n\nst.sidebar.markdown('''[](https://plexocap.com/)'''.format(img_to_bytes(\"plexo-logo.png\")), unsafe_allow_html=True)\n \nst.sidebar.header('Plexo Capital Quick Sheet')\n\ncompName = st.sidebar.text_input('Company Name', '')\n\nst.sidebar.subheader('Opportunity Economics : ')\n\nroundSize = st.sidebar.number_input('Round Size (in USD Millions)', 0.1,100.0,1.0)\npostVal = st.sidebar.number_input('Post Money Valutaion (in USD Millions)', 1,50000,10)\nfees = st.sidebar.number_input('Management Fees (one time, in % of allocation)', 0,10,0)\ncarry = st.sidebar.number_input('Carried Interest (in % of allocation)', 0,50,20)\n\nstage = st.sidebar.selectbox('Opportunity Type',('Early Stage','Growth Stage','Late Stage'))\ntimeline = st.sidebar.selectbox('Exit Timeline',('<6 months','6-12 months','12-24 months','24-36 months','36+ months'))\nrounds = st.sidebar.number_input('Additional number of rounds before an exit', 0,10,3)\n\nst.sidebar.subheader('Market Cap Expectations : ')\n\nbull = st.sidebar.number_input('Best Case Scenario (in USD Millions)', 1,50000,1000)\nbase = st.sidebar.number_input('Base Case Scenario (in USD Millions)', 1,50000,100)\nbear = st.sidebar.number_input('Bear Case Scenario (in USD Millions)', 0,10000,0)\n\n\n\"\"\"\n# Plexo Capital IC Quick Sheet!\n\nWelcome to Plexo Capital Quick Sheet. This page is intended to do some quick math to evaluate a direct opportunity for the Plexo Capital Investment Team. Please fill the details on the left side of your screen to see the magic begin.\n\nThe way this works is you can slide the allocation marker to see the allocations change in bull/base/bear scenarios. It accounts for the fees and carry economics and is based on the inputs provided on the left side. For calculating a probability weighted return multiple (PWRM), we use the probability of success marker. The value selected in the slider is divided equally between the bull and base scenarios. The probability of failure (bear scenario) is just 100%-probability of success. Based on stage and exit timeline, any opportunity with a PWRM less than 10x (early stage) or 5x (late stage) can be simply passed. \n\nIf you have any questions about the tool, reach out to me at . Alternatively see the source code on github through the dropdown on the right. See my previous work on sector/industry analysis for Plexo Capital [here] (https://plexocap.herokuapp.com/).\n\nBelow is the quick sheet analysis:\n\n\"\"\"\n\nif compName != '':\n st.markdown(\n f\"\"\"\n * Name of the Company : {compName}\n * Round Size (in USD Million) : {roundSize}\n * Post Money Valuation (in USD Million) : {postVal}\n * Stage : {stage}\n \"\"\"\n )\n \n\nprob = st.slider(\"Percentage Probability of Sucess\", 1, 100, 30)\nbullProb = prob/200\nbaseProb = prob/200\nbearProb = 1-prob/100\nallocation = st.slider(\"Capital Allocation (in USD Millions)\", 0.1, 10.0, 1.0)\nallocation = allocation*(1-fees/100.0)\n\ndata = []\nfor finVal in [bull,base,bear]:\n slope = finVal*(1-carry/100)/(postVal*(rounds+1))\n scene = [allocation if i == 0 else allocation*i*slope for i in range(rounds+2)]\n data.append(scene)\n\ndataDf = pd.DataFrame(data).T\ndataDf.columns = ['Bull','Base','Bear']\n\n''' Hover Over the integer indices to see the values '''\nst.line_chart(dataDf)\n\nmultZip = zip(dataDf.iloc[-1]/allocation,[bullProb,baseProb,bearProb])\npwrm = sum(val*prob for val,prob in multZip)\n\nst.info('The Probability Weighted Return Multiple for this opportunity is : %sX'%(int(pwrm)))\n\n\n \n","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":3804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"455633932","text":"# Neural Networks from Scratch, SentDex\n# https://www.youtube.com/watch?v=Wo5dMEP_BbI\n\ninputs = [1.2, 5.1, 2.1]\nweights = [3.1, 2.1, 8.7]\nbias = 3\n\noutput = inputs[0]*weights[0] + inputs[1] * \\\n weights[1] + inputs[2]*weights[2] + bias\nprint(output)\n","sub_path":"p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"264949001","text":"# Sürüme Göre İşlem Yapan Program\n\nimport sys\n\nversion2x=\"\"\"\nPython'un 2.x sürümlerinden birini kullanıyorsanız programı çalıştıramazsınız!\n Programı çalıştırabilmek için 3.x sürümü yükleyiniz..\n\"\"\"\n\nversion3x=\"Programa hoşgeldiniz!\"\n\nif sys.version_info.major < 3:\n print(version2x)\nelse:\n print(version3x)\n\n\n# sys.version_info komutu ile kullandığımız pythonun sürümünü öğrenebiliyoruz (run:sys.version_info(major=3, minor=9, micro=6, releaselevel='final', serial=0)\n# bu komuta göre pythonun 3.9 sürümünü kullanıyormuşuz. major ana sürüm, minor ise ara. micro yazısı ise pythonun 3.6 ile başladığını gösteriyor 3.x serisine\n# sys.version_info.minor komutu ile de minorü öğrenebiliyoruz.\n\n# sys.version komutu da bize pythonun sürümünü veriyor aslında ama şu şekilde (run: 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)])\n# eğer if den sonra sys.version u kullancak olsaydın \"in\" ile birlikte kullanman gerekirdi. processbyversion2 de bunu gösterdim.","sub_path":"level0/processbyversion.py","file_name":"processbyversion.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"414422291","text":"# Licensed under a 3-clause BSD style license - see PYFITS.rst\n\nimport re\nimport warnings\nfrom contextlib import suppress\n\nfrom astropy.io.fits.card import Card\nfrom astropy.io.fits.column import KEYWORD_NAMES as TABLE_KEYWORD_NAMES\nfrom astropy.io.fits.column import TDEF_RE\nfrom astropy.io.fits.header import Header\n\n__all__ = [\"CompImageHeader\"]\n\n\nclass CompImageHeader(Header):\n \"\"\"\n Header object for compressed image HDUs designed to keep the compression\n header and the underlying image header properly synchronized.\n\n This essentially wraps the image header, so that all values are read from\n and written to the image header. However, updates to the image header will\n also update the table header where appropriate.\n\n Note that if no image header is passed in, the code will instantiate a\n regular `~astropy.io.fits.Header`.\n \"\"\"\n\n # TODO: The difficulty of implementing this screams a need to rewrite this\n # module\n\n _keyword_remaps = {\n \"SIMPLE\": \"ZSIMPLE\",\n \"XTENSION\": \"ZTENSION\",\n \"BITPIX\": \"ZBITPIX\",\n \"NAXIS\": \"ZNAXIS\",\n \"EXTEND\": \"ZEXTEND\",\n \"BLOCKED\": \"ZBLOCKED\",\n \"PCOUNT\": \"ZPCOUNT\",\n \"GCOUNT\": \"ZGCOUNT\",\n \"CHECKSUM\": \"ZHECKSUM\",\n \"DATASUM\": \"ZDATASUM\",\n }\n\n _zdef_re = re.compile(r\"(?P