diff --git "a/2153.jsonl" "b/2153.jsonl" new file mode 100644--- /dev/null +++ "b/2153.jsonl" @@ -0,0 +1,646 @@ +{"seq_id":"456667389","text":"import nnabla as nn\nimport nnabla.functions as F\nimport nnabla.parametric_functions as PF\nfrom nnabla.contrib.context import extension_context\nimport numpy as np\n\n# Residual Unit\ndef res_unit(x, scope_name, act=F.relu, dn=False, test=False):\n C = x.shape[1]\n\n with nn.parameter_scope(scope_name):\n # Conv -> BN -> Relu\n with nn.parameter_scope(\"conv1\"):\n h = PF.convolution(x, C/2, kernel=(1, 1), pad=(0, 0), with_bias=False)\n h = PF.batch_normalization(h, decay_rate=0.9, batch_stat=not test)\n h = act(h)\n # Conv -> BN -> Relu\n with nn.parameter_scope(\"conv2\"):\n h = PF.convolution(h, C/2, kernel=(3, 3), pad=(1, 1), with_bias=False)\n h = PF.batch_normalization(h, decay_rate=0.9, batch_stat=not test)\n h = act(h)\n # Conv -> BN\n with nn.parameter_scope(\"conv3\"): \n h = PF.convolution(h, C, kernel=(1, 1), pad=(0, 0), with_bias=False)\n h = PF.batch_normalization(h, decay_rate=0.9, batch_stat=not test)\n # Residual -> Relu\n h = F.add2(h, x)\n h = act(h)\n \n # Maxpooling\n if dn:\n h = F.max_pooling(h, kernel=(2, 2), stride=(2, 2))\n \n return h\n\ndef resnet_model(ctx, x, inmaps=64, act=F.relu, test=False):\n # Conv -> BN -> Relu\n with nn.context_scope(ctx):\n with nn.parameter_scope(\"conv1\"):\n h = PF.convolution(x, inmaps, kernel=(3, 3), pad=(1, 1), with_bias=False)\n h = PF.batch_normalization(h, decay_rate=0.9, batch_stat=not test)\n h = act(h)\n \n h = res_unit(h, \"conv2\", act, False) # -> 32x32\n h = res_unit(h, \"conv3\", act, True) # -> 16x16\n with nn.parameter_scope(\"bn0\"):\n h = PF.batch_normalization(h, batch_stat=not test)\n if not test:\n h = F.dropout(h)\n h = res_unit(h, \"conv4\", act, False) # -> 16x16\n h = res_unit(h, \"conv5\", act, True) # -> 8x8\n with nn.parameter_scope(\"bn1\"):\n h = PF.batch_normalization(h, batch_stat=not test)\n if not test:\n h = F.dropout(h)\n h = res_unit(h, \"conv6\", act, False) # -> 8x8\n h = res_unit(h, \"conv7\", act, True) # -> 4x4\n with nn.parameter_scope(\"bn2\"):\n h = PF.batch_normalization(h, batch_stat=not test)\n if not test:\n h = F.dropout(h)\n h = res_unit(h, \"conv8\", act, False) # -> 4x4\n h = F.average_pooling(h, kernel=(4, 4)) # -> 1x1\n \n pred = PF.affine(h, 10)\n return pred\n\ndef ce_loss(ctx, pred, y_l):\n with nn.context_scope(ctx):\n loss_ce = F.mean(F.softmax_cross_entropy(pred, y_l))\n return loss_ce\n\ndef sr_loss(ctx, pred0, pred1):\n with nn.context_scope(ctx):\n pred_x_u0 = F.softmax(pred0)\n pred_x_u1 = F.softmax(pred1)\n loss_sr = F.mean(F.squared_error(pred_x_u0, pred_x_u1))\n return loss_sr\n\ndef er_loss(ctx, pred):\n with nn.context_scope(ctx):\n bs = pred.shape[0]\n d = np.prod(pred.shape[1:])\n denominator = bs * d\n pred_normalized = F.softmax(pred)\n pred_log_normalized = F.log(F.softmax(pred))\n loss_er = - F.sum(pred_normalized * pred_log_normalized) / denominator\n return loss_er\n","sub_path":"st2/st2/cifar10/cnn_model_019.py","file_name":"cnn_model_019.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"210145936","text":"\"\"\"\n322. Coin Change\nYou are given coins of different denominations and a total amount of money amount.\nWrite a function to compute the fewest number of coins that you need to make up that \namount. If that amount of money cannot be made up by any combination of the coins, \nreturn -1.\n\"\"\"\ndef coinChange(self, coins: List[int], amount: int) -> int:\n dp = [0] + [float('inf')] * amount\n for c in coins:\n for i in range(coin, amount+1):\n \"\"\"\n dp[i-c] is the amount of coins it takes for\n the value of the amount left over after you\n take a coin away. You add one to this because you \n will have to add one more coin(c) to dp[i].\n \"\"\"\n dp[i] = min(dp[i], dp[i-c] +1)\n return dp[-1] if dp[-1] != float('inf') else -1","sub_path":"dynamicprogramming/coinchange.py","file_name":"coinchange.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"222844556","text":"from django.conf.urls import url,patterns,include\r\n\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n url(r'^$',views.IndexView.as_view(), name='index'), \r\n url(r'^/categories$' , views.CategoryView.as_view(), name='categories'),\r\n url(r'^/addquestion$' , views.AddQuestionView.as_view(), name='addquestion'),\r\n url(r'^(?P[0-9]+)/$' , views.DetailView.as_view(), name='detail'),\r\n url(r'^(?P[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),\r\n url(r'^/post/$', views.post, name='post'),\r\n ]\r\n\r\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"250797762","text":"\"\"\"web_server URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.views.generic import TemplateView\nfrom .views import api1, send_data, rev_commande, home\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', home, name=\"home\"),\n path('home', TemplateView.as_view(\n template_name = 'landing_page.html'\n ),\n name=\"ex\",\n ),\n path('api/', api1),\n path('send', send_data, name=\"send_data\"),\n path('rev_commande', rev_commande, name=\"rev_commande\"),\n]\n","sub_path":"web_server/web_server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"640174081","text":"\nimport urllib.request\nimport os, shutil\nimport subprocess\nimport argparse\nimport time\n\n\n\ndef execute_command_with_output(cmd):\n\n out, err = subprocess.Popen(cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True).communicate()\n output = out.decode('ascii').strip('\\n')\n print(\"Command: %s\" % cmd)\n print(\"Output: %s \" % output)\n return output\n\ndef parse_cmd_arguments():\n\t\n\tparser = argparse.ArgumentParser(description='Upgrader manager')\n\n\tparser.add_argument('-git',\n\t\t\t\t\ttype=str,\n default=None,\n\t\t\t\t\tdest='git',\n\t\t\t\t\thelp='DUT device name')\n\tparser.add_argument('-c',\n\t\t\t\t\ttype=str,\n\t\t\t\t\tdest='cmd',\n\t\t\t\t\thelp='DUT device name')\n\n\targuments = parser.parse_args()\n\treturn arguments\ndef pullGit(ip, gitPath, command):\n execute_command_with_output(\"sshpass -p tester ssh tester@%s \\\"cd /home/tester/%s && %s\\\"\" % (ip, gitPath, command))\n\nif __name__ == '__main__':\n\n args = parse_cmd_arguments()\n\n setups = [\n '192.168.51.10', #Lima_zefir\n '192.168.51.11', #LW60_zefir\n '192.168.51.14', #Jalapeno_Zefir\n '192.168.51.75', #Carambola2\n '192.168.51.76', #Lima\n '192.168.51.7' , #Rambutan\n '192.168.51.4' , #LW_60_zefir\n '192.168.51.3' , #Kinkan\n '192.168.51.34', #Jalapeno\n '192.168.51.22', #Rambutan_zefir\n '192.168.51.15' #Komikan\n ]\n\n for ip in setups:\n print(\"----------------\")\n print(\"IP %s\" % ip)\n if args.git:\n pullGit(ip, args.git, args.cmd)\n\n\n","sub_path":"pullGits.py","file_name":"pullGits.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"375842239","text":"import pykube\napi = pykube.HTTPClient(pykube.KubeConfig.from_file(\"./kubeconfig\"))\n\nlimitRange = {\n \"kind\": \"LimitRange\",\n \"apiVersion\": \"v1\",\n \"metadata\": {\n \"name\": \"limit\",\n \"namespace\": \"development\"\n },\n \"spec\": {\n \"limits\": [\n {\n \"type\": \"Pod\",\n \"max\": {\n \"cpu\": \"4\",\n \"memory\": \"2Gi\",\n },\n \"min\": {\n \"cpu\": \"200m\",\n \"memory\": \"6Mi\",\n },\n \"maxLimitRequestRatio\": {\n \"cpu\": \"3\",\n \"memory\": \"2\"\n }\n },\n {\n \"type\": \"Container\",\n \"max\": {\n \"cpu\": \"2\",\n \"memory\": \"1Gi\"\n },\n \"min\": {\n \"cpu\": \"100m\",\n \"memory\": \"3Mi\"\n },\n \"default\": {\n \"cpu\": \"300m\",\n \"memory\": \"200Mi\"\n },\n \"defaultRequest\": {\n \"cpu\": \"200m\",\n \"memory\": \"100Mi\"\n },\n \"maxLimitRequestRatio\": {\n \"cpu\": \"5\",\n \"memory\": \"4\"\n }\n }\n ]\n }\n}\n\npykube.LimitRange(api,limitRange).create()\n","sub_path":"python/k8s/k8s_limitRange.py","file_name":"k8s_limitRange.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"182763295","text":"import zmq\nfrom socket import getfqdn\nimport json\nfrom types import FunctionType\nimport cv2\nfrom functools import wraps\nimport numpy as np\n\nfrom f_camera_photonics.component_capture import single_shot, video_mean\nfrom f_camera_photonics.attenuator_driver import atten_db\n\nremote_address_default = '686NAM3560B.campus.nist.gov'\nremote_port_default = 5551\n\n\n# Commands are tokened by the name of the function\n_available_commands = dict()\n_raw_returners = set()\ndef tcp_command(json_codec=True):\n def tcp_register(func):\n global _available_commands\n global _raw_returners\n _available_commands[func.__name__] = func\n if not json_codec:\n _raw_returners.add(func.__name__)\n return func\n return tcp_register\n\n\n@tcp_command()\ndef ping():\n return 'Hello there'\n\n@tcp_command(json_codec=False)\ndef capture(avgcnt=1):\n img = video_mean(avgcnt)\n return pack_image(img)\n\n@tcp_command()\ndef kill():\n ''' Windows doesn't like keyboard interrupts '''\n raise RuntimeError('Remote server kill')\n\n@tcp_command()\ndef attenuate(atten=None):\n ''' in dB '''\n return atten_db(atten)\n\n\n## command and control layer.\n# Converts between arg/kwarg-like objects and TCP messages.\n# Calls the server-side functions\n\ndef pack_image(img_array):\n img_serial = cv2.imencode('.png', img_array)[1].tobytes()\n return img_serial\n\ndef unpack_image(img_serial):\n nparr = np.fromstring(img_serial, np.uint8)\n img_array = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n return img_array\n\ndef pack_command(cmd_name, *args, **kwargs):\n if type(cmd_name) is FunctionType:\n cmd_name = cmd_name.__name__\n if cmd_name not in _available_commands.keys():\n raise KeyError('No command named {}'.format(cmd_name))\n command_struct = (cmd_name, args, kwargs)\n return json.dumps(command_struct).encode()\n\ndef parse_command(msg_bytes):\n cmd_name, args, kwargs = json.loads(msg_bytes.decode())\n func = _available_commands[cmd_name]\n resp = func(*args, **kwargs)\n if cmd_name in _raw_returners:\n return resp\n else:\n return json.dumps(resp).encode()\n\ndef unpack_response(resp_bytes):\n return json.loads(resp_bytes.decode())\n\n\n## Process layer\n\ndef run_server(port=None):\n if port is None:\n port = remote_port_default\n context = zmq.Context()\n socket = context.socket(zmq.REP)\n print('Starting camera photonics server')\n print('FQDN =', getfqdn())\n print('PORT =', port)\n socket.bind(\"tcp://*:{}\".format(port)) # * means localhost\n\n try:\n while True:\n message = socket.recv()\n print(\"Received request: %s\" % message)\n response = parse_command(message)\n socket.send(response)\n except:\n socket.close()\n\ndef remote_call(cmd_name, address=None, port=None, **kwargs):\n ''' Make sure to specify argument names i.e. kwargs '''\n if address is None:\n address = remote_address_default\n if port is None:\n port = remote_port_default\n\n context = zmq.Context()\n socket = context.socket(zmq.REQ)\n socket.setsockopt(zmq.LINGER, 0) # makes timeout possible\n socket.connect('tcp://{}:{}'.format(address, port))\n\n if type(cmd_name) is FunctionType:\n cmd_name = cmd_name.__name__\n\n args = ()\n timeout = 5\n try:\n socket.send(pack_command(cmd_name, *args, **kwargs))\n if cmd_name == 'kill':\n return None\n poller = zmq.Poller()\n poller.register(socket, zmq.POLLIN)\n if poller.poll(timeout*1000):\n rec = socket.recv()\n else:\n raise IOError(\"Timeout processing command request\")\n finally:\n socket.close()\n\n if cmd_name in _raw_returners:\n return rec\n else:\n return unpack_response(rec)\n\n\nif __name__ == '__main__':\n run_server()\n\n","sub_path":"f_camera_photonics/tcp_link.py","file_name":"tcp_link.py","file_ext":"py","file_size_in_byte":3837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"384052606","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 22 11:21:27 2019\n\nSUPPORTS AN ANALYTICAL PROFILE FOR WIND ONLY...\n\n@author: TempestGuerra\n\"\"\"\n\nimport numpy as np\n\ndef computeShearProfileOnGrid(PHYS, JETOPS, P0, PZ, dlnPZdz):\n \n # Get jet profile options\n U0 = JETOPS[0]\n uj = JETOPS[1]\n b = JETOPS[2]\n \n # Compute the normalized pressure coordinate (Ullrich, 2015)\n pcoord = 1.0 / P0 * PZ;\n lpcoord = np.log(pcoord);\n lpcoord2 = np.power(lpcoord, 2.0)\n \n # Compute the decay portion of the jet profile\n jetDecay = np.exp(-(1.0 / b**2.0 * lpcoord2));\n UZ = -uj * np.multiply(lpcoord, jetDecay) + U0;\n \n # Compute the shear\n temp = np.multiply(jetDecay, (1.0 - 2.0 / b**2 * lpcoord2))\n dUdz = -uj * temp * np.reciprocal(pcoord);\n dUdz *= (1.0 / P0);\n dUdz *= P0 * (pcoord * dlnPZdz);\n \n return UZ, dUdz\n \n ","sub_path":"computeShearProfileOnGrid.py","file_name":"computeShearProfileOnGrid.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"594113398","text":"import unittest\nimport Isoperimetric\nfrom sympy import var, pi\nfrom sympy.functions import exp, log, cos\n# import SPCVUnittests\n\nfrom Isoperimetric import t, x, x_diff\nC1 = Isoperimetric.Isoperimetric.C1\nC2 = Isoperimetric.Isoperimetric.C2\nlambda_0 = Isoperimetric.Isoperimetric.lambda_0\nlambda_1 = var('lambda_1')\nlambda_2 = var('lambda_2')\n\n\n# ToDo Think about inheritance\nclass TestIsoperimetricBase(unittest.TestCase):\n\n # ToDo Why setUp yellow???\n def setUp(self, f0, t0, t1, x0, x1, f_list, alphas,\n general_solution, coefficients, particular_solution, extreme_value):\n\n self.f0 = f0\n self.t0 = t0\n self.t1 = t1\n self.x0 = x0\n self.x1 = x1\n self.f_list = f_list\n self.alphas = alphas\n\n self.general_solution = general_solution\n self.coefficients = coefficients\n self.particular_solution = particular_solution\n self.extreme_value = extreme_value\n\n self.Isoperimetric = Isoperimetric.Isoperimetric(f0=self.f0,\n t0=self.t0,\n t1=self.t1,\n x0=self.x0,\n x1=self.x1,\n f_list=self.f_list,\n alphas=self.alphas)\n self.Isoperimetric.solve()\n\n def test_f0(self):\n self.assertEqual(self.Isoperimetric.f0,\n self.f0)\n\n def test_t0(self):\n self.assertEqual(self.Isoperimetric.t0,\n self.t0)\n\n def test_t1(self):\n self.assertEqual(self.Isoperimetric.t1,\n self.t1)\n\n def test_x0(self):\n self.assertEqual(self.Isoperimetric.x0,\n self.x0)\n\n def test_x1(self):\n self.assertEqual(self.Isoperimetric.x1,\n self.x1)\n\n def test_f_list(self):\n self.assertEqual(self.Isoperimetric.f_list,\n self.f_list)\n\n def test_alphas(self):\n self.assertEqual(self.Isoperimetric.alphas,\n self.alphas)\n\n def test_general_solution(self):\n self.assertEqual(self.Isoperimetric.general_solution,\n self.general_solution)\n\n def test_coefficients(self):\n self.assertEqual(self.Isoperimetric.coefficients,\n self.coefficients)\n\n def test_particular_solution(self):\n self.assertEqual(self.Isoperimetric.particular_solution,\n self.particular_solution)\n\n def test_extreme_value(self):\n self.assertEqual(self.Isoperimetric.extreme_value,\n self.extreme_value)\n\n def runTest(self):\n self.test_f0()\n self.test_t0()\n self.test_t1()\n self.test_x0()\n self.test_x1()\n self.test_f_list()\n self.test_alphas()\n self.test_general_solution()\n self.test_coefficients()\n self.test_particular_solution()\n self.test_extreme_value()\n\n\nclass TestIsoperimetric1(TestIsoperimetricBase):\n\n def setUp(self):\n super().setUp(f0=x_diff**2,\n t0=0,\n t1=1,\n x0=0,\n x1=1,\n f_list=[x],\n alphas=[0],\n general_solution=C1 + C2*t + lambda_1*t**2/(4*lambda_0),\n coefficients={C1: 0,\n lambda_1/lambda_0: 12,\n C2: -2},\n particular_solution=3*t**2 - 2*t,\n extreme_value=4)\n\n\nclass TestIsoperimetric2(TestIsoperimetricBase):\n\n def setUp(self):\n super().setUp(f0=x_diff**2,\n t0=0,\n t1=1,\n x0=0,\n x1=1,\n f_list=[t * x],\n alphas=[0],\n general_solution=C1 + C2*t + lambda_1*t**3/(12*lambda_0),\n coefficients={C1: 0,\n lambda_1/lambda_0: 30,\n C2: -3/2},\n particular_solution=5*t**3/2 - 3*t/2,\n extreme_value=6)\n\n\nclass TestIsoperimetric3(TestIsoperimetricBase):\n\n def setUp(self):\n super().setUp(f0=x_diff**2,\n t0=0,\n t1=1,\n x0=0,\n x1=0,\n f_list=[x, t * x],\n alphas=[1, 0],\n general_solution=C1 + C2*t + lambda_1*t**2/(4*lambda_0) + \\\n lambda_2*t**3/(12*lambda_0),\n coefficients={C1: 0,\n lambda_2/lambda_0: 720,\n lambda_1/lambda_0: -384,\n C2: 36},\n particular_solution=60*t**3 - 96*t**2 + 36*t,\n extreme_value=192)\n\n\nclass TestIsoperimetric4(TestIsoperimetricBase):\n\n def setUp(self):\n super().setUp(f0=x_diff**2,\n t0=0,\n t1=pi,\n x0=1,\n x1=-1,\n f_list=[x * cos(t)],\n alphas=[pi / 2],\n general_solution=C1 + C2*t - lambda_1*cos(t)/(2*lambda_0),\n coefficients={C1: 0,\n lambda_1/lambda_0: -2,\n C2: 0},\n particular_solution=cos(t),\n extreme_value=pi/2)\n\n # ToDo May have errors\nclass TestIsoperimetric5(TestIsoperimetricBase):\n\n def setUp(self):\n super().setUp(f0=t ** 2 * x_diff ** 2,\n t0=1,\n t1=2,\n x0=1,\n x1=2,\n f_list=[t * x],\n alphas=[7 / 3],\n general_solution=C1 + C2/t + lambda_1*t/(4*lambda_0),\n coefficients={C1: 0,\n C2: 0,\n lambda_1/lambda_0: 4},\n particular_solution=t,\n extreme_value=7 / 3)\n\n\nif __name__ == '__main__':\n suite = unittest.TestSuite()\n suite.addTests([TestIsoperimetric1(),\n TestIsoperimetric2(),\n TestIsoperimetric3(),\n TestIsoperimetric4(),\n TestIsoperimetric5()])\n runner = unittest.TextTestRunner()\n runner.run(suite)\n","sub_path":"IsoperimetricUnittests.py","file_name":"IsoperimetricUnittests.py","file_ext":"py","file_size_in_byte":6764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"320989688","text":"import json\nimport random\nimport urllib.request as urllib2\n\n\"\"\"\nUses the safebooru API. There is no API key needed.\n\"\"\"\n\nclass pysbooru:\n def __init__(self, tags='', post_limit=100): #post limit default 100 images\n self.tags = 'tags=' + tags\n self.post_limit = 'limit=' + str(post_limit)\n self.post_id = ''\n self.image = ''\n\n def get_posts(self):\n images = []\n post_ids = []\n\n #does stuff.\n try:\n post_array = self.__create_response(str(self.post_limit), self.tags) #generate json response\n except:\n return False\n else:\n return post_array\n\n # Private function to deal with link concatenation\n def __create_response(self, *args):\n booru_url = 'https://safebooru.org/index.php?page=dapi&s=post&q=index&json=1' # Default url for all responses\n image_dict = []\n\n while image_dict == []:\n page_number = random.randint(1, 50)\n if len(args) == 0:\n return False\n else:\n for i in args:\n booru_url = booru_url + f'&{i}'\n booru_url = booru_url + '&pid=' + str(page_number)\n\n json_obj = urllib2.urlopen(booru_url) # json into an object\n image_dict = json.load(json_obj) # Stores list of image dictionaries into a variable\n\n return image_dict\n \n #Create link for actual post\n def generate_post_link(self, data):\n base_url = 'https://safebooru.org/index.php?page=post&s=view'\n ids = []\n #iterate through list of dictionaries\n for i in range(len(data)):\n ids.append(base_url + f'&id={str(data[i][\"id\"])}')\n \n return ids\n\n #Create link to direct image file.\n def generate_image_link(self, data):\n base_url = 'https://safebooru.org/images'\n ids = []\n #iterate through list of dictionaries\n for i in range(len(data)):\n ids.append(base_url + f'/{str(data[i][\"directory\"])}/{str(data[i][\"image\"])}') \n\n return ids\n\n\n","sub_path":"safebooru_app.py","file_name":"safebooru_app.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"234119233","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 26 11:11:09 2018\n\n@author: George\n\"\"\"\nfrom __future__ import print_function\nimport sys, getopt, re\n\n\ndef main(argv):\n inputfile = ''\n outputfile = ''\n try:\n opts, args = getopt.getopt(argv,\"hi:o:\",[\"ifile=\",\"ofile=\"])\n except getopt.GetoptError:\n print ('searchText_commLine.py -i -o ')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print ('searchText_commLine.py -i -o ')\n sys.exit()\n elif opt in (\"-i\", \"--ifile\"):\n inputfile = arg\n elif opt in (\"-o\", \"--ofile\"):\n outputfile = arg\n\n try:\n searchFile = open(inputfile, \"r\")\n text = searchFile.read()\n searchFile.close()\n except:\n print('Unable to open input file')\n \n #find all occurences of text within parentheses\n result = re.findall('\\(.*?\\)',text)\n \n result2 = re.findall(r'(.*?)\\(.*?\\)',text)\n \n result3 = []\n \n for i in range(len(result)):\n if re.search('\\d+',result[i]) and len(result[i]) > 4:\n result[i] = result[i].encode('ascii', 'replace').decode('ascii')\n result2[i] = result2[i].encode('ascii', 'replace').decode('ascii')\n try:\n result3.append([result2[i][-30:],result[i]])\n except:\n result3.append([result2[i],result[i]])\n \n try:\n saveFile = open(outputfile, 'w')\n \n for item in result3:\n print(*item,file=saveFile, sep=',')\n \n saveFile.close()\n except:\n print('Unable to write results file')\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])","sub_path":"SoundScience/searchText_comLine.py","file_name":"searchText_comLine.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"621424882","text":"#Importing package and modules \nimport arcpy, os, sys\n\n#Setting envrionment\narcpy.env.overwriteOutput = True\n\n#Path to text file\ngpsFile = r\"c:\\Geo\\geo465\\Aawaj_Joshi\\lab10\\lab10\\TextFiles\\track.txt\"\n\n#Setting path for output file\noutFC = r\"c:\\Geo\\geo465\\Aawaj_Joshi\\lab10\\lab10\\Data\\gpstrack.shp\"\n\n#Path for the desired coordinate file\ncoordsys = r\"c:\\Geo\\geo465\\Aawaj_Joshi\\lab10\\Data\\WGS 1984 UTM ZONE 15N.prj\"\n\narcpy.env.workspace = os.path.dirname(outFC)\nfeatClass = os.path.basename(outFC)\n\n#If featClass already exists, then deleting it \nif arcpy.Exists(featClass):\n arcpy.Delete_management(featClass)\n\narcpy.CreateFeatureclass_management(arcpy.env.workspace, featClass, \"POLYLINE\", \"\", \"\", \"\", coordsys)\n\n#Reading data from the text file \nfileRead = open(gpsFile, 'r')\n\n#Reading one line at a time into headerLine variable\nheaderLine = fileRead.readline()\n\n#Reading entire file into a list variable Lines\nLines = fileRead.readlines()\n\n#Closing the file after reading the necessary data\nfileRead.close()\n\n#Splittng the read data \nlstHeader = headerLine.split(\",\")\nyCoordIndex = lstHeader.index(\"y_proj\")\nxCoordIndex = lstHeader.index(\"x_proj\")\n\n#Creating an array lineArray\nlineArray = arcpy.Array()\nlid = 1\npid = 1\n\n#Creating a list fieldList\nfieldList = [\"ID\", \"SHAPE@\"]\n\n#Creating insert cursor \nwith arcpy.da.InsertCursor(featClass, fieldList) as isCursor:\n for gpsPnt in Lines:\n lstValue = gpsPnt.split(\",\")\n yCoord = float(lstValue[yCoordIndex])\n xCoord = float(lstValue[xCoordIndex])\n\n #Adding the coordinates to the array \n lineArray.add(arcpy.Point(xCoord, yCoord))\n\n #Printing message saying each point was added to the array\n print(\"Add point {0} into line array\".format(pid))\n pid = pid + 1\n\n #Inserting new row \n isCursor.insertRow([lid, arcpy.Polyline(lineArray)])\n print(\"Add line {0} into line feature class\".format(lid))\n\n #Removing all values\n lineArray.removeAll()\n\n","sub_path":"Scripts/Creating line features.py","file_name":"Creating line features.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"133347712","text":"from __future__ import print_function\n''' import print_function to be backward compatible to python 2 '''\n\nplainText = \"im technischen bereich kann man an der fachhochschule kaernten zwischen mehreren bachelorstudiengaengen sowie masterstudiengaengen auswaehlen\"\nshift = \"j\"\n\n\ndef caesar(plainText, shift):\n for ch in plainText:\n if not ch==\" \": # remove spaces to prevent easy decryption\n if ch.isalpha(): # implementation just for alphabetic characters\n alph2num = ord(ch) + (ord(shift) - 96) # convert character to unicode, and start a = 1 therefore offset equals -96\n if alph2num > ord(\"z\"): # check if unicode of shifted character is higher than the unicode of z\n alph2num -= 26 # if unicode is higher than z, start at the beginning\n print(chr(alph2num)) # print and transform from unicode to character\n\n\ncaesar(plainText, shift)","sub_path":"it-network_sec/ceasar_cipher.py","file_name":"ceasar_cipher.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"505680107","text":"import os\nimport pickle\nimport numpy as np\nimport xgboost as xgb\nimport pandas as pd\n\nfrom bayes_opt import BayesianOptimization\nfrom .xgb_callbacks import callback_overtraining, early_stop\nfrom .xgboost2tmva import convert_model\n\nimport warnings\n\n# Effective RMS evaluation function for xgboost\ndef evaleffrms(preds, dtrain, c=0.683):\n labels = dtrain.get_label()\n # return a pair metric_name, result. The metric name must not contain a colon (:) or a space\n # since preds are margin(before logistic transformation, cutoff at 0)\n x = np.sort(preds / labels, kind=\"mergesort\")\n m = int(c * len(x)) + 1\n effrms = np.min(x[m:] - x[:-m]) / 2.0\n return \"effrms\", effrms # + 10*(max(np.median(preds/labels), np.median(labels/preds)) - 1)\n\n\n# The space of hyperparameters for the Bayesian optimization\n#hyperparams_ranges = {'min_child_weight': (1, 30),\n# 'colsample_bytree': (0.1, 1),\n# 'max_depth': (2, 20),\n# 'subsample': (0.5, 1),\n# 'gamma': (0, 20),\n# 'reg_alpha': (0, 10),\n# 'reg_lambda': (0, 20)}\n\n# The default xgboost parameters\n#xgb_default = {'min_child_weight': 1,\n# 'colsample_bytree': 1,\n# 'max_depth': 6,\n# 'subsample': 1,\n# 'gamma': 0,\n# 'reg_alpha': 0,\n# 'reg_lambda': 1}\n\n\ndef format_params(params):\n \"\"\" Casts the hyperparameters to the required type and range.\n \"\"\"\n p = dict(params)\n p['min_child_weight'] = p[\"min_child_weight\"]\n p['colsample_bytree'] = max(min(p[\"colsample_bytree\"], 1), 0)\n p['max_depth'] = int(p[\"max_depth\"])\n# p['subsample'] = max(min(p[\"subsample\"], 1), 0)\n p['gamma'] = max(p[\"gamma\"], 0)\n# p['reg_alpha'] = max(p[\"reg_alpha\"], 0)\n p['reg_lambda'] = max(p[\"reg_lambda\"], 0)\n return p\n\n\ndef merge_two_dicts(x, y):\n \"\"\" Merge two dictionaries.\n\n Writing such a function is necessary in Python 2.\n\n In Python 3, one can just do:\n d_merged = {**d1, **d2}.\n \"\"\"\n z = x.copy() # start with x's keys and values\n z.update(y) # modifies z with y's keys and values & returns None\n return z\n\n\nclass XgboFitter(object):\n \"\"\"Fits a xgboost classifier/regressor with Bayesian-optimized hyperparameters.\n\n Public attributes:\n\n Private attributes:\n _random_state (int): seed for random number generation\n \"\"\"\n\n\n def __init__(self, out_dir,\n random_state = 2018,\n num_rounds_max = 3000,\n num_rounds_min = 0,\n early_stop_rounds = 100,\n nthread = 16,\n regression = False,\n useEffSigma =True\n ):\n \"\"\"The __init__ method for XgboFitter class.\n\n Args:\n data (pandas.DataFrame): The data frame containing the features\n and target.\n X_cols (:obj:`list` of :obj:`str`) : Names of the feature columns.\n y_col (str) : Name of the colum containing the target of the binary\n classification. This column has to contain zeros and\n ones.\n \"\"\"\n self._out_dir = out_dir\n pkl_file = open(out_dir+'/param_range.pkl', 'rb')\n global hyperparams_ranges\n hyperparams_ranges= pickle.load(pkl_file)\n pkl_file.close()\n pkl_file = open(out_dir+'/param_default.pkl', 'rb')\n global xgb_default\n xgb_default= pickle.load(pkl_file)\n pkl_file.close()\n if not os.path.exists(os.path.join(out_dir, \"cv_results\")):\n os.makedirs(os.path.join(out_dir, \"cv_results\"))\n\n self._random_state = random_state\n self._num_rounds_max = num_rounds_max\n self._num_rounds_min = num_rounds_min\n self._early_stop_rounds = early_stop_rounds\n\n self.params_base = {\n\n 'silent' : 1,\n 'verbose_eval': 0,\n 'seed' : self._random_state,\n 'nthread' : nthread,\n 'objective' : 'reg:linear',\n }\n \n if regression:\n xgb_default['base_score']=1#for regression the base_score should be 1, not 0.5. If enough iteration this will not matter much\n if useEffSigma:\n self._cv_cols = [\"train-effrms-mean\", \"train-effrms-std\",\n \"test-effrms-mean\", \"test-effrms-std\"]\n else:\n self._cv_cols = [\"train-rmse-mean\", \"train-rmse-std\",\n \"test-rmse-mean\", \"test-rmse-std\"]\n else:\n self._cv_cols = [\"train-auc-mean\", \"train-auc-std\", \"test-auc-mean\", \"test-auc-std\"]\n\n self.params_base[\"objective\"] = \"binary:logitraw\"\n self.params_base[\"eval_metric\"] = \"auc\"\n\n self._regression = regression\n self._useEffSigma = useEffSigma\n\n # Increment the random state by the number of previously done\n # experiments so we don't use the same numbers twice\n summary_file = os.path.join(out_dir, \"summary.csv\")\n if os.path.isfile(summary_file):\n df = pd.read_csv(summary_file)\n self._random_state = self._random_state + len(df)\n\n # Set up the Bayesian optimization\n self._bo = BayesianOptimization(self.evaluate_xgb, hyperparams_ranges, random_state=self._random_state)\n\n # This list will memorize the number of rounds that each step in the\n # Bayesian optimization was trained for before early stopping gets\n # triggered. This way, we can train our final classifier with the\n # correct n_estimators matching to the optimal hyperparameters.\n self._early_stops = []\n\n # This dictionary will hold the xgboost models created when running\n # this training class.\n self._models = {}\n\n self._cv_results = []\n self._cvi = 0\n\n #\n self._callback_status = []\n\n self._tried_default = False\n\n # Load the summary file if it already exists in the out_dir\n if os.path.isfile(summary_file):\n self._load_data()\n\n def _load_data(self):\n\n summary_file = os.path.join(self._out_dir, \"summary.csv\")\n\n df = pd.read_csv(summary_file)\n\n print(\"Found results of {} optimization rounds in ouptut directory, loading...\".format(len(df)))\n\n self._early_stops += list(df.n_estimators.values)\n self._callback_status += list(df.callback.values)\n\n self._tried_default = True\n\n # Load the cross validation results\n for i in range(len(df)):\n cv_file = os.path.join(self._out_dir, \"cv_results/{0:04d}.csv\".format(i))\n self._cv_results.append(pd.read_csv(cv_file))\n self._cvi = len(df)\n\n # Load the optimization results so far into the Bayesian optimization object\n eval_col = self._cv_cols[2]\n\n if self._regression:\n idx_max = df[eval_col].idxmin()\n max_val = -df[eval_col].min()\n else:\n idx_max = df[eval_col].idxmax()\n max_val = df[eval_col].max()\n\n if self._regression:\n df[\"target\"] = -df[eval_col]\n else:\n df[\"target\"] = df[eval_col]\n\n for idx in df.index:\n value = df.loc[idx, eval_col]\n if self._regression:\n value = -value\n\n params = df.loc[idx, list(hyperparams_ranges)].to_dict()\n self._bo.register(params, value)\n\n def evaluate_xgb(self, **hyperparameters):\n\n params = format_params(merge_two_dicts(self.params_base, hyperparameters))\n\n if len(self._bo.res) == 0:\n best_test_eval_metric = -9999999.0\n else:\n self.summary.to_csv(os.path.join(self._out_dir, \"summary.csv\"))\n best_test_eval_metric = max([d[\"target\"] for d in self._bo.res])\n\n feval = None\n callback_status = {\"status\": 0}\n\n if self._regression:\n if self._useEffSigma:\n callbacks = [early_stop(self._early_stop_rounds, start_round=self._num_rounds_min, verbose=True, eval_idx=-2)]\n feval = evaleffrms\n else:\n callbacks = [early_stop(self._early_stop_rounds, start_round=self._num_rounds_min, verbose=True),\n callback_overtraining(best_test_eval_metric, callback_status)]\n else:\n callbacks = [\n early_stop(self._early_stop_rounds, start_round=self._num_rounds_min, verbose=True),\n callback_overtraining(best_test_eval_metric, callback_status),\n ]\n\n cv_result = xgb.cv(\n params,\n self._xgtrain,\n num_boost_round=self._num_rounds_max,\n nfold=self._nfold,\n seed=self._random_state,\n callbacks=callbacks,\n verbose_eval=10,\n feval=feval,\n )\n\n cv_result.to_csv(os.path.join(self._out_dir, \"cv_results/{0:04d}.csv\".format(self._cvi)))\n self._cvi = self._cvi + 1\n\n self._early_stops.append(len(cv_result))\n\n self._cv_results.append(cv_result)\n self._callback_status.append(callback_status[\"status\"])\n\n if self._regression:\n return -cv_result[self._cv_cols[2]].values[-1]\n else:\n return cv_result[self._cv_cols[2]].values[-1]\n\n def optimize(self, xgtrain, init_points=3, n_iter=3, nfold=3, acq=\"ei\"):\n\n self._nfold = nfold\n\n # Save data in xgboosts DMatrix format so the encoding doesn't have to\n # be repeated at every step of the Bayesian optimization.\n self._xgtrain = xgtrain\n\n # Explore the default xgboost hyperparameters\n if not self._tried_default:\n self._bo.probe({k: [v] for k, v in xgb_default.items()}, lazy=False)\n self._tried_default = True\n\n # Do the Bayesian optimization\n self._bo.maximize(init_points=init_points, n_iter=0, acq=acq)\n\n self._started_bo = True\n for i in range(n_iter):\n self._bo.maximize(init_points=0, n_iter=1, acq=acq)\n\n # Save summary after each step so we can interrupt at any time\n self.summary.to_csv(os.path.join(self._out_dir, \"summary.csv\"))\n\n # Final save of the summary\n self.summary.to_csv(os.path.join(self._out_dir, \"summary.csv\"))\n\n def fit(self, xgtrain, model=\"optimized\"):\n\n if model == \"default\":\n # Set up the parameters for the default training\n params = merge_two_dicts(self.params_base, xgb_default)\n params[\"n_estimators\"] = self._early_stops[0]\n\n if model == \"optimized\":\n # Set up the parameters for the Bayesian-optimized training\n argmax = np.argmax([d[\"target\"] for d in self._bo.res])\n params = merge_two_dicts(self.params_base, format_params(self._bo.res[argmax][\"params\"]))\n params[\"n_estimators\"] = self._early_stops[argmax]\n\n self._models[model] = xgb.train(params, xgtrain, params[\"n_estimators\"], verbose_eval=10)\n\n def predict(self, xgtest, model=\"optimized\"):\n return self._models[model].predict(xgtest)\n\n @property\n def summary(self):\n # res is a list of dictionaries with the keys \"target\" and \"params\"\n res = [dict(d) for d in self._bo.res]\n\n n = len(res)\n for i in range(n):\n res[i][\"params\"] = format_params(res[i][\"params\"])\n\n data = {}\n\n for name in self._cv_cols:\n data[name] = [cvr[name].values[-1] for cvr in self._cv_results]\n\n for k, v in hyperparams_ranges.items():\n data[k] = [res[i][\"params\"][k] for i in range(n)]\n\n data[\"n_estimators\"] = self._early_stops\n data[\"callback\"] = self._callback_status\n\n return pd.DataFrame(data=data)\n\n def save_model(self, feature_names, model=\"optimized\"):\n \"\"\"Save model from booster to binary, text and XML.\n \"\"\"\n print(\"Saving model\")\n model_dir = os.path.join(self._out_dir, \"model_\" + model)\n\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n\n # Save text dump\n self._models[model].dump_model(os.path.join(model_dir, \"dump.raw.txt\"))\n\n # Save in binary format\n self._models[model].save_model(os.path.join(model_dir, \"model.bin\"))\n\n # Convert to TMVA or GBRForest compatible weights file\n tmvafile = os.path.join(model_dir, \"weights.xml\")\n try:\n convert_model(\n self._models[model].get_dump(),\n input_variables=list(zip(feature_names, len(feature_names) * [\"F\"])),\n output_xml=tmvafile,\n )\n os.system(\"xmllint --format {0} > {0}.tmp\".format(tmvafile))\n os.system(\"mv {0} {0}.bak\".format(tmvafile))\n os.system(\"mv {0}.tmp {0}\".format(tmvafile))\n os.system(\"gzip -f {0}\".format(tmvafile))\n os.system(\"mv {0}.bak {0}\".format(tmvafile))\n except:\n warnings.warn(\n \"Warning:\\nSaving model in TMVA XML format failed.\\nDon't worry now, you can still convert the xgboost model later.\"\n )\n\n\nclass XgboRegressor(XgboFitter):\n def __init__(\n self, out_dir, random_state=2018, num_rounds_max=3000, num_rounds_min=0, early_stop_rounds=100, nthread=16\n ):\n super(XgboRegressor, self).__init__(\n out_dir,\n random_state=random_state,\n num_rounds_max=num_rounds_max,\n num_rounds_min=num_rounds_min,\n early_stop_rounds=early_stop_rounds,\n nthread=nthread,\n regression=True,\n )\n\n\nclass XgboClassifier(XgboFitter):\n def __init__(\n self, out_dir, random_state=2018, num_rounds_max=3000, num_rounds_min=0, early_stop_rounds=100, nthread=16\n ):\n super(XgboClassifier, self).__init__(\n out_dir,\n random_state=random_state,\n num_rounds_max=num_rounds_max,\n num_rounds_min=num_rounds_min,\n early_stop_rounds=early_stop_rounds,\n nthread=nthread,\n regression=False,\n )\n","sub_path":"xgbo/xgbo.py","file_name":"xgbo.py","file_ext":"py","file_size_in_byte":14253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"23578144","text":"import socket\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET-->IPV4, SOCK_STREAM-->TCP\nclient.settimeout(3)\ntarget_host = \"\"\ntarget_port = 80\nmsg = \"GET / HTTP/1.1\\nHost: example.com\\n\\n\"\n\ntry:\n client.connect((target_host, target_port)) # conectando client ao target\n client.send(msg.encode())\n response = client.recv(4096)\n print(response.decode())\nexcept:\n print(\"Falha na conexao\")\n exit()\n\n","sub_path":"sockets/clientTCP.py","file_name":"clientTCP.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"540532171","text":"# Néttoie le texte de la ponstuation\ndef nettoyer(texte_epure):\n for lettre in '.,;:!?()<>\"_':\n texte_epure = texte_epure.replace(lettre, '')\n return texte_epure\n\n# Lit et transforme en minuscule un fichier\ndef gettext_lower():\n fichier = input(\"Veuillez saisir le chemin absolu du fichier: \")\n with open(fichier, 'r') as f:\n texte = f.read().lower()\n f.close()\n return texte\n\n# Met en liste le fichier néttoyé\ndef liste(text_file):\n liste_mots = nettoyer(text_file).split()\n nb_mots = len(liste_mots)\n print(\"Dans le text il y a {} mots.\".format(nb_mots))\n return liste_mots\n\n# Compte le nombre de fois un mot qu'à rentré un utilisateur\ndef compter():\n mot = input(\"Veuillez choisir un mot à compter: \").lower()\n occurrence = liste_mots.count(mot)\n print(\"Dans le text il y a {} fois '{}'.\".format(occurrence, mot))\n\n# Donne le nombre de mots différents existant dans le fichier\ndef mots_diff():\n diff = len(set(liste_mots))\n print(\"Il y a {} mots différents.\".format(diff))\n\n# Créer un dictionnaire à partir de la liste\ndef liste_occu():\n liste_unique = set(liste_mots)\n dictionnaire = dict()\n print(\"Génération du dictionnaire, cela peut prendre du temps:\")\n for key in liste_unique:\n dictionnaire.setdefault(key, liste_mots.count(key))\n print(dictionnaire)\n return dictionnaire\n\n# Donne le mot le plus utilisé dans le fichier\ndef grande_occu(dictionnaire):\n occurrence_max = 0\n values = ''\n for k, v in dictionnaire.items():\n if occurrence_max < v :\n occurrence_max = v\n values = k\n\n print(\"Le mot le plus utilisés est: '{}', {} fois\".format(values, occurrence_max))\n\n\ntexte_fichier = gettext_lower()\nliste_mots = liste(texte_fichier)\ncompter()\nmots_diff()\ngrande_occu(liste_occu())\n","sub_path":"Lecteur_fichier.py","file_name":"Lecteur_fichier.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"354611998","text":"#!/usr/bin/env python3\n#\n# -*- coding: utf-8 -*-\n# vim: ts=4 sw=4 tw=100 et ai si\n#\n# Copyright (C) 2020 Intel Corporation\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# Author: Antti Laakso \n\n\"\"\"\nTest module for 'wult' project. Includes following bad input tests for both, 'wult', and 'ndl':\n- Non-existing device ID.\n- Bad filter name.\n- Bad function name.\n- Empty CSV -file.\n- Random data in CSV -file.\n- Too short line.\n- Too long line.\n- Directory as input file.\n- \"/dev/null\" as input file.\n- \"/dev/urandom\" as input file.\n\"\"\"\n\n# pylint: disable=redefined-outer-name\n\nimport os\nimport subprocess\nfrom pathlib import Path\nimport pytest\nfrom wultlibs.helperlibs import Exceptions\n\nclass CmdLineRunner():\n \"\"\"Class for running commandline commands.\"\"\"\n\n @staticmethod\n def _command(cmd):\n \"\"\"Run 'cmd' command and return output, if any.\"\"\"\n\n try:\n result = subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n except subprocess.CalledProcessError as err:\n raise Exceptions.Error(str(err))\n #raise Exception(str(err))\n\n if not result:\n return None\n\n return result.decode(\"utf-8\").strip()\n\n def _has_outdir(self, cmd):\n \"\"\"Check if 'cmd' command has 'outdir' -option.\"\"\"\n\n cmd = [self._tool_path, cmd, \"-h\"]\n helptext = self._command(cmd)\n\n return \"outdir\" in helptext\n\n def command(self, cmd, arg=None):\n \"\"\"Run commandline tool with arguments.\"\"\"\n\n if self._has_outdir(cmd) and self._tmpdir:\n arg += f\" -o {self._tmpdir}\"\n\n cmd = [self._tool_path, cmd]\n if arg:\n cmd += arg.split()\n\n return self._command(cmd)\n\n def __init__(self, toolname, devid, tmpdir=None):\n \"\"\"The constructor.\"\"\"\n\n self._tmpdir = str(tmpdir)\n self._devid = devid\n\n tooldir = Path(__file__).parents[1].resolve()\n testdataroot = tooldir / \"tests\" / \"testdata\"\n self._tool_path = tooldir / toolname\n assert self._tool_path.exists()\n\n self.good_paths = []\n self.bad_paths = []\n for dirpath, dirnames, _ in os.walk(testdataroot / toolname):\n if dirnames:\n continue\n if \"good\" in Path(dirpath).parts:\n self.good_paths.append(dirpath)\n else:\n self.bad_paths.append(dirpath)\n\n assert self.good_paths\n assert self.bad_paths\n\nclass WultTest(CmdLineRunner):\n \"\"\"Class for running tests for 'wult'.\"\"\"\n\n def __init__(self, devid, tmpdir=None):\n \"\"\"The constructor.\"\"\"\n\n super().__init__(\"wult\", devid, tmpdir)\n\nclass NdlTest(CmdLineRunner):\n \"\"\"Class for running tests for 'ndl'.\"\"\"\n\n def __init__(self, devid, tmpdir=None):\n \"\"\"The constructor.\"\"\"\n\n super().__init__(\"ndl\", devid, tmpdir)\n\n@pytest.fixture(params=[WultTest, NdlTest], ids=[\"wult\", \"ndl\"])\ndef tool(request, devid, tmp_path_factory):\n \"\"\"Common fixture to return test object for 'wult' and 'ndl'.\"\"\"\n\n tmpdir = tmp_path_factory.mktemp(request.fixturename)\n return request.param(devid, tmpdir=tmpdir)\n\ndef test_bad_input_data(tool):\n \"\"\"Test 'report', 'stats', and 'start' commands for bad input data.\"\"\"\n\n for cmd in (\"filter\", \"report\", \"start\", \"stats\"):\n for args in tool.bad_paths:\n if cmd == \"filter\":\n args = f\"--rfilt 'index!=0' {args}\"\n with pytest.raises(Exceptions.Error):\n tool.command(cmd, args)\n\ndef test_bad_filter_names(tool):\n \"\"\"Test 'filter' and 'stats' commands for bad filter names.\"\"\"\n\n for cmd in (\"filter\", \"stats\", \"report\"):\n for argname in (\"rfilt\", \"rsel\", \"cfilt\", \"csel\"):\n # 'report' command don't have 'cfilt' and 'csel' arguments.\n if cmd == \"report\" and argname.startswith(\"c\"):\n continue\n # Need only one good testdata path.\n args = f\"--{argname} 'bad_filter' {tool.good_paths[0]}\"\n with pytest.raises(Exceptions.Error):\n tool.command(cmd, args)\n\ndef test_stats(tool):\n \"\"\"Test 'stats' command for bad arguments.\"\"\"\n\n with pytest.raises(Exceptions.Error):\n tool.command(\"stats\", f\"-f 'bad_function' {tool.good_paths[0]}\")\n","sub_path":"tests/test_bad_input.py","file_name":"test_bad_input.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"466674981","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 14 17:13:28 2018\n\n@author: fzhan\n\"\"\"\n\n \n#alpha-beta pruning\n#record self.board,self.play_times,self.win_times for each action\n#adjent expand to 2 or 3\n\nimport time\nfrom copy import deepcopy\nimport math\nimport random\nfrom itertools import product\n\nclass MCTS(object):\n \"\"\"\n AI player, use Monte Carlo Tree Search with UCB\n \"\"\"\n\n def __init__(self, board, play_turn, n_in_row=5, time=5):\n\n self.board = board\n self.play_turn = play_turn \n self.time_limit = float(time) # time limit of each step\n self.n_in_row = n_in_row #if 5 positions in one line, win\n self.player = play_turn[0] \n self.confident = 1.96 # the constant in UCB\n self.play_times = {} # {(player,move):times} record (player,move) simulating times\n self.win_times = {} # record win times of (player,mover)\n\n\n def get_action(self): # return move\n # if there is just one available position, return this one\n if len(self.board.availables) == 1:\n return self.board.availables[0] \n\n self.play_times = {} \n self.win_times = {}\n simulations = 0\n begin = time.time()\n while time.time() - begin < self.time_limit:\n #simulation will change board, so separate the new board with old one\n board_copy = deepcopy(self.board) \n play_turn_copy = deepcopy(self.play_turn) \n self.run_simulation(board_copy, play_turn_copy) # run MCTS\n simulations += 1\n \n move = self.select_one_move() # choose the best move\n #print(self.play_times)\n return move\n\n\n def run_simulation(self, board, play_turn):\n \"\"\"\n MCTS main process\n \"\"\"\n visited_states = set() # records all moves before expand\n expand = True\n \n while True:\n # Selection\n player = self.get_player(play_turn) # get the current player\n availables = board.availables\n # if there is statistical information for each move, get move with maximum UCB\n if all(self.play_times.get((player, move)) for move in availables):\n log_total = math.log(\n sum(self.play_times[(player, move)] for move in availables))\n value, move = max(\n ((self.win_times[(player, move)] / self.play_times[(player, move)]) +\n math.sqrt(self.confident * log_total / self.play_times[(player, move)]), move)\n for move in availables) \n else:\n #if there are the adjacent positions without statistical information\n #randomly choose position from them\n adjacents = []\n if len(availables) > self.n_in_row: \n adjacents = self.adjacent_moves(board, player) \n if len(adjacents):\n move = random.choice(adjacents)\n else:\n # else randomly choose a move from peripheral positions without statistical information\n peripherals = []\n for move in availables:\n if not self.play_times.get((player, move)):\n peripherals.append(move) \n move = random.choice(peripherals) \n\n board.update(player, move)\n if expand:\n visited_states.add((player, move))\n\n # Expand\n # for each simulation, just expand once and add one move\n if expand and (player, move) not in self.play_times:\n expand = False\n self.play_times[(player, move)] = 0\n self.win_times[(player, move)] = 0\n \n #End simulation\n #if there is a winner or not postion left on board, the simulation is over\n is_full = not len(availables)\n win, winner = self.has_a_winner(board)\n if is_full or win: \n break \n\n # Back-propagation\n for player, move in visited_states:\n self.play_times[(player, move)] += 1 \n if player == winner:\n self.win_times[(player, move)] += 1 \n\n\n def get_player(self, players):\n p = players.pop(0)\n players.append(p)\n return p\n \n \n def isLegalMove(self,board,x,y):\n if 0<=x')\r\n sys.stdout.write (new_movie)\r\n print()\r\n for i in range(len(exp)):sys.stdout.write('*')\r\n \r\n\r\n\r\n#RENAME\\SEARCH\\COPY TO BASE VARIOUS FILES IN FOLDER \r\nall_folders=list()\r\nall_folders.append(BASE_ADDRESS)\r\nfile=open('log.txt','a+')\r\nlog=file.read() \r\nfile.close()\r\ndef main():\r\n global log\r\n while len(all_folders):\r\n address=all_folders.pop()\r\n url,movies=get_files(address)\r\n for movie in movies:\r\n new_movie_names=list()\r\n new_movie_names.append(condenseName(movie))\r\n \r\n # REMOVING UNWANTED FILES \r\n if new_movie_names[0] == UNWANTED_FILENAME_ERRORCODE:\r\n os.remove(movie)\r\n else:\r\n if new_movie_names[0] == movie:\r\n handle_error('NAME NOT CHANGED!',movie,new_movie_names[0]) #ERROR\r\n \r\n \r\n # IF STATEMENT FOR RENAME\r\n if new_movie_names[0] not in os.listdir(os.curdir):\r\n print \r\n sys.stdout.write(movie+'----------->')\r\n sys.stdout.write (new_movie_names[0])\r\n os.rename(movie,new_movie_names[0]) #RENAME \r\n log+=movie+\"|\"+new_movie_names[0]+\"\\n\"\r\n #ERROR HANDLING\r\n else:\r\n if movie != new_movie_names[0]:\r\n handle_error('NAME CLASH ERROR!',movie,new_movie_names[0]) #ERROR\r\n # IF STATEMENT FOR RENAME ENDED\r\n \r\n \r\n #COPYING TO BASE\r\n #MAIN OPERTIONS\r\n if new_movie_names[0] not in os.listdir(BASE_ADDRESS):\r\n shutil.move(new_movie_names[0],BASE_ADDRESS)\r\n #ERROR HANDLING\r\n else:\r\n if new_movie_names[0] != movie:\r\n handle_error('DUBLICATE FILE',movie,new_movie_names[0]) #ERROR\r\n #ENDING COPYING TO BASE DONE \r\n\r\n for folder_url in url:\r\n if folder_url not in all_folders:\r\n all_folders.append(folder_url)\r\n print('\\n-------------------------------------------------------------------------\\n')\r\n \r\n\r\n\r\n#DELETING FOLDERS\\CHECKING FOR FOLDERS\r\ndef clear():\r\n os.chdir(BASE_ADDRESS)\r\n files=os.listdir(BASE_ADDRESS)\r\n movies=list()\r\n folders=list()\r\n for each_file in files:\r\n if os.path.isdir(each_file):\r\n folders.append(each_file)\r\n if len(folders)==0:\r\n print('Every thing is good!')\r\n return\r\n print('Preparing to remove:' +str(folders))\r\n choice=input('Enter YES to remove:')\r\n if choice.lower()!='yes':\r\n return \r\n for folder in folders:\r\n sys.stdout.write('Removing '+folder)\r\n shutil.rmtree(folder)\r\n print('\\n'+folder+' --Removed')\r\n\r\n\r\n#-------------------------------------END OF FUNCTIONS-----------------------------------------------------\r\n\r\n \r\nif __name__==\"__main__\":\r\n main()\r\n clear()\r\n input('Enter to exit!')\r\n file=open('log.txt','a+') \r\n file.write(log)\r\n file.close()\r\n exit()\r\n","sub_path":"movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":5570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"620164597","text":"def main():\n #escribe tu código abajo de esta línea\n minutos = float(input(\"Dame los minutos: \"))\n\n segundos = minutos * 60\n milimetros = segundos*5.7\n cm = milimetros/10\n\n print(\"Centímentros recorridos:\",cm)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"assignments/08Caracol/src/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"589306023","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\n\nimport shop.views\n\napp_name = shop\n\nurlpatterns = [\n url(r'^$', shop.views.IndexListView.as_view(), name='home'),\n url(r'^product/(?P[0-9]+)$', shop.views.ProductDetailView.as_view(), name='product-detail'),\n url(r'^product/(?P[0-9]+)/buy$', shop.views.ProductBuyView.as_view(), name='product-buy'),\n url(r'^product/order$', shop.views.OrderView.as_view(), name='order'),\n\n url(r'^manage$', shop.views.ProductsListManageView.as_view(), name='product-list-manage'),\n url(r'^manage/create$', shop.views.ProductCreateView.as_view(), name='product-create'),\n url(r'^manage/(?P[0-9]+)/update$', shop.views.ProductUpdateView.as_view(), name='product-update'),\n url(r'^manage/(?P[0-9]+)/remove$', shop.views.ProductRemoveView.as_view(), name='product-remove'),\n\n url(r'^accounts/', include('accounts.urls')),\n url(r'^admin/', admin.site.urls),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"enigmaproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"362468537","text":"# -*- coding: utf-8 -*-\nfrom abc import ABCMeta\n\nimport requests\n\nfrom . import app\n\n\nurl = {\n 'diff': {\n 'get': None\n },\n 'municipality': {\n 'get': {\n 'insee':\n lambda insee:\n '{ban_base_url}/municipality/insee:{insee}'.format(\n ban_base_url=app.config['BAN_BASE_URL'],\n insee=str(insee).zfill(5)),\n },\n },\n 'postcode': {\n 'get': {\n 'id':\n lambda id:\n '{ban_base_url}/postcode/{id}'.format(\n ban_base_url=app.config['BAN_BASE_URL'], id=id),\n 'code':\n lambda code:\n '{ban_base_url}/postcode/?code:{code}'.format(\n ban_base_url=app.config['BAN_BASE_URL'],\n code=str(code).zfill(5)),\n },\n },\n 'group': {\n 'get': {\n 'id':\n lambda id:\n '{ban_base_url}/group/{id}'.format(\n ban_base_url=app.config['BAN_BASE_URL'], id=id),\n 'municipality_id':\n lambda municipality_id:\n '{ban_base_url}/group/?municipality={municipality_id}'\n .format(ban_base_url=app.config['BAN_BASE_URL'],\n municipality_id=str(municipality_id)),\n },\n },\n 'housenumber': {\n 'get': {\n 'id':\n lambda id:\n '{ban_base_url}/housenumber/{id}'.format(\n ban_base_url=app.config['BAN_BASE_URL'], id=id),\n 'group_id':\n lambda group_id:\n '{ban_base_url}/housenumber/?parent={group_id}'.format(\n ban_base_url=app.config['BAN_BASE_URL'],\n group_id=str(group_id)),\n },\n },\n 'position': {\n 'get': {\n 'id':\n lambda id:\n '{ban_base_url}/position/{id}'.format(\n ban_base_url=app.config['BAN_BASE_URL'], id=id),\n 'housenumber_id':\n lambda housenumber_id:\n '{ban_base_url}/position/?housenumber={housenumber_id}'\n .format(ban_base_url=app.config['BAN_BASE_URL'],\n housenumber_id=str(housenumber_id)),\n },\n },\n}\n\n\ndef get_url(resource, action, data_name, value):\n return url[resource][action][data_name](value)\n\n\ndef get_headers_url():\n \"\"\"Collect headers to use in url.\"\"\"\n\n return app.config['BAN_HEADERS']\n\n\ndef get_diff_url(last_increment=None):\n \"\"\"Construct BanDiff Url thanks to last_increment.\"\"\"\n\n if last_increment:\n url_base = '{ban_base_url}/diff?increment='.format(\n ban_base_url=app.config['BAN_BASE_URL']\n )\n url = '{url} {last_increment}'.format(\n url=url_base, last_increment=str(last_increment)\n )\n else:\n url = '{ban_base_url}/diff'.format(\n ban_base_url=app.config['BAN_BASE_URL']\n )\n\n return url\n\n\nclass API():\n \"\"\"Collect all params to call an API.\"\"\"\n\n __metaclass__ = ABCMeta\n\n def __init__(self, url, data=None):\n self.url = url\n self.headers = get_headers_url()\n self.data = data\n\n\nclass APIGet(API):\n \"\"\"Get data through an API call.\"\"\"\n\n __metaclass__ = ABCMeta\n\n def get_data(self):\n\n response = {\"code\": None, \"data\": None}\n r_get = requests.get(self.url, headers=self.headers)\n\n if r_get:\n self.data = r_get.json()\n else:\n self.data = None\n\n if r_get.status_code == 401:\n self.data = 'Client Error - Unauthorized. (Is your token defined?)'\n\n response['code'] = r_get.status_code\n response['data'] = self.data\n\n # return self.data\n return response\n\n\nclass APIPatch(API):\n \"\"\"Patch data through an API call.\"\"\"\n\n __metaclass__ = ABCMeta\n\n def patch_data(self):\n response = {\"code\": None, \"data\": None}\n r_patch = requests.patch(\n self.url, json=self.data, headers=get_headers_url()\n )\n\n if r_patch:\n self.data = r_patch.json()\n else:\n self.data = None\n\n if r_patch.status_code == 401:\n self.data = 'Client Error = Unauthorized. (Is your token defined?)'\n\n response['code'] = r_patch.status_code\n response['data'] = self.data\n\n # return self.data\n return response\n\n\nclass APIGetResource(APIGet):\n \"\"\" Get Resource data through an API. \"\"\"\n\n def get_data(self):\n return super().get_data()\n\n\nclass APIGetCollection(APIGet):\n \"\"\" Get Collection data through an API. \"\"\"\n\n def get_data(self):\n\n response = super().get_data()\n\n # Data or no data?\n if response['code'] == 401:\n return response\n\n if response['code'] == 200 and response['data']['collection'] == []:\n response['data'] = None\n\n return response\n\n\nclass APIPatchResource(APIPatch):\n \"\"\" Patch a Resource through an API with data. \"\"\"\n\n def patch_data(self):\n return super().patch_data()\n","sub_path":"monitoring/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":5195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"351509491","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 13 17:20:54 2021\n\n@author: Anderson Ryen\n\"\"\"\n\nimport os\n\n#文件的绝对路径\nfile_path = \"E:\\GitHub Desktop\\GitHub\\dy-pic\\siyan\\\\\"\n#CDN前缀\nweb_path = \"https://cdn.jsdelivr.net/gh/\"\n#GITHUB账户名\nuser_path = \"anderson-ryen\"\n#仓库名\nwarehouse_path = \"dy-pic\"\n#仓库内文件夹\nimg_path = \"siyan\"\n#合并path\napi_path = os.path.join( web_path + user_path + \"/\" + warehouse_path + \"/\" + img_path + \"/\")\n\n\nprint(\"\")\nprint(\"前缀预览: \" + api_path)\nprint(\"\")\nprint(\"=\" *50)\nprint(\"siyan已完成\")\nprint(\"地址预览:E:\\GitHub Desktop\\GitHub\\dy-pic\\\\api-py\\siyan.txt\")\nprint(\"=\" *50)\nprint(\"\")\n\nif __name__ == '__main__':\n filelist = os.listdir(file_path)\n with open(r\"E:\\GitHub Desktop\\GitHub\\dy-pic\\api-py\\siyan.txt\",'w',encoding='utf-8') as f:\n for file in filelist:\n f.write(api_path+file+'\\n')\n","sub_path":"php-api/dy/siyan.py","file_name":"siyan.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"411008652","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 3 15:25:12 2020\n\n@author: Meet\n\"\"\"\n\nimport os\nimport argparse\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\nFILL = {\n 'NO': 0,\n 'FLOOD': 1,\n 'THRESHOLD': 2,\n 'MORPH': 3,\n}\n\n'''files = {\n \"image1\": \"D:\\segmentation_work\\color\\Image1.JPG\",\n \"image2\": \"D:\\segmentation_work\\color\\Image2.JPG\"\n }'''\n\n# error message when image could not be read\nIMAGE_NOT_READ = 'IMAGE_NOT_READ'\n\n# error message when image is not colored while it should be\nNOT_COLOR_IMAGE = 'NOT_COLOR_IMAGE'\n\n\ndef read_image(file_path, read_mode=cv2.IMREAD_COLOR):\n \"\"\"\n Read image file with all preprocessing needed\n Args:\n file_path: absolute file_path of an image file\n read_mode: whether image reading mode is rgb, grayscale or somethin\n Returns:\n np.ndarray of the read image or None if couldn't read\n Raises:\n ValueError if image could not be read with message IMAGE_NOT_READ\n \"\"\"\n # read image file in grayscale\n image = cv2.imread(file_path, read_mode)\n\n if image is None:\n raise ValueError(IMAGE_NOT_READ)\n else:\n return image\n\n\ndef ensure_color(image):\n \"\"\"\n Ensure that an image is colored\n Args:\n image: image to be checked for\n Returns:\n nothing\n Raises:\n ValueError with message code if image is not colored\n \"\"\"\n if len(image.shape) < 3:\n raise ValueError(NOT_COLOR_IMAGE)\n\n\ndef div0(a, b):\n \"\"\" ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0] \"\"\"\n with np.errstate(divide='ignore', invalid='ignore'):\n q = np.true_divide(a, b)\n q[ ~ np.isfinite(q) ] = 0 # -inf inf NaN\n\n return q\n\n\ndef excess_green(image, scale = 2):\n \"\"\"\n Compute excess green index for colored image\n Args:\n image: image to be converted\n scale: number to scale green channel of the image\n Returns:\n new image with excess green\n \"\"\"\n\n ensure_color(image)\n\n bgr_sum = np.sum(image, axis=2)\n debug(bgr_sum, 'green bgr sum')\n\n blues = div0(image[:, :, 0], bgr_sum)\n greens = div0(image[:, :, 1], bgr_sum)\n reds = div0(image[:, :, 2], bgr_sum)\n\n index = scale * greens - (reds + blues)\n\n return index\n\n\ndef excess_red(image, scale=1.4):\n \"\"\"\n Compute excess red index for colored image\n Args:\n image: image to be converted\n scale: number to scale red channel of the image\n Returns:\n new image with excess red\n \"\"\"\n\n ensure_color(image)\n\n bgr_sum = np.sum(image, axis=2)\n\n blues = div0(image[:, :, 0], bgr_sum)\n greens = div0(image[:, :, 1], bgr_sum)\n reds = div0(image[:, :, 2], bgr_sum)\n\n index = scale * reds - greens\n\n return index\n\n\ndef index_diff(image, green_scale=2.0, red_scale=1.4):\n\n ensure_color(image)\n\n bgr_sum = np.sum(image, axis=2)\n\n blues = div0(image[:, :, 0], bgr_sum)\n greens = div0(image[:, :, 1], bgr_sum)\n reds = div0(image[:, :, 2], bgr_sum)\n\n green_index = green_scale * greens - (reds + blues)\n red_index = red_scale * reds - (greens)\n\n return green_index - red_index\n\n\ndef debug(value, name=None):\n if isinstance(value, np.ndarray):\n name = 'ndarray' if name is None else name\n\n print(\"{}: {}\".format(name, value))\n print(\"{} shape: {}\".format(name, value.shape))\n else:\n name = 'value' if name is None else name\n\n print(\"{} type: {}\".format(name, type(value)))\n print(\"{}: {}\".format(name, value))\n\n\ndef remove_whites(image, marker):\n \"\"\"\n Remove pixels resembling white from marker as background\n Args:\n image:\n marker: to be overloaded with white pixels to be removed\n Returns:\n nothing\n \"\"\"\n # setup the white remover to process logical_and in place\n white_remover = np.full((image.shape[0], image.shape[1]), True)\n\n # below line same as: white_remover = np.logical_and(white_remover, image[:, :, 0] > 200)\n white_remover[image[:, :, 0] <= 200] = False # blue channel\n\n # below line same as: white_remover = np.logical_and(white_remover, image[:, :, 1] > 220)\n white_remover[image[:, :, 1] <= 220] = False # green channel\n\n # below line same as: white_remover = np.logical_and(white_remover, image[:, :, 2] > 200)\n white_remover[image[:, :, 2] <= 200] = False # red channel\n\n # remove whites from marker\n marker[white_remover] = False\n\n\ndef remove_blacks(image, marker):\n \"\"\"\n Remove pixels resembling black from marker as background\n Args:\n image:\n marker: to be overloaded with black pixels to be removed\n Returns:\n nothing\n \"\"\"\n # setup the black remover to process logical_and in place\n black_remover = np.full((image.shape[0], image.shape[1]), True)\n\n # below line same as: black_remover = np.logical_and(black_remover, image[:, :, 0] < 30)\n black_remover[image[:, :, 0] >= 30] = False # blue channel\n\n # below line same as: black_remover = np.logical_and(black_remover, image[:, :, 1] < 30)\n black_remover[image[:, :, 1] >= 30] = False # green channel\n\n # below line same as: black_remover = np.logical_and(black_remover, image[:, :, 2] < 30)\n black_remover[image[:, :, 2] >= 30] = False # red channel\n\n # remove blacks from marker\n marker[black_remover] = False\n\n\ndef remove_blues(image, marker):\n \"\"\"\n Remove pixels resembling blues better than green from marker as background\n Args:\n image:\n marker: to be overloaded with blue pixels to be removed\n Returns:\n nothing\n \"\"\"\n # choose pixels that have higher blue than green\n blue_remover = image[:, :, 0] > image[:, :, 1]\n\n # remove blues from marker\n marker[blue_remover] = False\n\n\ndef color_index_marker(color_index_diff, marker):\n \"\"\"\n Differentiate marker based on the difference of the color indexes\n Threshold below some number(found empirically based on testing on 5 photos,bad)\n If threshold number is getting less, more non-green image\n will be included and vice versa\n Args:\n color_index_diff: color index difference based on green index minus red index\n marker: marker to be updated\n Returns:\n nothing\n \"\"\"\n marker[color_index_diff <= -0.05] = False\n\n\ndef texture_filter(image, marker, threshold=220, window=3):\n \"\"\"\n Update marker based on texture of an image\n Args:\n image (ndarray of grayscale image):\n marker (ndarray size of image): marker to be updated\n threshold (number): minimum size of texture measurement(entropy) allowed\n window (int): window size of a square the texture computed from\n Returns: nothing\n \"\"\"\n\n window = window - window//2 - 1\n for x in range(0, image.shape[0]):\n for y in range(0, image.shape[1]):\n # print('x y', x, y)\n # print('window', image[x:x + window, y:y + window])\n x_start = x - window if x < window else x\n y_start = y - window if y < window else y\n x_stop = x + window if x < image.shape[0] - window else image.shape[0]\n y_stop = y + window if y < image.shape[1] - window else image.shape[1]\n\n local_entropy = np.sum(image[x_start:x_stop, y_start:y_stop]\n * np.log(image[x_start:x_stop, y_start:y_stop] + 1e-07))\n # print('entropy', local_entropy)\n if local_entropy > threshold:\n marker[x, y] = False\n\n\ndef otsu_color_index(excess_green, excess_red):\n return cv2.threshold(excess_green - excess_red, 0, 255,cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n\n\ndef generate_floodfill_mask(bin_image):\n \"\"\"\n Generate a mask to remove backgrounds adjacent to image edge\n Args:\n bin_image (ndarray of grayscale image): image to remove backgrounds from\n Returns:\n a mask to backgrounds adjacent to image edge\n \"\"\"\n y_mask = np.full(\n (bin_image.shape[0], bin_image.shape[1]), fill_value=255, dtype=np.uint8\n )\n x_mask = np.full(\n (bin_image.shape[0], bin_image.shape[1]), fill_value=255, dtype=np.uint8\n )\n\n xs, ys = bin_image.shape[0], bin_image.shape[1]\n\n for x in range(0, xs):\n item_indexes = np.where(bin_image[x,:] != 0)[0]\n # min_start_edge = ys\n # max_final_edge = 0\n if len(item_indexes):\n start_edge, final_edge = item_indexes[0], item_indexes[-1]\n x_mask[x, start_edge:final_edge] = 0\n # if start_edge < min_start_edge:\n # min_start_edge = start_edge\n # if final_edge > max_final_edge:\n # max_final_edge = final_edge\n\n for y in range(0, ys):\n item_indexes = np.where(bin_image[:,y] != 0)[0]\n if len(item_indexes):\n start_edge, final_edge = item_indexes[0], item_indexes[-1]\n\n y_mask[start_edge:final_edge, y] = 0\n # mask[:start_edge, y] = 255\n # mask[final_edge:, y] = 255\n\n return np.logical_or(x_mask, y_mask)\n\n\ndef select_largest_obj(img_bin, lab_val=255, fill_mode=FILL['FLOOD'],\n smooth_boundary=False, kernel_size=15):\n \"\"\"\n Select the largest object from a binary image and optionally\n fill holes inside it and smooth its boundary.\n Args:\n img_bin (2D array): 2D numpy array of binary image.\n lab_val ([int]): integer value used for the label of the largest\n object. Default is 255.\n fill_mode (string {no,flood,threshold,morph}): hole filling techniques which are\n - no: no filling of holes\n - flood: floodfilling technique without removing image edge sharing holes\n - threshold: removing holes based on minimum size of hole to be removed\n - morph: closing morphological operation with some kernel size to remove holes\n smooth_boundary ([boolean]): whether smooth the boundary of the\n largest object using morphological opening or not. Default\n is false.\n kernel_size ([int]): the size of the kernel used for morphological\n operation. Default is 15.\n Returns:\n a binary image as a mask for the largest object.\n \"\"\"\n\n # set up components\n n_labels, img_labeled, lab_stats, _ = \\\n cv2.connectedComponentsWithStats(img_bin, connectivity=8, ltype=cv2.CV_32S)\n\n # find largest component label(label number works with labeled image because of +1)\n largest_obj_lab = np.argmax(lab_stats[1:, 4]) + 1\n\n # create a mask that will only cover the largest component\n largest_mask = np.zeros(img_bin.shape, dtype=np.uint8)\n largest_mask[img_labeled == largest_obj_lab] = lab_val\n\n if fill_mode == FILL['FLOOD']:\n # fill holes using opencv floodfill function\n\n # set up seedpoint(starting point) for floodfill\n bkg_locs = np.where(img_labeled == 0)\n bkg_seed = (bkg_locs[0][0], bkg_locs[1][0])\n\n # copied image to be floodfill\n img_floodfill = largest_mask.copy()\n\n # create a mask to ignore what shouldn't be filled(I think no effect)\n h_, w_ = largest_mask.shape\n mask_ = np.zeros((h_ + 2, w_ + 2), dtype=np.uint8)\n\n cv2.floodFill(img_floodfill, mask_, seedPoint=bkg_seed,\n newVal=lab_val)\n holes_mask = cv2.bitwise_not(img_floodfill) # mask of the holes.\n\n # get a mask to avoid filling non-holes that are adjacent to image edge\n non_holes_mask = generate_floodfill_mask(largest_mask)\n holes_mask = np.bitwise_and(holes_mask, np.bitwise_not(non_holes_mask))\n\n largest_mask = largest_mask + holes_mask\n elif fill_mode == FILL['MORPH']:\n # fill holes using closing morphology operation\n kernel_ = np.ones((50, 50), dtype=np.uint8)\n largest_mask = cv2.morphologyEx(largest_mask, cv2.MORPH_CLOSE,\n kernel_)\n elif fill_mode == FILL['THRESHOLD']:\n # fill background-holes based on hole size threshold\n # default hole size threshold is some percentage\n # of size of the largest component(i.e leaf component)\n\n # invert to setup holes of background, sorry for the incovenience\n inv_img_bin = np.bitwise_not(largest_mask)\n\n # set up components\n inv_n_labels, inv_img_labeled, inv_lab_stats, _ = \\\n cv2.connectedComponentsWithStats(inv_img_bin, connectivity=8, ltype=cv2.CV_32S)\n\n # find largest component label(label number works with labeled image because of +1)\n inv_largest_obj_lab = np.argmax(inv_lab_stats[1:, 4]) + 1\n\n # setup sizes and number of components\n inv_sizes = inv_lab_stats[1:, -1]\n sizes = lab_stats[1:, -1]\n inv_nb_components = inv_n_labels - 1\n\n # find the greater side of the image\n inv_max_side = np.amax(inv_img_labeled.shape)\n\n # set the minimum size of hole that is allowed to stay\n inv_min_size = int(0.3 * sizes[largest_obj_lab - 1]) # todo: specify good min size\n\n # generate the mask that allows holes greater than minimum size(weird)\n inv_mask = np.zeros((inv_img_labeled.shape), dtype=np.uint8)\n for inv_i in range(0, inv_nb_components):\n if inv_sizes[inv_i] >= inv_min_size:\n inv_mask[inv_img_labeled == inv_i + 1] = 255\n\n largest_mask = largest_mask + np.bitwise_not(inv_mask)\n\n if smooth_boundary:\n # smooth edge boundary\n kernel_ = np.ones((kernel_size, kernel_size), dtype=np.uint8)\n largest_mask = cv2.morphologyEx(largest_mask, cv2.MORPH_OPEN,\n kernel_)\n\n return largest_mask\n\n\ndef simple_test():\n # image = read_image(files['jpg1'])\n # g_img = excess_green(image)\n # r_img = excess_red(image)\n # debug(image[0], 'image')\n # debug(g_img[0], 'excess_green')\n # debug(r_img[0], 'excess_red')\n # debug(g_img[0]-r_img[0], 'diff')\n\n original_image = read_image(files['jpg1'], cv2.IMREAD_GRAYSCALE)\n marker = np.full((original_image.shape[0], original_image.shape[1]), True)\n texture_filter(original_image, marker)\n\n\ndef test():\n\n image = read_image(files['jpg1'])\n\n rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n plt.imshow(rgb_image)\n plt.show()\n\n # plt.imshow(cv2.cvtColor(excess_green(image), cv2.COLOR_BGR2RGB))\n # plt.show()\n #\n # plt.imshow(cv2.cvtColor(excess_red(image), cv2.COLOR_BGR2RGB))\n # plt.show()\n\n\n''' segment.py here '''\n\ndef generate_background_marker(file):\n \"\"\"\n Generate background marker for an image\n Args:\n file (string): full path of an image file\n Returns:\n tuple[0] (ndarray of an image): original image\n tuple[1] (ndarray size of an image): background marker\n \"\"\"\n\n # check file name validity\n '''if not os.path.isfile(file):\n raise ValueError('{}: is not a file'.format(file))'''\n\n original_image = read_image(file)\n\n marker = np.full((original_image.shape[0], original_image.shape[1]), True)\n\n # update marker based on vegetation color index technique\n color_index_marker(index_diff(original_image), marker)\n\n # update marker to remove blues\n # remove_blues(original_image, marker)\n\n return original_image, marker\n\n\ndef segment_leaf(image_file, filling_mode, smooth_boundary, marker_intensity):\n \"\"\"\n Segments leaf from an image file\n Args:\n image_file (string): full path of an image file\n filling_mode (string {no, flood, threshold, morph}): \n how holes should be filled in segmented leaf\n smooth_boundary (boolean): should leaf boundary smoothed or not\n marker_intensity (int in rgb_range): should output background marker based\n on this intensity value as foreground value\n Returns:\n tuple[0] (ndarray): original image to be segmented\n tuple[1] (ndarray): A mask to indicate where leaf is in the image\n or the segmented image based on marker_intensity value\n \"\"\"\n # get background marker and original image\n original, marker = generate_background_marker(image_file)\n\n # set up binary image for futher processing\n bin_image = np.zeros((original.shape[0], original.shape[1]))\n bin_image[marker] = 255\n bin_image = bin_image.astype(np.uint8)\n\n # further processing of image, filling holes, smoothing edges\n largest_mask = \\\n select_largest_obj(bin_image, fill_mode=filling_mode,\n smooth_boundary=smooth_boundary)\n\n if marker_intensity > 0:\n largest_mask[largest_mask != 0] = marker_intensity\n image = largest_mask\n else:\n # apply marker to original image\n image = original.copy()\n image[largest_mask == 0] = np.array([0, 0, 0])\n\n return original, image\n\n\ndef rgb_range(arg):\n \"\"\"\n Check if arg is in range for rgb value(between 0 and 255)\n Args:\n arg (int convertible): value to be checked for validity of range\n Returns:\n arg in int form if valid\n Raises:\n argparse.ArgumentTypeError: if value can not be integer or not in valid range\n \"\"\"\n\n try:\n value = int(arg)\n except ValueError as err:\n raise argparse.ArgumentTypeError(str(err))\n\n if value < 0 or value > 255:\n message = \"Expected 0 <= value <= 255, got value = {}\".format(value)\n raise argparse.ArgumentTypeError(message)\n\n return value\n\n\nif __name__ == '__main__':\n # handle command line arguments\n parser = argparse.ArgumentParser('segment')\n parser.add_argument('-m', '--marker_intensity', type=rgb_range, default=0,\n help='Output image will be as black background and foreground '\n 'with integer value specified here')\n parser.add_argument('-f', '--fill', choices=['no', 'flood', 'threshold', 'morph'],\n help='Change hole filling technique for holes appearing in segmented output',\n default='flood')\n parser.add_argument('-s', '--smooth', action='store_true',\n help='Output image with smooth edges')\n parser.add_argument('-d', '--destination',\n help='Destination directory for output image. '\n 'If not specified destination directory will be input image directory')\n parser.add_argument('-o', '--with_original', action='store_true',\n help='Segmented output will be appended horizontally to the original image')\n parser.add_argument('image_source', help='A path of image filename or folder containing images')\n \n # set up command line arguments conveniently\n args = parser.parse_args()\n filling_mode = FILL[args.fill.upper()]\n smooth = True if args.smooth else False\n if args.destination:\n if not os.path.isdir(args.destination):\n print(args.destination, ': is not a directory')\n exit()\n\n # set up files to be segmented and destination place for segmented output\n if os.path.isdir(args.image_source):\n files = [entry for entry in os.listdir(args.image_source)\n if os.path.isfile(os.path.join(args.image_source, entry))]\n base_folder = args.image_source\n\n # set up destination folder for segmented output\n if args.destination:\n destination = args.destination\n else:\n if args.image_source.endswith(os.path.sep):\n args.image_source = args.image_source[:-1]\n destination = args.image_source + '_markers'\n os.makedirs(destination, exist_ok=True)\n else:\n folder, file = os.path.split(args.image_source)\n files = [file]\n base_folder = folder\n\n # set up destination folder for segmented output\n if args.destination:\n destination = args.destination\n else:\n destination = folder\n\n for file in files:\n try:\n # read image and segment leaf\n original, output_image = \\\n segment_leaf(os.path.join(base_folder, file), filling_mode, smooth, args.marker_intensity)\n\n except ValueError as err:\n if str(err) == IMAGE_NOT_READ:\n print('Error: Could not read image file: ', file)\n elif str(err) == NOT_COLOR_IMAGE:\n print('Error: Not color image file: ', file)\n else:\n raise\n # if no error when segmenting write segmented output\n else:\n # handle destination folder and fileaname\n filename, ext = os.path.splitext(file)\n if args.with_original:\n new_filename = filename + '_marked_merged' + ext\n print('created')\n else:\n new_filename = filename + '_marked' + ext\n print('created')\n new_filename = os.path.join(destination, new_filename)\n\n # change grayscale image to color image format i.e need 3 channels\n if args.marker_intensity > 0:\n output_image = cv2.cvtColor(output_image, cv2.COLOR_GRAY2RGB)\n\n # write the output\n if args.with_original:\n print('writing in folder')\n cv2.imwrite(new_filename, np.hstack((original,output_image)))\n else:\n print('writing in folder')\n cv2.imwrite(new_filename, output_image)\n print('Marker generated for image file: ', file)","sub_path":"Meet/segment.py","file_name":"segment.py","file_ext":"py","file_size_in_byte":21482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"1179866","text":"\"\"\"\nStudent: Imke Lansky\nStudent number: 10631194\nFile: helper.py\nDate: 23-05-2016\n\nDescription:\nThis file contains some functions which are used in multiple of the methods\ndefined in the Simulation Class. By storing them in a helper file they are\neasily accessible.\n\"\"\"\n\nfrom numpy import sqrt, ndarray\nimport json\nimport numpy as np\nimport shapely.geometry as geom\nfrom scipy.interpolate import splprep, splev\n\ndef LineString_linspace(line, num):\n '''Return `num` equally distance points in the line'''\n\n distance_linspace = np.linspace(0., 1., num, endpoint=True)\n points = []\n x, y = [], []\n \n for dist in distance_linspace:\n points.append(line.interpolate(dist, normalized=True))\n x.append(points[len(points)-1].x)\n y.append(points[len(points)-1].y)\n\n return points, x, y\n\n\n\ndef preprocess_x_y(x, y, thr=170, interpolate=True, save_csv=False, filename=''):\n \"\"\"\n Sort [x_i, y_i] points in a circular order\n \n Parameters\n ----------\n x : numpy 1D array\n y : numpy 1D array\n thr : int, optional\n Threshold used to separate top and bottom sides of the embryo.\n This is necessary for sorting the points.\n interpolate : bool, optional\n Whether the function interpolates the x, y or not, if yes, it will return 6000 points\n save_csv : bool, optional\n To save the 2D array of [[x], [y]] into a CSV file\n filename : str, optional\n Output file name\n \n Returns\n -------\n TYPE\n Sorted (interpolated) x and y\n \"\"\"\n\n \n # Todo: pick the split point automatically in the middle\n\n \n x_top = x[y >= thr]\n x_bot = x[y < thr]\n \n y_top = y[y >= thr]\n y_bot = y[y < thr]\n \n unique_index = x_top.searchsorted(np.array(list(set(x_top))))\n x_top_un = x_top[unique_index]\n y_top_un = y_top[unique_index]\n x_top_sorted = sorted(x_top_un)\n y_top_sorted = y_top_un[x_top_un.argsort()]\n \n unique_index = x_bot.searchsorted(np.array(list(set(x_bot))))\n x_bot_un = x_bot[unique_index]\n y_bot_un = y_bot[unique_index]\n x_bot_sorted = sorted(x_bot_un)\n y_bot_sorted = y_bot_un[x_bot_un.argsort()]\n \n# x_new = np.concatenate((x_top_un, x_bot_un[::-1]))\n# y_new = np.concatenate((y_top_un, y_bot_un[::-1]))\n \n x_new = np.concatenate((x_top_sorted, x_bot_sorted[::-1], [x_top_sorted[0]]))\n y_new = np.concatenate((y_top_sorted, y_bot_sorted[::-1], [y_top_sorted[0]]))\n \n line = geom.LinearRing(zip(x_new, y_new))\n points, xn, yn = LineString_linspace(line, 50)\n\n if interpolate:\n spline_inf, _ = splprep([xn, yn], k=2, s=0)\n x_new, y_new = splev(np.linspace(0, 1, 6000), spline_inf)\n \n if save_csv:\n np.savetxt(filename, np.array([x_new, y_new]), delimiter=',')\n \n return x_new, y_new\n\n\nclass NumpyAwareJSONEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.ndarray) and obj.ndim == 1:\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\n\ndef spline_length(coords):\n \"\"\"\n Calculates the length of the spline by taking the distances between\n consecutive points and adding these up. Also keep track of an array\n which the cumulative lengths that are calculated for determing the\n point indices later on.\n\n PARAMETERS\n ==============\n coords: numpy.ndarray\n 2D array which contains the coordinates.\n\n RETURNS\n ==============\n total_length: float\n The length of the boundary.\n cumulative_length: list\n List which contains the length at each index.\n \"\"\"\n\n total_length = 0\n cumulative_length = []\n for i in range(0, len(coords) - 1):\n length = sqrt((coords[i + 1][0] - coords[i][0])**2 +\n (coords[i + 1][1] - coords[i][1])**2)\n cumulative_length.append(total_length + length)\n total_length += length\n return total_length, cumulative_length\n\n\ndef remove_dimensions(arr):\n \"\"\"\n When multiple splines are used for drawing a boundary, these sets of points\n are in separate lists. This must be transformed into one 1D list of values.\n\n PARAMETERS\n ==============\n arr: numpy.ndarray\n The array which we want to flatten.\n\n RETURNS\n ==============\n arr: numpy.ndarray\n The flattened array with spline points.\n \"\"\"\n\n if arr.shape[0] >= 2:\n return arr.flatten()\n else:\n return arr\n\n\ndef check_nd_array(arr):\n \"\"\"\n Checks whether the given array is a multidimensional array.\n\n PARAMETERS\n ==============\n arr: numpy.ndarray\n Array for which to check whether it is multidimensional or not.\n\n RETURNS\n ==============\n Boolean which says if the array is multidimensional.\n \"\"\"\n\n return isinstance(arr[0], ndarray)\n","sub_path":"NematostellaMorphGen-master/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"508733987","text":"import datetime\n\nimport httpx\nimport pandas as pd\n\nfrom ...crypto_exchange_etl import S3CryptoExchangeETL\nfrom ...historical_downloader import calculate_notional\nfrom .constants import BTCUSD, BYBIT, URL\n\n\ndef calc_notional(x):\n if x[\"symbol\"] == BTCUSD:\n return x[\"volume\"] / x[\"price\"]\n else:\n # Notional depends on underlying.\n return 0\n\n\nclass BybitPerpetualETL(S3CryptoExchangeETL):\n def __init__(self, symbol, date_from=None, date_to=None, verbose=False):\n exchange = BYBIT\n min_date = datetime.date(2019, 10, 1)\n super().__init__(\n exchange,\n symbol,\n min_date,\n date_from=date_from,\n date_to=date_to,\n verbose=verbose,\n )\n\n def get_url(self, date):\n directory = f\"{URL}{self.symbol}/\"\n response = httpx.get(directory)\n if response.status_code == 200:\n return f\"{URL}{self.symbol}/{self.symbol}{date.isoformat()}.csv.gz\"\n else:\n print(f\"{self.exchange.capitalize()} {self.symbol}: No data\")\n\n def parse_dataframe(self, data_frame):\n # No false positives.\n # Source: https://pandas.pydata.org/pandas-docs/stable/user_guide/\n # indexing.html#returning-a-view-versus-a-copy\n pd.options.mode.chained_assignment = None\n # Bybit is reversed.\n data_frame = data_frame.iloc[::-1]\n data_frame[\"index\"] = data_frame.index.values[::-1]\n data_frame[\"timestamp\"] = pd.to_datetime(data_frame[\"timestamp\"], unit=\"s\")\n data_frame = super().parse_dataframe(data_frame)\n data_frame = calculate_notional(data_frame, calc_notional)\n return data_frame\n\n def calculate_notional(self, data_frame):\n return calculate_notional(data_frame, calc_notional)\n","sub_path":"crypto_exchange_etl/data_providers/bybit/perpetual.py","file_name":"perpetual.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"123013807","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nsys.setrecursionlimit(10**6)\n\nM,D = map(int,input().split())\nlength = 201\ndp = [[False for i in range(1800+2)] for j in range(length)]\ndp[0][0] = 1\nfor i in range(1,10):\n dp[0][i] = 1\nfor n in range(1,length):\n dp[n] = dp[n-1]+[]\n for i in range(1,10):\n for d in range(1800+2)[::-1]:\n if d+i < 1800+2 and dp[n-1][d] is not False: \n dp[n][d+i] += dp[n-1][d]\n\n#ある桁数のその数字までの値を求める\ndef hoge(digit,n):\n n = int(n)\n xs = [0 for i in range(1800+2)]\n upper = 0\n for i in range(int(n)):\n for d in range(1800+2)[::-1]:\n if d+i < 1800+2: \n xs[d+i] += dp[digit-1][d]\n return xs\n\ndef solve(num,digit):\n #numまでは足して,numになったらnum以降の数字で出来たものにnumを足したものを返す\n if digit == 0:\n a = [1 if i <= int(num) else 0 for i in range(0,1800+2)]\n return a\n n = int(num[0])\n a = hoge(digit,n)\n b = solve(num[1:],digit-1)\n for i in range(1800+2):\n if i+n < 1800+2:\n a[i+n] += b[i]\n return a\n\nM_count = solve(str(M),len(str(M))-1)\n\nD_count = solve(str(D),len(str(D))-1)\n\nans = 0\nfor i in range(1,1800+2):\n ans += M_count[i] * D_count[i] %(10**9+9)\nprint(ans%(10**9+9))\n","sub_path":"yukicoder/189.py","file_name":"189.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"629242556","text":"__author__ = 'kmcinti2'\nimport webbrowser\n\n\nclass Video():\n \"\"\"\"This class provides a way to basic video information.\"\"\"\n\n def __init__(self, title, duration, description, video_sample):\n self.title = title\n self.duration = duration\n self.description = description\n self.video_sample = video_sample\n\n def show_video(self):\n webbrowser.open_new(self.video_sample)\n\n\nclass TvShow(Video):\n \"\"\"\"This class provides a way to store TV information. Inherits from the Video class.\"\"\"\n\n def __init__(self, title, duration, season, episode_number, description, station, video_sample):\n Video.__init__(title, duration, description, video_sample)\n self.season = season\n self.episode_number = episode_number\n self.station = station\n\n\nclass Movie(Video):\n \"\"\"This class provides a way to store movie information\"\"\"\n\n VALID_RATINGS = ['G', 'PG', 'PG-13', 'R']\n\n def __init__(self, title, duration, description, poster, video_sample):\n Video.__init__(self, title, duration, description, video_sample)\n self.title = title\n self.poster_image_url = poster","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"605328435","text":"import unittest\nimport numpy as np\nfrom pymicro.xray.detectors import RegArrayDetector2d\n\nclass DetectorsTests(unittest.TestCase):\n\n def setUp(self):\n \"\"\"testing the detectors module:\"\"\"\n self.detector = RegArrayDetector2d(size=(1024, 512), u_dir=[0, -1, 0], v_dir=[0, 0, -1])\n self.detector.pixel_size = 0.1 # mm\n self.detector.ref_pos = np.array([100., 0., 0.]) # position in the laboratory frame of the middle of the detector\n\n def test_project_along_direction(self):\n \"\"\"Verify the project_along_direction method.\"\"\"\n R = self.detector.project_along_direction(direction=(1., 0., 0.), origin=(0., 0., 0.))\n (u, v) = self.detector.lab_to_pixel(R)[0]\n self.assertEqual(u, 512)\n self.assertEqual(v, 256)\n # project in the top left corner of the detector\n v = np.array([0.1, 0.04, 0.02])\n v /= np.linalg.norm(v)\n R = self.detector.project_along_direction(direction=v, origin=(0., 0., 0.))\n (u, v) = self.detector.lab_to_pixel(R)[0]\n self.assertEqual(int(u), 112)\n self.assertEqual(int(v), 56)\n RR = self.detector.pixel_to_lab(u, v)[0]\n self.assertListEqual(RR.tolist(), R.tolist())\n size_mm_1 = self.detector.get_size_mm()\n\n # use a 2x2 binning\n self.detector.pixel_size = 0.2 # mm\n self.detector.size = (512, 256)\n size_mm_2 = self.detector.get_size_mm()\n self.assertEqual(size_mm_1[0], size_mm_2[0])\n self.assertEqual(size_mm_1[1], size_mm_2[1])\n (u, v) = self.detector.lab_to_pixel(R)[0]\n self.assertEqual(int(u), 56)\n self.assertEqual(int(v), 28)\n RR = self.detector.pixel_to_lab(u, v)[0]\n self.assertListEqual(RR.tolist(), R.tolist())\n\n def test_detector_tilt(self):\n \"\"\"Verify the tilted coordinate frame \"\"\"\n for tilt in [1, 5, 10, 15]:\n # Detector tilt alpha/X ; beta/Y ; gamma/Z\n alpha = np.radians(tilt) # degree to rad, rotate around X axis\n beta = np.radians(tilt) # degree to rad, rotate around Y axis\n gamma = np.radians(tilt) # degree to rad, rotate around Z axis\n\n\n u1 = np.sin(gamma) * np.cos(beta)\n u2 = - np.cos(gamma) * np.cos(alpha) + np.sin(gamma) * np.sin(beta) * np.sin(alpha)\n u3 = - np.cos(gamma) * np.sin(alpha) - np.sin(gamma) * np.sin(beta) * np.cos(alpha)\n\n v1 = - np.sin(beta)\n v2 = np.cos(beta) * np.sin(alpha)\n v3 = - np.cos(beta) * np.cos(alpha)\n\n det_tilt = RegArrayDetector2d(size=(487, 619),\n u_dir=[u1, u2, u3], v_dir=[v1, v2, v3])\n\n # compute w using trigonometry\n w1 = np.cos(gamma) * np.cos(beta)\n w2 = np.cos(gamma) * np.sin(beta) * np.sin(alpha) + np.sin(gamma) * np.cos(alpha)\n w3 = np.sin(gamma) * np.sin(alpha) - np.cos(gamma) * np.sin(beta) * np.cos(alpha)\n\n self.assertAlmostEqual(w1, det_tilt.w_dir[0], 7)\n self.assertAlmostEqual(w2, det_tilt.w_dir[1], 7)\n self.assertAlmostEqual(w3, det_tilt.w_dir[2], 7)\n","sub_path":"pymicro/xray/tests/test_detectors.py","file_name":"test_detectors.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"302825301","text":"class Solution(object):\n def myPow(self, x, n):\n \"\"\"\n :type x: float\n :type n: int\n :rtype: float\n \"\"\"\n sign = 1 if n > 0 else -1\n n = abs(n)\n # final mulltiple y\n if n == 0:\n return 1\n else:\n res = self.myPow(x, n//2)**2 # take care here is squre\n if n % 2 == 1:\n res *= x # need to add this\n return res if sign == 1 else 1.0/res\n ","sub_path":"pow/recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"614108377","text":"\"\"\"\nEntradas\nladoa-->float-->Lado1\nladob-->float-->Lado2\nladoc-->float-->Lado3\nsalidas\np-->float-->sperimetro\nA-->float-->area\n\"\"\"\n#entrada\nLado1=float(input(\"Ingrese la longitud del primer lado: \"))\nLado2=float(input(\"Ingrese la longitud del segundo lado: \"))\nLado3=float(input(\"Ingrese la longitud del tercer lado: \"))\n#caja negra\nsperimetro=(Lado1+Lado2+Lado3)/2\narea=((sperimetro*(sperimetro-Lado1)*(sperimetro-Lado2)*(sperimetro-Lado3))**0.5)\nprint(\"El Semiperimetro es: \" +str(sperimetro))\nprint(\"El Area del triangulo es: \"\"{:.5F}\".format(area))","sub_path":"taller_2/ejercicio_08.py","file_name":"ejercicio_08.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"483134256","text":"import socket\nimport time\nimport sys\nimport os\nimport aislib\nimport signal\nfrom pykml import parser\nfrom os import path\nimport urllib2\n\nurl = 'http://localhost/rov.kml'\n\ntimestamp = 0\n\naismsg = aislib.AISPositionReportMessage(\n mmsi = 237772000,\n status = 8,\n sog = 1,\n pa = 1,\n lon = (25*60+00)*10000,\n lat = (35*60+30)*10000,\n cog = 0,\n ts = 40,\n raim = 1,\n comm_state = 82419 \n)\n\nmySearch = \"GPS on vehicle\"\n\nHOST = '' # Symbolic name meaning the local host\nPORT = 50012 # Arbitrary non-privileged port\n\nwhile 1:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((HOST, PORT))\n s.listen(1)\n conn, addr = s.accept()\n print ('Connected by', addr)\n while 1:\n #Read from file\n fileobject = urllib2.urlopen(url)\n doc = parser.parse(fileobject).getroot()\n #kml_file = path.join('kmltest.xml')\n #with open(kml_file) as f:\n #doc = parser.parse(f).getroot()\n #fileobject = urllib2.urlopen(url)\n #doc = parser.parse(fileobject).getroot()\n for pm in doc.Document.Placemark:\n if(pm.name == mySearch):\n posarray = pm.Point.coordinates.text\n posarray2 = posarray.split(',')\n poslong = posarray2[0]\n poslongfilter = poslong.replace('\\n','')\n poslat = posarray2[1]\n poslatfilter = poslat.replace('\\n','')\n longfloat = float(poslongfilter)\n latfloat = float(poslatfilter)\n timestamp = timestamp + 1\n if timestamp > 59:\n timestamp = 0\n aismsg.ts = timestamp\n int_lat_1 = int(latfloat)\n int_lat_1 = int_lat_1 * 60 * 10000\n int_lat_2 = latfloat - float((int(latfloat)))\n int_lat_2 = int_lat_2 * 60 * 10000\n int_lat_3 = int_lat_2 + int_lat_1\n aismsg.lat = int(int_lat_3)\n int_long_1 = int(longfloat)\n int_long_1 = int_long_1 * 60 * 10000\n int_long_2 = longfloat - float((int(longfloat)))\n int_long_2 = int_long_2 * 60 * 10000\n int_long_3 = int_long_2 + int_long_1\n aismsg.lon = int(int_long_3)\n heading = float(doc.Document.Style.IconStyle.heading.text)\n heading = heading * 10\n aismsg.cog = int(heading)\n ais = aislib.AIS(aismsg)\n payload = ais.build_payload(False)\n conn.send(payload)\n conn.send('\\n\\r')\n time.sleep(1)\n except KeyboardInterrupt:\n print(\"Got ctrl+c, exit... bye!\")\n #conn.close()\n #p.close()\n s.close()\n sys.exit()\n except:\n print(\"Session closed, restart server\")\n #conn.close()\n #p.close()\n s.close()\n continue\n # sys.exit()","sub_path":"kmldecode.py","file_name":"kmldecode.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"600109513","text":"from threading import Timer\nimport pyrebase\nfrom TempReader import TempReader\nfrom datetime import datetime\nimport RPi.GPIO as GPIO\nimport board\nimport digitalio\nimport adafruit_character_lcd.character_lcd as characterlcd\nimport time\nimport datetime\nimport boto3\nimport os\n\nclass ConnectedTempSensor:\n \n def __init__(self):\n # set up LCD\n self.lcd_columns = 16\n self.lcd_rows = 2\n\n self.lcd_rs = digitalio.DigitalInOut(board.D22)\n self.lcd_en = digitalio.DigitalInOut(board.D17)\n self.lcd_d4 = digitalio.DigitalInOut(board.D25)\n self.lcd_d5 = digitalio.DigitalInOut(board.D24)\n self.lcd_d6 = digitalio.DigitalInOut(board.D23)\n self.lcd_d7 = digitalio.DigitalInOut(board.D18)\n self.backlight_d8 = digitalio.DigitalInOut(board.D8)\n\n self.lcd = characterlcd.Character_LCD_Mono(self.lcd_rs, self.lcd_en, self.lcd_d4, self.lcd_d5, self.lcd_d6, self.lcd_d7, self.lcd_columns, self.lcd_rows, self.backlight_d8)\n\n self.timerQue = []\n\n\n # configure system to read temperature probe\n os.system('modprobe w1-gpio') \n os.system('modprobe w1-therm')\n\n #set up button and switch\n self.button = 16\n self.powerSwitch = 26\n GPIO.setup(self.button, GPIO.IN,pull_up_down=GPIO.PUD_UP)\n GPIO.setup(self.powerSwitch, GPIO.IN,pull_up_down=GPIO.PUD_UP)\n\n # set up firebase\n self.firebaseConfig = { \n \"apiKey\": \"AIzaSyA1XkaqnfFO8pm-yuTK5ggZpAsY27eOwn8\", \n \"authDomain\": \"connected-temp-sensor.firebaseapp.com\", \n \"databaseURL\": \"https://connected-temp-sensor-default-rtdb.firebaseio.com\", \n \"projectId\": \"connected-temp-sensor\", \n \"storageBucket\": \"connected-temp-sensor.appspot.com\", \n \"messagingSenderId\": \"363436241273\", \n \"appId\": \"1:363436241273:web:3404021c99f76d3ed2bfa8\", \n \"measurementId\": \"G-CD08HW864M\" \n } \n\n #instantiate variables to keep track of program\n self.firebaseDatabase = pyrebase.initialize_app(self.firebaseConfig).database()\n self.last300 = []\n self.virtualButtonPressed = False\n self.lastTempReading = None\n\n self.firebaseDatabase.child(\"virtual_button_pressed\").stream(self.virtualButton)\n\n self.lcd.backlight = True\n self.lcd.message = \"Powering on :)\"\n time.sleep(5.0)\n\n def updateTempReading(self):\n \n temp = TempReader.getTemp()\n self.lastTempReading = temp\n \n if (len(self.last300) < 300):\n self.last300.append(self.lastTempReading)\n else:\n self.last300.pop(0)\n self.last300.append(self.lastTempReading)\n \n self.firebaseDatabase.update({\"last_300_seconds\" : self.last300})\n print(\"last T reading = \" + temp)\n \n if (self.lastTempReading == \"US\"):\n time.sleep(0.85)\n \n self.t = Timer(0.1, self.updateTempReading)\n self.t.start()\n \n self.timerQue.append(self.t)\n \n #if (len(self.timerQue) > 10):\n # self.timerQue.pop(0)\n\n\n #firebase listener function\n def virtualButton(self, event):\n self.virtualButtonPressed = event[\"data\"]\n print(event[\"data\"])\n\n # main controll loop\n def run(self):\n \n # begin reading t values\n self.t = Timer(0.1, self.updateTempReading)\n self.t.start()\n self.timerQue.append(self.t)\n \n while (True):\n \n self.buttonState = GPIO.input(self.button)\n self.powerSwitchState = GPIO.input(self.powerSwitch)\n \n if (self.powerSwitchState != False):\n \n if (self.buttonState == False or self.virtualButtonPressed == \"True\"):\n\n self.lcd.backlight = True\n \n if (self.lastTempReading != \"US\"):\n \n self.lcd.message = TempReader.convertToDisplayFormat(self.lastTempReading)\n else:\n self.lcd.message = \"Sensor Unplugged\"\n \n else:\n self.lcd.backlight = False\n self.lcd.clear()\n self.updatedSinceLastTempReading = True\n \n time.sleep(0.05)\n \n else:\n \n print(*self.timerQue, sep=\", \")\n \n for timer in self.timerQue:\n if (timer.isAlive()):\n timer.cancel()\n timer.join()\n \n self.timerQue.clear()\n \n self.lcd.backlight = True\n self.lcd.message = \"Powering off :(\"\n time.sleep(2)\n self.lcd.backlight = False\n self.lcd.clear()\n \n while (self.powerSwitchState == False):\n \n time.sleep(2)\n self.powerSwitchState = GPIO.input(self.powerSwitch)\n \n self.lcd.backlight = True\n self.lcd.message = \"Powering on :)\"\n time.sleep(2.5)\n self.lcd.clear()\n self.lcd.backlight = False\n \n self.t = Timer(0.1, self.updateTempReading)\n self.t.start()\n \n \n \n \n\n\n\n \n \n\n","sub_path":"ConnectedTemperatureSensor.py","file_name":"ConnectedTemperatureSensor.py","file_ext":"py","file_size_in_byte":5509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"527874936","text":"import random\nimport numpy as np\nfrom collections import deque\n\nclass PGHistoryBuffer:\n def __init__(self, gamma = 0.99):\n # initialize variables\n self._discount_factor = gamma\n\n # record reward history for normalization\n self._all_rewards = []\n self._max_reward_length = 1000000\n\n # initialize buffers\n self._state_buffer = []\n self._reward_buffer = []\n self._action_buffer = []\n\n def store_rollout(self, state, action, reward):\n self._action_buffer.append(action)\n self._reward_buffer.append(reward)\n self._state_buffer.append(state)\n\n def clean_up(self):\n self._state_buffer = []\n self._reward_buffer = []\n self._action_buffer = []\n \n def compute_discounted_rewards(self):\n N = len(self._reward_buffer)\n # compute discounted future rewards\n discounted_rewards = np.zeros(N)\n r = 0\n\n for t in reversed(xrange(N)):\n # future discounted reward from now on\n if self._reward_buffer[t] != 0: r = 0 # reset the sum, since this was a game boundary (pong specific!)\n r = self._reward_buffer[t] + self._discount_factor * r\n discounted_rewards[t] = r\n\n # update reward history\n self._all_rewards += discounted_rewards.tolist()\n self._all_rewards = self._all_rewards[:self._max_reward_length]\n\n # normalize rewards\n discounted_rewards -= np.mean(self._all_rewards)\n discounted_rewards /= np.std(self._all_rewards)\n\n return discounted_rewards\n\nclass FrameHistoryBuffer:\n \"\"\" frame history buffer maintains a fixed number of history frames\n \"\"\"\n def __init__(self, image_size, buffer_size):\n assert buffer_size > 0\n assert len(image_size) == 2\n self._buffer = np.zeros((image_size[0], image_size[1], buffer_size))\n self._buffer_size = buffer_size\n self._image_size = image_size\n self._frame_received = 0\n\n def copy_content(self, size=None):\n assert self._frame_received >= self._buffer_size\n if size is None:\n return self._buffer.copy()\n else:\n assert(size > self._buffer_size)\n return self._buffer[:, :, 0:size].copy()\n\n def record(self, frame):\n if self._buffer_size > 1:\n self._buffer[:, :, 1:self._buffer_size] = self._buffer[:, :, 0:self._buffer_size-1]\n self._buffer[:, :, 0] = frame\n self._frame_received += 1\n\n def fill_with(self, frame):\n for _ in range(self._buffer_size):\n self.record(frame)\n\n def clear(self):\n self._frame_received = 0\n\n def get_buffer_size(self):\n return self._buffer_size\n\n def save(self, file_path):\n f = open(file_path, 'wb')\n dump = {}\n dump['buffer'] = self._buffer\n dump['buffer_size'] = self._buffer_size\n dump['image_size'] = self._image_size\n dump['frame_received'] = self._frame_received\n pickle.dump(dump, f)\n\n def load(self, file_path):\n f = open(file_path, 'rb')\n dump = pickle.load(f)\n self._buffer = dump['buffer']\n self._buffer_size = dump['buffer_size']\n self._image_size = dump['image_size']\n self._frame_received = dump['frame_received']\n\n\nclass ExperienceReplayMemory:\n \"\"\" Experience Replay Memory used in DQN\n \"\"\"\n def __init__(self, capacity):\n self._memory = deque()\n self._count = 0\n self._capacity = capacity\n\n def sample(self, size=1):\n result = []\n for _ in range(size):\n result.append(self._sample_single())\n return result\n\n def add(self, experience):\n if self._count == self._capacity:\n self._memory.popleft()\n self._count -= 1\n self._memory.append(experience)\n self._count += 1\n\n def clear(self):\n self._memory.clear()\n self._count = 0\n\n def get_capacity(self):\n return self._capacity\n\n def get_grow_size(self):\n return self._count\n\n def save(self, file_path):\n f = open(file_path, 'wb')\n dump = {} \n dump['memory'] = self._memory\n dump['count'] = self._count\n dump['capacity'] = self._capacity\n pickle.dump(dump, f)\n\n def load(self, file_path):\n f = open(file_path, 'rb')\n dump = pickle.load(f) \n self._memory = dump['memory']\n self._count = dump['count']\n self._capacity = dump['capacity']\n\n def _sample_single(self):\n idx = random.randrange(0, self._count)\n return self._memory[idx]\n","sub_path":"PG/PGUtil.py","file_name":"PGUtil.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"535768614","text":"import copy\nimport io\nimport os\nimport shutil\nimport subprocess\n\nimport pytest\n\nimport unasync\n\nTEST_DIR = os.path.dirname(os.path.abspath(__file__))\nASYNC_DIR = os.path.join(TEST_DIR, \"async\")\nSYNC_DIR = os.path.join(TEST_DIR, \"sync\")\nTEST_FILES = sorted([f for f in os.listdir(ASYNC_DIR) if f.endswith(\".py\")])\n\n\ndef list_files(startpath):\n output = \"\"\n for root, dirs, files in os.walk(startpath):\n level = root.replace(startpath, \"\").count(os.sep)\n indent = \" \" * 4 * (level)\n output += \"{}{}/\".format(indent, os.path.basename(root))\n output += \"\\n\"\n subindent = \" \" * 4 * (level + 1)\n for f in files:\n output += \"{}{}\".format(subindent, f)\n output += \"\\n\"\n return output\n\n\n@pytest.mark.parametrize(\"source_file\", TEST_FILES)\ndef test_unasync(tmpdir, source_file):\n\n unasync.unasync_file(\n os.path.join(ASYNC_DIR, source_file), fromdir=ASYNC_DIR, todir=str(tmpdir)\n )\n\n encoding = \"latin-1\" if \"encoding\" in source_file else \"utf-8\"\n with io.open(os.path.join(SYNC_DIR, source_file), encoding=encoding) as f:\n truth = f.read()\n with io.open(os.path.join(str(tmpdir), source_file), encoding=encoding) as f:\n unasynced_code = f.read()\n assert unasynced_code == truth\n\n\ndef test_build_py_modules(tmpdir):\n\n source_modules_dir = os.path.join(TEST_DIR, \"example_mod\")\n mod_dir = str(tmpdir) + \"/\" + \"example_mod\"\n shutil.copytree(source_modules_dir, mod_dir)\n\n env = copy.copy(os.environ)\n env[\"PYTHONPATH\"] = os.path.realpath(os.path.join(TEST_DIR, \"..\"))\n subprocess.check_call([\"python\", \"setup.py\", \"build\"], cwd=mod_dir, env=env)\n\n unasynced = os.path.join(mod_dir, \"build/lib/_sync/some_file.py\")\n tree_build_dir = list_files(mod_dir)\n\n with open(unasynced) as f:\n unasynced_code = f.read()\n assert unasynced_code == \"def f():\\n return 1\\n\"\n\n\ndef test_build_py_packages(tmpdir):\n\n source_pkg_dir = os.path.join(TEST_DIR, \"example_pkg\")\n pkg_dir = str(tmpdir) + \"/\" + \"example_pkg\"\n shutil.copytree(source_pkg_dir, pkg_dir)\n\n env = copy.copy(os.environ)\n env[\"PYTHONPATH\"] = os.path.realpath(os.path.join(TEST_DIR, \"..\"))\n subprocess.check_call([\"python\", \"setup.py\", \"build\"], cwd=pkg_dir, env=env)\n\n unasynced = os.path.join(pkg_dir, \"build/lib/example_pkg/_sync/__init__.py\")\n\n with open(unasynced) as f:\n unasynced_code = f.read()\n assert unasynced_code == \"def f():\\n return 1\\n\"\n\n\ndef test_project_structure_after_build_py_packages(tmpdir):\n\n source_pkg_dir = os.path.join(TEST_DIR, \"example_pkg\")\n pkg_dir = str(tmpdir) + \"/\" + \"example_pkg\"\n shutil.copytree(source_pkg_dir, pkg_dir)\n\n env = copy.copy(os.environ)\n env[\"PYTHONPATH\"] = os.path.realpath(os.path.join(TEST_DIR, \"..\"))\n subprocess.check_call([\"python\", \"setup.py\", \"build\"], cwd=pkg_dir, env=env)\n\n _async_dir_tree = list_files(\n os.path.join(source_pkg_dir, \"src/example_pkg/_async/.\")\n )\n unasynced_dir_tree = list_files(\n os.path.join(pkg_dir, \"build/lib/example_pkg/_sync/.\")\n )\n\n assert _async_dir_tree == unasynced_dir_tree\n","sub_path":"tests/test_unasync.py","file_name":"test_unasync.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"284834757","text":"\nimport os\nimport tkinter as tk\n\nfrom PIL import ImageTk\n\nfrom anstoss3k.engine.definitions import GameAction\nfrom anstoss3k.ui.definitions import MEDIA_PATH, StateScreen\n\n\nclass SeasonEndStateScreen(StateScreen):\n def _draw_static_graphics(self):\n img_path = os.path.join(MEDIA_PATH, 'backgrounds', 'Year End (grafik_cpr-0000001875).jpg')\n self.background = ImageTk.PhotoImage(file=img_path) # pylint: disable=attribute-defined-outside-init\n self.canvas.create_image(0, 0, image=self.background, anchor=tk.NW)\n\n def _draw_dynamic_graphics(self):\n print('SeasonEndStateScreen:Call _draw_dynamic_graphics()')\n button_path = os.path.join(MEDIA_PATH, 'buttons', 'OK Not Selected (grafik_cpr-0000002713)_TRANS.png')\n self.ok_button_normal_img = ImageTk.PhotoImage(file=button_path) # pylint: disable=attribute-defined-outside-init\n button_path = os.path.join(MEDIA_PATH, 'buttons', 'OK Selected (grafik_cpr-0000002704)_TRANS.png')\n self.ok_button_pressed_img = ImageTk.PhotoImage(file=button_path) # pylint: disable=attribute-defined-outside-init\n\n self.button = self.canvas.create_image( # pylint: disable=attribute-defined-outside-init\n 400 - 88 / 2, 440 - 95 / 2, image=self.ok_button_normal_img, anchor=tk.NW)\n self.canvas.tag_bind(self.button, '', self.ok_pressed)\n self.canvas.tag_bind(self.button, '', self.ok_released)\n\n def _draw_dynamic_content(self):\n print('SeasonEndStateScreen:Call _draw_dynamic_content()')\n\n def _draw_completed(self):\n print('SeasonEndStateScreen:Call _draw_completed()')\n\n def ok_pressed(self, event): # pylint: disable=unused-argument\n print('SeasonEndStateScreen:Call ok_pressed()')\n self.canvas.itemconfigure(self.button, image=self.ok_button_pressed_img)\n\n def ok_released(self, event): # pylint: disable=unused-argument\n print('SeasonEndStateScreen:Call ok_released()')\n self.canvas.itemconfigure(self.button, image=self.ok_button_normal_img)\n self.ui_actions.append(GameAction.FINISH_MOVE)\n","sub_path":"anstoss3k/ui/states/season_end.py","file_name":"season_end.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"437986216","text":"from django.conf import settings\nfrom django.urls import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.utils.translation import ugettext_noop, ugettext as _\nfrom djangular.views.mixins import allow_remote_invocation\n\nfrom corehq import privileges\nfrom corehq.apps.app_manager.dbaccessors import domain_has_apps, get_brief_apps_in_domain\nfrom corehq.apps.dashboard.models import (\n TileConfiguration,\n AppsPaginatedContext,\n IconContext,\n ReportsPaginatedContext, Tile, DataPaginatedContext, DatadogContext)\nfrom corehq.apps.domain.decorators import login_and_domain_required\nfrom corehq.apps.domain.views import DomainViewMixin, LoginAndDomainMixin, \\\n DefaultProjectSettingsView\nfrom corehq.apps.domain.utils import user_has_custom_top_menu\nfrom corehq.apps.hqwebapp.view_permissions import user_can_view_reports\nfrom corehq.apps.hqwebapp.views import BasePageView, HQJSONResponseMixin\nfrom corehq.apps.users.views import DefaultProjectUserSettingsView\nfrom corehq.apps.locations.permissions import location_safe, user_can_edit_location_types\nfrom corehq.apps.style.decorators import use_angular_js\nfrom corehq.toggles import DASHBOARD_GRAPHS\nfrom django_prbac.utils import has_privilege\n\n\n@login_and_domain_required\n@location_safe\ndef dashboard_default(request, domain):\n return HttpResponseRedirect(default_dashboard_url(request, domain))\n\n\ndef default_dashboard_url(request, domain):\n couch_user = getattr(request, 'couch_user', None)\n\n if domain in settings.CUSTOM_DASHBOARD_PAGE_URL_NAMES:\n return reverse(settings.CUSTOM_DASHBOARD_PAGE_URL_NAMES[domain], args=[domain])\n\n if couch_user and user_has_custom_top_menu(domain, couch_user):\n return reverse('saved_reports', args=[domain])\n\n if not domain_has_apps(domain):\n return reverse('default_app', args=[domain])\n\n return reverse(DomainDashboardView.urlname, args=[domain])\n\n\nclass BaseDashboardView(LoginAndDomainMixin, BasePageView, DomainViewMixin):\n\n @use_angular_js\n def dispatch(self, request, *args, **kwargs):\n return super(BaseDashboardView, self).dispatch(request, *args, **kwargs)\n\n @property\n def main_context(self):\n context = super(BaseDashboardView, self).main_context\n context.update({\n 'domain': self.domain,\n })\n return context\n\n @property\n def page_url(self):\n return reverse(self.urlname, args=[self.domain])\n\n\nclass NewUserDashboardView(BaseDashboardView):\n urlname = 'dashboard_new_user'\n page_title = ugettext_noop(\"HQ Dashboard\")\n template_name = 'dashboard/dashboard_new_user.html'\n\n @property\n def page_context(self):\n return {'templates': self.templates(self.domain)}\n\n @classmethod\n def get_page_context(cls, domain):\n return {\n 'apps': get_brief_apps_in_domain(domain),\n 'templates': cls.templates(domain),\n }\n\n @classmethod\n def templates(cls, domain):\n templates = [{\n 'heading': _('Blank Application'),\n 'url': reverse('default_new_app', args=[domain]),\n 'icon': 'fcc-blankapp',\n 'lead': _('Start from scratch'),\n 'action': 'Blank',\n 'description': 'Clicked Blank App Template Tile',\n }]\n\n templates = [{\n 'heading': _('Case Management'),\n 'url': reverse('app_from_template', args=[domain, 'case_management']),\n 'icon': 'fcc-casemgt',\n 'lead': _('Track information over time'),\n 'action': 'Case Management',\n 'description': 'Clicked Case Management App Template Tile',\n }] + templates\n\n templates = [{\n 'heading': _('Survey'),\n 'url': reverse('app_from_template', args=[domain, 'survey']),\n 'icon': 'fcc-survey',\n 'lead': _('One-time data collection'),\n 'action': 'Survey',\n 'description': 'Clicked Survey App Template Tile',\n }] + templates\n\n return templates\n\n\n@location_safe\nclass DomainDashboardView(HQJSONResponseMixin, BaseDashboardView):\n urlname = 'dashboard_domain'\n page_title = ugettext_noop(\"HQ Dashboard\")\n template_name = 'dashboard/dashboard_domain.html'\n\n def dispatch(self, request, *args, **kwargs):\n return super(DomainDashboardView, self).dispatch(request, *args, **kwargs)\n\n @property\n def tile_configs(self):\n return _get_default_tile_configurations()\n\n @property\n def slug_to_tile(self):\n return dict([(a.slug, a) for a in self.tile_configs])\n\n @property\n def page_context(self):\n return {\n 'dashboard_tiles': [{\n 'title': d.title,\n 'slug': d.slug,\n 'ng_directive': d.ng_directive,\n } for d in self.tile_configs],\n }\n\n def make_tile(self, slug, in_data):\n config = self.slug_to_tile[slug]\n return Tile(config, self.request, in_data)\n\n @allow_remote_invocation\n def update_tile(self, in_data):\n tile = self.make_tile(in_data['slug'], in_data)\n if not tile.is_visible:\n return {\n 'success': False,\n 'message': _('You do not have permission to access this tile.'),\n }\n return {\n 'response': tile.context,\n 'success': True,\n }\n\n @allow_remote_invocation\n def check_permissions(self, in_data):\n tile = self.make_tile(in_data['slug'], in_data)\n return {\n 'success': True,\n 'hasPermissions': tile.is_visible,\n }\n\n\ndef _get_default_tile_configurations():\n can_edit_data = lambda request: (request.couch_user.can_edit_data()\n or request.couch_user.can_access_any_exports())\n can_edit_apps = lambda request: (request.couch_user.is_web_user()\n or request.couch_user.can_edit_apps())\n can_view_reports = lambda request: user_can_view_reports(request.project, request.couch_user)\n can_edit_users = lambda request: (request.couch_user.can_edit_commcare_users()\n or request.couch_user.can_edit_web_users())\n\n def can_edit_locations_not_users(request):\n if not has_privilege(request, privileges.LOCATIONS):\n return False\n user = request.couch_user\n return not can_edit_users(request) and (\n user.can_edit_locations() or user_can_edit_location_types(user, request.project)\n )\n\n can_view_commtrack_setup = lambda request: (request.project.commtrack_enabled)\n\n can_view_exchange = lambda request: can_edit_apps(request) and not settings.ENTERPRISE_MODE\n\n def _can_access_sms(request):\n return has_privilege(request, privileges.OUTBOUND_SMS)\n\n def _can_access_reminders(request):\n return has_privilege(request, privileges.REMINDERS_FRAMEWORK)\n\n can_use_messaging = lambda request: (\n (_can_access_reminders(request) or _can_access_sms(request))\n and not request.couch_user.is_commcare_user()\n and request.couch_user.can_edit_data()\n )\n\n is_billing_admin = lambda request: request.couch_user.can_edit_billing()\n\n return [\n TileConfiguration(\n title=_('Applications'),\n slug='applications',\n icon='fcc fcc-applications',\n context_processor_class=AppsPaginatedContext,\n visibility_check=can_edit_apps,\n urlname='default_app',\n help_text=_('Build, update, and deploy applications'),\n ),\n TileConfiguration(\n title=_('Form Submissions'),\n slug='graph',\n icon='fcc fcc-reports',\n context_processor_class=DatadogContext,\n visibility_check=DASHBOARD_GRAPHS.enabled_for_request,\n help_text=_(\"Form submissions for this domain over the last 7 days\"),\n ),\n TileConfiguration(\n title=_('Reports'),\n slug='reports',\n icon='fcc fcc-reports',\n context_processor_class=ReportsPaginatedContext,\n urlname='reports_home',\n visibility_check=can_view_reports,\n help_text=_('View worker monitoring reports and inspect '\n 'project data'),\n ),\n TileConfiguration(\n title=_('{cc_name} Supply Setup').format(cc_name=settings.COMMCARE_NAME),\n slug='commtrack_setup',\n icon='fcc fcc-commtrack',\n context_processor_class=IconContext,\n urlname='default_commtrack_setup',\n visibility_check=can_view_commtrack_setup,\n help_text=_(\"Update {cc_name} Supply Settings\").format(cc_name=settings.COMMCARE_NAME),\n ),\n TileConfiguration(\n title=_('Data'),\n slug='data',\n icon='fcc fcc-data',\n context_processor_class=DataPaginatedContext,\n urlname=\"data_interfaces_default\",\n visibility_check=can_edit_data,\n help_text=_('Export and manage data'),\n ),\n TileConfiguration(\n title=_('Users'),\n slug='users',\n icon='fcc fcc-users',\n context_processor_class=IconContext,\n urlname=DefaultProjectUserSettingsView.urlname,\n visibility_check=can_edit_users,\n help_text=_('Manage accounts for mobile workers '\n 'and CommCareHQ users'),\n ),\n TileConfiguration(\n title=_('Organization'),\n slug='locations',\n icon='fcc fcc-users',\n context_processor_class=IconContext,\n urlname='default_locations_view',\n visibility_check=can_edit_locations_not_users,\n help_text=_('Manage the Organization Hierarchy'),\n ),\n TileConfiguration(\n title=_('Messaging'),\n slug='messaging',\n icon='fcc fcc-messaging',\n context_processor_class=IconContext,\n urlname='sms_default',\n visibility_check=can_use_messaging,\n help_text=_('Configure and schedule SMS messages and keywords'),\n ),\n TileConfiguration(\n title=_('Exchange'),\n slug='exchange',\n icon='fcc fcc-exchange',\n context_processor_class=IconContext,\n urlname='appstore',\n visibility_check=can_view_exchange,\n url_generator=lambda urlname, req: reverse(urlname),\n help_text=_('Download and share CommCare applications with '\n 'other users around the world'),\n ),\n TileConfiguration(\n title=_('Settings'),\n slug='settings',\n icon='fcc fcc-settings',\n context_processor_class=IconContext,\n urlname=DefaultProjectSettingsView.urlname,\n visibility_check=is_billing_admin,\n help_text=_('Set project-wide settings and manage subscriptions'),\n ),\n TileConfiguration(\n title=_('Help Site'),\n slug='help',\n icon='fcc fcc-help',\n context_processor_class=IconContext,\n url='http://help.commcarehq.org/',\n help_text=_(\"Visit CommCare's knowledge base\"),\n ),\n ]\n","sub_path":"corehq/apps/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"345106331","text":"'''\nhttps://github.com/fchollet/keras/blob/master/examples/variational_autoencoder.py\n'''\nimport numpy as np\nfrom keras.layers import Input, Dense, Lambda, Layer\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras import metrics\nfrom keras.datasets import mnist\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nimport sklearn.model_selection\n\nbatch_size = 100\noriginal_dim = 784\nlatent_dim = 64\nintermediate_dim = 256\nepochs = 100\nepsilon_std = 1.0\n\nVAL_SEED = 123456\n\ndef sampling(args):\n z_mean, z_log_var = args\n epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0.,\n stddev=epsilon_std)\n return z_mean + K.exp(z_log_var / 2) * epsilon\n\n\n\ndef load_mnist():\n x = Input(batch_shape=(batch_size, original_dim))\n h = Dense(intermediate_dim, activation='relu')(x)\n z_mean = Dense(latent_dim)(h)\n z_log_var = Dense(latent_dim)(h)\n\n # Custom loss layer\n class CustomVariationalLayer(Layer):\n def __init__(self, **kwargs):\n self.is_placeholder = True\n super(CustomVariationalLayer, self).__init__(**kwargs)\n\n def vae_loss(self, x, x_decoded_mean):\n xent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean)\n kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)\n return K.mean(xent_loss + kl_loss)\n\n def call(self, inputs):\n x = inputs[0]\n x_decoded_mean = inputs[1]\n loss = self.vae_loss(x, x_decoded_mean)\n self.add_loss(loss, inputs=inputs)\n # We won't actually use the output.\n return x\n\n # note that \"output_shape\" isn't necessary with the TensorFlow backend\n z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])\n\n # we instantiate these layers separately so as to reuse them later\n decoder_h = Dense(intermediate_dim, activation='relu')\n decoder_mean = Dense(original_dim, activation='sigmoid')\n h_decoded = decoder_h(z)\n x_decoded_mean = decoder_mean(h_decoded)\n\n\n y = CustomVariationalLayer()([x, x_decoded_mean])\n vae = Model(x, y)\n vae.compile(optimizer='rmsprop', loss=None)\n\n\n # train the VAE on MNIST digits\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n x_train = x_train.astype('float32') / 255.\n x_test = x_test.astype('float32') / 255.\n x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))\n x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))\n\n\n model_checkpoint = ModelCheckpoint('mnist_vae.model', monitor='val_loss',\n verbose=1, save_best_only=True, mode='auto')\n early_stopping = EarlyStopping(monitor='val_loss', patience=15, verbose=1, mode='auto')\n\n\n vae.fit(x_train,\n shuffle=True,\n epochs=epochs,\n batch_size=batch_size,\n validation_data=(x_test, x_test),\n callbacks=[model_checkpoint, early_stopping])\n\n vae.load_weights('mnist_vae.model')\n\n # build a model to project inputs on the latent space\n encoder = Model(x, z_mean)\n\n x_train_encoded = encoder.predict(x_train, batch_size=batch_size)\n x_test_encoded = encoder.predict(x_test, batch_size=batch_size)\n\n x1, x2, y1, y2 = sklearn.model_selection.train_test_split(x_train_encoded, y_train, test_size=0.2, random_state=VAL_SEED)\n\n return x1, y1, x2, y2, x_test_encoded, y_test\n","sub_path":"mnist_vae.py","file_name":"mnist_vae.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"313928663","text":"from django.shortcuts import render\nfrom django.core import serializers\nimport json\nfrom django.db.models import Q\nfrom django.http import HttpResponse, JsonResponse\nfrom .forms import *\nfrom .models import *\nfrom service_repair.models import *\nfrom modal_quality_check_mac.models import *\nfrom modal_quality_check_mdg.models import *\nimport uuid\nfrom itertools import chain\nfrom mplus.mydecorator import *\n\n@authenticate_login\ndef index(request):\n FormConsignment = FormConsignment2()\n context={'page':\"consignment\",\n 'FormConsignment':FormConsignment,\n }\n \n template=request.session['account_type']+\".html\"\n return render(request,template,context)\n\n@authenticate_login\ndef add_newConsign(request):\n if request.method == 'POST':\n air_way_bill = request.POST.get(\"air_way_bill\",\"\")\n gsx_confirmation = request.POST.get(\"gsx_confirmation\",\"\")\n ar_number_purchase_order = request.POST.get(\"ar_number_purchase_order\",\"\")\n part_number = request.POST.get(\"part_number\",\"\")\n model_number = request.POST.get(\"model_number\",\"\")\n description = request.POST.get(\"description\",\"\")\n serial_number = request.POST.get(\"serial_number\",\"\")\n wur_sur = request.POST.get(\"wur_sur\",\"\")\n \n newConsign = Consignment(air_way_bill=air_way_bill,\n gsx_confirmation=gsx_confirmation,\n ar_number_purchase_order=ar_number_purchase_order,\n part_number=part_number,\n model_number=model_number,\n description=description,\n serial_number=serial_number,\n wur_sur=wur_sur)\n newConsign.save()\n return JsonResponse({'save':'True'})\n \n@authenticate_login\ndef pull_arrivedConsign(request):\n if request.method == 'POST':\n consigntransaction_id = request.POST.get(\"consign_transaction_id\",\"\")\n log_notes = list(Consignment.objects.filter(consignment_transaction_num_id=consigntransaction_id))\n# log_notes = list(PartMainInput.objects.all())\n data = serializers.serialize(\"json\", log_notes) \n return HttpResponse(json.dumps(data), content_type='application/json')\n","sub_path":"consignment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"224794936","text":"import logging\n\nfrom .enum import Mode\nfrom .types import TCPConnectResult\nfrom ..lib.task_manager_base import TaskError\nfrom ..common import Object\nfrom .base_command import BaseCommand\n\n\nclass Network(BaseCommand):\n \"\"\" Gateway Network configuration APIs \"\"\"\n\n def get_status(self):\n \"\"\"\n Retrieve the network interface status\n \"\"\"\n return self._gateway.get('/status/network/ports/0')\n\n def ifconfig(self):\n \"\"\"\n Retrieve the ip configuration\n \"\"\"\n return self.ipconfig()\n\n def ipconfig(self):\n \"\"\"\n Retrieve the ip configuration\n \"\"\"\n return self._gateway.get('/config/network/ports/0')\n\n def set_static_ipaddr(self, address, subnet, gateway, primary_dns_server, secondary_dns_server=None):\n \"\"\"\n Set a Static IP Address\n\n :param str address: The static address\n :param str subnet: The subnet for the static address\n :param str gateway: The default gateway\n :param str primary_dns_server: The primary DNS server\n :param str,optinal secondary_dns_server: The secondary DNS server, defaults to None\n \"\"\"\n ip = self._gateway.get('/config/network/ports/0/ip')\n ip.DHCPMode = Mode.Disabled\n ip.address = address\n ip.netmask = subnet\n ip.gateway = gateway\n ip.autoObtainDNS = False\n ip.DNSServer1 = primary_dns_server\n\n if secondary_dns_server is not None:\n ip.DNSServer2 = secondary_dns_server\n\n logging.getLogger().info('Configuring a static ip address.')\n\n self._gateway.put('/config/network/ports/0/ip', ip)\n\n logging.getLogger().info(\n 'Network settings updated. %s',\n {'address': address, 'subnet': subnet, 'gateway': gateway, 'DNS1': primary_dns_server, 'DNS2': secondary_dns_server}\n )\n\n def set_static_nameserver(self, primary_dns_server, secondary_dns_server=None):\n \"\"\"\n Set the DNS Server addresses statically\n\n :param str primary_dns_server: The primary DNS server\n :param str,optinal secondary_dns_server: The secondary DNS server, defaults to None\n \"\"\"\n ip = self._gateway.get('/config/network/ports/0/ip')\n ip.autoObtainDNS = False\n ip.DNSServer1 = primary_dns_server\n\n if secondary_dns_server is not None:\n ip.DNSServer2 = secondary_dns_server\n\n logging.getLogger().info('Configuring nameserver settings.')\n\n self._gateway.put('/config/network/ports/0/ip', ip)\n\n logging.getLogger().info('Nameserver settings updated. %s', {'DNS1': primary_dns_server, 'DNS2': secondary_dns_server})\n\n def reset_mtu(self):\n \"\"\"\n Set the default maximum transmission unit (MTU) settings\n \"\"\"\n self._set_mtu(False, 1500)\n\n def set_mtu(self, mtu):\n \"\"\"\n Set a custom network maximum transmission unit (MTU)\n\n :param int mtu: Maximum transmission unit\n \"\"\"\n self._set_mtu(True, mtu)\n\n def _set_mtu(self, jumbo, mtu):\n settings = self._gateway.get('/config/network/ports/0/ethernet')\n settings.jumbo = jumbo\n settings.mtu = mtu\n return self._gateway.put('/config/network/ports/0/ethernet', settings)\n\n def enable_dhcp(self):\n \"\"\"\n Enable DHCP\n \"\"\"\n ip = self._gateway.get('/config/network/ports/0/ip')\n ip.DHCPMode = Mode.Enabled\n ip.autoObtainDNS = True\n\n logging.getLogger().info('Enabling DHCP.')\n\n self._gateway.put('/config/network/ports/0/ip', ip)\n\n logging.getLogger().info('Network settings updated. Enabled DHCP.')\n\n def diagnose(self, services):\n \"\"\"\n Test a TCP connection to a host over a designated port\n\n :param list[cterasdk.edge.types.TCPService] services: List of services, identified by a host and a port\n :returns: A list of named-tuples including the host, port and a boolean value indicating whether TCP connection can be established\n :rtype: list[cterasdk.edge.types.TCPConnectResult]\n \"\"\"\n return [self.tcp_connect(service) for service in services]\n\n def tcp_connect(self, service):\n \"\"\"\n Test a TCP connection between the Gateway and the provided host address\n\n :param cterasdk.edge.types.TCPService service: A service, identified by a host and a port\n :returns: A named-tuple including the host, port and a boolean value indicating whether TCP connection can be established\n :rtype: cterasdk.edge.types.TCPConnectResult\n \"\"\"\n param = Object()\n param.address = service.host\n param.port = service.port\n\n logging.getLogger().info(\"Testing connection. %s\", {'host': service.host, 'port': service.port})\n\n task = self._gateway.execute(\"/status/network\", \"tcpconnect\", param)\n try:\n task = self._gateway.tasks.wait(task)\n logging.getLogger().debug(\"Obtained connection status. %s\", {'status': task.result.rc})\n if task.result.rc == \"Open\":\n return TCPConnectResult(service.host, service.port, True)\n except TaskError:\n pass\n\n logging.getLogger().warning(\"Couldn't establish TCP connection. %s\", {'address': service.host, 'port': service.port})\n\n return TCPConnectResult(service.host, service.port, False)\n","sub_path":"cterasdk/edge/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":5371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"163319537","text":"# 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.\n\n# What is the sum of the digits of the number 2^1000?\n\n\ndef sum_of_digits(n):\n sum = 0\n while n > 0:\n sum += n % 10\n n = n // 10\n return sum\n\n\nif __name__ == '__main__':\n print(sum_of_digits(2 ** 1000))\n","sub_path":"problem016.py","file_name":"problem016.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"636326715","text":"\"\"\"Funkcii\"\"\"\n\"\"\"Domasni\"\"\"\n\nlist1 = [1,2,3,4,5,6]\nfor l in range(0, len(list1)):\n if l%3 == 0:\n print(list1[l])\n\n\ncTuple = (\"lemon\", \"blueberry\", \"strawberry\", \"apple\", \"orange\")\n\nif \"orange\" in cTuple:\n print(cTuple.index(\"orange\"))\n\n\ndict = {\n\n \"city\" : \"New York\",\n \"country\":\"New York\",\n \"population\": 7000000,\n \"coastline\": \"east\"\n\n}\n#\nfor item in dict.items():\n print(item)\n\nfor value in dict.values():\n print(value)\n\nfor key in dict.keys():\n print(key)\n\n\ndef favourite_book(book):\n print (\"My favourite book is \" + book)\n\n\nfavourite_book(\"Myths\")\nfavourite_book(\"Luna\")\n\n\ndef name(first_name, last_name):\n print(\"My first name is \" + first_name + \" and my last name is \" + last_name)\n\n\nname(\"Viktorija\", \"Jordanova\")\n\n\ndef display_message():\n print(\"This chapter is about functions in Python\")\n\n\ndisplay_message()\n\n# Funkcija so koja se presmetuva suma na elementi vo lista, lista da bide vlezen parametar i so int ili so float\n\ndef suma(list):\n print(sum(list))\n\n\nsuma([1,5,6,8,9,2])\n\n\ndef t_shirt(size, message):\n print(\"This T-Shirt is size \" + size + \" and the message says: \" + message)\n\n\nt_shirt(\"M\", \"I love Python\")\n\ndef make_shirt(size, text):\n print(\"Your size is \" + size)\n print(\"Printed text: \" + text)\n\nmake_shirt(\"L\", \"Just smile! :)\")\n\ndef div_by_five(a):\n if a%5 == 0:\n print(\"Is divisible by five\")\n else:\n print(\"Not divisible by five\")\n\ndiv_by_five(9)\n\n\"\"\"Default parametri\"\"\"\n\ndef describe_city(city, country = \"Macedonia\"):\n print(city + \" is in \" + country)\n\ndescribe_city(\"Skopje\")\n\n\n\"\"\"Kvadraten koren na broj\"\"\"\ndef square(x):\n return x*x\n\nsquare(2)\n\nsquare(4)\n\n\"\"\"Pass\"\"\"\ndef multiply():\n pass\n\ndef my_func(a):\n return a*5\n\nprint(my_func(6))\n\n\n\n\"\"\"Absolutna vrednost na broj - funkcija\"\"\"\ndef abs_value(num):\n if num >= 0:\n return num\n elif num < 0:\n return -num\n\n# print(abs_value(9))\nprint(abs_value(-9))\n\n\n\"\"\"Da se isprintaat parni broevi od tuple so funkcija\"\"\"\n\ndef parni_broevi(aTuple):\n for t in aTuple:\n if t%2 != 0:\n print(t)\n else:\n print(\"Nema neparni broevi vo ovoj tuple\")\n\nparni_broevi((2,6,8,10))\n\n\ndef my_func1 (x):\n print(\"This value is part of the function \" + x)\n\nmy_func1(\"Five\")\ny = \"Six\"\nprint(\"This parameter is not in the function \" + y)\n\n# da se napravi funkcija koja ke prima lista so ovosja, i ke gi isprinta so ciklus\n\n\ndef funkcija(list):\n for a in list:\n print(a)\n\n\nfunkcija([\"Orange\", \"Lemon\", \"Apple\"])\n\n\n# da se najde faktoriel na daden broj\n\n# factorel (5) = 5*(4)*(3)*(2)*1\n# factoriel (3) = 3*2*1 = 6\n# factoriel(0) = 1\n\n\"\"\"Factoriel rekurzivna funkcija\"\"\"\ndef factoriel(num):\n if num == 1:\n return 1\n elif num < 1:\n print(\"NA\")\n else:\n return num * factoriel(num-1)\n\n# num*factoriel(num-1) = 5*4*3*2*1\n\nprint(factoriel(5))\n\n\n\"\"\"За дадената листа да се најде вредноста 20 во листата и да се замени со 200.
 list1 = [5, 10, 15, 20, 25, 50, 20]\"\"\"\ndef dvaeset(list):\n for i in list:\n if i == 20:\n print(200)\n\ndvaeset([5, 10, 15, 20, 25, 50, 20])\n\n\"\"\"Ova e funkcija koja go bara brojot 20 i go zamenuva so 200\"\"\"\n\ndef funkcija(lista):\n for neshto in lista:\n if neshto == 20:\n lista.remove(neshto)\n lista.append(200)\n return lista\n\ndef no_def_func():\n pass\n\nlist1 = [5, 10, 15, 20, 25, 50, 20]\n\n\ndef funkcija1(lista):\n for neshto in lista:\n if neshto == 20:\n a = list1.index(neshto)\n list1[a] = 200\n print(lista)\nfunkcija(list1)\n\n\nprint(funkcija([5, 10, 15, 20, 25, 50, 20]))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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":"Lesson5.py","file_name":"Lesson5.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"505390287","text":"#coding=utf-8\nimport socket\nimport xml.etree.cElementTree as et\nimport urllib\nimport sqlite3\nimport requests\nfrom lxml import etree\nimport json\nimport os\nimport codecs\nimport threading\nimport time\nfrom requests.adapters import HTTPAdapter\nfrom HTMLParser import HTMLParser\nimport brotli\n\n\nclass Crawl():\n\n json_root = ''\n\n\n fanhao_json = []\n\n proxies_config = {'http':'http://127.0.0.1:1080', 'https':'http://127.0.0.1:1080'}\n\n header_info = {\n 'Host':'www.tom97.net',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0',\n 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language':'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Accept-Encoding':'gzip, deflate, br',\n \"Upgrade-Insecure-Requests\": \"1\",\n 'Connection':'keep-alive',\n 'Cache-Control':'max-age=0',\n 'Cookie':'ASPSESSIONIDSCQQBASD=EFLIHPODJNDHBDIOPGJEHECI'\n }\n\n use_proxies = False\n brotli = False\n\n\n def crawlurl(self, url):\n content = self.request_url(url)\n #print(resp.headers)\n #print(resp.encoding)\n #print(content)\n #print(content.decode('utf-8'))\n return etree.HTML(content)\n\n def request_url(self, url):\n session = requests.Session()\n session.mount('http://', HTTPAdapter(max_retries=3))\n session.mount('https://', HTTPAdapter(max_retries=3))\n\n resp = None\n if self.use_proxies:\n resp = session.get(url,timeout=15, headers=self.header_info, proxies=self.proxies_config)\n else:\n resp = session.get(url,timeout=15, headers=self.header_info)\n\n #print(dir(resp))\n #print(\"session get url:{0}\".format(resp.status_code))\n #print(resp.reason)\n #print(resp.text)\n #print(dir(resp))\n\n content = resp.content\n\n #print(self.brotli)\n if self.brotli:\n try:\n content = brotli.decompress(resp.content)\n except Exception as ex:\n print(ex)\n\n return content\n\n urls = []\n\n def __init__(self,urls):\n #self.json_root = json_root\n self.urls = urls\n","sub_path":"idope/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"24477041","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport requests\nfrom lxml import html\n\nfrom util import get_image_name, add_row_values\n\nf = open(\"moves.in\", \"r\")\nout = open(\"moves.out\", \"w\")\nfor i, attack_name in enumerate(f):\n attack_name = attack_name.strip()\n values = [attack_name]\n print(i, attack_name)\n\n lookup_name = attack_name.lower().replace(\" \", \"\")\n if lookup_name == \"judgement\":\n lookup_name = \"judgment\"\n\n page = requests.get('http://www.serebii.net/attackdex-sm/' + lookup_name + '.shtml')\n tree = html.fromstring(page.text)\n main_table = tree.xpath('/html/body/table[2]/tr[2]/td[2]/font/div[3]/font/p')[-1].getnext()\n\n row_index = 1\n\n # Name, Type, Category\n row = main_table[row_index]\n attack_type = get_image_name(row.xpath('td[2]/a/img')[0])\n category = get_image_name(row.xpath('td[3]/a/img')[0])\n if category == \"Other\":\n category = \"Status\"\n values.append(attack_type)\n values.append(category)\n print(attack_type, category)\n\n # PP, Base Power, Accuracy\n row_index += 2\n add_row_values(main_table, row_index, values, 1, 2, 3)\n\n # Description\n row_index += 2\n add_row_values(main_table, row_index, values, 1)\n\n if main_table[row_index + 1].text_content().strip() == \"In-Depth Effect:\":\n row_index += 2\n\n # Secondary Effect and Effect Chance\n row_index += 2\n add_row_values(main_table, row_index, values, 2)\n\n # Z-Move things\n row_index += 2\n\n # Crit Rate, Speed Priority, Target\n row_index += 2\n add_row_values(main_table, row_index, values, 1, 2)\n\n # I don't know I guess it's a new fucking table now?\n main_table = main_table.getnext()\n row_index = 1\n\n # Physical Contact, Sound-Type, Punch Move, Snatchable, Z-Move\n add_row_values(main_table, row_index, values, 1, 2, 3, 4)\n\n # Defrost, Triple Battle, Magic Bounce, Protected, Mirror Move\n row_index += 2\n add_row_values(main_table, row_index, values, 1, 3, 4, 5)\n\n for value in values:\n out.write(value + '\\n')\nf.close()\nout.close()\n","sub_path":"scripts/movescript.py","file_name":"movescript.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"589531784","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractBaseUser\nfrom django.contrib.auth.models import PermissionsMixin\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils import timezone\nfrom .managers import UserManager\n\n\nclass User(AbstractBaseUser, PermissionsMixin):\n \n email = models.EmailField(\n _('email address'),\n unique=True\n )\n \n username = models.CharField(\n _('username'),\n max_length=30,\n unique=True,\n blank=False,\n null=False\n )\n\n first_name = models.CharField(\n _('first name'),\n max_length=30,\n unique=False,\n blank=False,\n null=False\n )\n\n last_name = models.CharField(\n _('last name'),\n max_length=30,\n unique=False,\n blank=False,\n null=False\n )\n\n is_staff = models.BooleanField(\n default=False\n )\n \n is_active = models.BooleanField(\n default=True\n )\n \n date_joined = models.DateTimeField(\n default=timezone.now\n )\n\n USERNAME_FIELD = 'email'\n \n REQUIRED_FIELDS = [\n 'username',\n 'first_name',\n 'last_name'\n ]\n\n objects = UserManager()\n\n def __str__(self):\n return self.email","sub_path":"accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"144267624","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras import models\nfrom keras import layers\n\n#讀取檔案 #讀取正規化檔案,需自行至Excel填入column名稱\norg_data = pd.read_csv('norm_265590185.csv', encoding='utf-8')\n#print(org_data.head(5))\ndf_org_data = pd.DataFrame(data=org_data)\nprint(df_org_data.head(5))\nprint('---------------------確認資料是否讀取進來----------------------') #ok\n\n#定義欄位為data及targets\nBrain_y = df_org_data['Brain perfusion']\n#print(Brain_y)\nBrain_x = df_org_data[['SBP','DBP','Brain tissue oxygen','ICP','CPP']]\nprint(Brain_x)\nprint('---------------------確認欄位是否正確----------------------') #ok\n\n#資料分割:訓練及測試\nX_train,X_test,Y_train,Y_test = train_test_split(Brain_x,Brain_y,test_size=0.3)\n#print(y_test)\nprint(X_train.shape)\nprint(Y_test.shape)\nprint('---------------------確認資料分割是否完成----------------------') #ok\n\ndef build_model():\n model = Sequential()\n model.add(layers.Dense(32, input_shape=(X_train.shape[1],), activation=\"relu\"))\n model.add(layers.Dense(16, activation=\"relu\"))\n model.add(layers.Dense(1))\n # 編譯模型\n model.compile(loss=\"mse\", optimizer=\"sgd\",metrics=[tf.keras.metrics.MeanAbsoluteError()])\n return model\n\nk = 4\nnb_val_samples = len(X_train) // k\nnb_epochs = 500\nmse_scores = []\nmae_scores = []\nall_mae_histories = []\nfor i in range(k):\n print(\"Processing Fold #\" + str(i))\n # 取出驗證資料集\n X_val = X_train[ i *nb_val_samples: ( i +1 ) *nb_val_samples]\n Y_val = Y_train[ i *nb_val_samples: ( i +1 ) *nb_val_samples]\n # 結合出訓練資料集\n X_train_p = np.concatenate(\n [X_train[: i *nb_val_samples],\n X_train[( i +1 ) *nb_val_samples:]], axis=0)\n Y_train_p = np.concatenate(\n [Y_train[: i *nb_val_samples],\n Y_train[( i +1 ) *nb_val_samples:]], axis=0)\n model = build_model()\n # 訓練模型\n history = model.fit(X_train_p, Y_train_p, epochs=nb_epochs,validation_data=(X_val,Y_val),batch_size=16, verbose=0)\n # 評估模型\n mse, mae = model.evaluate(X_val, Y_val)\n mse_scores.append(mse)\n mae_scores.append(mae) #all_scores[]\n\n mae_history = history.history['val_mean_absolute_error'] #作圖\n all_mae_histories.append(mae_history)\n\nprint(\"MSE_val: \", np.mean(mse_scores))\nprint(\"MAE_val: \", np.mean(mae_scores))\n\naverage_mae_history = [np.mean([x[i] for x in all_mae_histories]) for i in range(nb_epochs)]\nplt.plot(range(1, len(average_mae_history)+1), all_mae_histories)\nplt.xlabel('Epochs')\nplt.ylabel('Validation MAE')\nplt.show()","sub_path":"kfold.py","file_name":"kfold.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"53916175","text":"import telebot\nimport traceback\nimport pyaudio\nimport wave\nimport soundfile as sf\nimport subprocess\nimport audioop\nimport time\nimport threading\nimport os\n\nLOCK = threading.Lock()\nAPI_KEY = os.environ[\"API_TOKEN_2\"]\n\ndef convert_audio(old_file_name, new_file_name):\n\tprocess = subprocess.run(['ffmpeg', '-i', old_file_name, new_file_name])\n\ndef send_voice_file(bot, chat_id, file_name):\n\tvoice = None\n\ttry:\n\t\tvoice = open(file_name, 'rb')\n\t\tbot.send_voice(chat_id, voice)\n\tfinally:\n\t\tif voice:\n\t\t\tvoice.close()\n\n\ndef reverse_audio(old_file_name, new_file_name):\n\twith wave.open(old_file_name) as fd:\n\t params = fd.getparams()\n\t frames = fd.readframes(1000000) \n\n\tframes = audioop.reverse(frames, params.sampwidth)\n\n\twith wave.open(new_file_name, 'wb') as fd:\n\t fd.setparams(params)\n\t fd.writeframes(frames)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\nbot = telebot.TeleBot(API_KEY, parse_mode=None)\n\n@bot.message_handler(content_types=['voice',])\ndef handle_message(message):\n\tglobal LOCK\n\tif not LOCK.acquire(False):\n\t\tbot.send_message(message.chat.id, \"Sorry!!! I am busy...\")\n\t\treturn\n\ttry:\n\t\tfile_info = bot.get_file(message.voice.file_id)\n\t\tdownloaded_file = bot.download_file(file_info.file_path)\n\n\t\tfile_name = str(time.time())\n\n\t\twith open(file_name + \".ogg\", 'wb') as new_file:\n\t\t\tnew_file.write(downloaded_file)\n\n\t\tconvert_audio(file_name + '.ogg', file_name + '.wav')\n\t\treverse_audio(file_name + '.wav', file_name + \"_reverse.wav\")\n\t\tconvert_audio(file_name + \"_reverse.wav\", file_name + \"_reverse.ogg\")\n\n\t\tsend_voice_file(bot, message.chat.id, file_name + \"_reverse.ogg\")\n\t\tos.remove(file_name + \".ogg\")\n\t\tos.remove(file_name + \".wav\")\n\t\tos.remove(file_name + \"_reverse.wav\")\n\t\tos.remove(file_name + \"_reverse.ogg\")\n\texcept:\n\t\ttraceback.print_exc()\n\tfinally:\n\t\tLOCK.release()\n\ndef main():\n\tprint(\"Starting bot\")\n\tbot.polling()\n\nmain()\n","sub_path":"bots/tennet_audio_bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"533321311","text":"import configparser\n\n\nmyConfigParser = configparser.ConfigParser()\nmyConfigParser.read(\"config.ini\")\nsectionName = \"TrainTestDictionaryComparator\"\ntrainSpecsLocationConfig = \"trainSpecsLocation\"\ntrainTitlesLocationConfig = \"trainTitlesLocation\"\ntestSpecsLocationConfig = \"testSpecsLocation\"\ntestTitlesLocationConfig = \"testTitlesLocation\"\nextraContentLocationConfig = \"extraContentLocation\"\nattributesLocationConfig = \"attributesLocation\"\nconfigSection = myConfigParser[sectionName]\ntrainSpecsLocation = configSection[trainSpecsLocationConfig]\ntrainTitlesLocation = configSection[trainTitlesLocationConfig]\ntestSpecsLocation = configSection[testSpecsLocationConfig]\ntestTitlesLocation = configSection[testTitlesLocationConfig]\nextraContentLocation = configSection[extraContentLocationConfig]\nattributesLocation = configSection[attributesLocationConfig]\n\nimport re\ndef getLabelFromWords(label):\n return re.sub('_', ' ', label);\n\n\ndef readContentInList(fileLocation):\n output = []\n with open(fileLocation, \"r\") as f:\n for line in f:\n line = line.strip()\n if len(line)==0:\n output.append([])\n else:\n line = line.split()\n output.append(line)\n return output\n\ndef getEndIndex(lines, index, attributeIndex, word, label):\n attributeName = getLabelFromWords(label[2:])\n startAttributeName = label[2:]\n totalLines = len(lines)\n attributeValue = word\n if index!=totalLines:\n while index0:\n label = line[attributeIndex]\n word = line[0]\n if label!=\"O\":\n index+=1\n (endIndex, attributeName, attributeValue) = getEndIndex(lines, index, attributeIndex, word, label)\n index=endIndex\n if not attributeName in attributesDict:\n bufferSet = set([])\n else:\n bufferSet = attributesDict[attributeName]\n bufferSet.add(attributeValue)\n attributesDict[attributeName] = bufferSet\n index+=1\n return attributesDict\n\ndef combineDict(d1, d2):\n for (k, v) in d2.items():\n if k in d1:\n d1[k] = d1[k].union(v)\n else:\n d1[k] = v\n return d1\n\ndef getExtraContent(testDict, trainDict):\n output = {}\n for (k, v) in testDict.items():\n if not k in trainDict:\n output[k] = v\n else:\n diff = v.difference(trainDict[k])\n if len(diff)>0:\n output[k] = diff\n return output\n\n# testTitlesContent = readContentInList(testTitlesLocation)\n# testTitlesDict = getAttributesDictionary(testTitlesContent, 3)\n# print(testTitlesDict)\n\n\ndef convertSetToStr(s):\n output = \"\"\n for item in s:\n output+=item+\"\\n\"\n return output\n\ndef writeStrToLocation(l, s):\n with open(l, \"w\") as f:\n f.write(s)\n\n\nimport os.path\ndef readAllFileNames(folderLocation):\n # print(folderLocation)\n # print(os.listdir(folderLocation))\n return [f for f in os.listdir(folderLocation) if os.path.isfile(folderLocation + \"/\" + f)]\n\n\ndef readFileContentInListAsSet(fileLocation):\n lines = []\n with open(fileLocation) as file:\n for line in file:\n line = line.strip() # or some other preprocessing\n lines.append(line) # storing everything in memory!\n return list(set(lines))\n\n\n\ndef readAllAttributesDictionary(attributeLocation):\n allAttributesLocation = readAllFileNames(attributeLocation)\n attributesDict = {}\n for attribute in allAttributesLocation:\n attributeFileLocation = attributeLocation + \"/\" + attribute\n dictContent = readFileContentInListAsSet(attributeFileLocation)\n if len(dictContent)>0:\n attributesDict[attribute] = dictContent\n return attributesDict\n\ntrainSpecsContent = readContentInList(trainSpecsLocation)\ntrainTitlesContent = readContentInList(trainTitlesLocation)\ntestSpecsContent = readContentInList(testSpecsLocation)\ntestTitlesContent = readContentInList(testTitlesLocation)\ntrainSpecsDict = getAttributesDictionary(trainSpecsContent, 2)\ntrainTitlesDict = getAttributesDictionary(trainTitlesContent, 2)\ntestSpecsDict = getAttributesDictionary(testSpecsContent, 3)\ntestTitlesDict = getAttributesDictionary(testTitlesContent, 3)\ntrainDict = combineDict(trainSpecsDict, trainTitlesDict)\ntestDict = combineDict(testSpecsDict, testTitlesDict)\ncompleteAttributes = readAllAttributesDictionary(attributesLocation)\nextraDictContent = getExtraContent(testDict, trainDict)\ncompleteExtraDictContent = getExtraContent(testDict, completeAttributes)\nfor (k, v) in completeExtraDictContent.items():\n print(\"Key:\" + str(k))\n print(\"Value:- \" + str(v))\n\n# for (k, v) in trainDict.items():\n# print(\"Key:\" + str(k))\n# print(\"Value:- \" + str(v))\n#\n# for (k, v) in trainDict.items():\n# print(\"Key:\" + str(k))\n# print(\"Value:- \" + str(v))\noutput = \"\"\nfor (k, v) in extraDictContent.items():\n l = extraContentLocation+\"/\"+k\n s = convertSetToStr(v)\n output+=k+\"\\n======================================\\n\"\n output+=s+\"\\n-------------------------------------------\\n\\n\"\n writeStrToLocation(l, s)\nwriteStrToLocation(extraContentLocation+\"/completeExtraInfo\", output)\nprint(\"Written everything\")\n # print(\"TrainSpecs dictionary:-\")\n# print(trainSpecsDict)","sub_path":"TrainTestDictionaryComparator.py","file_name":"TrainTestDictionaryComparator.py","file_ext":"py","file_size_in_byte":6227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"97890436","text":"#!/usr/bin/env python\n\"\"\"\nOpen an index file and start ban-ing the entries.\n\nWishlist:\n* some sort of rate limiting.\n* repeat or just a single run through?\n* should the list of urls be shuffled?\n\nAuthor: Lasse Karstensen , December 2014.\n\"\"\"\nfrom sys import argv\nfrom httplib import HTTPConnection\nfrom urlparse import urlparse, ParseResult\nfrom time import sleep\nfrom pprint import pprint\nfrom logging import basicConfig, DEBUG, INFO, debug, info\n\ndef ban(url):\n assert type(url) == ParseResult\n assert url.scheme == \"http\"\n\n conn = HTTPConnection(url.netloc)\n conn.request(\"BAN\", url.path, \"\")\n if 0:\n resp = conn.getresponse()\n pprint(resp)\n pprint(resp.read())\n\ndef main():\n if \"-v\" in argv:\n basicConfig(level=DEBUG)\n argv.pop(argv.index(\"-v\"))\n else:\n basicConfig(level=INFO)\n\n info(\"Startup.\")\n for line in open(argv[1]):\n url = urlparse(line.strip())\n debug(\"Banning \" + url.geturl())\n ban(url)\n sleep(0.1)\n info(\"Completed.\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bansender.py","file_name":"bansender.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"41320682","text":"import http\nfrom flask import Blueprint, jsonify, abort\nfrom ..models import db, User, Role\n\n\nusers = Blueprint(\"users\", __name__, template_folder=\"templates\")\n\n@users.route('', methods=['GET'])\ndef get_all():\n user_models = db.session.query(User)\n return jsonify({'data': [u.to_dict() for u in user_models]})\n\n@users.route('/by_email/', methods=['GET'])\ndef get_by_email(email):\n user = db.session.query(User).filter_by(email=email).first()\n if not user:\n abort(http.client.NOT_FOUND)\n return jsonify({'data': user.to_dict()})\n\n\n@users.route('/', methods=['GET'])\ndef get(user_id):\n user = db.session.query(User).filter_by(id=user_id).first()\n if not user:\n abort(http.client.NOT_FOUND)\n return jsonify({'data': user.to_dict()})\n\ndef has_role(user, role):\n if isinstance(user, int):\n user = db.session.query.get(user)\n if user is None:\n return False\n user_roles = {r.name for r in user.roles}\n if 'admin' in user_roles:\n return True\n return role in user_roles\n","sub_path":"flask_app/blueprints/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"508286226","text":"import pygame\nimport sys\nimport inputbox\nfrom Button import Button\nimport errorScreen\nfrom pygame.locals import *\nfrom constants import *\nimport game1\nimport game2\nimport game3\n\ndef startGame(DISPLAY_SURF):\n\tbackground=pygame.image.load('Images/simphy.jpg')\n\tDISPLAY_SURF.blit(background,SCREEN_TOPLEFT)\n\tpygame.mixer.music.load('Sound/bill1.ogg')\n\tpygame.mixer.music.play(-1, 0.0)\n\ttry:\n\t\tbtn_linear_motion = pygame.image.load('Images/buttons/linear_motion_button.png')\n\t\tbtn_vertical_motion = pygame.image.load('Images/buttons/vertical_motion_button.png')\n\t\tbtn_momentum = pygame.image.load('Images/buttons/momentum_button.png')\n\t\tclock = pygame.time.Clock()\n\t\trun1= True;\n\t\twhile run1:\n\t\t\tDISPLAY_SURF.blit(background,SCREEN_TOPLEFT)\n\t\t\tmouse = pygame.mouse.get_pos()\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tif pygame.mixer.music.get_busy():\n\t\t\t\t\t\tpygame.mixer.music.stop()\n\t\t\t\t\trun1 = False\n\t\t\t\t\tpygame.quit()\n\t\t\t\t\tsys.exit()\n\t\t\t\telif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\t\tif rect_linear_motion.collidepoint(mouse):\n\t\t\t\t\t\tgame1.startGame1(DISPLAY_SURF)\n\t\t\t\t\telif rect_vertical_motiond.collidepoint(mouse):\n\t\t\t\t\t\tgame2.startGame2(DISPLAY_SURF)\n\t\t\t\t\telif rect_momentum.collidepoint(mouse):\n\t\t\t\t\t\tprint (\"game 3\")\n\t\t\t\t\t\tgame3.startGame3(DISPLAY_SURF)\n\t\t\t\t\t\t\n\t\t\trect_linear_motion = DISPLAY_SURF.blit(btn_linear_motion ,(100,210))\n\t\t\trect_vertical_motiond = DISPLAY_SURF.blit(btn_vertical_motion,(300,210))\n\t\t\trect_momentum= DISPLAY_SURF.blit(btn_momentum,(200,310))\n\n\t\t\tpygame.display.update()\n\t\t\tclock.tick(60)\n\texcept Exception:\t\t\t\t\t\t\t# except is the python equivalent of catch block\n\t\tprint (\"error in demo\")\n\t\terrorScreen.errorScreen(DISPLAY_SURF,\"Something went wrong\")\n\telse:\n\t\tprint (\"all good\")\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"463777970","text":"from orm.services.customer_manager.cms_rest.data.sql_alchemy.customer_record import CustomerRecord\nfrom orm.services.customer_manager.cms_rest.data.sql_alchemy.models import CustomerRegion\nfrom orm.services.customer_manager.cms_rest.data.sql_alchemy.region_record import RegionRecord\nfrom orm.services.customer_manager.cms_rest.logger import get_logger\n\nLOG = get_logger(__name__)\n\n\nclass CustomerRegionRecord:\n def __init__(self, session):\n\n # thie model uses for the parameters for any acceess methods - not as instance of record in the table\n self.__customer_region = CustomerRegion()\n # self.setRecordData(self.__customers)\n # self.__customers.Clear()\n\n self.__TableName = \"customer_region\"\n\n if (session):\n self.session = session\n\n def setDBSession(self, session):\n self.session = session\n\n @property\n def customer_region(self):\n return self.__customer_region\n\n @customer_region.setter\n def customer_region(self):\n self.__customer_region = CustomerRegion()\n\n def insert(self, customer_region):\n try:\n self.session.add(customer_region)\n except Exception as exception:\n LOG.log_exception(\"Failed to insert customer_region\" + str(customer_region), exception)\n raise\n\n def get_regions_for_customer(self, customer_uuid):\n customer_regions = []\n\n try:\n customer_record = CustomerRecord(self.session)\n customer_id = customer_record.get_customer_id_from_uuid(customer_uuid)\n query = self.session.query(CustomerRegion).filter(CustomerRegion.customer_id == customer_id)\n\n for customer_region in query.all():\n customer_regions.append(customer_region)\n return customer_regions\n\n except Exception as exception:\n message = \"Failed to get_region_names_for_customer: %d\" % (customer_id)\n LOG.log_exception(message, exception)\n raise\n\n def delete_region_for_customer(self, customer_id, region_name):\n # customer_id can be a uuid (type of string) or id (type of int)\n # if customer_id is uuid I get id from uuid and use the id in the next sql command\n if isinstance(customer_id, basestring):\n customer_record = CustomerRecord(self.session)\n customer_id = customer_record.get_customer_id_from_uuid(customer_id)\n # get region id by the name I got (region_name)\n region_record = RegionRecord(self.session)\n region_id = region_record.get_region_id_from_name(region_name)\n if region_id is None:\n raise ValueError(\n 'region with the region name {0} not found'.format(\n region_name))\n result = self.session.connection().execute(\n \"delete from customer_region where customer_id = {} and region_id = {}\".format(customer_id, region_id)) # nosec\n self.session.flush()\n\n if result.rowcount == 0:\n LOG.warn('region with the region name {0} not found'.format(region_name))\n raise ValueError('region with the region name {0} not found'.format(region_name))\n\n LOG.debug(\"num records deleted: \" + str(result.rowcount))\n return result\n\n def delete_all_regions_for_customer(self, customer_id): # not including default region which is -1\n # customer_id can be a uuid (type of string) or id (type of int)\n # if customer_id is uuid I get id from uuid and use the id in the next sql command\n if isinstance(customer_id, basestring):\n customer_record = CustomerRecord(self.session)\n customer_id = customer_record.get_customer_id_from_uuid(customer_id)\n\n result = self.session.connection().execute(\n \"delete from customer_region where customer_id = {} and region_id <> -1 \".format(customer_id)) # nosec\n # print \"num records deleted from customer regions: \" + str(result.rowcount)\n return result\n","sub_path":"orm/services/customer_manager/cms_rest/data/sql_alchemy/customer_region_record.py","file_name":"customer_region_record.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"297155336","text":"import unittest\nimport os\nfrom dotenv import load_dotenv\n\nimport nlpaug.augmenter.word as naw\n\n\nclass TestWordEmbsAug(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n env_config_path = os.path.abspath(os.path.join(\n os.path.dirname(__file__), '..', '..', '..', '.env'))\n load_dotenv(env_config_path)\n\n model_dir = os.environ.get(\"MODEL_DIR\")\n\n full_test_case = False\n\n cls.augs = [\n naw.WordEmbsAug(model_type='word2vec', model_path=model_dir+'GoogleNews-vectors-negative300.bin'),\n naw.WordEmbsAug(model_type='glove', model_path=model_dir+'glove.6B.50d.txt'),\n naw.WordEmbsAug(model_type='fasttext', model_path=model_dir + 'wiki-news-300d-1M.vec')\n ]\n\n if full_test_case:\n cls.augs.extend([\n naw.WordEmbsAug(model_type='glove', model_path=model_dir+'glove.42B.300d.txt'),\n naw.WordEmbsAug(model_type='glove', model_path=model_dir+'glove.840B.300d.txt'),\n naw.WordEmbsAug(model_type='glove', model_path=model_dir+'glove.twitter.27B.25d.txt'),\n naw.WordEmbsAug(model_type='glove', model_path=model_dir+'glove.twitter.27B.50d.txt'),\n naw.WordEmbsAug(model_type='glove', model_path=model_dir+'glove.twitter.27B.100d.txt'),\n naw.WordEmbsAug(model_type='glove', model_path=model_dir+'glove.twitter.27B.200d.txt'),\n naw.WordEmbsAug(model_type='fasttext', model_path=model_dir+'wiki-news-300d-1M-subword.vec'),\n naw.WordEmbsAug(model_type='fasttext', model_path=model_dir+'crawl-300d-2M.vec'),\n naw.WordEmbsAug(model_type='fasttext', model_path=model_dir+'crawl-300d-2M-subword.vec'),\n ])\n\n def test_oov(self):\n unknown_token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'\n\n for aug in self.augs:\n aug.action = 'substitute'\n\n augmented_text = aug.augment(unknown_token)\n self.assertEqual(unknown_token, augmented_text)\n\n text = unknown_token + ' the'\n\n augmented_text = aug.augment(text)\n self.assertNotEqual(text, augmented_text)\n self.assertTrue(unknown_token in augmented_text)\n\n def test_insert(self):\n texts = [\n 'The quick brown fox jumps over the lazy dog'\n ]\n\n for aug in self.augs:\n aug.action = 'insert'\n\n for text in texts:\n self.assertLess(0, len(text))\n augmented_text = aug.augment(text)\n\n self.assertLess(len(text.split(' ')), len(augmented_text.split(' ')))\n self.assertNotEqual(text, augmented_text)\n\n self.assertLess(0, len(texts))\n\n def test_substitute(self):\n texts = [\n 'The quick brown fox jumps over the lazy dog'\n ]\n\n for aug in self.augs:\n aug.action = 'substitute'\n\n for text in texts:\n self.assertLess(0, len(text))\n augmented_text = aug.augment(text)\n self.assertNotEqual(text, augmented_text)\n\n self.assertLess(0, len(texts))\n\n def test_bogus_fasttext_loading(self):\n import nlpaug.model.word_embs.fasttext as ft\n test_file = os.path.join(os.path.dirname(__file__), 'bogus_fasttext.vec')\n expected_vector = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n\n fasttext = ft.Fasttext(lean=False)\n fasttext.read(test_file)\n\n for word in fasttext.w2v:\n self.assertSequenceEqual(list(fasttext.w2v[word]), expected_vector)\n\n self.assertSequenceEqual([\"test1\", \"test2\", \"test_3\", \"test 4\", \"test -> 5\"], fasttext.vocab)\n\n self.assertEqual(len(fasttext.vectors), 5)\n\n def test_incorrect_model_type(self):\n with self.assertRaises(ValueError) as error:\n naw.WordEmbsAug(\n model_type='test_model_type',\n model_path=os.environ.get(\"MODEL_DIR\") + 'GoogleNews-vectors-negative300.bin')\n\n self.assertTrue('Model type value is unexpected.' in str(error.exception))\n\n def test_reset_top_k(self):\n original_aug = naw.WordEmbsAug(\n model_type='word2vec', model_path=os.environ.get(\"MODEL_DIR\") + 'GoogleNews-vectors-negative300.bin')\n original_top_k = original_aug.model.top_k\n\n new_aug = naw.WordEmbsAug(\n model_type='word2vec', model_path=os.environ.get(\"MODEL_DIR\") + 'GoogleNews-vectors-negative300.bin',\n top_k=original_top_k+1)\n new_top_k = new_aug.model.top_k\n\n self.assertEqual(original_top_k+1, new_top_k)\n\n def test_case_insensitive(self):\n retry_cnt = 10\n\n text = 'Good'\n aug = naw.WordEmbsAug(\n model_type='word2vec', model_path=os.environ.get(\"MODEL_DIR\") + 'GoogleNews-vectors-negative300.bin',\n top_k=2)\n\n for _ in range(retry_cnt):\n augmented_text = aug.augment(text)\n self.assertNotEqual(text.lower(), augmented_text.lower())\n\n self.assertLess(0, retry_cnt)\n","sub_path":"test/augmenter/word/test_word_embs.py","file_name":"test_word_embs.py","file_ext":"py","file_size_in_byte":5065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"592869435","text":"from PIL import Image\n# 将一个图片转化为txt\nfrom numpy import savetxt, asarray\n\n\ndef imgToArray():\n image = Image.open(\"1_2.png\").convert(\"1\").resize((32, 32))\n data = asarray(image)\n savetxt(\"1_2.txt\", data, fmt=\"%d\", delimiter='')\n\nimgToArray()","sub_path":"caitong_trade/util/ocr_test3.py","file_name":"ocr_test3.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"523155114","text":"import discord\nimport random\nfrom discord.ext import commands\nfrom .Bot import extended_bot\n\nclient = discord.Client()\nbot = extended_bot.Bot(command_prefix='/', description='D&D bot')\n\nfrom .Bot import character\n\n@bot.command(pass_context=True)\nasync def roll(ctx, dice_arg):\n if '+' not in dice_arg:\n dice_arg += '+0'\n first_half, mod = dice_arg.split('+')[:2]\n mod = int(mod)\n count, size = map(int, first_half.split('d')[:2])\n rolls = []\n tot = 0\n for i in range(count):\n curr_roll = random.randint(1, size)\n tot += curr_roll\n rolls.append(f'{curr_roll}')\n tot += mod\n await bot.send_message(ctx.message.channel, f'({\" + \".join(rolls)}) + {mod} = {tot}')\n\n@bot.event\nasync def on_ready():\n print(f'Logged in as: {bot.user.name}, with id {bot.user.id}')\n\n@bot.event\nasync def on_command_error(error, ctx):\n await bot.send_message(ctx.message.channel, error)\n","sub_path":"DnD_discord_bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"213022837","text":"\"\"\"Console script for justice.\"\"\"\nimport argparse\nimport pprint\nimport sys\n\nfrom justice.justice import Justice\n\n\ndef main():\n \"\"\"Console script for justice.\"\"\"\n pp = pprint.PrettyPrinter(indent=4)\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-g', '--get', type=str, nargs='*')\n parser.add_argument('-s', '--search', type=str, nargs='+')\n args = parser.parse_args()\n\n if args.get:\n for subject in args.get:\n pp.pprint(Justice.get_detail(subject_id=subject))\n elif args.search:\n pp.pprint(Justice.search(string=' '.join(args.search)))\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main()) # pragma: no cover\n","sub_path":"justice/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"633199423","text":"\"\"\"\nCONFIDENTIALITY NOTE: This code is intended only for the instructors of\nCS1, as well as graders and mentors of this course who have previously\nreceived permission to use said material in assisting students. Under no\ncircumstances should this program be reviewed, retransmitted, disseminated\nor in any other way shared with anyone other than the intended recipients\nmentioned above. If you received this program and are not its intended\naudience, please contact the author immediately and destroy all copies\n(electronic or hardcopy).\n\"\"\"\n\n\"\"\"\nProject: Unigrams\nTask: Word Frequencies and Average Word Length (Part Two/Three)\n\nThis is a plotting utility the students will use in parts two and\nthree of the project to plot the data the calculate. This plotter\nuses the Python defacto standard GUI, tkInter.\n\nAuthor: Amar Saric and Ebisan Ekperigin\nLanguage: Python 3\n\"\"\"\n\nimport tkinter\nfrom tkinter import font as tkfont\nimport math\n\n###########################################################\n# IMPLEMENTATION\n###########################################################\n\nclass plot2D(tkinter.Tk):\n\n class _plot2D_canvas(tkinter.Canvas):\n\n def __init__(self, root, labels):\n super().__init__(root, width=800, height=600)\n self.boundary = 25\n self.space_label = 40 if labels != ('','') else 0\n self.left_boundary = 100 + self.space_label\n self.bottom_boundary = 75 + self.space_label\n self.hlabel, self.vlabel = labels\n self.pack(fill=\"both\", expand=True)\n self.configure(background='white')\n self.bind(\"\", self.plot)\n self.font = tkfont.Font(family='Courier', size=12, weight='normal')\n self.data =[]\n\n def add_point(self, x, y):\n self.data.append((x, y))\n\n def plot(self, event):\n if len(self.data) < 1:\n return\n\n width, height= event.width, event.height\n self.create_rectangle(0, 0, width, height, fill=\"white\")\n width -= self.boundary + self.left_boundary\n height -= self.boundary + self.bottom_boundary\n\n if width < 2*self.boundary or height < 2*self.boundary: # too small to display anything\n return\n\n def range_x(data):\n return min (a for (a,_) in data), max (a for (a,_) in data)\n\n def range_y(data):\n return min (b for (_,b) in data), max (b for (_,b) in data)\n\n x_min, x_max= range_x(self.data)\n y_min, y_max= range_y(self.data)\n\n len_x, len_y= x_max - x_min, y_max - y_min\n if len_x <= 0 or len_y <= 0:\n return\n\n scaled = [ ((x-x_min)*width/len_x + self.left_boundary, -(y-y_min)*height/len_y+ self.boundary + height)\n for (x,y) in self.data ]\n\n first = True\n for x, y in scaled:\n if first:\n first = False\n else:\n self.create_line( prev_x, prev_y, x, y, fill=\"black\") #@UndefinedVariable\n prev_x, prev_y = x, y #@UnusedVariable\n\n #grid...\n def log_magnitude (x):\n return math.floor(math.log(math.fabs(x))/math.log(10)) - 1\n\n def format_label(val,inc):\n if (math.fabs(int (inc) - inc) < 0.00001):\n label = str(int(val))\n else:\n label = \"{:.2f}\".format(val)\n if len(label) > 7:\n label = '{:.1e}'.format(val)\n return label\n\n x_min_bound, x_max_bound = range_x (scaled)\n y_min_bound, y_max_bound = range_y (scaled)\n width, height= x_max_bound - x_min_bound, y_max_bound - y_min_bound\n\n inc_x, inc_y = 10**log_magnitude(len_x), 10**log_magnitude(len_y)\n delta_x, delta_y = inc_x, inc_y\n step_x, step_y = 0, 0\n\n for i in [1, 5, 10, 50, 100]:\n if step_x >= 50 and step_y >= 50:\n break\n if step_x < 50:\n inc_x = i*delta_x\n step_x = inc_x * width/len_x\n if step_y < 50:\n inc_y = i*delta_y\n step_y = inc_y * height/len_y\n\n start_x, start_y = x_min//inc_x*inc_x, y_min//inc_y*inc_y\n offset_x, offset_y = (start_x - x_min)* width/len_x, (start_y - y_min)* height/len_y\n num_x_lines, num_y_lines= math.floor(width/step_x), math.floor( height/step_y)\n\n for i in range ( num_x_lines + 2):\n x = self.left_boundary + offset_x + i*step_x\n if not (x_min_bound < x < x_max_bound):\n continue\n self.create_line(x, self.boundary, x, self.boundary + height, dash = (2, 4))\n label = format_label(start_x + i*inc_x, inc_x)\n self.create_text(x, y_max_bound + (self.bottom_boundary-self.space_label)/2,\n font = self.font, text=label)\n for i in range (num_y_lines + 2):\n y = self.boundary + height - offset_y - i*step_y\n if not (y_min_bound < y < y_max_bound):\n continue\n self.create_line(self.left_boundary, y, self.left_boundary + width, y, dash=(2, 4))\n label = format_label(start_y + i*inc_y, inc_y)\n self.create_text((self.left_boundary-self.space_label)/2 +self.space_label, y, font=self.font, text=label)\n\n #labels...\n vlablel_offset = (y_min_bound + y_max_bound)/2 - 25 * len(self.vlabel)//2\n for i in range (len(self.vlabel)):\n self.create_text(self.space_label /2,vlablel_offset + 25*i,\n font = self.font, text= self.vlabel[i])\n self.create_text( (x_min_bound + x_max_bound)/2,\n y_max_bound + self.bottom_boundary - self.space_label,\n font = self.font, text= self.hlabel)\n\n #box ...\n self.create_line( x_min_bound, y_min_bound, x_max_bound, y_min_bound, fill=\"black\")\n self.create_line( x_min_bound, y_max_bound, x_max_bound, y_max_bound, fill=\"black\")\n self.create_line( x_min_bound, y_min_bound, x_min_bound, y_max_bound, fill=\"black\")\n self.create_line( x_max_bound, y_min_bound, x_max_bound, y_max_bound, fill=\"black\")\n\n def __init__ (self, title, labels = ('','')):\n super().__init__()\n self.title(title)\n self.canvas = self._plot2D_canvas(self,labels)\n\n def addPoint(self,p):\n self.canvas.add_point(p[0],p[1])\n\n def display(self):\n self.canvas.update()\n self.mainloop()\n\n###########################################################\n# EXAMPLES\n###########################################################\n\nif __name__ == '__main__':\n labels = 'X values', 'Y values'\n plot = plot2D('XY plot demo', labels)\n for i in range(3000):\n x = i/100 - 10\n point = x, 1099.122*(math.sin(x)+math.log(11+x)) + 123.22\n plot.addPoint(point)\n plot.display()\n labels = 'Log x values', 'Log y values'\n plot = plot2D('XY loglog plot demo', labels)\n for i in range(1,3000):\n x = i/100\n point = math.log(x,10), math.log(x**(-5)*10**2,10)\n plot.addPoint(point)\n plot.display()\n\n\n\n###########################################################\n# INTERFACE\n###########################################################\n\ndef wordFreqPlot(freqList):\n \"\"\"\n Plot the frequency counts of words on a log-log plot to show Zipf's Law.\n Assumes that all values are positive.\n :param freqList (list): A list of WordCount objects\n :return: None\n :rtype: NoneType\n \"\"\"\n labels = 'Log of word rank', 'Log of frequency'\n plot = plot2D(\"Zipf's Law (log-log plot)\", labels)\n\n for i, wordCount in enumerate(freqList):\n point = math.log(1+i)/math.log(10), math.log(1 + wordCount.count)/math.log(10)\n plot.addPoint(point)\n\n plot.display()\n\ndef averageWordLengthPlot(startYear, endYear, lengthsList):\n \"\"\"\n This routine plots the average word lengths over a range of years.\n :param startYear (int): The start year\n :param endYear (int): The end year\n :param lengthsList (list): List of average lengths (floats)\n :return: None\n :rtype: NoneType\n \"\"\"\n labels = 'Year', 'Length of word'\n plot = plot2D(\"Average word length:\", labels)\n\n for i, year in enumerate(range(startYear, endYear +1)):\n point = year, lengthsList[i]\n plot.addPoint(point)\n\n plot.display()\n","sub_path":"simplePlot.py","file_name":"simplePlot.py","file_ext":"py","file_size_in_byte":8707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"18817150","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport json\n\nimport tensorflow as tf\nimport util\nimport argparse\nfrom tqdm import tqdm\n\nimport numpy as np\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"model_name\", type=str, help=\"Model name\")\n parser.add_argument(\"input_path\", type=str, help=\"Input file in .jsonlines format\")\n parser.add_argument(\"--output_path\", type=str, help=\"Predictions will be written to this file in .jsonlines format.\")\n parser.add_argument(\"--npy_output_path\", type=str, help=\"Output npy pickle file with model scores\")\n args = parser.parse_args()\n\n model_name = args.model_name\n input_filename = args.input_path\n output_filename = args.output_path\n npy_output_filename = args.npy_output_path\n\n config = util.initialize_from_env(name=model_name)\n log_dir = config[\"log_dir\"]\n\n model = util.get_model(config)\n saver = tf.train.Saver()\n\n k_sum = 0\n c_sum = 0\n count = 0\n\n if npy_output_filename:\n data_dicts = []\n\n with tf.Session() as session:\n model.restore(session)\n\n input_file = open(input_filename, \"r\")\n if output_filename:\n output_file = open(output_filename, \"w\")\n\n for example_num, line in enumerate(tqdm(input_file.readlines())):\n example = json.loads(line)\n tensorized_example = model.tensorize_example(example, is_training=False)\n feed_dict = {i:t for i,t in zip(model.input_tensors, tensorized_example)}\n _, _, _, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores = session.run(model.predictions, feed_dict=feed_dict)\n\n if npy_output_filename:\n data_dict = {\n \"example_num\": example_num,\n \"example\": example,\n \"top_span_starts\": top_span_starts,\n \"top_span_ends\": top_span_ends,\n \"top_antecedents\": top_antecedents,\n \"top_antecedent_scores\": top_antecedent_scores\n }\n\n # top_antecedents, top_antecedent_scores = \\\n # prune_antec_scores(top_antecedents, top_antecedent_scores, 5)\n\n data_dicts.append(data_dict)\n\n predicted_antecedents = model.get_predicted_antecedents(top_antecedents, top_antecedent_scores)\n example[\"predicted_clusters\"], _ = model.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents)\n example[\"top_spans\"] = list(zip((int(i) for i in top_span_starts), (int(i) for i in top_span_ends)))\n example['head_scores'] = []\n\n if output_filename:\n output_file.write(json.dumps(example))\n output_file.write(\"\\n\")\n # if example_num % 20 == 0:\n # print(\"Decoded {} examples.\".format(example_num + 1))\n\n input_file.close()\n if output_filename:\n output_file.close()\n\n if npy_output_filename:\n dict_to_npy = {\"data_dicts\": data_dicts}\n with open(npy_output_filename, \"wb\") as f:\n np.save(f, dict_to_npy)\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"508164576","text":"#\n# @lc app=leetcode.cn id=21 lang=python3\n#\n# [21] 合并两个有序链表\n#\n\n# @lc code=start\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n if l1 and l2 and l1.val<=l2.val:\n rst,idx_A,idx_B=l1,l1,l2\n elif l2==None:\n return l1\n else:\n rst,idx_A,idx_B=l2,l2,l1\n while(True):\n if idx_B==None:\n return rst\n elif idx_A.next and idx_A.next.val<=idx_B.val:\n idx_A=idx_A.next\n else:\n idx_tmp=idx_B.next\n idx_B.next=idx_A.next\n idx_A.next=idx_B\n idx_B=idx_tmp\n \n# @lc code=end\n\n","sub_path":"Week_01/21.合并两个有序链表.py","file_name":"21.合并两个有序链表.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"238475355","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# basic run script - adds bin to pythonpath, then run the script given in arg\n\nif __name__==\"__main__\": \n import sys, os.path\n thisdir = os.path.split(__file__)[0]\n bindir = os.path.abspath(os.path.join(thisdir,'build/bin'))\n if os.path.isdir(bindir):\n sys.path.append(bindir)\n print('%s added to PATH' % bindir)\n else:\n print('%s not found' % bindir)\n sys.exit()\n\n if len(sys.argv)==1:\n print('missing argument.\\nusage: %s file.py' % os.path.basename(sys.argv[0]))\n sys.exit()\n __file__ = os.path.abspath(sys.argv[1])\n exec(open(sys.argv[1]).read())\n","sub_path":"classes/minibarreTE/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"313744507","text":"#!/usr/bin/env python\n\nfrom nuagectl.updatemanagers.manager import Manager, UpdateManagerException, \\\n Package\n\n\nclass YumManager(Manager):\n\n def _parse_yum_list(self, lines):\n for line in lines.splitlines()[1:]:\n try:\n package, version, repo = line.split()\n except ValueError:\n pass\n else:\n yield dict(package=package, version=version, repo=repo)\n\n def _combine_packages(self, installed_packages, packages_to_update):\n indexed_packages = {}\n\n # Indexing all installed packages with a dict\n for package in installed_packages:\n indexed_packages[package['package']] = package\n\n packages = []\n for update in packages_to_update:\n current_version = indexed_packages \\\n .get(update['package'])['version']\n\n package = Package(\n update['package'], current_version, update['repo'])\n\n package.new_version = update['version']\n packages.append(package)\n\n return packages\n\n def _refresh_cache(self):\n self._machine.run(\n 'yum clean expire-cache && yum makecache fast -q', quiet=True)\n\n def get_updates(self):\n self._refresh_cache()\n\n check_update = self._machine.run(\n 'yum list updates -q --color=never',\n combine_stderr=False, quiet=True)\n\n # return_code == 0 -> have updates\n if check_update.return_code == 0:\n packages_to_update = self._parse_yum_list(check_update)\n\n list_installed = self._machine.run(\n 'yum list installed -q --color=never')\n if list_installed.return_code != 0:\n raise UpdateManagerException(\n 'Failed to get already installed packages.')\n\n installed_packages = self._parse_yum_list(list_installed)\n return self._combine_packages(\n installed_packages, packages_to_update)\n\n # return_code == 100 -> no updates\n elif check_update.return_code == 100:\n return {}\n # other return_code -> error\n else:\n raise UpdateManagerException('Error when trying to get updates.')\n\n def count_updates(self):\n return len(self.get_updates())\n\n def update_machine(self):\n self._refresh_cache()\n self._machine.run('yum update -q -y')\n\n def download_updates(self):\n self._refresh_cache()\n self._machine.run('yum update --downloadonly -q -y')\n","sub_path":"nuagectl/updatemanagers/yum_manager.py","file_name":"yum_manager.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"528245474","text":"# coding: utf-8\n\"\"\"\n-------------------------------------------------\n File Name: get_count.py\n Author : Scar\n E-mail : scarforhere@gmail.com\n Date: 2021-05-01 10:11 AM\n-------------------------------------------------\nDescription :\n\n Count numbers of ch in s\n\n\"\"\"\n\n\ndef get_count(s, ch):\n \"\"\"\n Count numbers of ch in s\n\n :param s: string\n :param ch: char\n :return: numbers of char in string\n \"\"\"\n count = 0\n for item in s:\n if ch.upper() == item or ch.lower() == item:\n count += 1\n return count\n","sub_path":"get_count.py","file_name":"get_count.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"74023740","text":"from os.path import basename as _basename\nfrom os import remove as _remove\n\nform_name=_basename(__file__).split('.')[0][4:]+':id'\n\nis_form = {\n 'uniprot:id': form_name,\n 'UniProt:id': form_name\n }\n\ndef to_aminoacids1_seq(form_id):\n\n import urllib as _urllib\n\n url_fasta = 'http://www.uniprot.org/uniprot/'+UniProt_id+'.fasta'\n request_fasta = _urllib.request.Request(url_fasta)\n request_fasta.add_header('User-Agent', 'Python at https://github.com/uibcdf/MolModMT || prada.gracia@gmail.com')\n response_fasta = _urllib.request.urlopen(request_fasta)\n fasta_result = response_fasta.read().decode('utf-8')\n lines_fasta=fasta_result.split('\\n')\n tmp_sequence=''.join(lines_fasta[1:])\n del(url_fasta,request_fasta,response_fasta,fasta_result)\n return tmp_sequence\n\ndef to_aminoacids3_seq(form_id):\n from molmodmt.forms.seqs.api_aminoacids1 import to_aminoacids3_seq as _to_aa3_seq\n tmp_sequence = to_aminoacids1_seq(form_id)\n tmp_sequence = _to_aa3_seq(tmp_sequence)\n del(_to_aa3_seq)\n return tmp_sequence\n\n","sub_path":"molmodmt/forms/ids/api_UniProt.py","file_name":"api_UniProt.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"134627323","text":"\"\"\"Test irrigation_unlimited history.\"\"\"\nfrom unittest.mock import patch\nfrom datetime import datetime\nimport pytest\nimport homeassistant.core as ha\nfrom homeassistant.config import load_yaml_config_file\nfrom homeassistant.setup import async_setup_component\n\nfrom custom_components.irrigation_unlimited.const import DOMAIN\nfrom custom_components.irrigation_unlimited.__init__ import CONFIG_SCHEMA\nfrom tests.iu_test_support import quiet_mode, test_config_dir\n\nquiet_mode()\n\n\n@pytest.fixture(name=\"mock_history\")\ndef mock_history():\n with patch(\n \"homeassistant.components.recorder.history.state_changes_during_period\"\n ) as mock:\n\n def s2dt(adate: str) -> datetime:\n return datetime.fromisoformat(adate + \"+00:00\")\n\n result = {}\n id = \"binary_sensor.irrigation_unlimited_c1_z1\"\n result[id] = []\n result[id].append(ha.State(id, \"on\", None, s2dt(\"2021-01-04 04:30:00\")))\n result[id].append(ha.State(id, \"off\", None, s2dt(\"2021-01-04 04:32:00\")))\n result[id].append(ha.State(id, \"on\", None, s2dt(\"2021-01-04 05:30:00\")))\n result[id].append(ha.State(id, \"off\", None, s2dt(\"2021-01-04 05:32:00\")))\n id = \"binary_sensor.irrigation_unlimited_c1_z2\"\n result[id] = []\n result[id].append(ha.State(id, \"on\", None, s2dt(\"2021-01-04 04:35:00\")))\n result[id].append(ha.State(id, \"off\", None, s2dt(\"2021-01-04 04:38:00\")))\n result[id].append(ha.State(id, \"on\", None, s2dt(\"2021-01-04 05:35:00\")))\n result[id].append(ha.State(id, \"off\", None, s2dt(\"2021-01-04 05:38:00\")))\n result[id].append(ha.State(id, \"on\", None, s2dt(\"2021-01-04 05:40:00\")))\n mock.return_value = result\n yield\n\n\nasync def test_history(hass: ha.HomeAssistant, skip_dependencies, mock_history):\n\n full_path = test_config_dir + \"test_history.yaml\"\n config = CONFIG_SCHEMA(load_yaml_config_file(full_path))\n await async_setup_component(hass, DOMAIN, config)\n await hass.async_block_till_done()\n s = hass.states.get(\"binary_sensor.irrigation_unlimited_c1_z1\")\n assert s.attributes[\"today_total\"] == 4.0\n","sub_path":"tests/test_history.py","file_name":"test_history.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"354985327","text":"import requests\nfrom bs4 import BeautifulSoup\nimport os\nimport re\n\n\ndef getHTMLText(url, code='utf-8'):\n headers = {\n 'Host': 'www.169pic.com',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',\n 'Connection': 'keep-alive',\n 'Pragma': 'no-cache',\n 'Cache-Control': 'no-cache',\n 'Upgrade-Insecure-Requests': '1',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',\n }\n try:\n r = requests.get(url, headers=headers)\n r.raise_for_status()\n r.encoding = code\n data = r.content\n return data\n except:\n return 'fail'\n\n\ndef parserHTML(html):\n soup = BeautifulSoup(html, 'html.parser')\n\n all_pic = soup.select('p[align=\"center\"] img')\n\n # 查找标题作为文件名, 因为有分页所以会有数字后缀, 用正则把数字给去掉\n name = soup.select('.position')[0].getText().split('>')[-1].strip()\n name = ''.join(re.findall(r'[^\\x00-\\xff]', name))\n\n if all_pic:\n print('Could not find image')\n else:\n try:\n os.makedirs('169pic/{}'.format(name), exist_ok=True)\n for pic in all_pic:\n picurl = pic.get('src')\n print('正在下载图片,地址:' + picurl)\n res = requests.get(picurl, headers={'Host': '724.169pp.net',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',\n })\n res.raise_for_status()\n\n filename = ''.join(picurl.split('/')[-3:])\n\n with open('169pic/{}/{}'.format(name, filename), 'wb') as f:\n f.write(res.content)\n except Exception as exc:\n print(exc)\n\n # 翻页设置\n page = soup.select('.pagelist li a')\n nextPage = page[-1]\n # 获得当前页面的网址去除最后的部分\n URL = soup.select('link[rel=\"alternate\"]')[0].get('href')[:-10]\n\n # 下一个美女的链接\n nextHref = soup.select('.fenxianga a')[0].get('href')\n\n # 如果翻页为#则表示全都下载完, 返回下一个美女的链接\n if nextPage.get('href') != '#':\n url = URL + nextPage.get('href')\n return url\n return nextHref\n\n\nif __name__ == \"__main__\":\n\n url = \"http://www.169pic.com/xingganmeinv/2017/0514/38594.html\"\n os.makedirs('169pic', exist_ok=True)\n\n html = getHTMLText(url)\n pics = parserHTML(html)\n\n while pics != '':\n html = getHTMLText(pics)\n pics = parserHTML(html)\n","sub_path":"spider169pic.py","file_name":"spider169pic.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"319706347","text":"import rospy\nimport smach\nfrom copy import deepcopy\n\nfrom apc_util.moveit import scene, execute_known_trajectory\nfrom apc_util.grasping import gripper\nfrom apc_util.shelf import BIN\nfrom apc_util.smach import on_exception\n\n\nclass PlaceItem(smach.State):\n \"\"\"\n Place the item in the bin for shipping\n \"\"\"\n\n def __init__(self, robot):\n smach.State.__init__(self, outcomes=['Success', 'Failure', 'Fatal'],\n input_keys=['bin'], output_keys=[])\n self.arm = robot.arm_left_torso\n\n @on_exception(failure_state=\"Failure\")\n def execute(self, userdata):\n rospy.loginfo(\"Trying to place from bin '\"+userdata.bin+\"'...\")\n\n # rospy.sleep(4)\n from apc_util.moveit import goto_pose, follow_path\n from geometry_msgs.msg import Pose, Point, Quaternion\n target = Pose(\n position=Point(x=0.4062, y=0.43, z=0.85),\n orientation=Quaternion(x=-0.12117, y=0.49833, z=0.85847, w=0.0020136)\n # position=Point(x=0.50071, y=0.048405, z=0.97733),\n # orientation=Quaternion(x=-0.0042023, y=-0.008732, z=-0.80657, w=0.59106)\n )\n if not goto_pose(self.arm, target, [2, 2, 5, 10, 30], shelf=BIN(userdata.bin)):\n return 'Failure'\n\n poses = [target]\n poses.append(deepcopy(poses[-1]))\n poses[-1].position.z -= 0.15\n if not follow_path(self.arm, poses, False):\n return 'Failure'\n\n # with BIN(userdata.bin):\n # if not execute_known_trajectory(self.arm, \"Drop\", userdata.bin):\n # return \"Failure\"\n\n if not gripper.open():\n return \"Failure\"\n\n poses.reverse()\n if not follow_path(self.arm, poses, False):\n return 'Failure'\n\n scene.remove_attached_object(\"arm_left_link_7_t\")\n return 'Success'\n","sub_path":"task_controller/src/task_controller/PlaceItem.py","file_name":"PlaceItem.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"488682322","text":"class DailyFrequency:\n empty_stomach = False\n morning = False\n afternoon = False\n evening =False\n night = False\n def __init(self):\n self.empty_stomach= False\n self.morning = False\n self.afternoon = False\n self.evening = False\n self.night = False\n\nclass MedSchedule:\n# medicine_name = \"NA\",\n# till_x_days = 100000, #default is infinite days\n# specifications = 0, # 0 = no specifications, 1 = before meal, 2 = after meal\n# weekly_frequency = -1, #0=daily, 1= alternate days, 2= twice a week, 3 = once a week\n# Sos = False #true when the medicine is to be taken only on emergency\n# daily_frequency = DailyFrequency()\n \n def __init__(self):\n self.medicine_name = \"NA\"\n self.till_x_days = 100000\n self.specifications = 0\n self.weekly_frequency = -1\n self.Sos = False\n self.daily_frequency = DailyFrequency()\n \n def printSchedule(self):\n print(\"Medicine Name: \", self.medicine_name)\n \n if(self.Sos == True):\n print(\"SOS only\")\n \n if (self.till_x_days != 100000):\n print(\"Till \", self.till_x_days, \"Days\")\n \n if (self.weekly_frequency == 0):\n print(\"To be taken : Daily\" )\n elif (self.weekly_frequency == 1):\n print(\"To be taken : On alternate days\" )\n elif (self.weekly_frequency == 2):\n print(\"To be taken : Once a week\" )\n elif (self.weekly_frequency == 3):\n print(\"To be taken : Twice a week\" )\n \n print(\"Daily Schedule: -> \")\n# if self.daily_frequency.empty_stomach:\n print(\"Empty Stomach: \", self.daily_frequency.empty_stomach)\n# if self.daily_frequency.morning:\n print(\"Morning: \", self.daily_frequency.morning)\n# if self.daily_frequency.afternoon:\n print(\"Afternoon: \", self.daily_frequency.afternoon)\n# if self.daily_frequency.evening:\n print(\"Evening: \", self.daily_frequency.evening)\n# if self.daily_frequency.night:\n print(\"Night: \", self.daily_frequency.night)\n \n if (self.specifications == 2):\n print(\"Specifcations : After Meal\" )\n elif (self.specifications == 1):\n print(\"Specifcations : Before Meal\" )\n print(\"--------------------------------------\")\n","sub_path":"src/ScheduleModel.py","file_name":"ScheduleModel.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"260588423","text":"\nfrom .base import *\nfrom .base_class import NN_BASE\n\nimport keras.backend as K\nK.set_image_dim_ordering('th')\n#GOOD\n\n#incept 3\n# dept 1\n# width 20\n#l2 0.0001\n#opt rmsprop\n\n\n#FOR OIL DATASET\n#2x30 Dense\n#Maxnorm 4 for all\n#nbepoch=100\n#batch=64\n\n\n#MSE: 5708\n#Best params:{'n_depth': 3, 'l2w': 0.00029999999999999997, 'n_width': 100, 'seed': 3014}\n#OIL Best params:{'seed': 3014, 'l2w': 0.000706122448979592, 'n_depth': 2, 'n_width': 90}\n#GAS Best params:{'n_depth': 2, 'seed': 3014, 'l2w': 0.00030204081632653063, 'n_width': 60}\n\n#GAS Best params:{'n_width': 100, 'l2w': 0.00015000000000000001, 'n_depth': 2, 'seed': 3014}\n#OIL Best params:{'n_width': 60, 'l2w': 0.001, 'n_depth': 2, 'seed': 3014},Best params:{'n_width': 90, 'l2w': 0.0007, 'n_depth': 3, 'seed': 3014}\nsas=5708\nOUT = 'GAS'\n\nTRAIN_ES=1720-500\nTRAIN_ES=1690-500\n\nGASE=1500\nclass NCNET1_GJOA2(NN_BASE):\n\n\n\n def __init__(self,n_depth=2,n_width=90,l2w=0.00095,dp_rate=0,seed=3014,output_act='relu',n_epoch=1500,DATA='GAS'):\n\n\n\n self.input_tags = {}\n\n self.well_names = ['C1', 'C2', 'C3', 'C4', 'B1', 'B3', 'D1']\n\n\n measurement_tags = ['CHK', 'PBH','PWH','PDC']\n for name in self.well_names:\n self.input_tags[name] = []\n for tag in measurement_tags:\n if (name == 'C2' or name == 'D1') and tag == 'PBH':\n pass\n else:\n self.input_tags[name].append(name + '_' + tag)\n\n if DATA == 'GAS':\n self.output_tags = OIL_WELLS_QGAS_OUTPUT_TAGS\n else:\n self.output_tags = OIL_WELLS_QOIL_OUTPUT_TAGS\n\n self.loss_weights = {\n 'B1_out': 0.0,\n 'B3_out': 0.0,\n 'C2_out': 0.0,\n 'C3_out': 0.0,\n 'D1_out': 0.0,\n 'C4_out': 0.0,\n 'C1_out': 0.0,\n\n 'GJOA_TOTAL': 1.0,\n }\n\n\n self.output_layer_activation = output_act\n\n # Training config\n optimizer = 'adam'\n loss =huber\n nb_epoch = n_epoch\n batch_size = 64\n self.activation='relu'\n\n self.model_name ='GJOA_OIL_WELLS_OIL_HUBER_MODEL_FINAL2_TESTDATA2'# 'GJOA_OIL2S_WELLS_{}_D{}_W{}_L2{}_DPR{}'.format(loss, n_depth, n_width, l2w,dp_rate)\n\n\n\n super().__init__(n_width=n_width,n_depth=n_depth,l2_weight=l2w,dp_rate=dp_rate,seed=seed,\n optimizer=optimizer,loss=loss,nb_epoch=nb_epoch,batch_size=batch_size)\n\n\n\n\n\n\n def initialize_model(self):\n print('Initializing %s' % (self.model_name))\n print('Training with params:\\n n_width: {}\\n n_depth: {}\\n l2_weight: {}\\n'\n 'dp_rate: {}\\n seed: {}\\n loss: {}\\n optimizer: {}\\n nb_epoch: {}\\n'\n 'batch_size: {}\\n output_activation: {}'.format(self.n_width,self.n_depth,self.l2weight,self.dp_rate,self.seed,self.optimizer,self.loss,self.nb_epoch,self.batch_size,self.output_layer_activation))\n\n aux_inputs=[]\n inputs=[]\n merged_outputs=[]\n outputs=[]\n\n for key in self.well_names:\n n_input=len(self.input_tags[key])\n aux_input,input,merged_out,out=self.generate_input_module(name=key,n_input=n_input)\n\n aux_inputs.append(aux_input)\n inputs.append(input)\n merged_outputs.append(merged_out)\n\n\n merged_input = Add(name='GJOA_TOTAL')(merged_outputs)\n\n all_outputs=merged_outputs+[merged_input]\n all_inputs = inputs\n\n if self.add_thresholded_output:\n all_inputs+=aux_inputs\n\n\n self.model = Model(inputs=all_inputs, outputs=all_outputs)\n self.model.compile(optimizer=self.optimizer, loss=self.loss, loss_weights=self.loss_weights)\n #print(self.model.summary())\n #exit()\n def initialize_model2(self):\n print('Initializing %s' % (self.model_name))\n\n aux_inputs=[]\n inputs=[]\n merged_outputs=[]\n outputs=[]\n #merged_outputs=[]\n\n for key in self.well_names:\n n_input=len(self.input_tags[key])\n aux_input_mod1, aux_input_mod2, input_layer, merged_output_mod1, merged_output_mod2, main_out=self.generate_input_module_gas(name=key,n_input=n_input)\n\n aux_inputs.append(aux_input_mod1)\n aux_inputs.append(aux_input_mod2)\n inputs.append(input_layer)\n merged_outputs.append(main_out)\n #merged_outputs.append(merged_output_mod2)\n #outputs.append(main_out)\n\n\n merged_input = Add(name='GJOA_TOTAL')(merged_outputs)\n\n all_outputs=merged_outputs+[merged_input]\n all_inputs = inputs\n\n if self.add_thresholded_output:\n all_inputs+=aux_inputs\n\n\n self.model = Model(inputs=all_inputs, outputs=all_outputs)\n self.model.compile(optimizer=self.optimizer, loss=self.loss, loss_weights=self.loss_weights)\n\n\n\n def generate_input_module(self, name, n_input):\n\n\n input_layer = Input(shape=(n_input,), dtype='float32', name=name)\n #temp_output=GaussianNoise(0.1)(input_layer)\n\n temp_output = Dense(self.n_width,activation=self.activation,kernel_regularizer=l2(self.l2weight),kernel_initializer=self.init,use_bias=True,name=name+'_0')(input_layer)\n #temp_output = MaxoutDense(self.n_width,kernel_regularizer=l2(self.l2weight),kernel_initializer=self.init,use_bias=True)(input_layer)\n #temp_output=PReLU()(temp_output)\n for i in range(1,self.n_depth):\n if self.dp_rate>0:\n temp_output=Dropout(self.dp_rate,name=name+'_dp_'+str(i))(temp_output)\n temp_output = Dense(self.n_width, activation=self.activation,kernel_regularizer=l2(self.l2weight),kernel_initializer=self.init,use_bias=True,name=name+'_'+str(i))(temp_output)\n #temp_output = PReLU()(temp_output)\n\n output_layer = Dense(1, kernel_initializer=self.init,kernel_regularizer=l2(self.l2weight),activation=self.output_layer_activation, use_bias=True,name=name+'_o')(temp_output)\n\n aux_input, merged_output = add_thresholded_output(output_layer, n_input, name)\n\n return aux_input, input_layer, merged_output, output_layer\n\n\n def update_model(self,activation='relu',epoch=10000):\n self.nb_epoch=epoch\n self.output_layer_activation=activation\n self.aux_inputs=[]\n self.inputs=[]\n self.merged_outputs=[]\n self.outputs=[]\n\n old_model=self.model\n self.initialize_model()\n weights=old_model.get_weights()\n self.model.set_weights(weights)\n\n\nclass ENSEMBLE(NN_BASE):\n\n\n\n def __init__(self,PATHS):\n\n self.model_name='NCNET2_ENSEMBLE_LEARNING'\n\n self.PATHS=PATHS\n\n\n self.output_layer_activation='relu'\n\n # Training config\n optimizer = 'adam'\n self.activation='relu'\n loss =huber\n nb_epoch = 1\n batch_size = 64\n verbose = 0\n self.reg_constraint=False\n\n #Model config\n\n\n #Input module config\n self.n_inception =0\n n_depth = 2\n self.n_depth_incept=3\n self.n_width_incept=50\n n_width = 60\n seed=3014\n\n\n l2weight = 0.0001\n self.models=[]\n\n\n self.make_same_model_for_all=True\n self.add_thresholded_output=True\n\n self.input_tags = {}\n\n self.well_names = ['C1','C2', 'C3', 'C4','B1','B3','D1']\n self.well_names = ['F1', 'B2', 'D3', 'E1']\n\n tags = ['CHK','PBH','PWH','PDC']\n\n for name in self.well_names:\n\n self.input_tags[name] = []\n for tag in tags:\n if (name=='C2' or name=='D1') and tag=='PBH':\n pass\n else:\n self.input_tags[name].append(name + '_' + tag)\n\n OUT='GAS'\n if OUT=='GAS':\n self.output_tags = GAS_WELLS_QGAS_OUTPUT_TAGS\n else:\n self.output_tags = OIL_WELLS_QOIL_OUTPUT_TAGS\n\n self.loss_weights = {\n #'B1_out': 0.0,\n #'B3_out': 0.0,\n #'C2_out': 0.0,\n #'C3_out': 0.0,\n #'D1_out': 0.0,\n #'C4_out': 0.0,\n #'C1_out': 0.0,\n\n #'GJOA_TOTAL': 1.0,\n\n 'F1_out': 0.0,\n 'B2_out': 0.0,\n 'D3_out': 0.0,\n 'E1_out': 0.0,\n 'GJOA_QGAS': 1.0\n\n\n }\n\n super().__init__(n_width=n_width, n_depth=n_depth, l2_weight=l2weight, seed=seed,\n optimizer=optimizer, loss=loss, nb_epoch=nb_epoch, batch_size=batch_size)\n\n def load_model(self,path):\n print('Initializing %s' % (self.model_name))\n\n aux_inputs = []\n inputs = []\n merged_outputs = []\n outputs = []\n\n for key in self.well_names:\n n_input = len(self.input_tags[key])\n aux_input, input, merged_out, out = self.generate_input_module(name=key, n_input=n_input)\n\n aux_inputs.append(aux_input)\n inputs.append(input)\n merged_outputs.append(merged_out)\n\n merged_input = Add(name='GJOA_QGAS')(merged_outputs)\n\n all_outputs = merged_outputs + [merged_input]\n all_inputs = inputs\n\n if self.add_thresholded_output:\n all_inputs += aux_inputs\n\n model = Model(inputs=all_inputs, outputs=all_outputs)\n model.compile(optimizer=self.optimizer, loss=self.loss, loss_weights=self.loss_weights)\n model.load_weights(path)\n return model\n\n def generate_input_module(self, name, n_input):\n\n\n input_layer = Input(shape=(n_input,), dtype='float32', name=name)\n #temp_output=GaussianNoise(0.1)(input_layer)\n\n temp_output = Dense(self.n_width,activation=self.activation,kernel_regularizer=l2(self.l2weight),kernel_initializer=self.init,use_bias=True,name=name+'_0')(input_layer)\n #temp_output = MaxoutDense(self.n_width,kernel_regularizer=l2(self.l2weight),kernel_initializer=self.init,use_bias=True)(input_layer)\n #temp_output=PReLU()(temp_output)\n for i in range(1,self.n_depth):\n if self.dp_rate>0:\n temp_output=Dropout(self.dp_rate,name=name+'_dp_'+str(i))(temp_output)\n temp_output = Dense(self.n_width, activation=self.activation,kernel_regularizer=l2(self.l2weight),kernel_initializer=self.init,use_bias=True,name=name+'_'+str(i))(temp_output)\n #temp_output = PReLU()(temp_output)\n\n output_layer = Dense(1, kernel_initializer=self.init,kernel_regularizer=l2(self.l2weight),activation=self.output_layer_activation, use_bias=True,name=name+'_o')(temp_output)\n\n aux_input, merged_output = add_thresholded_output(output_layer, n_input, name)\n\n return aux_input, input_layer, merged_output, output_layer\n\n def initialize_model(self):\n print('Initializing %s' % (self.model_name))\n from keras.models import load_model\n self.models=[]\n for path in self.PATHS:\n print('Initializing '+path)\n self.models.append(self.load_model(path))\n self.model=self.models[0]\n\n def predict(self, X):\n predictions=[]\n\n for model in self.models:\n prediction=self.get_prediction(X,model)\n predictions.append(prediction)\n\n pred_concat=pd.concat(predictions,axis=1)\n pred_out=pd.DataFrame()\n\n for col in self.output_tag_ordered_list:\n pred_out[col]=pred_concat[col].mean(axis=1)\n\n return pred_out\n\n def get_prediction(self, X,model):\n X_dict,_=self.preprocess_data(X)\n predicted_data=model.predict(X_dict)\n #print(predicted_data[0])\n N_output_modules=len(self.output_tags.keys())\n\n #print(predicted_data.shape)\n\n\n\n if N_output_modules>1:\n predicted_data_reshaped=np.asarray(predicted_data[0])\n #print(predicted_data_reshaped)\n for i in range(1,N_output_modules):\n temp_data=np.asarray(predicted_data[i])\n predicted_data_reshaped=np.hstack((predicted_data_reshaped,temp_data))\n else:\n predicted_data_reshaped=np.asarray(predicted_data)\n #print(predicted_data_reshaped.shape)\n return pd.DataFrame(data=predicted_data_reshaped,columns=self.output_tag_ordered_list)\n","sub_path":"Models/NeuralNetworks/NCNET1_GJOA2.py","file_name":"NCNET1_GJOA2.py","file_ext":"py","file_size_in_byte":12183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"600092050","text":"#!/usr/bin/env python\n\"\"\"An example of cursor dealing with prepared statements.\n\nA cursor can be used as a regular one, but has also a prepare() statement. If\nprepare() is called, execute() and executemany() can be used without query: in\nthis case the parameters are passed to the prepared statement. The functions\nalso execute the prepared statement if the query is the same prepared before.\n\nPrepared statements aren't automatically deallocated when the cursor is\ndeleted, but are when the cursor is closed. For long-running sessions creating\nan unbound number of cursors you should make sure to deallocate the prepared\nstatements (calling close() or deallocate() on the cursor).\n\n\"\"\"\n\n# Copyright (C) 2012 Daniele Varrazzo \n\nimport os\nimport re\nfrom threading import Lock\n\nimport psycopg2\nimport psycopg2.extensions as ext\n\nclass PreparingCursor(ext.cursor):\n _lock = Lock()\n _ncur = 0\n def __init__(self, *args, **kwargs):\n super(PreparingCursor, self).__init__(*args, **kwargs)\n # create a distinct name for the statements prepared by this cursor\n self._lock.acquire()\n self._prepname = \"psyco_%x\" % self._ncur\n PreparingCursor._ncur += 1\n self._lock.release()\n\n self._prepared = None\n self._execstmt = None\n\n _re_replargs = re.compile(r'(%s)|(%\\([^)]+\\)s)')\n\n def prepare(self, stmt):\n \"\"\"Prepare a query for execution.\n\n TODO: handle literal %s and $s in the string.\n \"\"\"\n # replace the python placeholders with postgres placeholders\n parlist = []\n parmap = {}\n parord = []\n\n def repl(m):\n par = m.group(1)\n if par is not None:\n parlist.append(par)\n return \"$%d\" % len(parlist)\n else:\n par = m.group(2)\n assert par\n idx = parmap.get(par)\n if idx is None:\n idx = parmap[par] = \"$%d\" % (len(parmap) + 1)\n parord.append(par)\n\n return idx\n\n pgstmt = self._re_replargs.sub(repl, stmt)\n\n if parlist and parmap:\n raise psycopg2.ProgrammingError(\n \"you can't mix positional and named placeholders\")\n\n self.deallocate()\n self.execute(\"prepare %s as %s\" % (self._prepname, pgstmt))\n\n if parlist:\n self._execstmt = \"execute %s (%s)\" % (\n self._prepname, ','.join(parlist))\n elif parmap:\n self._execstmt = \"execute %s (%s)\" % (\n self._prepname, ','.join(parord))\n else:\n self._execstmt = \"execute %s\" % (self._prepname)\n\n self._prepared = stmt\n\n @property\n def prepared(self):\n \"\"\"The query currently prepared.\"\"\"\n return self._prepared\n\n def deallocate(self):\n \"\"\"Deallocate the currently prepared statement.\"\"\"\n if self._prepared is not None:\n self.execute(\"deallocate \" + self._prepname)\n self._prepared = None\n self._execstmt = None\n\n def execute(self, stmt=None, args=None):\n if stmt is None or stmt == self._prepared:\n stmt = self._execstmt\n elif not isinstance(stmt, basestring):\n args = stmt\n stmt = self._execstmt\n\n if stmt is None:\n raise psycopg2.ProgrammingError(\n \"execute() with no query called without prepare\")\n\n return super(PreparingCursor, self).execute(stmt, args)\n\n def executemany(self, stmt, args=None):\n if args is None:\n args = stmt\n stmt = self._execstmt\n\n if stmt is None:\n raise psycopg2.ProgrammingError(\n \"executemany() with no query called without prepare\")\n else:\n if stmt != self._prepared:\n self.prepare(stmt)\n\n return super(PreparingCursor, self).executemany(self._execstmt, args)\n\n def close(self):\n if not self.closed and not self.connection.closed and self._prepared:\n self.deallocate()\n\n return super(PreparingCursor, self).close()\n\n\n\"\"\"\ndb_dict = {\n 'db_type' : \"postgres\",\n 'db_name' : \"prod\", #\"postgres\"\n 'db_user' : \"postgres\",\n 'db_host' : \"188.165.197.228\",\n 'db_pass' : \"penny9690\"\n }\n\nglobal query_dict\nquery_dict = {\n 'query_id' : \"SELECT m.mail_id FROM md5 AS m WHERE m.md5 = %s\",\n\n 'query_optin' : \"SELECT opt.id FROM optin_match AS opt \" + \\\n \"WHERE opt.mail_id = %s AND opt.optin_id IN \" + \\\n \"(SELECT opt_list.id FROM optin_list AS opt_list \" + \\\n \"WHERE opt_list.abreviation = %s)\",\n\n 'query_desabo' : \"SELECT desabo.id FROM optin_desabo AS desabo \" + \\\n \"WHERE desabo.mail_id = %s AND desabo.optin_id IN \" + \\\n \"(SELECT opt_list.id FROM optin_list AS opt_list \" + \\\n \"WHERE opt_list.abreviation = %s)\",\n\n 'query_info' : \"SELECT b.mail, id.civilite, id.prenom, id.nom FROM base AS b \" + \\\n \"INNER JOIN id_unik AS id ON b.id = id.mail_id \" + \\\n \"WHERE id.mail_id = %s\",\n\n 'query_log' : \"INSERT INTO log_criteo (mail_id, optin_id, status, date) VALUES (%s,%s,%s,%s)\",\n\n 'query_log_id_list' : \"SELECT id FROM optin_list WHERE abreviation = %s\"\n }\n\nimport psycopg2\nimport psycopg2.extensions\nimport psycopg2.pool\nconnect_token = \"dbname='%s' user='%s' host='%s' password='%s'\" \\\n % (db_dict['db_name'], db_dict['db_user'], db_dict['db_host'], db_dict['db_pass'])\nconn_pool = psycopg2.pool.ThreadedConnectionPool(1,100, connect_token)\n\nfrom contextlib import contextmanager\n@contextmanager\ndef getconnection():\n con = conn_pool.getconn()\n try:\n yield con\n finally:\n conn_pool.putconn(con)\n\n@contextmanager\ndef getcursor():\n con = conn_pool.getconn()\n try:\n yield con.cursor()\n finally:\n conn_pool.putconn(con)\n\"\"\"\n\n\"\"\"\nwith getconnection() as conn:\n cursor = conn.cursor(cursor_factory=PreparingCursor)\n query = query_dict['query_optin']\n cursor.prepare(query)\n cursor.execute(query, (12, 'sho'))\n print cursor.fetchone()\n #cursor.prepare(query)\n cursor.execute(query, (12, 'sho'))\n print cursor.fetchone()\n\"\"\"","sub_path":"psycopg2_prepare.py","file_name":"psycopg2_prepare.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"118715454","text":"#!/usr/bin/python3\n'''\nCreated on Jan 13, 2017\n\n@author: tonyq\n'''\n\nimport matplotlib\nmatplotlib.use('Agg')\nprint(matplotlib.get_backend())\nfrom matplotlib import pylab\nfrom matplotlib import font_manager\nfrom sklearn.manifold import TSNE\nimport numpy as np\nimport tensorflow as tf\n\nimport argparse\nimport os\nimport json\nfrom collections import namedtuple\n\nfrom model import Model\n\nWORK_DIR = ''\nnum_points = 0\nOUTPUT = ''\nOS = ''\n\ndef plot(embeddings, labels):\n if OS == 'win':\n myfont = font_manager.FontProperties(fname='c:\\Windows\\Fonts\\simsun.ttc')\n else:\n myfont = font_manager.FontProperties(fname='/usr/share/fonts/truetype/moe/MoeStandardSong.ttf')\n assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'\n pylab.figure(figsize=(15,15)) # in inches\n for i, label in enumerate(labels):\n x, y = embeddings[i,:]\n pylab.scatter(x, y)\n pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',\n ha='right', va='bottom',fontproperties=myfont)\n if OS == 'win':\n pylab.show()\n else:\n pylab.savefig(OUTPUT)\n \ndef main(_):\n\n with open(os.path.join(WORK_DIR, 'vocab.npy'), 'rb') as fh:\n id2word = np.load(fh).tolist()\n# word2id = dict(zip(id2word, range(len(id2word))))\n\n with open(os.path.join(WORK_DIR, 'config.json'), 'r') as fh:\n d = json.load(fh)\n d['batch_size'] = 1\n d['num_steps'] = 1\n config = namedtuple('ModelConfig', d.keys())(*d.values())\n\n with tf.Graph().as_default(), tf.Session() as session:\n initializer = tf.random_uniform_initializer(-config.init_scale,\n config.init_scale)\n with tf.variable_scope(\"model\", reuse=None, initializer=initializer):\n m = Model(is_training=False, config=config)\n\n tf.global_variables_initializer().run()\n saver = tf.train.Saver(tf.global_variables())\n ckpt = tf.train.get_checkpoint_state(WORK_DIR)\n saver.restore(session, ckpt.model_checkpoint_path)\n\n final_embeddings = session.run([m.embedding])\n print(len(final_embeddings[0]))\n print(len(final_embeddings[0][1:num_points+1]))\n\n tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)\n two_d_embeddings = tsne.fit_transform(final_embeddings[0][1:num_points+1])\n words = [id2word[i] for i in range(1, num_points+1)]\n plot(two_d_embeddings, words)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='LSTM word vector viewer')\n parser.add_argument(\"--source\", default='../data-test', help=\"source folder\",)\n parser.add_argument(\"--output\", default='wordvec.png', help=\"output file\",)\n parser.add_argument(\"--points\", default='400', help=\"number of points to draw\",)\n parser.add_argument(\"--os\", default='win', help=\"draw in windows or to file\",)\n args = parser.parse_args()\n WORK_DIR = args.source\n num_points = int(args.points)\n OUTPUT = os.path.join(WORK_DIR, args.output)\n OS = args.os\n \n tf.app.run()","sub_path":"src/word2gph.py","file_name":"word2gph.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"619780496","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as opt\nimport torch.utils.data as Data\nimport matplotlib.pyplot as plt\nimport time\n\n# trainingdatat loading\n\ntorch.manual_seed(1)\ndata_train = np.loadtxt('myvoice_trainingdata_selected.csv', delimiter=',', dtype=np.float32)\nprint('Successfully loading training data')\n\nx_train = data_train[:, 0:-1]\n#print(x_train)\nlabels_train = data_train[:, [-1]]\n\nx_train, labels_train = torch.from_numpy(x_train), torch.from_numpy(labels_train)\n\nEPOCH = 100\nBATCH_SIZE = 20\nLR = 0.001\n\ndataset_train = Data.TensorDataset(x_train, labels_train)\n\n# print(x_train)\n# print(labels_train)\ntrain_loader = Data.DataLoader(\n dataset=dataset_train,\n batch_size=BATCH_SIZE,\n shuffle=True,\n num_workers=0,\n)\n\nclass LINEAR(nn.Module):\n def __init__(self):\n super(LINEAR, self).__init__()\n self.hidden = nn.Sequential(\n nn.Linear(20, 64),\n nn.ReLU(),\n \n\n nn.Linear(64, 64),\n nn.Tanh(),\n\n nn.Linear(64, 128),\n nn.Tanh(),\n\n nn.Linear(128, 128),\n nn.Tanh(),\n\n nn.Linear(128, 64),\n nn.ReLU(),\n\n nn.Linear(64, 64),\n nn.Tanh(),\n\n nn.Linear(64, 2)\n )\n\n\n def forward(self, x):\n\n output = self.hidden(x)\n return output\n\nlinear =LINEAR()\n\nall_loss_linear = []\n\noptimizer = opt.Adam(linear.parameters(), lr=LR)\nloss_func = nn.CrossEntropyLoss()\n\nfor epoch in range(EPOCH):\n start_time = time.time()\n print('EPOCH {}'.format(epoch+1))\n for step, (x_batch, label_batch)in enumerate(train_loader):\n x_batch = x_batch.squeeze().view(x_batch.size(0), 20)\n # x_batch = Variable(x_batch)\n # label_batch = Variable(label_batch)\n my_output = linear(x_batch)\n #print(my_output)\n label_batch = label_batch.squeeze().long()\n #print(label_batch)\n loss = loss_func(my_output, label_batch)\n #print(loss)\n all_loss_linear.append(loss)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n end_time = time.time()\n print('time', end_time-start_time)\n\ntorch.save(linear, 'linear_2.pkl')\n\n\ndata_test = np.loadtxt('myvoice_testingdata_selected.csv', delimiter=',', dtype=np.float32)\nprint('Successfully loading testing data')\n\nx_test = data_test[:, 0:-1]\nlabel_test = data_test[:, [-1]]\nprint('Begin testing')\nsum = 0\ntotal_num = 1000\nfor i in range(total_num):\n datain = torch.from_numpy(x_test[i]).view(1, 1, -1)\n #print('datain', datain)\n out = linear(datain)\n #print(out)\n out = out.squeeze(1)\n #print(out)\n out = torch.max(out, 1)[1].float()\n #print('out', out.type())\n ylabel = torch.from_numpy(label_test[i]).view(1, -1)\n # ylabel = ylabel.squeeze()\n #print('ylabel', ylabel)\n if(ylabel==out):\n sum = sum+1\nprint('Accuracy', sum/total_num)\n\n\nplt.figure(1)\nplt.plot(all_loss_linear, label='all_loss_linear_2')\nplt.legend(loc='best')\nplt.show()","sub_path":"voicegender_Linear_2.py","file_name":"voicegender_Linear_2.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"64625835","text":"# coding=utf-8\n# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport logging\n\nfrom pants.base.exceptions import TaskError\nfrom pants.base.revision import Revision\nfrom pants.java.distribution.distribution import DistributionLocator\nfrom pants.subsystem.subsystem import Subsystem\nfrom pants.util.memo import memoized_method, memoized_property\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass JvmPlatform(Subsystem):\n \"\"\"Used to keep track of repo compile settings.\"\"\"\n\n # NB(gmalmquist): These assume a java version number N can be specified as either 'N' or '1.N'\n # (eg, '7' is equivalent to '1.7'). New versions should only be added to this list\n # if they follow this convention. If this convention is ever not followed for future\n # java releases, they can simply be omitted from this list and they will be parsed\n # strictly (eg, if Java 10 != 1.10, simply leave it out).\n SUPPORTED_CONVERSION_VERSIONS = (6, 7, 8,)\n\n class IllegalDefaultPlatform(TaskError):\n \"\"\"The --default-platform option was set, but isn't defined in --platforms.\"\"\"\n\n class UndefinedJvmPlatform(TaskError):\n \"\"\"Platform isn't defined.\"\"\"\n\n def __init__(self, target, platform_name, platforms_by_name):\n scope_name = JvmPlatform.options_scope\n messages = ['Undefined jvm platform \"{}\" (referenced by {}).'\n .format(platform_name, target.address.spec if target else 'unknown target')]\n if not platforms_by_name:\n messages.append('In fact, no platforms are defined under {0}. These should typically be'\n ' specified in [{0}] in pants.ini.'.format(scope_name))\n else:\n messages.append('Perhaps you meant one of:{}'.format(\n ''.join('\\n {}'.format(name) for name in sorted(platforms_by_name.keys()))\n ))\n messages.append('\\nThese are typically defined under [{}] in pants.ini.'\n .format(scope_name))\n super(JvmPlatform.UndefinedJvmPlatform, self).__init__(' '.join(messages))\n\n options_scope = 'jvm-platform'\n\n @classmethod\n def register_options(cls, register):\n super(JvmPlatform, cls).register_options(register)\n register('--platforms', advanced=True, type=dict, default={}, fingerprint=True,\n help='Compile settings that can be referred to by name in jvm_targets.')\n register('--default-platform', advanced=True, type=str, default=None, fingerprint=True,\n help='Name of the default platform to use if none are specified.')\n register('--compiler', choices=['zinc', 'javac'], default='zinc',\n help='Java compiler implementation to use.')\n\n @classmethod\n def subsystem_dependencies(cls):\n return super(JvmPlatform, cls).subsystem_dependencies() + (DistributionLocator,)\n\n def _parse_platform(self, name, platform):\n return JvmPlatformSettings(platform.get('source', platform.get('target')),\n platform.get('target', platform.get('source')),\n platform.get('args', ()),\n name=name)\n\n @classmethod\n def preferred_jvm_distribution(cls, platforms, strict=False):\n \"\"\"Returns a jvm Distribution with a version that should work for all the platforms.\n\n Any one of those distributions whose version is >= all requested platforms' versions\n can be returned unless strict flag is set.\n\n :param iterable platforms: An iterable of platform settings.\n :param bool strict: If true, only distribution whose version matches the minimum\n required version can be returned, i.e, the max target_level of all the requested\n platforms.\n :returns: Distribution one of the selected distributions.\n \"\"\"\n if not platforms:\n return DistributionLocator.cached()\n min_version = max(platform.target_level for platform in platforms)\n max_version = Revision(*(min_version.components + [9999])) if strict else None\n return DistributionLocator.cached(minimum_version=min_version, maximum_version=max_version)\n\n @memoized_property\n def platforms_by_name(self):\n platforms = self.get_options().platforms or {}\n return {name: self._parse_platform(name, platform) for name, platform in platforms.items()}\n\n @property\n def _fallback_platform(self):\n logger.warn('No default jvm platform is defined.')\n source_level = JvmPlatform.parse_java_version(DistributionLocator.cached().version)\n target_level = source_level\n platform_name = '(DistributionLocator.cached().version {})'.format(source_level)\n return JvmPlatformSettings(source_level, target_level, [], name=platform_name)\n\n @memoized_property\n def default_platform(self):\n name = self.get_options().default_platform\n if not name:\n return self._fallback_platform\n platforms_by_name = self.platforms_by_name\n if name not in platforms_by_name:\n raise self.IllegalDefaultPlatform(\n \"The default platform was set to '{0}', but no platform by that name has been \"\n \"defined. Typically, this should be defined under [{1}] in pants.ini.\"\n .format(name, self.options_scope)\n )\n return JvmPlatformSettings(*platforms_by_name[name], name=name, by_default=True)\n\n @memoized_method\n def get_platform_by_name(self, name, for_target=None):\n \"\"\"Finds the platform with the given name.\n\n If the name is empty or None, returns the default platform.\n If not platform with the given name is defined, raises an error.\n :param str name: name of the platform.\n :param JvmTarget for_target: optionally specified target we're looking up the platform for.\n Only used in error message generation.\n :return: The jvm platform object.\n :rtype: JvmPlatformSettings\n \"\"\"\n if not name:\n return self.default_platform\n if name not in self.platforms_by_name:\n raise self.UndefinedJvmPlatform(for_target, name, self.platforms_by_name)\n return self.platforms_by_name[name]\n\n def get_platform_for_target(self, target):\n \"\"\"Find the platform associated with this target.\n\n :param JvmTarget target: target to query.\n :return: The jvm platform object.\n :rtype: JvmPlatformSettings\n \"\"\"\n if not target.payload.platform and target.is_synthetic:\n derived_from = target.derived_from\n platform = derived_from and getattr(derived_from, 'platform', None)\n if platform:\n return platform\n return self.get_platform_by_name(target.payload.platform, target)\n\n @classmethod\n def parse_java_version(cls, version):\n \"\"\"Parses the java version (given a string or Revision object).\n\n Handles java version-isms, converting things like '7' -> '1.7' appropriately.\n\n Truncates input versions down to just the major and minor numbers (eg, 1.6), ignoring extra\n versioning information after the second number.\n\n :param version: the input version, given as a string or Revision object.\n :return: the parsed and cleaned version, suitable as a javac -source or -target argument.\n :rtype: Revision\n \"\"\"\n conversion = {str(i): '1.{}'.format(i) for i in cls.SUPPORTED_CONVERSION_VERSIONS}\n if str(version) in conversion:\n return Revision.lenient(conversion[str(version)])\n\n if not hasattr(version, 'components'):\n version = Revision.lenient(version)\n if len(version.components) <= 2:\n return version\n return Revision(*version.components[:2])\n\n\nclass JvmPlatformSettings(object):\n \"\"\"Simple information holder to keep track of common arguments to java compilers.\"\"\"\n\n class IllegalSourceTargetCombination(TaskError):\n \"\"\"Illegal pair of -source and -target flags to compile java.\"\"\"\n\n def __init__(self, source_level, target_level, args, name=None, by_default=False):\n \"\"\"\n :param source_level: Revision object or string for the java source level.\n :param target_level: Revision object or string for the java target level.\n :param list args: Additional arguments to pass to the java compiler.\n :param str name: name to identify this platform.\n :param by_default: True if this value was inferred by omission of a specific platform setting.\n \"\"\"\n self.source_level = JvmPlatform.parse_java_version(source_level)\n self.target_level = JvmPlatform.parse_java_version(target_level)\n self.args = tuple(args or ())\n self.name = name\n self._by_default = by_default\n self._validate_source_target()\n\n def _validate_source_target(self):\n if self.source_level > self.target_level:\n if self.by_default:\n name = \"{} (by default)\".format(self.name)\n else:\n name = self.name\n raise self.IllegalSourceTargetCombination(\n 'Platform {platform} has java source level {source_level} but target level {target_level}.'\n .format(platform=name,\n source_level=self.source_level,\n target_level=self.target_level)\n )\n\n @property\n def by_default(self):\n return self._by_default\n\n def __iter__(self):\n yield self.source_level\n yield self.target_level\n yield self.args\n\n def __eq__(self, other):\n return tuple(self) == tuple(other)\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(tuple(self))\n\n def __cmp__(self, other):\n return cmp(tuple(self), tuple(other))\n\n def __str__(self):\n return 'source={source},target={target},args=({args})'.format(\n source=self.source_level,\n target=self.target_level,\n args=' '.join(self.args)\n )\n","sub_path":"src/python/pants/backend/jvm/subsystems/jvm_platform.py","file_name":"jvm_platform.py","file_ext":"py","file_size_in_byte":9655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"100676582","text":"import json\nfrom unittest2 import skipIf\nfrom django.test.utils import override_settings\nfrom django.test import TestCase\nfrom django.conf import settings\nfrom django.test.client import Client\nfrom django.core.urlresolvers import reverse\nfrom myuw.test.api import missing_url, get_user, get_user_pass\n\n\nFDAO_SWS = 'restclients.dao_implementation.sws.File'\nSession = 'django.contrib.sessions.middleware.SessionMiddleware'\nCommon = 'django.middleware.common.CommonMiddleware'\nCsrfView = 'django.middleware.csrf.CsrfViewMiddleware'\nAuth = 'django.contrib.auth.middleware.AuthenticationMiddleware'\nRemoteUser = 'django.contrib.auth.middleware.RemoteUserMiddleware'\nMessage = 'django.contrib.messages.middleware.MessageMiddleware'\nXFrame = 'django.middleware.clickjacking.XFrameOptionsMiddleware'\nUserService = 'userservice.user.UserServiceMiddleware'\nAUTH_BACKEND = 'django.contrib.auth.backends.ModelBackend'\n\n\n@override_settings(RESTCLIENTS_SWS_DAO_CLASS=FDAO_SWS,\n MIDDLEWARE_CLASSES=(Session,\n Common,\n CsrfView,\n Auth,\n RemoteUser,\n Message,\n XFrame,\n UserService,\n ),\n AUTHENTICATION_BACKENDS=(AUTH_BACKEND,)\n )\nclass TestDispatchErrorCases(TestCase):\n def setUp(self):\n self.client = Client()\n\n @skipIf(missing_url(\"myuw_home\"), \"myuw urls not configured\")\n def test_javerage(self):\n url = reverse(\"myuw_book_api\",\n kwargs={'year': 2013,\n 'quarter': 'spring',\n 'summer_term': ''})\n get_user('javerage')\n self.client.login(username='javerage',\n password=get_user_pass('javerage'))\n\n response = self.client.put(url)\n self.assertEquals(response.status_code, 405)\n\n response = self.client.post(url)\n self.assertEquals(response.status_code, 405)\n\n response = self.client.delete(url)\n self.assertEquals(response.status_code, 405)\n","sub_path":"myuw/test/views/rest_dispatch.py","file_name":"rest_dispatch.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"511133741","text":"import os\nimport hashlib\nimport webapp2\nimport json\nfrom google.appengine.api import namespace_manager\n\nfrom api.company.models import Company\n\nclass add(webapp2.RequestHandler):\n\t\"\"\" Adds a new company.\n\t\"\"\"\n\tdef post(self):\n\t\tresponse = None\n\n\t\tinput_doc = json.loads(self.request.body)\n\t\t\n\t\tnew_company = Company(\n\t\t\tname = input_doc['name']\n\t\t)\n\t\tnew_company.put()\n\n\t\tresponse = { \n\t\t\t\"meta\": {\n\t\t\t\t\"status\" : 200,\n\t\t\t\t\"message\": \"OK\"\n\t\t\t}, \n\t\t\t\"response\": {\n\t\t\t\t\"key\" : new_company.key.urlsafe()\n\t\t\t}\n\t\t}\n\n\t\tself.response.headers['Content-Type'] = \"application/json\"\n\t\tself.response.out.write(json.dumps(response, sort_keys = False, indent=4))\n\nclass delete(webapp2.RequestHandler):\n\t\"\"\" Deletes and existing company\n\t\"\"\"\n\tdef delete(self, input_urlkey):\n\t\tresponse = None\n\t\tself.response.out.write(Company().delete(input_urlkey))\n\n\t\tresponse = { \n\t\t\t\"meta\": {\n\t\t\t\t\"status\" : 200,\n\t\t\t\t\"message\": \"OK\"\n\t\t\t}, \n\t\t\t\"response\": {\n\t\t\t\t\"id\" : new_company.id\n\t\t\t}\n\t\t}\n\n\t\tself.response.headers['Content-Type'] = \"application/json\"\n\t\tself.response.out.write(json.dumps(response, sort_keys = False, indent=4))\n\nclass get_list(webapp2.RequestHandler):\n\t\"\"\" Returns a list of all companies.\n\t\"\"\"\n\tdef get(self):\n\t\tresponse = None\n\n\t\tcompanies = Company().get_list()\n\n\t\tif companies[0] == 200:\n\t\t\tresponse = {\n\t\t\t\t\"meta\" : {\n\t\t\t\t\t\"status\":200, \n\t\t\t\t\t\"message\":\"OK\"\n\t\t\t\t},\n\t\t\t\t\"response\" : { \"companies\" : companies[1] }\n\t\t\t}\n\t\telse:\n\t\t\tresponse = {\n\t\t\t\t\"meta\" : {\n\t\t\t\t\"status\": companies[0], \n\t\t\t\t\"message\": companies[1]\n\t\t\t\t}\n\t\t\t}\n\n\t\tself.response.headers['Content-Type'] = \"application/json\"\n\t\tself.response.out.write(json.dumps(response, sort_keys = False, indent=4))\n\nclass get_info(webapp2.RequestHandler):\n\t\"\"\" Returns information about a company.\n\t\"\"\"\n\tdef get(self, input_urlkey):\n\t\tesponse = None\n\n\t\tcompanies = Company().by_id(input_urlkey)\n\n\t\tif companies[0] == 200:\n\t\t\tresponse = {\n\t\t\t\t\"meta\" : {\n\t\t\t\t\t\"status\":200, \n\t\t\t\t\t\"message\":\"OK\"\n\t\t\t\t},\n\t\t\t\t\"response\" : { \"companies\" : companies[1] }\n\t\t\t}\n\t\telse:\n\t\t\tresponse = {\n\t\t\t\t\"meta\" : {\n\t\t\t\t\"status\": companies[0], \n\t\t\t\t\"message\": companies[1]\n\t\t\t\t}\n\t\t\t}\n\n\t\tself.response.headers['Content-Type'] = \"application/json\"\n\t\tself.response.out.write(json.dumps(response, sort_keys = False, indent=4))\n\nclass search(webapp2.RequestHandler):\n\t\"\"\" Retuns a lit of studies that match the given search string.\n\t\"\"\"\n\tdef get(self, search_string):\n\t\tself.response.out.write('{\"return\":\"SEARCH\", \"value\":\"' + id + '\"}')\n\t\t","sub_path":"api/company/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"630663872","text":"import requests\nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nfrom bs4 import BeautifulSoup\nfrom lxml import etree\nfrom time import sleep\nfrom concurrent.futures import ProcessPoolExecutor\nlinks = []\n\nheader = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36\"}\n\ndef GetDownloadLink():\n for i in range(2, 40):\n url = \"http://111av.org/list/4-{}.html\".format(i)\n response = requests.get(url,headers=header,verify=False)\n if response.status_code == 200:\n html = etree.HTML(response.text)\n for j in range(1,15):\n hrefs = html.xpath(u'/html/body/div[1]/div[6]/div[2]/div[2]/ul/li[{}]/div/h2/a'.format(j))\n for href in hrefs:\n yield href.attrib['href']\n\ndef GetDownload():\n for i in GetDownloadLink():\n href_2nd_level = \"http://111av.org/\"+i\n response2 = requests.get(href_2nd_level,headers=header,verify=False)\n response2.encoding = 'utf-8'\n html = etree.HTML(response2.text)\n title = html.xpath(u'/html/body/div[1]/div[6]/div[1]/div[3]/h1')\n resource = html.xpath(u'/html/body/div[1]/div[6]/div[2]/div/ul/li[1]/a')\n for m,n in zip(title,resource):\n print(m.text,\" # \",n.attrib['href'])\n\n\n\n\n\n\nif __name__ == \"__main__\":\n GetDownload()\n # with ProcessPoolExecutor(max_workers=10) as pool:\n # for i in range(2, 40):\n # url = \"http://111av.org/list/4-{}.html\".format(i)\n # pool.submit(GetDownload)\n","sub_path":"Python_Practise/pa_111av.py","file_name":"pa_111av.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"329898876","text":"#encoding:utf-8\n\nfrom utils import get_url\n\n\nt_channel = '@r_fantheories'\nsubreddit = 'fantheories'\n\n\ndef send_post(submission, r2t):\n what, url, ext = get_url(submission)\n title = submission.title\n link = submission.shortlink\n text = '{t}\\n{l}'.format(t=title, l=link)\n\n if what == 'text':\n punchline = submission.selftext\n text = '{t}\\n\\n{p}\\n\\n{l}'.format(t=title, p=punchline, l=link)\n return r2t.send_text(text)\n elif what == 'other':\n base_url = submission.url\n text = '{t}\\n{b}\\n\\n{l}'.format(t=title, b=base_url, l=link)\n return r2t.send_text(text)\n elif what == 'album':\n base_url = submission.url\n text = '{t}\\n{b}\\n\\n{l}'.format(t=title, b=base_url, l=link)\n r2t.send_text(text)\n r2t.send_album(url)\n return True\n elif what in ('gif', 'img'):\n return r2t.send_gif_img(what, url, ext, text)\n else:\n return False\n","sub_path":"channels/r_fantheories/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"385934613","text":"import os\nimport discord\nimport time\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.constants as cts\nfrom dotenv import load_dotenv\nfrom discord.ext import tasks\nfrom PIL import Image\nfrom io import StringIO\nfrom contextlib import redirect_stdout\n\n# Command keys\n# =========================================================================\n\ntex_cmd = \"tex>\"\nbot_cmd = \"bot>\"\ncts_cmd = \"cts>\"\nptn_cmd = \"python>\"\n\n# Configuration for rendering latex\n# =========================================================================\n\nplt.rcParams.update({\n \"text.usetex\": True,\n \"font.family\": \"sans-serif\",\n \"font.sans-serif\": [\"Helvetica\"],\n \"font.size\": 20})\n\nplt.style.use('dark_background')\n\n\ndef latex_render(message):\n\n output_file = \"reply.png\"\n\n fig,ax = plt.subplots(figsize=(3, 2), dpi=300)\n ax.text(0, 0, message.replace(tex_cmd+\" \", \"\"), va=\"center\", ha=\"center\")\n ax.set_xlim(-4,4)\n ax.set_ylim(-1,1)\n ax.axis(\"off\")\n plt.savefig(output_file, transparent=True)\n\n padding = 20.0\n padding = np.asarray([-1, -1, 1, 1]) * padding\n\n with Image.open(output_file) as im:\n\t\n imageBox = im.getbbox()\n imageBox = tuple(np.asarray(imageBox) + padding)\n cropped = im.crop(imageBox)\n cropped.save(output_file)\n\n#=========================================================================\n\n\ndef find_constant(message):\n\n constants = cts.find(message.replace(cts_cmd+\" \", \"\"))\n \n if constants != []:\n\n table = [\"{}\\t{} {}\".format(c, cts.value(c), cts.unit(c)) for c in constants]\n table = \"\\n\".join(table)\n return table\n\n else:\n\n return \"No hubo resultados\"\n\n\ndef pass_to_python(message):\n\n output = StringIO()\n\n with redirect_stdout(output):\n \n exec(message.replace(ptn_cmd, \"\"), {})\n\n return output.getvalue()\n\nbotzmann = discord.Client()\n\nload_dotenv()\ntoken = os.getenv(\"TOKEN\")\nadmin_id = int(os.getenv(\"ADMIN_ID\"))\nserver_id = int(os.getenv(\"SERVER_ID\"))\nannouncements_channel_id = int(os.getenv(\"ANNOUNCEMENTS_CHANNEL_ID\"))\nclass_channel_id = int(os.getenv(\"CLASS_CHANNEL_ID\"))\ntesting_channel_id = int(os.getenv(\"TESTING_CHANNEL_ID\"))\n\n\n# Schedule\nclass_days = [\"Mon\", \"Wed\", \"Fri\"]\nstart_hour = \"09:50\"\nend_hour = \"12:10\"\ntolerance = datetime.timedelta(minutes=40)\n\n# For Testing\nif False:\n class_days.append(time.strftime(\"%a\"))\n start_hour = datetime.datetime.now() + datetime.timedelta(minutes=1)\n end_hour = start_hour + datetime.timedelta(minutes=2)\n start_hour = start_hour.strftime(\"%H:%M\")\n end_hour = end_hour.strftime(\"%H:%M\")\n\n\ndef is_not_holiday():\n\n today = time.strftime(\"%d %b\")\n\n holidays = [line.strip() for line in open(\"holidays.txt\", \"r\")]\n\n return not (today in holidays)\n\n\ndef is_class_starting(class_days, start_hour):\n\n now = time.strftime(\"%H:%M\")\n today = time.strftime(\"%a\")\n\n return (today in class_days) and (now == start_hour) and is_not_holiday()\n\n\ndef is_class_ending(class_days, end_hour):\n\n now = time.strftime(\"%H:%M\")\n today = time.strftime(\"%a\")\n\n return (today in class_days) and (now == end_hour) and is_not_holiday()\n\n\n instructions = message.replace(bot_cmd, \"\")\n\n\n\"\"\"\n@tasks.loop(minutes=1)\nasync def check_schedule():\n\n if is_class_starting(class_days, start_hour):\n\n print(\"Class starting on\", time.strftime(\"%d %b %y\"))\n\n global invitation\n\n point_up = \"☝️\"\n invitation = \"Hola, la ayudantía comenzará pronto.\"\n invitation += \"Para asistir pica la manita y pasa a\"\n invitation += class_channel.mention\n invitation += \". Tienes hasta las **10:30 AM** para ingresar\"\n\n # invitation = await testing_channel.send(invitation)\n invitation = await announcements_channel.send(invitation)\n await invitation.add_reaction(point_up)\n\n if is_class_ending(class_days, end_hour):\n\n await class_channel.send(\"La ayundantía ha acabado\")\n\n [await member.remove_roles(nerd_role) for member in members_list]\n await class_channel.purge(limit=None)\n\"\"\"\n\n\n@botzmann.event\nasync def on_ready():\n\n print(\"Logged on\", time.strftime(\"%d %b %y\"))\n\n global server\n server = botzmann.get_guild(server_id)\n\n global admin\n admin = await botzmann.fetch_user(admin_id)\n\n global members_list\n members_list = await server.fetch_members().flatten()\n\n global class_channel\n class_channel = botzmann.get_channel(class_channel_id)\n\n global announcements_channel\n announcements_channel = botzmann.get_channel(announcements_channel_id)\n\n global testing_channel\n testing_channel = botzmann.get_channel(testing_channel_id)\n\n global nerd_role\n nerd_role = discord.utils.get(server.roles, name=\"Nerd\")\n\n [await member.remove_roles(nerd_role) for member in members_list]\n\n await check_schedule.start()\n\n\n@botzmann.event\nasync def on_reaction_add(reaction, user):\n\n if (user != botzmann.user) and (invitation == reaction.message):\n\n print(user.display_name, \"is here\")\n await user.add_roles(nerd_role)\n\n\n@botzmann.event\nasync def on_message(message):\n\n author_name = message.author.display_name\n origin = message.channel\n\n if message.author == botzmann.user:\n\n return\n\n elif message.content.startswith(tex_cmd):\n\n print(\"LaTeX render called\")\n latex_render(message.content)\n if os.path.exists(\"reply.png\"):\n\n await origin.send(\n \"**\" + author_name + \"** dice:\", file=discord.File(\"reply.png\")\n )\n\n os.remove(\"reply.png\")\n\n else:\n\n await origin.send(\n author_name + \", no pude compilar tu mensaje. Vúelvelo a intentar\"\n )\n\n elif message.content.startswith(cts_cmd):\n\n print(\"Looking for contants with scipy\")\n\n await origin.send(find_constant(message.content))\n\n elif message.content.startswith(ptn_cmd):\n\n await origin.send(pass_to_python(message.content))\n\n # TODO add a few more commands\n elif message.content.startswith(\"bot> purge!\") and message.author == admin:\n\n await origin.purge(limit=None)\n\n else:\n\n pass\n\n\nbotzmann.run(token)\n","sub_path":"botzmann.py","file_name":"botzmann.py","file_ext":"py","file_size_in_byte":6194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"415430799","text":"import sqlite3\r\nimport time\r\n\r\n# Housekeeping. Update relevancy of jobs.\r\n\r\n# Connect to database.\r\nconn = sqlite3.connect('C:/sqllite/jobs')\r\ncur = conn.cursor()\r\n\r\n# Update relevant flag to true for particular job titles.\r\ntitles = ['bi ', 'data analyst', 'data sci', 'data engineer', 'business intelligence', 'analytics', 'data modeller',\r\n 'python', 'big data', 'teradata', 'machine learning', 'data architect', 'data consultant'];\r\nfor title in titles:\r\n try:\r\n cur.execute(\"UPDATE jobs SET relevant = 1 WHERE lower(title) like ?\", ('%' + title + '%',))\r\n conn.commit();\r\n except Exception as e:\r\n print(\"Failed to write to DB\")\r\n print(e)\r\nconn.close()","sub_path":"housekeeping.py","file_name":"housekeeping.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"652517397","text":"#!/usr/bin/env python3.8\n\"\"\"\nCreated on 15/11/2020\n@author: Jiacheng Wu, jcwu@pku.edu.cn\n\"\"\"\n\nimport numpy as np\nimport netCDF4 as nc\nimport ode_solver\nimport pde_solver\nimport plot_data\nimport Finite_Volume_Method as fv\n\ndef init(n=256):\n x_grid = pde_solver.generate_grid(xb, n)\n y = np.zeros(n)\n ic = 2\n \"\"\"\n ic: The identifier of initial condition\n 1: Square wave\n 2: Sine\n 3: Gaussian \n \"\"\"\n if ic == 1:\n y[int(0.4*n):int(0.6*n)] = 1.0\n elif ic == 2:\n y = np.sin(np.deg2rad(x_grid))\n elif ic == 3:\n y = np.exp(-(x_grid - xb/2)**2 / (2*(0.2*xb/2)**2))\n return x_grid, y\n\n\ndef init_nc():\n file_path = './ic_homework3.nc'\n file_obj = nc.Dataset(file_path)\n x_deg = file_obj.variables['x_deg'][:]\n x_rad = file_obj.variables['x_rad'][:]\n y = file_obj.variables['N'][:]\n return x_deg, x_rad, y\n\n\ndef tend_fd(y):\n if pde_scheme == 1:\n pypx = pde_solver.centraldiff2_1d(y, dx)\n elif pde_scheme == 2:\n pypx = pde_solver.centraldiff4_1d(y, dx)\n else:\n print(\"Undefined identifier: (pde_scheme) is undefined!!\")\n raise SystemExit\n return -u0*pypx\n\n\ndef tend_psm(y):\n c = np.fft.fft(y)\n for k in range(kmax):\n c[k] = c[k] * jj * k * (2*np.pi/nx)\n c[-k] = c[-k] * jj * (-k) * (2*np.pi/nx)\n c[kmax] = c[kmax] * jj * kmax * (2*np.pi/nx)\n pypx = np.fft.ifft(c)\n return -u0*pypx.real\n\n\ndef tend_fv(y):\n pypt = fv.fv_superb(y, dx, u0, co)\n return pypt\n\n\nif __name__ == '__main__':\n nx = 360\n xb = 360 # unit: degree\n test = False\n save = False\n if test:\n x, y0 = init(nx)\n else:\n x, x_r, y0 = init_nc()\n # print(\"x = \", x)\n # print(\"y0 = \", y0)\n dx = x[1] - x[0]\n dt = 0.02 # unit: day\n steps = 1800\n u0 = 10 # unit: degree/day\n kmax = int(nx/2)\n jj = (0+1j) # The imaginary unit\n ode_scheme = \"rk4\"\n pde_scheme = 2\n\n co = u0*dt/dx\n try:\n if co < 1:\n print(\"The CFL condition is satisfied, with Courant Number = \", u0*dt/dx)\n except Exception:\n print(\"The CFL condition is violated!!\")\n raise SystemExit\n\n print(\"\\n Method 1: Finite Difference\")\n FD = ode_solver.Ode(y0, tend_fd, dt, steps, debug=0)\n FD.integrate(ode_scheme)\n\n print(\"\\n Method 2: Pseudo Spectral Method\")\n PSM = ode_solver.Ode(y0, tend_psm, dt, steps, debug=0)\n PSM.integrate(ode_scheme)\n\n print(\"\\n Method 3: Finite Volume Method\")\n FV = ode_solver.Ode(y0, tend_fv, dt, steps, debug=0)\n FV.integrate(scheme=\"forward\")\n print(FV.trajectory[-1, :])\n\n # ---------------------------------------\n # Plotting\n # ---------------------------------------\n plot_data.plot_2d(4, x,\n (y0, FD.trajectory[-1, :],\n PSM.trajectory[-1, :], FV.trajectory[-1, :]),\n color=('y', 'r', 'b', 'g'), lw=(5, 2, 2, 2),\n lb=(\"Analytic\", \"FD\", \"PSM\", \"FV\"), ti=\"Plot\", xl=\"Longitude\", yl=\"N\",\n xlim=(0, 360), ylim=(-0.25, 1.25),\n fn=\"plot_compare_method.pdf\", sa=save)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"639583827","text":"from Rk2_Classes import *\r\nfrom os import system\r\nfrom unittest import main\r\n\r\ndef word_in_orchestra_search(orchestras_list, conductors_list, orchestras_dict, word):\r\n for i in range(len(orchestras_list)):\r\n if word in orchestras_list[i].name:\r\n conductors_list.extend(orchestras_dict[i])\r\n yield orchestras_list[i]\r\n\r\ndef return_conductors(storage, conductors_list):\r\n for i in range(len(conductors_list)):\r\n yield storage.return_conductor_by_id(conductors_list[i])\r\n\r\ndef show_middle_salary_list(orcestra_list, average_salaries_list):\r\n for i in range(len(average_salaries_list)):\r\n orcestra_id = average_salaries_list[i][1]\r\n yield {\"название\": orcestra_list[orcestra_id].show(False),\r\n \"id\": \"(id = \" + str(orcestra_id) + \")\",\r\n \"срзп\": average_salaries_list[i][0]\r\n }\r\n\r\ndef check_conductures_first_letter(conductors_list, orcestra_list, letter):\r\n for i in range(len(conductors_list)):\r\n if letter == (conductors_list[i].sername)[0]:\r\n orcestra_id = conductors_list[i].orchestra_id\r\n yield {\"фио\": conductors_list[i].show(False),\r\n \"id\": \"(id = \" + str(conductors_list[i].conductor_id) + \")\",\r\n \"оркестр\": orcestra_list[orcestra_id].name,\r\n \"фамилия\": conductors_list[i].sername\r\n }\r\n\r\ndef main1():\r\n S = Storage()\r\n \r\n #Создаем оркестры:\r\n S.add_orchestra([Orchestra(\"Малый симфонический\"), Orchestra(\"Практикантов (малый)\"), Orchestra(\"Большой симфонический\"), Orchestra(\"Очень малый малый\")])\r\n new_orchestra = Orchestra(\"Не знаю, как назвать :<\")\r\n S.add_orchestra([new_orchestra])\r\n \r\n #Создаем дирижеров:\r\n S.add_conductor([Conductor(0, \"Иван\", \"Крылов\", \"Матвеевич\", 250000), Conductor(0, \"Григорий\", \"Авдеев\", \"Артемович\", 300000)], 0)\r\n S.add_conductor([Conductor(1, \"Troll\", \"Face\", \"Memow\", 15000), Conductor(1, \"V\", \"Анонимный\", \"Anonimous\", 1830000)], 1)\r\n S.add_conductor([Conductor(2, \"Василий\", \"Шуткин\", \"Тотсамович\", 257000), Conductor(2, \"Товарищ\", \"Майор\", \"Вездесущевич\", 100)], 2)\r\n S.add_conductor([Conductor(S.find_orcestra_by_name(\"Очень малый малый\"), \"Антон\", \"Антонов\", \"Михеевич\", 248000)], \r\n S.find_orcestra_by_name(\"Очень малый малый\"))\r\n S.add_conductor([Conductor(S.find_orcestra_by_name(\"Очень малый малый\"), \"Рептилоид\", \"Мировопорядков\", \"Иллюминатович\", 248000)], \r\n S.find_orcestra_by_name(\"Не знаю, как назвать :<\"))\r\n\r\n #================================[E1]================================#\r\n workers_list = [] #Лист дирижеров оркестров, удовлетворяющих требованию\r\n\r\n #Выведем все оркестры, в названия которых входит слово \"малый\"(c учетом регистра)\r\n print(\"Оркестры, содержащие в названии слово \\\"малый\\\" (с учетом регистра):\")\r\n for i in word_in_orchestra_search(S.orchestras_list, workers_list, S.orchestras_dict, \"малый\"):\r\n i.show(); print(\"; \", end =\"\")\r\n\r\n #И всех дирижеров этих оркестров:\r\n print(\"\\n\\nДирижеры этих оркестров:\")\r\n for i in return_conductors(S, workers_list):\r\n i.show(); print(\"; \", end=\"\")\r\n\r\n #================================[E2]================================#\r\n #Рассчитаем среднюю зарплату и занесем во вложенный список:\r\n print(\"\\n\\n\\nОркестры по возрастанию средней зарплаты в них:\")\r\n average_salaries_list = S.count_average_salary()\r\n\r\n #Выведем его:\r\n for i in show_middle_salary_list(S.orchestras_list, average_salaries_list):\r\n print(\"%-26s%-9s%-3s%6d%7s\" % (i[\"название\"], i[\"id\"], \"->\", i[\"срзп\"], \"рублей\"))\r\n \r\n #================================[E3]================================#\r\n #Выведем список всех дирижеров, чья фамилия начинается на А и названия их отделов:\r\n print(\"\\n\\n\\nСписок всех дирижеров, чья фамилия начинается на А и их названия оркестров:\")\r\n for i in check_conductures_first_letter(S.conductors_list, S.orchestras_list, \"А\"):\r\n print(\"%-16s%-9s%-9s%6s\" % (i[\"фио\"], i[\"id\"], \"оркестр:\", i[\"оркестр\"]))\r\n\r\nif __name__ == \"__main__\":\r\n #main1()\r\n #system(\"pause\")\r\n main()\r\n","sub_path":"Rk2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"289250319","text":"'''\nCreated on 16.12.2016\n\n@author: Marius\n'''\n\n#Import libraries\nimport requests, json, struct #to communicate with the camera, send json objects, structs\nfrom pygame import image\nimport io\nfrom PIL import Image\nfrom urllib.request import urlopen\nfrom SonyPhotobooth.Input import getKey\n\nclass CameraConnectionError(Exception):\n pass\n\nclass SonyCamera():\n \n def __init__(self,url,pygame,Ser,Keys,numKeys):\n self.url = url\n self.pygame = pygame\n self.Ser = Ser\n self.Keys = Keys\n self.numKeys = numKeys\n self.connected = False\n self.recMode = False\n pass\n \n #Checks if reachable\n #def checkStatus(self):\n\n # Camera communication\n def postMethod(self,method,par = []): #general postMethod for communication with camera\n \n payload = {'method': method, 'params': par, 'id': 1, 'version': '1.0'}\n data = json.dumps(payload)\n \n while True:\n try:\n respReq = requests.post(self.url, data=data).json()\n self.connected = True\n try:\n resp = respReq.get('result')[0]\n break\n except:\n return\n except:\n self.connected = False\n print('Coudln''t connect. Retry in 3s. Press Exit-Key to stop trying.')\n Clock = self.pygame.time.Clock()\n ticksStart = self.pygame.time.get_ticks() #ticks for moment of start (=ms)/(1000ms/s))\n \n while self.pygame.time.get_ticks()-ticksStart<3000:\n Clock.tick(30)\n if (getKey(self.pygame,self.Ser,self.Keys,self.numKeys) == self.numKeys-1):\n print('Exit-Key pressed.')\n raise SystemExit\n \n print('Try reconnecting.')\n \n return str(resp)\n \n def startRecMode(self):\n \n print('Starting recording mode.')\n self.postMethod('startRecMode',[])\n \n def startLiveview(self): #start camera liveview\n \n print('Starting liveview.')\n self.link = self.postMethod('startLiveview',[])\n \n def takePhoto(self): #take one image and receive it\n \n method = 'actTakePicture'\n par = []\n \n payload = {'method': method, 'params': par, 'id': 1, 'version': '1.0'}\n data = json.dumps(payload)\n resp = requests.post(self.url, data=data).json()\n resCon = str(resp.get('result')[0][0]) #[0][0] instead of [0]\n \n byteRes = io.BytesIO(urlopen(resCon).read());\n photo = Image.open(byteRes)\n \n return photo\n \n def readImgBytes(self,stream):\n \n data = stream.read(136)\n size = struct.unpack('>i',b'\\x00'+data[12:15])[0] #Take relevant bytes\n imgData = stream.read(size)\n pygameImg = image.load(io.BytesIO(imgData))\n \n return pygameImg","sub_path":"SonyPhotobooth/CamCon.py","file_name":"CamCon.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"71239709","text":"from django.template.loader import get_template,render_to_string\nfrom django.core.mail import send_mail,EmailMultiAlternatives\nfrom django.shortcuts import render,redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom django.http import JsonResponse\nfrom datetime import datetime,timedelta,date\nfrom . import forms as f\nimport cliente.models as m\nfrom . import models as mCita\nfrom cliente import models as mCliente\nfrom creditos import models as mCreditos\nfrom django.db.models import Q\nfrom django.conf import settings\n\n\n# Create your views here.\n\n@login_required(redirect_field_name='login:login')\ndef agenda(request,idAsesorCliente):\n if request.user.persona.idRol.pk == 2 or request.user.persona.idRol.pk == 3:\n if request.method == \"POST\":\n fecha = request.POST.get(\"fecha\",None)\n tipoCita = request.POST.get(\"idTipoCita\",None)\n hora = request.POST.get(\"hora\",None)\n fecha = fecha+\" \"+hora\n fecha = datetime.strptime(fecha,\"%Y-%m-%d %H:%M\")\n direccion = request.POST.get(\"direccionCita\",None)\n descripcion = request.POST.get(\"descripcion\",None)\n estado = mCita.CatEstatuscita.objects.get(pk=1)\n tipoCita = mCita.CatTipocita.objects.get(pk=int(tipoCita))\n asesorCliente = mCliente.AsesorCliente.objects.get(pk=idAsesorCliente)\n creditos = mCreditos.Creditos.objects.filter(idAsesor=request.user,activo=True)\n tiene = 0\n if not asesorCliente.credito:\n if creditos:\n credito = mCreditos.Creditos.objects.filter(pk=creditos[0].pk)\n credito.update(\n activo = False,\n fechaActualizacion = date.today(),\n )\n else:\n messages.add_message(request, messages.ERROR, 'Regala más experiencias, adquiere tus creditos en el gestor de experiencias.')\n return redirect('agenda:contactos')\n else:\n tiene = 1\n\n cita = mCita.Cita(\n idAsesorCliente = asesorCliente,\n idTipoCita = tipoCita,\n idEstatus = estado,\n direccionCita = direccion,\n descripcion = descripcion,\n fecha = fecha,\n activada = True,\n )\n if tiene == 1:\n mCliente.AsesorCliente.objects.filter(pk=idAsesorCliente).update(\n fecha = fecha,\n estatusCita = str(estado.pk),\n )\n else:\n mCliente.AsesorCliente.objects.filter(pk=idAsesorCliente).update(\n fecha = fecha,\n estatusCita = str(estado.pk),\n credito = credito[0],\n )\n cita.save()\n mail_from = settings.EMAIL_HOST_USER\n mail_to = [asesorCliente.idCliente.user.email]\n\n if direccion == \"\":\n lugar = \"en línea: \"\n else:\n lugar = direccion\n\n ctx = {\n 'fecha':fecha,\n 'lugar': lugar,\n 'nombre_asesor':request.user.first_name + \" \" + request.user.last_name,\n }\n try:\n html_content = render_to_string('../templates/mails/cita.html',ctx)\n msg = EmailMultiAlternatives(\"!Confirmación reunión, vive tu futuro!\",\"\", mail_from,mail_to)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n messages.add_message(request, messages.SUCCESS, 'La experiencia se agendó correctamente.')\n except:\n messages.add_message(request, messages.WARNING, 'Hubo un error al mandar el correo, por favor verifícalo con tu cliente.')\n \n return redirect('agenda:contactos')\n else:\n cita = f.agendaForm()\n context = {\n \"cita\":cita,\n }\n return render(request,\"agenda/agenda.html\",context)\n else:\n return render(request,'error/404.html')\n\n@login_required(redirect_field_name='login:login')\ndef contactos(request):\n if request.user.persona.idRol.pk == 2 or request.user.persona.idRol.pk == 3:\n asesorClientes = m.AsesorCliente.objects.filter(idAsesor=request.user.id,activo=True)\n cita = []\n sin_agendar = []\n dia = datetime.today().strftime(\"%Y-%m-%d\")\n if asesorClientes:\n for i in range(0,len(asesorClientes)):\n\n try:\n citas = mCita.Cita.objects.get(idAsesorCliente=asesorClientes[i], fecha=asesorClientes[i].fecha, activada=True)\n if citas.activada == True:\n if citas.fecha.strftime(\"%Y-%m-%d\") >= dia:\n cita.append(citas)\n else:\n citas = mCita.Cita.objects.filter(idAsesorCliente=asesorClientes[i], fecha=asesorClientes[i].fecha)\n citas.update(\n activada = False,\n )\n sin_agendar.append(asesorClientes[i])\n else:\n sin_agendar.append(asesorClientes[i])\n except:\n sin_agendar.append(asesorClientes[i])\n\n if len(sin_agendar) == 0:\n bien = 1\n else:\n bien = 0\n else:\n bien = 2\n context = {\n \"clientes\":asesorClientes,\n \"sin_cita\":sin_agendar,\n \"citas\":cita,\n \"bien\":bien,\n }\n return render(request,\"agenda/contactos.html\",context)\n else:\n return render(request,'error/404.html')\n\n@login_required(redirect_field_name='login:login')\ndef editar(request,idCita):\n if request.user.persona.idRol.pk == 2 or request.user.persona.idRol.pk == 3:\n editar1 = mCita.Cita.objects.get(pk=idCita)\n if request.method == \"POST\":\n if editar1.idEstatus.pk == 1: #Se checa si una cita es nueva.\n editar = mCita.Cita.objects.filter(pk=idCita)\n editar.update(\n activada = False,\n )\n fecha = request.POST.get(\"fecha\",None)\n tipoCita = request.POST.get(\"idTipoCita\",None)\n hora = request.POST.get(\"hora\",None)\n fecha = fecha+\" \"+hora\n fecha = datetime.strptime(fecha,\"%Y-%m-%d %H:%M\")\n direccion = request.POST.get(\"direccionCita\",None)\n descripcion = request.POST.get(\"descripcion\",None)\n estado = mCita.CatEstatuscita.objects.get(pk=2)\n tipoCita = mCita.CatTipocita.objects.get(pk=int(tipoCita))\n cita = mCita.Cita(\n idAsesorCliente = editar1.idAsesorCliente,\n idTipoCita = tipoCita,\n idEstatus = estado,\n direccionCita = direccion,\n descripcion = descripcion,\n fecha = fecha,\n activada = True,\n )\n mCliente.AsesorCliente.objects.filter(pk=editar1.idAsesorCliente.pk).update(\n fecha = fecha,\n estatusCita = str(estado.pk),\n )\n cita.save()\n else: #Si no es nueva entonces se cambia el estado que se busca\n editar = mCita.Cita.objects.filter(pk=idCita)\n fecha = request.POST.get(\"fecha\",None)\n tipoCita = request.POST.get(\"idTipoCita\",None)\n hora = request.POST.get(\"hora\",None)\n fecha = fecha+\" \"+hora\n fecha = datetime.strptime(fecha,\"%Y-%m-%d %H:%M\")\n direccion = request.POST.get(\"direccionCita\",None)\n descripcion = request.POST.get(\"descripcion\",None)\n estado = mCita.CatEstatuscita.objects.get(pk=2)\n tipoCita = mCita.CatTipocita.objects.get(pk=tipoCita)\n editar.update(\n idTipoCita = tipoCita,\n idEstatus = estado,\n direccionCita = direccion,\n descripcion = descripcion,\n fecha = fecha,\n )\n editar = mCita.Cita.objects.get(pk=idCita)\n mCliente.AsesorCliente.objects.filter(pk=editar.idAsesorCliente.pk).update(\n fecha = fecha,\n estatusCita = str(estado.pk),\n )\n messages.add_message(request, messages.SUCCESS, 'La cita se edito correctamente.')\n return redirect('agenda:contactos')\n else:\n cita = f.agendaForm(instance=editar1)\n context = {\n \"cita\":cita,\n }\n return render(request,\"agenda/agenda.html\",context)\n\n else:\n return render(request,'error/404.html')\n\n@login_required(redirect_field_name='login:login')\ndef eliminar(request,idCita):\n if request.user.persona.idRol.pk == 2 or request.user.persona.idRol.pk == 3:\n eliminar = mCita.Cita.objects.filter(pk=idCita)\n estado = mCita.CatEstatuscita.objects.get(pk=4)\n eliminar.update(\n idEstatus = estado,\n activada = False,\n )\n eliminar = mCita.Cita.objects.get(pk=idCita)\n eliminar = mCliente.AsesorCliente.objects.filter(pk=eliminar.idAsesorCliente.pk)\n eliminar.update(\n estatusCita = \"4\",\n )\n return redirect('agenda:contactos')\n else:\n return render(request,'error/404.html')\n\n@login_required(redirect_field_name='login:login')\ndef hoy(request):\n if request.user.persona.idRol.pk == 2 or request.user.persona.idRol.pk == 3:\n asesorClientes = mCliente.AsesorCliente.objects.filter(idAsesor=request.user.id)\n hoy1 = []\n iterar = 0\n dia = datetime.today().strftime(\"%Y-%m-%d\")\n for i in asesorClientes:\n try:\n if i.fecha.strftime(\"%Y-%m-%d\") == dia and i.estatusCita != \"4\" and i.estatusCita != \"3\":\n hoy1.append(mCita.Cita.objects.get(idAsesorCliente=i,fecha=i.fecha,activada=True))\n except:\n pass\n context = {\n \"hoy1\":hoy1,\n }\n return render(request,\"agenda/hoy.html\",context)\n else:\n return render(request,'error/404.html')\n\n@login_required(redirect_field_name='login:login')\ndef historial(request):\n if request.user.persona.idRol.pk == 2 or request.user.persona.idRol.pk == 3:\n asesorClientes = mCliente.AsesorCliente.objects.filter(idAsesor=request.user.id)\n historial = []\n for i in asesorClientes:\n try:\n historial.append(mCita.Cita.objects.filter(idAsesorCliente=i).order_by('fecha'))\n except:\n pass\n\n context = {\n \"historial\":historial,\n }\n return render(request,\"agenda/historial.html\",context)\n else:\n return render(request,'error/404.html')\n\n@login_required(redirect_field_name='login:login')\ndef calendario(request):\n if request.user.persona.idRol.pk == 2 or request.user.persona.idRol.pk == 3:\n asesorClientes = m.AsesorCliente.objects.filter(idAsesor=request.user.id)\n cita = []\n hora = []\n minutos = []\n for a in asesorClientes:\n cita.append(mCita.Cita.objects.filter(idAsesorCliente = a.pk))\n \n context = {\n \"cita\":cita,\n }\n return render(request,\"agenda/calendario.html\",context)\n else:\n return render(request,'error/404.html')\n","sub_path":"agenda/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"188717248","text":"import json\nimport requests\nfrom lxml import etree\n\nheaders ={\n 'Intervention': '; level=\"warning\"',\n 'Referer':'http://yuedu.sogou.com/search?keyword=%E6%96%97%E7%BD%97%E5%A4%A7%E9%99%86',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'\n}\n\n\n\ndef fun1(url,bookname):\n res = requests.get(url=url, headers=headers).text\n ele = etree.HTML(res)\n bname = ele.xpath('//*[@id=\"content\"]/div[3]/ul/li[1]/div[2]/h4/span/a/span/text()')[0]\n if bookname != bname:\n f = input('查询结果最高相似度的是'+bname+',是否阅读,输入y或者n')\n if f == 'y':\n bookurl = ele.xpath(\"//ul[@class='sort_list']/li[@class='even'][1]/div[@class='sort_list_thumb']/a/@href\")[0]\n bookurl = 'http://yuedu.sogou.com/ajax' + bookurl[0:-14]\n fun2(bookurl)\n else:\n return '拜拜!'\n\n else:\n print('找到了你所说的书籍,正在存储')\n bookurl = ele.xpath(\"//ul[@class='sort_list']/li[@class='even'][1]/div[@class='sort_list_thumb']/a/@href\")[0]\n bookurl = 'http://yuedu.sogou.com/ajax' + bookurl[0:-14]\n fun2(bookurl)\n\ndef fun2(bookurl):\n res = requests.get(url=bookurl, headers=headers).text\n res = json.loads(res)\n for i in range(len(res['dir']['chapters'])):\n a = res['dir']['chapters'][i]['href'][11:].split(sep='/')[0]\n b = res['dir']['chapters'][i]['href'][11:].split(sep='/')[1]\n sectionurl = \"http://yuedu.sogou.com/ajax/user/buy/?bkey=\"+a+\"&ckey=\"+b+\"&buy=0&auto=0&_=1565348681263\"\n print(sectionurl)\n fun3(sectionurl)\n\ndef fun3(sectionurl):\n try:\n res = requests.get(url=sectionurl, headers=headers).text\n res = json.loads(res)\n title = res[\"detail\"][\"title\"]\n name = res[\"detail\"][\"name\"]\n neirong = res[\"detail\"][\"content\"]\n with open(\"D:/爬虫2/自己/day7/\"+name+\"/\"+title+'.txt','w',encoding='utf-8') as w:\n print('正在保存'+title)\n w.write(title+'\\n'+neirong)\n except:\n print('充钱才能看,整不来')\n\nif __name__ == '__main__':\n # fun1()\n bookname = input('请输入书名')\n url = \"http://yuedu.sogou.com/search?keyword=\" + bookname\n fun1(url,bookname)\n","sub_path":"Replace/晨讲/搜狗阅读.py","file_name":"搜狗阅读.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"565344416","text":"\"\"\"\nImplement Flatten Arrays.\nGiven an array that may contain nested arrays, give a single resultant array.\n\nExample:\n\nInput: var input = [2, 1, [3, [4, 5], 6], 7, [8]]\nflatten(input);\nOutput: [2, 1, 3, 4, 5, 6, 7, 8]\n\nInput: var input = (2, 1, (3, (4, 5), 6), 7, (8))\nflatten(input);\nOutput: [2, 1, 3, 4, 5, 6, 7, 8]\n\"\"\"\n\n# 基于递归的实现方法,isinstance 用于判断参数a是否属于(list, tuple)中的类型的一种,返回bool类型,与type的区别在于会继承判断类型。\ndef list_flat(l, a=None):\n # 如果a为None,创建一个空列表;否则将列表转为List类型\n a = list(a) if isinstance(a, (list, tuple)) else []\n # 遍历列表项中的元素\n for i in l:\n # 遇到仍然是列表项的进行递归\n if isinstance(i, (list, tuple)):\n a = list_flat(i, a)\n # 遇到单个元素的加入到列表a\n else:\n a.append(i)\n return a\n\na = [2, 1, [3, [4, 5], 6], 7, [8]]\nprint(list_flatten(a))\n","sub_path":"array/flatten.py","file_name":"flatten.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"528107010","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os\n\nfrom derrick.core.detector_report import DetectorReport\nfrom derrick.core.rigging import Rigging\nfrom derrick.detectors.general.image_repo import ImageRepoDetector\nfrom derrick.detectors.image.golang import GolangVersionDetector\nfrom derrick.detectors.platform.golang.package_name import PackageNameDetector\n\nGOLANG = \"Golang\"\n\n\nclass GolangRigging(Rigging):\n def detect(self, context):\n cwd = os.getcwd()\n for filename in os.listdir(cwd):\n if filename.endswith(\".go\"):\n return True, GOLANG\n return False, \"\"\n\n def compile(self, context):\n dc = DetectorReport()\n dn = dc.create_node(\"Dockerfile.j2\")\n dn.register_detector(GolangVersionDetector())\n dn.register_detector(PackageNameDetector())\n\n jn = dc.create_node(\"Jenkinsfile.j2\")\n jn.register_detector(ImageRepoDetector())\n\n dcn = dc.create_node(\"docker-compose.yml.j2\")\n dcn.register_detector(ImageRepoDetector())\n return dc.generate_report()\n","sub_path":"derrick/rigging/golang_rigging/golang_rigging.py","file_name":"golang_rigging.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"264243345","text":"no=int(input(\"Enter the no of elements: \"))\r\na=[]\r\nprint(\"Enter the elements of 1st matrix........\")\r\nfor i in range(no):\r\n\ta1=[]\r\n\tfor j in range(no):\r\n\t\ta1.append(int(input(\"Enter the element {0}{1}: \".format(i,j))))\r\n\ta.append(a1)\r\nb=[]\r\nprint(\"Enter the elements of 2nd matrix......\")\r\nfor i in range(no):\r\n\tb1=[]\r\n\tfor j in range(no):\r\n\t\tb1.append(int(input(\"Enter the element {0}{1}: \".format(i,j))))\r\n\tb.append(b1)\r\nresult=[[0,0,0],[0,0,0],[0,0,0]]\r\nmultiply=[[0,0,0],[0,0,0],[0,0,0]]\r\nprint(\"The product of two matrix is.........\")\r\nfor i in range(no):\r\n\tfor j in range(no):\r\n\t\tfor k in range(no):\r\n\t\t\tmultiply[i][j]=a[i][k]*b[k][j]\r\n\t\t\tresult[i][j]+=multiply[i][j]\r\nfor i in range(no):\r\n\tfor j in range(no):\r\n\t\tprint(result[i][j],end=\"\")\r\n\tprint(\"\\r\")\r\n","sub_path":"matrixproduct.py","file_name":"matrixproduct.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"420435987","text":"##-----------Problem 2------------\nbalance = 330\nannualInterestRate = 0.2\n# the able 2 fields are not for edx\nbalancex = balance\nmonthlyInterestRate = annualInterestRate / 12\nstep = 10\nmonthlyPayment = int(round(balance / 12, -1))\nif annualInterestRate == 0:\n print('Lowest Payment:',balance)\nelse:\n while balancex != 0:\n balancex = balance\n i = 1\n unpaid = 0\n for i in range (1,12):\n balancex = balancex - monthlyPayment\n unpaid = balancex + (balancex * monthlyInterestRate)\n balancex = unpaid\n i += 1\n if balancex <= monthlyPayment:\n print('Lowest Payment:',int(monthlyPayment))\n break\n if round(balancex,-1) > 10:\n monthlyPayment += step\n","sub_path":"MITx-6.00.1x/Archive/Problem Set 2 - Prob 2.py","file_name":"Problem Set 2 - Prob 2.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"585697783","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('members', '0011_membershippayment'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='MemberAKA',\n fields=[\n ('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID', primary_key=True)),\n ('aka', models.CharField(max_length=50, help_text='The AKA (probably a simple variation on their name).')),\n ('member', models.ForeignKey(to='members.Member', help_text='The member who has an AKA.', related_name='akas')),\n ],\n ),\n migrations.CreateModel(\n name='MembershipTerm',\n fields=[\n ('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID', primary_key=True)),\n ('membership_type', models.CharField(choices=[('R', 'Regular'), ('W', 'Work-Trade')], default='R', help_text='The type of membership.', max_length=1)),\n ('family_count', models.IntegerField(default=0, help_text='The number of ADDITIONAL family members included in this membership. Usually zero.')),\n ('start_date', models.DateField(help_text='The frist day on which the membership is valid.')),\n ('end_date', models.DateField(help_text='The last day on which the membership is valid.')),\n ('member', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.PROTECT, help_text='The member who made the payment.', to='members.Member', null=True, related_name='terms')),\n ],\n ),\n migrations.RemoveField(\n model_name='membershippayment',\n name='paying_member',\n ),\n migrations.DeleteModel(\n name='MembershipPayment',\n ),\n ]\n","sub_path":"members/migrations/0012_auto_20160109_1803.py","file_name":"0012_auto_20160109_1803.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"1959786","text":"#!/usr/bin/python\nimport os\nimport sys\n\ndef calc_row_value(input_string):\n \"\"\"\n This function takes a string input, converts it to an integer value and\n then outputs a \"new value\".\n ---\n args:\n input_string(str): input string\n returns:\n calc_value (int): output value\n \"\"\"\n\n if type(input_string) != str:\n raise ValueError(\"input_string must be a string type!\")\n\n str_conv = [int(d) for d in input_string if d.isdecimal()]\n calc_value = 0\n for index, digit in enumerate(str_conv):\n num_index = index + 1\n if num_index % 2 != 0:\n calc_value += digit * num_index\n else:\n calc_value -= digit * 5\n return calc_value\n\ninput_string = input(\"Please enter a number to convert:\\n\")\n\nprint(\"The converted number is:\",calc_row_value(input_string))\n","sub_path":"lessons/python_intro/calc_row_value.py","file_name":"calc_row_value.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"303831114","text":"#!/usr/bin/env python3\nimport cx_Oracle\nimport os\nimport openpyxl\n\n\ndef write_excel_xlsx(path, sheet_name, value):\n index = len(value)\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n sheet.title = sheet_name\n for i in range(0, index):\n for j in range(0, len(value[i])):\n sheet.cell(row=i + 1, column=j + 1, value=str(value[i][j]))\n workbook.save(path)\n print(\"xlsx格式表格写入数据成功!\")\n\n\ndef read_excel_xlsx(path, sheet_name):\n workbook = openpyxl.load_workbook(path)\n # sheet = wb.get_sheet_by_name(sheet_name)这种方式已经弃用,不建议使用\n sheet = workbook[sheet_name]\n for row in sheet.rows:\n for cell in row:\n print(cell.value, \"\\t\", end=\"\")\n print()\n\n\ndef query_data():\n os.environ['NSL_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'\n # os.environ['NSL_LANG'] = 'AMERICAN_AMERICA.ZHS16GBK'\n print(os.path)\n\n oracle_tns = 'system/orcl@192.168.128.5:1521/orcl'\n\n conn = cx_Oracle.connect(oracle_tns)\n\n curs = conn.cursor()\n\n sql_path = '/home/microsweet/pythonexercises/oracle/sql.txt'\n with open(sql_path) as file_object:\n contents = file_object.read()\n\n r = curs.execute(contents)\n\n rows = []\n for i in r:\n row = list(i)\n rows.append(row)\n\n for i in rows:\n sql = 'SELECT t.MESSAGE_ FROM GRID_ACTIVIT.ACT_HI_COMMENT t,' \\\n ' GRID_ACTIVIT.ACT_HI_TASKINST n ' \\\n 'WHERE t.TASK_ID_=n.ID_ AND t.PROC_INST_ID_=' \\\n + i[1] + \\\n ' AND n.NAME_=\\'二院处理\\' ORDER BY t.TIME_ DESC'\n n = curs.execute(sql)\n for j in n:\n try:\n i.append(j[0])\n except TypeError:\n i.append('')\n break\n\n curs.close()\n conn.close()\n write_excel_xlsx('/home/microsweet/export.xlsx', 'a', rows)\n print('end')\n\n\nquery_data()\n","sub_path":"oracle/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"633340088","text":"import os\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import KFold\nfrom torchvision import datasets\nimport argparse\n\n\ndef _get_target_indexes(dataset, target_label):\n target_indexes = []\n for index, (_, label) in enumerate(dataset):\n if label == target_label:\n target_indexes.append(index)\n return np.array(target_indexes)\n\n\ndef create_folds(cifar10_root, output_root, n_folds):\n folds_dir = os.path.join(output_root, 'folds', 'cifar10')\n validation_classes_root = os.path.join(output_root, 'validation_classes')\n validation_classes_path = os.path.join(validation_classes_root, 'cifar10.csv')\n\n os.makedirs(validation_classes_root, exist_ok=True)\n os.makedirs(folds_dir, exist_ok=True)\n\n dataset = datasets.CIFAR10(root=cifar10_root, train=True, download=True)\n classes = dataset.classes\n n_classes = len(classes)\n\n \"====================== GENERATE CLASSES FOR VALIDATION ======================\"\n\n if not os.path.exists(validation_classes_path):\n df = pd.DataFrame(columns=['class', 'class_name', 'valid_class', 'valid_class_name'])\n\n for _class in range(n_classes):\n available_classes = list(range(10))\n available_classes.remove(_class)\n\n valid_class = np.random.choice(available_classes)\n df.loc[_class] = [_class, classes[_class], valid_class, classes[valid_class]]\n\n df.to_csv(validation_classes_path, index=False)\n\n \"====================== CREATE K-FOLD CROSS-VALIDATION SPLIT ======================\"\n\n valid_classes_df = pd.read_csv(validation_classes_path)\n valid_classes_df.set_index('class')\n\n for _class in range(n_classes):\n anomaly_class = valid_classes_df.loc[_class]['valid_class']\n\n normal_indexes = _get_target_indexes(dataset, _class)\n valid_anomaly_indexes = _get_target_indexes(dataset, anomaly_class)\n\n normal_train_subindexes, normal_test_subindexes = list(zip(*KFold(n_splits=n_folds).split(normal_indexes)))\n _, anomaly_test_subindexes = list(zip(*KFold(n_splits=n_folds).split(valid_anomaly_indexes)))\n\n for i_fold, (normal_train_subindex, normal_test_subindex, anomaly_test_subindex) in \\\n enumerate(zip(normal_train_subindexes, normal_test_subindexes, anomaly_test_subindexes)):\n fold_dir = os.path.join(folds_dir, str(_class), str(i_fold))\n os.makedirs(fold_dir, exist_ok=True)\n\n np.save(os.path.join(fold_dir, 'test_normal'), normal_indexes[normal_test_subindex])\n np.save(os.path.join(fold_dir, 'test_anomaly'), valid_anomaly_indexes[anomaly_test_subindex])\n\n train_normal_indexes = normal_indexes[normal_train_subindex]\n np.random.shuffle(train_normal_indexes)\n\n val_n = int(0.2 * len(train_normal_indexes))\n val_normal_indexes = train_normal_indexes[:val_n]\n train_normal_indexes = train_normal_indexes[val_n:]\n\n np.save(os.path.join(fold_dir, 'train'), train_normal_indexes)\n np.save(os.path.join(fold_dir, 'val'), val_normal_indexes)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"-i\", \"--cifar10_root\",\n type=str,\n default='./data/data/cifar10',\n help='cifar10_root')\n parser.add_argument(\"-o\", \"--output_root\",\n required=True,\n type=str,\n help='output_root')\n parser.add_argument(\"-n\", \"--n_folds\",\n type=int,\n default=3,\n help='n_folds')\n\n args = parser.parse_args()\n\n cifar10_root = args.cifar10_root\n output_root = args.output_root\n n_folds = args.n_folds\n\n create_folds(cifar10_root, output_root, n_folds)\n","sub_path":"anomaly_detection/utils/preprocessing/create_folds/cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"558024541","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 31 09:53:19 2019\n\n@author: Administrator\n\"\"\"\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom dateutil.parser import parse \nimport pandas as pd\nimport numpy as np\nimport pytz\nnow = datetime.now()\nnow.year, now.month, now.day\ndelta = datetime(2011, 1, 7)-datetime(2008,6,23,8,15)##delta就是一种timedelta类型,表示两个时间之差\ndelta.days#delata.seconds\n\nstart = datetime(2011,1,7)\nstart + timedelta(12)\nstart-2*timedelta\n\nstamp = datetime(2011,1,3)\nstr(stamp)\nstamp.strftime('%Y-%m-%d')#strftime将时间格式变为时间字符串类型的数据\n\nvalue ='2019-1-1'\ndatetime.strptime(value,'%Y-%m-%d')##日期的参数形式必须与时间的形式匹配\ndatestrs = ['7/6/2011','8/6/2011']\n[datetime.strptime(x,'%m/%d/%Y') for x in datestrs ]#strptime结果的形式是(年,月,日,分钟,秒)\nparse('2011-01-03')\nparse('Jan 31, 1997 10:45PM')#输入的字符之间必须有空格,可以解析大部分人类能够看懂的日期\nparse('31/12/2019',dayfirst=True)#在许多国际场合,日期放在月份之前很常见,添加一个dayfirst参数就可以解析这种日期形式\n\n#to_datetime方法的使用\ndatestrs = ['2011-07-06 12:00:00','2011-08-06 00:00:00']\npd.to_datetime(datestrs)\npd.to_datetime(datestrs+[None])#pd.to_datetime可以处理空字符串,显示成NaT字符,表示not a time\n\n#时间序列基础\ndates = [datetime(2011,1,2),datetime(2011,1,5),datetime(2011,1,7),datetime(2011,1,8),\n datetime(2011,1,10),datetime(2011,1,12)]\nts = pd.Series(np.random.randn(6),index=dates)\nts+ts[::2]#不同时间序列之间的算数运运算在日期上自动对齐\nts['1/6/2011':'1/11/2011']#k可以切片,按照日期行标签索引进行切片\nts.truncate(after='1/9/2011')#truncate函数必须应用于排序之后的数据\ndates=pd.date_range('1/1/2000',periods=100,freq='W-WED')\nlong_df = pd.DataFrame(np.random.randn(100,4),index=dates,columns=['colorado','texas','new york','ohio'])\nlong_df.loc['5-2001']\ndates = pd.DatetimeIndex(['1/1/2000','1/2/2000','1/2/2000','1/2/2000','1/3/2000'])\ndup_ts = pd.Series(np.arange(5),index=dates)\ndup_ts.index.is_unique#检验是否为不重复的时间索引\ndup_ts['1/2/2000']#对于Series类型进行切片操作得到的结果是为Sereis类型还是标量值取决于时间戳是否为重复的\n\n#利用向groupby传递参数level=0对非唯一时间戳的数据进行聚合\ngrouped = dup_ts.groupby(level=0)\ngrouped.count\n\n##日期的频率及其移位操作\nresampler = ts.resample('D')\nindex = pd.date_range('2012-04-01','2012-06-01')\npd.date_range(end='2012-04-01',periods=20)\npd.date_range('2000-01-01',periods=10,freq='1h30min')##通过传递频率字符串设置产生额日期频率\nrng = pd.date_range('2012-01-01','2012-09-01',freq='WOM-3FRI')#week of month,freq=‘WOM-3FRI'表示每个月中的第三个星期五\n#移位操作\nts = pd.Series(np.random.randn(4),index=pd.date_range('1/1/2000',periods=4,freq='M'))\nts.shift(2)#值进行移位,索引不变,默认axis=0\nts.shift(2,freq='M')#值不变,索引即日期进行偏移,偏移单位是月,即进行偏移两个月\n\n#时区处理(先本地化在转换为另一时区)\npytz.common_timezones[-5:]\ntz = pytz.timezone('America/New_York')\nrng = pd.date_range('3/9/2012 9:30',periods=6,freq='D')#2012年3月9日\nts = pd.Series(np.random.randn(len(rng)),index=rng)\nts_utc = ts.tz_localize('America/New_York')#将简单时间序列转换为本地时间\nto_eastern = ts_utc.tz_convert('UTC')#将本地化时间转换为特定国家的时间\n\nrng = pd.date_range('3/7/2012 9:30',periods=10,freq='B')\nts = pd.Series(np.random.randn(len(rng)),index=rng)\nts1 = ts[:7].tz_localize('Europe/London')\nts2 = ts1[2:].tz_convert('Europe/Moscow')\nresult = ts1 + ts2\n\n#时间区间参数:利用函数Period实现,表示时间区间\np = pd.Period(2007,freq='A-DEC')\npd.Period('2014',freq='A-DEC')-p#频率相同的时间区间可以完成减法操作得到单位数\n#重新采样和频率转换\n#向下采样\nrng = pd.date_range('2000-01-01',periods=12,freq='T')\nts = pd.Series(np.random.randn(len(rng)),index=rng)\nts.resample('5min',closed='right').sum()#计算每一组的加和将这些数据聚合到五分钟的块或柱内\nts.resample('5min',closed='left',label='left').sum()#closed控制标签分组的区间闭合,label控制分组结果显示的区间边界\nts.resample('5min',closed='right',label='right',loffset='-1s').sum()\nts.resample('5min').ohlc()#ohic表示开端-峰值-谷值-结束\n#向上采样\nframe = pd.DataFrame(np.random.randn(2,4),index=pd.date_range('1/1/2000',periods=2,freq='W-WED'),\n columns=['colorado','texas','new york','ohio'])\ndf_daily = frame.resample('D').asfreq()#将低频率转换为高频率,默认填充值是NaN\nframe.resample('D').ffill()#前向填充值\n##适用区间进行重新采样,采样区间必须是原频率的父区间或者子区间\nframe = pd.DataFrame(np.random.randn(24,4),index=pd.period_range('1-2000','12-2001',freq='M'),\n columns=['colorado','texas','new york','ohio'])\nannual_frame = frame.resample('A-DEC').mean()\nannual_frame.resample('Q-DEC',convention='end').ffill()\n\n#移动窗口函数\nclose_px_all = pd.read_csv('stock_px_2.csv',parse_dates=True,index_col=0)\nclose_px = close_px_all[['AAPL','MSFT','XOM']]\nclose_px = close_px.resample('B').ffill()\nclose_px.AAPL.rolling(250).mean().plot()##观测的窗口长度是250\n#对时间序列进行滚动窗口计算\ndf = pd.DataFrame({'B': [1, 1, 2,3 , 4]},\n index = [pd.Timestamp('20130101 09:00:00'),\n pd.Timestamp('20130101 09:00:02'),\n pd.Timestamp('20130101 09:00:03'),\n pd.Timestamp('20130101 09:00:05'),\n pd.Timestamp('20130101 09:00:06')])\ndf.rolling('3s').sum()##求和的分组{58,59,00},{00,01,02}..,对DatetimeIndex类型的行标签索引进行分组\nappl_std250 = close_px.AAPL.rolling(250,min_periods=10).std()\nappl_std250.plot()\n#指数加权函数\naapl_px = close_px.AAPL['2006':'2007']\nma60 = aapl_px.rolling(30,min_periods=20).mean()\newma60 = aapl_px.ewm(span=30).mean()\n#二元移动窗口函数(计算相关性的函数corr)\nspx_px = close_px_all['SPX']\nspx_rets = spx_px.pct_change()\nreturns = close_px.pct_change()\ncorr = returns.AAPL.rolling(125,min_periods=100).corr(spx_rets)\ncorr.plot()\n\n\n\n\n\n\n","sub_path":"data_analysis/data_analysis_base/time_sequ.py","file_name":"time_sequ.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"33990828","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404, redirect, resolve_url\n\nfrom ..models import Comment, Question, Answer\n\n## 추천 관리 ##\n\n# 질문 추천\n@login_required(login_url='common:login')\ndef vote_question(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n\n if request.user == question.author:\n messages.error(request, '본인이 작성한 글은 추천할 수 없습니다')\n else: # ManyToManyField => add()\n question.voter.add(request.user)\n # ManyToManyField는 중복X => 여러번 추천해도 추천 수는 증가하지 않음\n return redirect('pybo:detail', question_id=question.id)\n\n\n# 답변 추천\n@login_required(login_url='common:login')\ndef vote_answer(request, answer_id):\n answer = get_object_or_404(Answer, pk=answer_id)\n\n if request.user == answer.author:\n messages.error(request, '본인이 작성한 글은 ��천할 수 없습니다')\n else:\n answer.voter.add(request.user)\n return redirect('{}#answer_{}'.format(resolve_url('pybo:detail', question_id=answer.question.id), answer_id))\n\n\n# 댓글 추천\n@login_required(login_url='common:login')\ndef vote_comment(request, comment_id):\n comment = get_object_or_404(Comment, pk=comment_id)\n\n if request.user == comment.author:\n messages.error(request, '본인이 작성한 글은 추천할 수 없습니다')\n else:\n comment.voter.add(request.user)\n \n if comment.question:\n return redirect('{}#comment_{}'.format(resolve_url('pybo:detail', question_id=comment.question.id), comment_id))\n else: # if comment.answer\n return redirect('{}#comment_{}'.format(resolve_url('pybo:detail', question_id=comment.answer.question.id), comment_id))\n","sub_path":"mysite/pybo/views/vote_views.py","file_name":"vote_views.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"170665767","text":"import cv2\nimport numpy as np\n\n#считываем изображения\nim_in=cv2.imread('Fill.JPG',cv2.IMREAD_GRAYSCALE)\n\n#Пороговое сравнение.\n# Установите значения, равные или выше 220 на 0.\n# Установите значения ниже 220 - 255.\n\nth, im_th = cv2.threshold(im_in, 220, 255, cv2.THRESH_BINARY_INV);\n\n#Делаем копию\nim_floodfill=im_th.copy()\n\n# Маска используется для заливки.\n# Обратите внимание, что размер должен быть 2 пикселя, чем изображение\nh, w = im_th.shape[:2]\nmask = np.zeros((h+2, w+2), np.uint8)\n\ncv2.floodFill(im_floodfill,mask,(0,0),255)\n# Инвертировать залитое изображение\nim_floodfill_inv = cv2.bitwise_not(im_floodfill)\n\n# Объедините два изображения, чтобы получить передний план.\nim_out = im_th | im_floodfill_inv\n\n# Display images.\ncv2.imshow(\"Thresholded Image\", im_th)\ncv2.imshow(\"Floodfilled Image\", im_floodfill)\ncv2.imshow(\"Inverted Floodfilled Image\", im_floodfill_inv)\ncv2.imshow(\"Foreground\", im_out)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"OPENCV/преобразование изображения/Fill.py","file_name":"Fill.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"224231386","text":"f = open('A-small-attempt0.in', 'r')\r\nw = open('A-small-attempt0.out', 'w')\r\ntest = int(f.readline())\r\nfor case in range(test):\r\n\tw.write('Case #%i: ' %(case + 1))\r\n\tn = int(f.readline())\r\n\tif n == 0:\r\n\t\tw.write('INSOMNIA')\r\n\telse:\r\n\t\ts = set()\r\n\t\tfor i in range(10):\r\n\t\t\ts.add(str(i))\r\n\t\tm = 0\r\n\t\twhile len(s) > 0:\r\n\t\t\tm += n\r\n\t\t\ttemp = str(m)\r\n\t\t\tfor i in range(len(temp)):\r\n\t\t\t\ts.discard(temp[i])\r\n\t\tw.write(str(m))\r\n\tw.write('\\n')","sub_path":"solutions_5652388522229760_0/Python/IcePupil/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"555890712","text":"from django.shortcuts import render, redirect\nfrom .models import Mentor \nfrom .forms import MentorForm\n# Create your views here.\n\ndef mentors(request):\n mentoring = Mentor.objects.all()\n return render(request, 'Mentor/mentor_temp.html',{'Mentors':mentoring}) \n\ndef mentor_list(request):\n if request.method == \"POST\":\n form = MentorForm(request.POST, request.FILES)\n if form.is_valid():\n post = form.save\n form.save()\n return redirect('Mentor')\n else:\n form = MentorForm()\n return render(request, 'Mentor/mentor_form.html',{'form': form })\n","sub_path":"Mentor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"245964157","text":"# -*- coding: utf-8 -*-#\n'''\n# Name: t2\n# Description: 逻辑回归问题,代价函数正则化\n# Author: super\n# Date: 2019-07-15\n'''\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.optimize as opt\n\ndef showData(data):\n '''\n 显示原始数据\n :param data:数据\n '''\n positive = data2[data2['Accepted'].isin([1])]\n negative = data2[data2['Accepted'].isin([0])]\n\n fig, ax = plt.subplots(figsize=(12, 8))\n ax.scatter(positive['Test 1'], positive['Test 2'], s=50, c='b', marker='o', label='Accepted')\n ax.scatter(negative['Test 1'], negative['Test 2'], s=50, c='r', marker='x', label='Rejected')\n ax.legend()\n ax.set_xlabel('Test 1 Score')\n ax.set_ylabel('Test 2 Score')\n plt.show()\n\ndef sigmoid(z):\n '''\n 函数值在0-1之间\n :param z:参数z\n :return:sigmoid函数之后的结果\n '''\n return 1 / (1+np.exp(-z))\n\ndef costReg(theta, X, y, learningRate):\n '''\n 正则化代价函数\n :param theta:参数\n :param X:分数\n :param y:类别\n :param learningRate:学习率,用来控制正则化\n :return:代价 \n '''\n theta = np.matrix(theta)\n X = np.matrix(X)\n y = np.matrix(y)\n first = np.multiply(-y, np.log(sigmoid(X * theta.T)))\n second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))\n reg = (learningRate / (2 * len(X))) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2))\n return np.sum(first - second) / len(X) + reg\n\n\ndef gradientReg(theta, X, y, learningRate):\n '''\n 梯度下降函数\n :param theta: 参数\n :param X: 分数\n :param y: 分数类别\n :param learningRate:学习率\n :return: 参数集合\n '''\n theta = np.matrix(theta)\n X = np.matrix(X)\n y = np.matrix(y)\n\n parameters = int(theta.ravel().shape[1])\n grad = np.zeros(parameters)\n\n error = sigmoid(X * theta.T) - y\n\n for i in range(parameters):\n term = np.multiply(error, X[:, i])\n\n if (i == 0):\n grad[i] = np.sum(term) / len(X)\n else:\n grad[i] = (np.sum(term) / len(X)) + ((learningRate / len(X)) * theta[:, i])\n\n return grad\n\nif __name__ == \"__main__\":\n path = 'ex2data2.txt'\n data2 = pd.read_csv(path, header=None, names=['Test 1', 'Test 2', 'Accepted'])\n print(data2)\n showData(data2)\n\n degree = 5\n x1 = data2['Test 1']\n x2 = data2['Test 2']\n\n data2.insert(3, 'Ones', 1)\n\n for i in range(1, degree):\n for j in range(0, i):\n data2['F' + str(i) + str(j)] = np.power(x1, i - j) * np.power(x2, j)\n\n data2.drop('Test 1', axis=1, inplace=True)\n data2.drop('Test 2', axis=1, inplace=True)\n\n # set X and y (remember from above that we moved the label to column 0)\n cols = data2.shape[1]\n X2 = data2.iloc[:, 1:cols]\n y2 = data2.iloc[:, 0:1]\n\n # convert to numpy arrays and initalize the parameter array theta\n X2 = np.array(X2.values)\n y2 = np.array(y2.values)\n theta2 = np.zeros(11)\n\n #设置默认学习率为1\n learningRate = 1\n print(costReg(theta2, x2, y2, learningRate))\n print(gradientReg(theta2, x2, y2, learningRate))\n\n\n\n","sub_path":"pythonBasis/ex2/t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"117446220","text":"\n# 3.输入一个整数(代表树干的高度)\n#   打印出如下一棵树\n# 输入:2\n# *\n# ***\n# *\n# *\n# 输入:3\n# *\n# ***\n# *****\n# *\n# *\n# *\nhight = int(input(\"请输入树干高度\"))\n#打印树冠\nn = 1\nwhile n <= hight: \n #星星数\n stars = 2 * n - 1 #(1,3,5)\n #空格数\n blank = hight - n\n #算出树冠\n leaf = \" \" * blank + \"*\" * stars\n print(leaf)\n n += 1\n#打印树干\nn = 1\nwhile n <= hight:\n blanks = hight - 1\n t = \" \" * blanks + \"*\"\n print(t)\n n += 1","sub_path":"aid1807a/练习题/python练习题/python基础习题/03/shengdanshu.py","file_name":"shengdanshu.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"492305810","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/11/2 20:01\n# @Author : 饭盆里\n# @File : test_qywx_contact.py\n# @Software: PyCharm\n# @desc : 企业微信联系人相关\n\"\"\"\"\n优化项\n1. 性别判断\n2. 断言\n3. 显示等待\n4. 滚动查找 添加用户\n4. 参数化\n 参数化运行的时候希望不重启APP,需要在案例运行结束后进入通讯录页面\n\"\"\"\nfrom time import sleep\n\nimport pytest\nimport yaml\nfrom appium import webdriver\nfrom appium.webdriver.common.mobileby import MobileBy\n\nwith open('./data/addcontact.yaml') as f:\n addcontacts = yaml.safe_load(f)\n\nwith open('./data/delcontact.yaml') as f:\n delcontacts = yaml.safe_load(f)\n\nclass TestQywxContact:\n def setup_class(self):\n desire_caps = {\n \"platformName\": \"android\",\n \"appPackage\": \"com.tencent.wework\",\n \"appActivity\": \".launch.WwMainActivity\",\n \"deviceName\": \"emulator-5554\",\n \"noReset\": \"true\",\n 'skipServerInstallation': 'true', # 跳过 uiautomator2 server的安装\n 'skipDeviceInitialization': 'true', # 跳过设备初始化\n 'settings[waitForIdleTimeout]': 0 , # 等待Idle为0\n 'dontStopAppOnReset':'true' #不关闭,重启APP\n }\n\n # 与server建立连接,初始化一个driver,创建session\n self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desire_caps)\n self.driver.implicitly_wait(5)\n\n def teardown_class(self):\n\n # 销毁session\n self.driver.quit()\n\n #参数化\n # @pytest.mark.parametrize('name,gender,mobile',[\n # (\"fanfan10\",\"男\",\"18700000010\"),\n # (\"fanfan09\", \"女\", \"18700000009\"),\n # ])\n @pytest.mark.parametrize('name,gender,mobile',addcontacts)\n def test_add_contact(self,name,gender,mobile):\n \"\"\"\n 1. 打开应用\n 2. 点击通讯录\n 3. 点击添加成员\n 4. 手动输入添加\n 5. 输入【用户名】、性别、手机号\n 6. 点击保存\n 7. 验证添加成功\n :return:\n \"\"\"\n # name = \"fanfan05\"\n # gender = \"男\"\n # mobile = \"18700000005\"\n\n #点击通讯录\n self.driver.find_element(MobileBy.XPATH,'//*[@text=\"通讯录\"]').click()\n\n #点击添加成员-->>滚动查找到这个元素\n self.driver.find_element_by_android_uiautomator('new UiScrollable(new UiSelector().scrollable(true).instance(0)).'\n 'scrollIntoView(new UiSelector().text(\"添加成员\").instance(0))').click()\n #点击手动输入添加\n self.driver.find_element(MobileBy.ID,'com.tencent.wework:id/hgx').click()\n\n #输入【用户名】\n self.driver.find_element(MobileBy.XPATH,\n '//*[@text=\"姓名 \"]/..//*[@class=\"android.widget.EditText\"]').send_keys(name)\n\n #性别\n self.driver.find_element(MobileBy.XPATH,'//*[@text=\"性别\"]/..//*[@text=\"男\"]').click()\n self.driver.find_element(MobileBy.XPATH,\n f'//*[@resource-id=\"com.tencent.wework:id/dyx\" and @text=\"{gender}\"]').click()\n\n #输入手机号\n self.driver.find_element(MobileBy.ID,'com.tencent.wework:id/f1e').send_keys(mobile)\n #保存\n self.driver.find_element(MobileBy.XPATH,'//*[@text=\"保存\"]').click()\n\n #断言 toast\n toast_message = self.driver.find_element(MobileBy.XPATH,'//*[@class=\"android.widget.Toast\"]').text\n\n assert '添加成功' in toast_message\n #返回到列表页\n self.driver.find_element(MobileBy.ID, 'com.tencent.wework:id/h9e').click()\n\n\n @pytest.mark.parametrize('name',delcontacts)\n def test_del_contact(self,name):\n \"\"\"\n 1. 打开应用\n 2. 点击通讯录\n 3. 找到要删除的联系人\n 4. 进入联系人页面\n 5. 点击右上角的三个点进入个人信息页面,点击编辑成员\n 6. 删除联系人\n 7. 确认删除\n 8. 验证删除成功\n :return:\n \"\"\"\n\n # name = 'fanfan11'\n\n # 点击通讯录\n self.driver.find_element(MobileBy.XPATH, '//*[@text=\"通讯录\"]').click()\n\n # 找到要删除的联系人\n self.driver.find_element(MobileBy.ID,'com.tencent.wework:id/h9z').click()\n self.driver.find_element(MobileBy.ID,'com.tencent.wework:id/fxc').send_keys(name)\n sleep(2)\n search_element_list = self.driver.find_elements(MobileBy.XPATH,f'//*[@text=\"{name}\"]')\n if len(search_element_list) <= 1:\n print('没有找到要删除的数据')\n return\n search_element_list[-1].click()\n\n print(len(search_element_list))\n\n # 点击右上角的三个点进入个人信息页面,点击编辑成员\n self.driver.find_element(MobileBy.ID,'com.tencent.wework:id/h9p').click()\n self.driver.find_element(MobileBy.XPATH,'//*[@text=\"编辑成员\"]').click()\n\n # 滚动查找到【删除成员】按钮,点击\n text = '删除成员'\n # self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR,f'new UiScrollable(new UiSelector().scrollable(true).instance(0))'\n # f'.scrollIntoView(new UiSelector().text(\"{text}\").instance(0));').click()\n self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR,\n f'new UiScrollable(new UiSelector().scrollable(true).instance(0))'\n f'.scrollIntoView(new UiSelector().text(\"{text}\").instance(0))').click()\n\n # 确认删除\n self.driver.find_element(MobileBy.ID,'com.tencent.wework:id/bci').click()\n\n # 验证删除成功\n sleep(2)\n search_element_list_after = self.driver.find_elements(MobileBy.XPATH, f'//*[@text=\"{name}\"]')\n sleep(2)\n print(len(search_element_list_after))\n assert len(search_element_list) - len(search_element_list_after) == 1\n\n\n","sub_path":"myappium/qiyeweixin/test_qywx_contact.py","file_name":"test_qywx_contact.py","file_ext":"py","file_size_in_byte":6024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"499026418","text":"#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3\n# -----------------------------------------------------------------------------\n# Name: CIS22C HW3 main file\n# Purpose: CIS22C HW3\n# Author: Raymond Cabrera\n# Created: 8/2/2016\n# -----------------------------------------------------------------------------\n\"\"\"\nCompute and print the area of different rooms in a house\n\nCompute the area of the kitchen, bedroom and family room in square feet.\nPrint the three areas in square feet.\n\"\"\"\n\nfrom hash_module import HashTable\n\n\ndef main():\n #dict_table = hash_module\n with open('dictionary.txt', 'r', encoding='utf-8') as infile:\n input_string = infile.read()\n input_list = input_string.split()\n dict_table = HashTable(len(input_list))\n for word in input_list:\n dict_table.put(word)\n dict_table.print_stats()\n #dict_table.print_hash_table()\n\n with open('document.txt', 'r', encoding='utf-8') as doc_file:\n doc_string = doc_file.read()\n\n print('\\nChained Hash Table Stats:')\n doc_list = set(doc_string.split())\n #dict_table.print_hash_table()\n\n print('\\nWords not in dictionary:')\n for word in doc_list:\n if word not in input_list:\n print(word)\n\n\nif __name__ == '__main__':\n main()","sub_path":"CIS22C_HW3.py","file_name":"CIS22C_HW3.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"651979077","text":"def _winrm_send_input(self, protocol, shell_id, command_id, stdin, eof=False):\n rq = {\n 'env:Envelope': protocol._get_soap_header(resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd', action='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Send', shell_id=shell_id),\n }\n stream = rq['env:Envelope'].setdefault('env:Body', {\n \n }).setdefault('rsp:Send', {\n \n }).setdefault('rsp:Stream', {\n \n })\n stream['@Name'] = 'stdin'\n stream['@CommandId'] = command_id\n stream['#text'] = base64.b64encode(to_bytes(stdin))\n if eof:\n stream['@End'] = 'true'\n protocol.send_message(xmltodict.unparse(rq))","sub_path":"Data Set/bug-fixing-5/8bbbe16d31d68e097a9748c7563bbea18cfdd87b-<_winrm_send_input>-fix.py","file_name":"8bbbe16d31d68e097a9748c7563bbea18cfdd87b-<_winrm_send_input>-fix.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"290949276","text":"#coding=utf8\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nimport hashlib, urllib2, json\n\nAPPID = 'wx2ecff3224aaee1b0'\nAPPSECRET = '1e1810df61f7711d4cd4f2795ff4b73c'\n\ndef index(request):\n\tcode = request.GET['code']\n\tstate = request.GET['state']\n\tif code:\n\t\t#get authorized access_token\n\t\turl = 'https://api.weixin.qq.com/sns/oauth2/access_token?'+\\\n\t\t\t\t'appid='+APPID+\\\n\t\t\t\t'&secret='+APPSECRET+\\\n\t\t\t\t'&code='+code+\\\n\t\t\t\t'&grant_type=authorization_code'\n\t\ttry:\n\t\t\tresp = urllib2.urlopen(url)\n\t\texcept:\n\t\t\treturn HttpResponse('get access_token failed')\n\t\tatdata = json.loads(resp.read())\n\t\tat = atdata['access_token']\n\t\toid = atdata['openid']\n\n\t\t#get user information\n\t\turl = 'https://api.weixin.qq.com/sns/userinfo?'+\\\n\t\t\t\t\t\t'access_token='+at+\\\n\t\t\t\t\t\t'&openid='+oid+\\\n\t\t\t\t\t\t'&lang=zh_CN'\n\t\ttry:\n\t\t\tresp = urllib2.urlopen(url)\n\t\texcept:\n\t\t\treturn HttpResponse('get user information failed')\n\t\tuserdata = json.loads(resp.read())\n\t\tif userdata['sex']==1:\n\t\t\tuserdata['sex'] = '男'\n\t\telif userdata['sex']==2:\n\t\t\tuserdata['sex'] = '女'\n\t\telse:\n\t\t\tuserdata['sex'] = ''\n\t\treturn render(request, 'weixin/userinfo.html', userdata)\n\telif state:\n\t\treturn HttpResponse('authorization refused')\n\telse:\n\t\t#unkown request\n\t\trequrl = request.get_host()+request.get_full_path()\n\t\treturn HttpResponse(requrl)\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"48154409","text":"import os\n\nclass PathComponents(object):\n \"\"\"\n Provides a convenient access to path components of a combined external/internal path to a dataset.\n \"\"\"\n def __init__(self, totalPath, cwd=None):\n \"\"\"\n Initialize the path components.\n \n :param totalPath: The entire path to the dataset, including any internal path (e.g. the path to an hdf5 dataset).\n For example, ``totalPath='/some/path/to/file.h5/with/internal/dataset'``\n\n :param cwd: If provided, relative paths will be converted to absolute paths using this arg as the working directory.\n \"\"\"\n #: Example: ``/some/path/to/file.h5``\n self.externalPath = None\n #: Example: ``/some/path/to``\n self.externalDirectory = None\n #: Example: ``file.h5``\n self.filename = None \n #: Example: ``file``\n self.filenameBase = None\n #: Example: ``.h5``\n self.extension = None\n #: Example: ``/with/internal/dataset``\n self.internalPath = None\n #: Example: ``dataset``\n self.internalDatasetName = None\n #: Example: ``/some/path/to/file.h5/with/internal``\n self.internalDirectory = None\n \n # For hdf5 paths, split into external, extension, and internal paths\n h5Exts = ['.ilp', '.h5', '.hdf5']\n ext = None\n extIndex = -1\n \n if cwd is not None:\n absPath, relPath = getPathVariants( totalPath, cwd )\n totalPath = absPath\n \n for x in h5Exts:\n if totalPath.find(x) > extIndex:\n extIndex = totalPath.find(x)\n ext = x\n\n # Comments below refer to this example path:\n # /some/path/to/file.h5/with/internal/dataset\n if ext is not None:\n self.extension = ext # .h5\n parts = totalPath.split(ext)\n \n # Must deal with pathological filenames such as /path/to/file.h5_with_duplicate_ext.h5\n while len(parts) > 2:\n parts[0] = parts[0] + ext + parts[1]\n del parts[1]\n self.externalPath = parts[0] + ext # /some/path/to/file.h5\n self.internalPath = parts[1].replace('\\\\', '/') # /with/internal/dataset\n\n self.internalDirectory = os.path.split( self.internalPath )[0] # /with/internal\n self.internalDatasetName = os.path.split( self.internalPath )[1] # dataset\n else:\n # For non-hdf5 files, use normal path/extension (no internal path)\n (self.externalPath, self.extension) = os.path.splitext(totalPath)\n self.externalPath += self.extension\n self.internalPath = None\n self.internalDatasetName = None\n self.internalDirectory = None\n\n self.externalDirectory = os.path.split( self.externalPath )[0] # /some/path/to\n self.filename = os.path.split( self.externalPath )[1] # file.h5\n self.filenameBase = os.path.splitext(self.filename)[0] # file\n\n def totalPath(self):\n \"\"\"\n Return the (reconstructed) totalPath to the dataset.\n \"\"\"\n total = self.externalPath \n if self.internalPath:\n total += self.internalPath\n return total\n\ndef getPathVariants(originalPath, workingDirectory):\n \"\"\"\n Take the given filePath (which can be absolute or relative, and may include an internal path suffix),\n and return a tuple of the absolute and relative paths to the file.\n \"\"\"\n lastDotIndex = originalPath.rfind('.')\n extensionAndInternal = originalPath[lastDotIndex:]\n extension = extensionAndInternal.split('/')[0]\n\n relPath = originalPath\n \n if os.path.isabs(originalPath):\n absPath = originalPath\n relPath = os.path.relpath(absPath, workingDirectory)\n else:\n relPath = originalPath\n absPath = os.path.normpath( os.path.join(workingDirectory, relPath) )\n \n return (absPath, relPath)\n\nif __name__ == \"__main__\":\n \n abs, rel = getPathVariants('/aaa/bbb/ccc/ddd.txt', '/aaa/bbb/ccc/eee')\n assert abs == '/aaa/bbb/ccc/ddd.txt'\n assert rel == '../ddd.txt'\n\n abs, rel = getPathVariants('../ddd.txt', '/aaa/bbb/ccc/eee')\n assert abs == '/aaa/bbb/ccc/ddd.txt'\n assert rel == '../ddd.txt'\n\n abs, rel = getPathVariants('ddd.txt', '/aaa/bbb/ccc')\n assert abs == '/aaa/bbb/ccc/ddd.txt'\n assert rel == 'ddd.txt'\n \n components = PathComponents('/some/external/path/to/file.h5/with/internal/path/to/data')\n assert components.externalPath == '/some/external/path/to/file.h5'\n assert components.extension == '.h5'\n assert components.internalPath == '/with/internal/path/to/data'\n\n components = PathComponents('/some/external/path/to/file.h5_crazy_ext.h5/with/internal/path/to/data')\n assert components.externalPath == '/some/external/path/to/file.h5_crazy_ext.h5'\n assert components.extension == '.h5'\n assert components.internalPath == '/with/internal/path/to/data'\n\n","sub_path":"lazyflow/utility/pathHelpers.py","file_name":"pathHelpers.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"404699924","text":"# coding: utf-8\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom pedidosapp.forms.produto_form import ProdutoForm\nfrom pedidosapp.models.produto_model import Produto\n\n\n@login_required\ndef listar(request):\n\n produtos = Produto().getAll()\n\n return render(request, 'produto/index.html', {\n 'produtos': produtos\n })\n\n\n@login_required\ndef adicionar(request):\n\n if request.method == 'POST':\n\n form = ProdutoForm(request.POST)\n\n if form.is_valid():\n\n produto = Produto()\n produto.setNome(request.POST['nome_produto'])\n produto.setPreco(request.POST['preco'])\n produto.setDescricao(request.POST['descricao'])\n produto.setSaldoEstoque(0) # Inicia com saldo zero\n produto.setCategoriaId(request.POST['categoria'])\n produto.save()\n messages.success(request, 'Produto adicionado com sucesso!')\n return HttpResponseRedirect('/produtos/')\n\n else:\n form = ProdutoForm()\n\n return render(request, 'produto/adicionar.html', {\n 'form': form\n })\n\n\n@login_required\ndef editar(request, produto_id):\n\n produto = Produto().getProdutoById(produto_id)\n\n if request.method == 'POST':\n\n form = ProdutoForm(request.POST)\n\n if form.is_valid():\n\n produto.setNome(request.POST['nome_produto'])\n produto.setPreco(request.POST['preco'])\n produto.setDescricao(request.POST['descricao'])\n produto.setCategoriaId(request.POST['categoria'])\n produto.save()\n messages.success(request, 'Produto editado com sucesso!')\n return HttpResponseRedirect('/produtos/')\n\n else:\n data = {\n 'nome_produto': produto.getNome(),\n 'preco': produto.getPreco(),\n 'descricao': produto.getDescricao(),\n 'categoria': produto.getCategoriaId()\n }\n form = ProdutoForm(initial=data)\n\n return render(request, 'produto/editar.html', {\n 'form': form,\n 'produto_id': produto.getId()\n })\n\n\n@login_required\ndef excluir(request, produto_id):\n\n produto = Produto().getProdutoById(produto_id)\n\n if produto.getId() is not None:\n produto.delete()\n messages.success(request, 'Produto excluído com sucesso!')\n return HttpResponseRedirect('/produtos/')\n","sub_path":"pedidosapp/views/produto_view.py","file_name":"produto_view.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"463500393","text":"from django.urls import path\nfrom base.views.dashboard_view import Dashboard\nfrom base.views.auth_view import UserLoginView, LogoutView\nfrom base.views.category_view import CategoryDeleteView\nfrom base.views.inventory_view import CreateInventoryView, InventoryListView, InventoryDetailView, \\\n InventoryUpdateView, InventoryDeleteView\nfrom base.views.tag_view import CreateListTagView, TagDeleteView\nfrom base.views.product_view import ProductListView, eventSellingproduct,lowProduct,expireProduct, lowSellingproduct, topSellingproduct\nfrom base.views.logout import logout_view\nfrom base.views.pos_view import POSView, cart_add, cart_updated, cart_remove\nfrom base.views.order_views import bulling_information_view, OrderItemView, search_orders\nfrom base.views.group import startGroup,manageGroup,updateGroup,deleteGroup\nfrom base.views.user import startUser, manageuser, updateuser, deleteuser, user_profile\nfrom base.views.orderView import *\nfrom base.views.product_view import (\n create_product, update_product, delete_product, search_products\n)\nfrom base.views.category_view import (\n create_category, update_category, categories\n)\nurlpatterns = [\n path('login/', UserLoginView.as_view(), name='login'),\n path('logout/', LogoutView.as_view(), name='logout'),\n path('dashboard/', Dashboard, name='dashboard'),\n # path('create-category/', CategoryCreateView.as_view(), name='create_category'),\n path('create-category/', create_category, name='create_category'),\n path('update-category//', update_category, name='update_category'),\n path('category/', categories, name='category_list'),\n # path('category//', CategoryUpdateView.as_view(), name='category_update'),\n path('category-delete//', CategoryDeleteView.as_view(), name='category_delete'),\n path('create-inventory/', CreateInventoryView.as_view(), name='inventory_create'),\n path('inventory/', InventoryListView.as_view(), name='inventory_list'),\n path('inventory//', InventoryDetailView.as_view(), name='inventory_detail'),\n path('inventory-update//', InventoryUpdateView.as_view(), name='inventory_update'),\n path('inventory-delete//', InventoryDeleteView.as_view(), name='inventory_delete'),\n path('tag/', CreateListTagView.as_view(), name='create_list_tag'),\n path('tag//', TagDeleteView.as_view(), name='tag_delete'),\n # path('create-product/', CreateProductView.as_view(), name='product_create'),\n path('product-list/', ProductListView.as_view(), name='product_list'),\n path('create-product/', create_product, name='product_create'),\n path('update-product/', update_product, name='product_update'),\n path('delete-product/', delete_product, name='delete_update'),\n path('search-products/', search_products, name='search_products'),\n path('cart/id/', cart_add, name='cart_add'),\n path('cart-update//', cart_updated, name='cart_updated'),\n path('cart-remove//', cart_remove, name='cart_remove'),\n path('pos/', POSView.as_view(), name='pos_view'),\n path('bulling-infromation/', bulling_information_view, name='bulling_information'),\n path('order-infromation/', OrderItemView.as_view(), name='order_information'),\n path('add_group/', startGroup, name='add_group'),\n path('manageGroup/', manageGroup, name='manageGroup'),\n path('group-update//', updateGroup, name='group_update'),\n path('group-delete/', deleteGroup, name='group_delete'),\n path('add_user/', startUser, name='add_user'),\n path('manageuser/', manageuser, name='manageuser'),\n path('user-profile//', user_profile, name='user_profile'),\n\n\n path('user-update//', updateuser, name='user_update'),\n path('user-delete/', deleteuser, name='user_delete'),\n path('logout', logout_view, name='logout'),\n path('low-product', lowProduct, name='low-product'),\n path('expireProduct', expireProduct, name='expire-Product'),\n path('topSellingProduct', topSellingproduct, name='top-selling-Product'),\n path('lowSellingproduct', lowSellingproduct, name='low-selling-Product'),\n path('eventSellingproduct', eventSellingproduct, name='event-selling-Product'),\n # path('add_order', add_order, name='Add-order'),\n path('invoice', invoice, name='Add-order'),\n path('viewOrder', viewOrder, name='view-order'),\n path('order-update//', updateOrder, name='order_update'),\n path('order-delete//', deleteOrder, name='order_delete'),\n path('search-orders/', search_orders, name='search_orders'),\n path('load-price', load_price, name='load-price'),\n\n path('create_order/', create_order, name='create_order'),\n path('get_product/', get_product, name='get_product'),\n path('ajax_create_order/', ajax_order_create, name='ajax_create_order'),\n]\n","sub_path":"base/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"570520110","text":"# Standard Python libraries\nfrom __future__ import (absolute_import, print_function,\n division, unicode_literals)\nfrom io import open\n\n# atomman imports\nimport atomman.unitconvert as uc\nfrom .atoms_prop_info import atoms_prop_info\nfrom .velocities_prop_info import velocities_prop_info\nfrom ...lammps import style\nfrom .. import dump_table\nfrom ...compatibility import stringtype, ispython2\n\ndef dump(system, f=None, atom_style='atomic', units='metal',\n float_format='%.13f', return_info=True):\n \"\"\"\n Write a LAMMPS-style atom data file from a System.\n \n Parameters\n ----------\n system : atomman.System \n The system to write to the atom data file.\n f : str or file-like object, optional\n File path or file-like object to write the content to. If not given,\n then the content is returned as a str.\n atom_style : str, optional\n The LAMMPS atom_style option associated with the data file. Default\n value is 'atomic'.\n units : str, optional\n The LAMMPS units option associated with the data file. Default value\n is 'metal'.\n float_format : str, optional\n c-style formatting string for floating point values. Default value is\n '%.13f'.\n return_info : bool, optional\n Indicates if the LAMMPS command lines associated with reading in the\n file are to be returned as a str. Default value is True.\n \n Returns\n -------\n content : str\n The data file contents (returned if f is not given).\n read_info : str\n The LAMMPS input command lines to read the created data file in (returned if return_info is True).\n \"\"\"\n # Wrap atoms because LAMMPS hates atoms out of bounds in atom data files\n system.wrap()\n \n # Get unit information according to the units style\n units_dict = style.unit(units)\n \n # Generate header info\n content = '\\n%i atoms\\n' % system.natoms\n content += '%i atom types\\n' % system.natypes\n \n # Extract and convert box values\n xlo = uc.get_in_units(system.box.xlo, units_dict['length'])\n xhi = uc.get_in_units(system.box.xhi, units_dict['length'])\n ylo = uc.get_in_units(system.box.ylo, units_dict['length'])\n yhi = uc.get_in_units(system.box.yhi, units_dict['length'])\n zlo = uc.get_in_units(system.box.zlo, units_dict['length'])\n zhi = uc.get_in_units(system.box.zhi, units_dict['length'])\n xy = system.box.xy\n xz = system.box.xz\n yz = system.box.yz\n \n # Write box values\n xf2 = float_format + ' ' + float_format\n content += xf2 % (xlo, xhi) +' xlo xhi\\n'\n content += xf2 % (ylo, yhi) +' ylo yhi\\n'\n content += xf2 % (zlo, zhi) +' zlo zhi\\n'\n if xy != 0.0 or xz != 0.0 or yz != 0.0:\n xf3 = float_format + ' ' + float_format + ' ' + float_format\n content += xf3 % (xy, xz, yz) + ' xy xz yz\\n'\n \n # Write atom info\n content += '\\nAtoms\\n\\n'\n prop_info = atoms_prop_info(atom_style, units)\n \n content += dump_table(system, prop_info=prop_info, float_format=float_format)\n \n # Handle velocity information if included\n if 'velocity' in system.atoms_prop():\n \n # Write velocity info\n content += '\\nVelocities\\n\\n'\n prop_info = velocities_prop_info(atom_style, units)\n \n content += dump_table(system, prop_info=prop_info, float_format=float_format)\n \n returns = []\n \n # Save to the file-like object\n if hasattr(f, 'write'):\n f.write(content)\n \n # Save to the file name\n elif f is not None:\n with open(f, 'w') as fp:\n fp.write(content)\n \n # Return as a string\n else:\n returns.append(content)\n \n if return_info is True:\n # Return appropriate units, atom_style, boundary, and read_data LAMMPS commands\n boundary = ''\n for i in range(3):\n if system.pbc[i]:\n boundary += 'p '\n else:\n boundary += 'm '\n \n if isinstance(f, stringtype):\n read_data = 'read_data ' + f\n else:\n read_data = ''\n newline = '\\n'\n read_info = newline.join(['# Script and atom data file prepared by atomman package',\n '',\n 'units ' + units,\n 'atom_style ' + atom_style,\n ''\n 'boundary ' + boundary,\n read_data])\n returns.append(read_info)\n \n if len(returns) == 1:\n return returns[0]\n elif len(returns) > 1:\n return tuple(returns)","sub_path":"atomman/dump/atom_data/dump.py","file_name":"dump.py","file_ext":"py","file_size_in_byte":4662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"532747590","text":"# Software License Agreement (BSD License)\n#\n# Copyright (c) 2010, Willow Garage, 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\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# * Neither the name of Willow Garage, Inc. nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# Revision $Id$\n\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport yaml\n\nimport rospkg\nfrom rospkg.distro import DistroStack\n\nimport roslib.stack_manifest\nimport roslib.manifest\n\ndef load_distro_index(filename):\n \"\"\"\n Load the distro index file, which is necessary for stacks that are installed in\n binary form instead of with the extra rosinstall meta fields\n \"\"\"\n with open(filename, 'r') as f:\n return yaml.load(f)\n\n\ndef repo_stacks(repo, checkout_dir, rospkg=rospkg):\n if repo.is_released_stack:\n # distro/debian install logic: repo is a released stack, no\n # need to crawl\n return [repo.name]\n else:\n # rosinstall logic\n repo_dir = os.path.join(checkout_dir, repo.local_path)\n if not os.path.exists(repo_dir):\n sys.stderr.write(\"checkout [%s] doesn't exist\\n\"%(repo_dir))\n return []\n\n stacks = rospkg.list_by_path(roslib.stack_manifest.STACK_FILE, repo_dir, {})\n if repo.name == 'ros':\n stacks.append('ros')\n return stacks\n\n\ndef repo_packages(repo, checkout_dir, rosstack=rospkg.RosStack()):\n if repo.is_released_stack:\n # distro/debian install logic: repo is a released stack, no\n # need to crawl\n try:\n packages = rosstack.packages_of(repo.name)\n except:\n packages = []\n else:\n # rosinstall logic\n repo_dir = os.path.join(checkout_dir, repo.local_path)\n packages = rospkg.list_by_path(roslib.manifest.MANIFEST_FILE, repo_dir, {})\n return packages\n\n\ndef load_repos_distro(distro_index_filename):\n \"\"\"\n Load repository index for stacks that were installed via the\n distribution/debian. We have to fake repository data for these as\n we are not actually retrieving from the repository itself.\n @return: ordered list of repositories\n @rtype: [(str:stackname, Repo)]\n \"\"\"\n repos = []\n\n # for released stacks, we use the metarepos logic to represent the\n # stack as its own repository as well as part of an aggregate\n # repository.\n distro_index = load_distro_index(distro_index_filename)\n distro_name = distro_index['distro_name']\n for stack_name in distro_index['stacks']:\n stack_data = distro_index['stacks'][stack_name]\n\n # should not be used (hopefully)\n if stack_name == 'ros':\n local_path = '/opt/ros/%s/ros'%(distro_name)\n else:\n local_path = '/opt/ros/%s/stacks/%s'%(distro_name, stack_name)\n\n distro_stack = DistroStack(stack_name, stack_data['version'],\n distro_name, stack_data['rules'])\n\n # TODO: broken for bzr\n rosinstalls = {}\n vcs_config = distro_stack.vcs_config\n if vcs_config is None:\n sys.stderr.write('Missing vcs config data for stack \"%s\"\\n' % stack_name)\n continue\n\n for branch_name in ['release', 'devel', 'distro']:\n rosinstalls[branch_name] = vcs_config.to_rosinstall(stack_name,\n branch_name,\n anonymous=True)[0]\n # use the release branch as that is what we are documenting\n rosinstall = rosinstalls['release'] # default rosinstall\n\n # for each debian-based stack, give it its own repo, plus an aggregate\n vcs_type = rosinstall.keys()[0]\n vcs_uri = rosinstall[vcs_type]['uri']\n\n print(\"loaded released stack repo: %s %s %s\"%(stack_name, vcs_type, vcs_uri))\n print(\"released stack repo rosinstall: %s \\n%s\"%(stack_name, rosinstall))\n\n r = Repo(name=stack_name,\n type_=vcs_type,\n uri=vcs_uri,\n rosinstall=rosinstall,\n local_path=local_path,\n aggregate_name=stack_data['repo'])\n\n r.is_released_stack = True\n r.rosinstalls = rosinstalls.copy()\n\n repos.append((stack_name, r))\n return repos\n\n\ndef load_repos(repos_filename, distro_index_filename=None):\n \"\"\"\n loads definitions of repos from both sources\n @return: list of pairs (stackname or localpath, repositories)\n \"\"\"\n repos = load_repos_rosinstall(repos_filename)\n if distro_index_filename is not None:\n repos.extend(load_repos_distro(distro_index_filename))\n return repos\n\n\ndef load_repos_rosinstall(filename):\n \"\"\"\n Load repository file, which is a rosinstall file with particular semantics\n\n @return: ordered list of repositories\n @rtype: [(str:localname, Repo)]\n \"\"\"\n with open(filename) as f:\n data = yaml.load(f.read())\n # rosinstall file is a list of dictionaries\n repos = []\n # have to reverse the repo order to match rosinstall precedence\n for item_dict in reversed(data):\n type_ = item_dict.keys()[0]\n if type_ == 'other':\n continue\n config = item_dict[type_]\n # filter 'other' like elements that don't bear VCS info\n if not 'uri' in config:\n continue\n\n local_name = local_path = config['local-name']\n aggregate_name = None\n if 'meta' in config and 'repo-name' in config['meta']:\n aggregate_name = config['meta']['repo-name']\n r = Repo(name=local_name,\n type_=type_,\n uri=config['uri'],\n rosinstall=item_dict,\n local_path=local_path,\n aggregate_name=aggregate_name)\n\n repos.append((local_name, r))\n return repos\n\n\nclass Repo(object):\n\n def __init__(self, name, type_, uri, rosinstall, local_path, aggregate_name=None):\n \"\"\"\n @param name: repository name\n @param type_: repository VCS type\n @param uri: repository VCS uri\n @param rosinstall: default rosinstall dictionary configuration data\n @param local_path: checkout-relative path for repository\n @param aggregate_name: (optional) aggregate name if we are\n grouping several repositories under a single name.\n Defaults to name.\n \"\"\"\n # stackname\n self.name = name\n self.type = type_\n self.uri = uri\n # rosinstall data as dict\n self.rosinstall = rosinstall\n self.local_path = local_path\n\n # aggregate is used to alias per-stack repositories to a\n # single name, e.g. ccny-ros-pkg\n self.aggregate_name = aggregate_name\n self.is_released_stack = False\n\n # dictionary of different rosinstall configurations of repo,\n # uses same keys as VcsConfig.to_rosinstall,\n # e.g. {'devel': rosinstall_dict, 'release': rosinstall_dict}\n self.rosinstalls = None\n\n\n_API_URL = \"http://ros.org/doc/api/\"\ndef package_link(package):\n return _API_URL + package + \"/html/\"\n\n\ndef stack_link(stack):\n return _API_URL + stack + \"/html/\"\n\n\ndef safe_encode(stringdict):\n \"\"\"\n modifies dict of strings or list of string such that all string values are encoded in utf-8\n \"\"\"\n d_copy = stringdict.copy()\n for key, val in d_copy.iteritems():\n if isinstance(val, basestring):\n try:\n stringdict[key] = val.encode(\"utf-8\")\n except UnicodeDecodeError as ude:\n sys.stderr.write(\"error: cannot encode value for key: %s\\n\"%str(ude), key)\n stringdict[key] = ''\n elif type(val) == list:\n try:\n stringdict[key] = [x.encode(\"utf-8\") for x in val]\n except UnicodeDecodeError as ude:\n sys.stderr.write(\"error: cannot encode value for key: %s\\n\"%str(ude), key)\n stringdict[key] = []\n return stringdict\n\n","sub_path":"rosdoc_rosorg/src/rosdoc_rosorg/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":9320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"225836358","text":"import pytest\ntry:\n from PyQt5.QtCore import QCoreApplication\nexcept ImportError:\n from PyQt4.QtCore import QCoreApplication\nfrom .. settings import (\n UserSettings,\n SystemSettings,\n)\n\n\nclass Sentinel(object):\n \"\"\"Dummy object for making unique identities.\n \"\"\"\n pass\n\n\nclass BaseTestSettings(object):\n pass\n\n def test_getitem_missing(self):\n settings = self.get_settings()\n key = u\"bar\"\n with pytest.raises(KeyError):\n settings[key]\n\n def test_get_missing_no_default(self):\n settings = self.get_settings()\n key = u\"bar\"\n bar = settings.get(key)\n assert bar is None\n\n def test_get_missing_default(self):\n settings = self.get_settings()\n key = u\"bar\"\n value = Sentinel()\n bar = settings.get(key, value)\n assert bar is value\n\n def test_setitem_getitem_delitem(self):\n settings = self.get_settings()\n key = u\"foo\"\n value = u\"bar\"\n\n settings[key] = value\n assert settings[key] == value\n del settings[key]\n with pytest.raises(KeyError):\n settings[key]\n sentinel = Sentinel()\n assert settings.get(key, sentinel) == sentinel\n\n\nclass TestUserSettings(BaseTestSettings):\n @classmethod\n def get_settings(self):\n settings = UserSettings(\"boundless\", \"bcptest\")\n return settings\n\n \nclass TestSystemSettings(BaseTestSettings):\n @classmethod\n def get_settings(self):\n settings = SystemSettings(\"boundless\", \"bcptest\")\n return settings\n","sub_path":"boundless_content/quagmire/tests/test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"384291146","text":"import os\nimport tempfile\nimport yaml\nfrom colors import green\n\nfrom fabric.api import get, execute, put, roles\nfrom fabric.context_managers import cd\nfrom fabric.decorators import task\nfrom fabric.operations import run\nfrom fabric.state import env\nfrom fabric.contrib import files\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nconfig = {\n \"name\": \"Parsers for social networks\",\n\n \"build_server\": \"34.212.65.19\",\n \"repo_url\": \"git@gitlab.com:ingenix/hashtag-parsing/parsing.git\",\n \"app_path\": \"~/parsing\",\n \"app_branch\": \"master\",\n\n \"docker_image\": \"registry.gitlab.com/ingenix/hashtag-parsing/parsing\",\n \"image_type\": \"prod\",\n \"image_version\": \"latest\",\n\n \"deploy_server\": \"34.209.224.107\",\n \"compose_path\": \"/opt/servers\",\n \"compose_block_name\": \"parsing-parser\"\n}\n\n\nenv.user = \"deployer\"\nenv.hosts = [\"34.212.65.19\"]\nenv.forward_agent = False\n\nenv.roledefs = {\n 'build': [],\n 'deploy': []\n}\n\n\n@task\ndef deploy():\n \"\"\"\n Make full step-by-step deploy\n\n :param config: Configuration dict, loaded by slug\n :return: Nothing, if deploy passed\n :raises: Various exceptions, if something went wrong during deploy\n \"\"\"\n env.roledefs['build'] = [config[\"build_server\"]]\n env.roledefs['deploy'] = [config[\"deploy_server\"]]\n execute(get_code, config)\n execute(build_container, config)\n execute(push_container, config)\n execute(update_compose, config)\n execute(reload_docker, config)\n\n if config.get('post_deploy'):\n execute(post_deploy, config)\n\n print(green(\"\"\"\n SUCCESS\n \"\"\"))\n print(\"\"\"{docker_image}:{image_type}-{image_version} ready\n \"\"\".format(**config))\n\n\n@roles('build')\n@task\ndef get_code(config):\n \"\"\"\n Pulls update from remote repository\n\n :param config: Configuration dict\n :return: Nothing, if process passed\n \"\"\"\n if files.exists(config[\"app_path\"]):\n # Update buld repo\n with cd(config[\"app_path\"]):\n run(\"git checkout {}\".format(config[\"app_branch\"]))\n run(\"git pull origin {}\".format(config[\"app_branch\"]))\n config[\"image_version\"] = run(\"git rev-parse --short {}\".format(config[\"app_branch\"]))\n else:\n raise Exception(\"App repo not found\")\n\n\n@roles('build')\n@task\ndef build_container(config):\n \"\"\"\n Builds docker image\n\n :param config: Configuration dict\n :return: Nothing, if process passed\n \"\"\"\n if files.exists(config[\"app_path\"]):\n # Update buld repo\n with cd(config[\"app_path\"]):\n command = \"docker build --build-arg version={image_type} -t {docker_image}:{image_type}-{image_version} .\"\n run(command.format(**config))\n\n\n@roles('build')\n@task\ndef push_container(config):\n \"\"\"\n Pushes docker image to gitlab\n\n :param config: Configuration dict\n :return: Nothing, if process passed\n \"\"\"\n if files.exists(config[\"app_path\"]):\n # Update buld repo\n with cd(config[\"app_path\"]):\n command = \"docker push {docker_image}:{image_type}-{image_version}\"\n run(command.format(**config))\n\n\n@roles('deploy')\n@task\ndef update_compose(config):\n filename = os.path.join(config['compose_path'], \"docker-compose.yml\")\n image = \"{docker_image}:{image_type}-{image_version}\".format(**config)\n\n with tempfile.TemporaryFile() as fd:\n get(filename, fd)\n fd.seek(0)\n data = yaml.load(fd.read())\n data['services'][config['compose_block_name']]['image'] = image\n fd.seek(0)\n fd.truncate()\n fd.write(yaml.dump(data).encode('utf-8'))\n fd.flush()\n put(fd, filename)\n\n\n@roles('deploy')\n@task\ndef reload_docker(config):\n with cd(config[\"compose_path\"]):\n run('docker-compose up -d')\n\n\n@roles('deploy')\n@task\ndef post_deploy(config):\n with cd(config[\"compose_path\"]):\n run(config[\"post_deploy\"])\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"59986934","text":"\nclass solution:\n def best(self, s):#切片后直接对比效率很高,费时很短,并不用避免使用。\n size = len(s)\n if size <= 1 or s[::-1] == s:\n return s\n start, maxlen = 0, 1\n for idx in range(1, size):\n temp1 = idx - maxlen - 1\n sub2 = s[temp1 : idx + 1]\n if temp1 >= 0 and sub2[::-1] == sub2:\n start = temp1\n maxlen += 2\n continue\n temp2 = idx - maxlen\n sub1 = s[temp2 : idx + 1]\n if temp2 >= 0 and sub1[::-1] == sub1:\n start = temp2\n maxlen += 1\n return s[start : start + maxlen]\n\n def mysolution(self, s):\n elem = {}\n _max = [1, 0]\n for i, e in enumerate(s):\n if e in elem:#找同一元素\n for j in elem[e]:#同一元素可能的位置\n elen = i-j+1\n jcen = (j+i)/2\n if (jcen in elem and elem[jcen]+2 == elen) or (jcen not in elem and elen <= 3):#寻找同一元素的回文中心,并判断是否延长回文\n elem[jcen] = elen\n else:\n continue\n if elen > _max[0]:#是否延长最大参数\n _max = [elen, jcen]\n elem[e].append(i)\n else:#不存在同一元素\n elem[e] = [i]\n x, y = _max[0], _max[1]\n a = int((2*y-x+1)/2)\n b = int((2*y+x-1)/2+1)\n return s[a:b]\n","sub_path":"LeetCode/5_longest_palindromic_substring.py","file_name":"5_longest_palindromic_substring.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"542761594","text":"import tornado.gen\nimport bcrypt\nimport momoko\nimport psycopg2\nimport time\nfrom modules.message import Message\nimport logging\n\nlogging.basicConfig(format = u'%(levelname)-8s [%(asctime)s] %(message)s', level = logging.DEBUG, filename = u'logs/app.log')\n\nclass MomokoDB:\n db = None\n def __init__(self):\n if self.db is None:\n # self.createSchema()\n self.db = momoko.Pool(\n dsn='dbname=%s '\n 'user=%s '\n 'password=%s '\n 'host=%s '\n 'port=%s' % ('viberdb',\n 'admin',\n '',\n 'localhost',\n '5432'),\n size=1,\n max_size=50,\n auto_shrink=True\n )\n self.db.connect()\n\n @tornado.gen.coroutine\n def createSchema(self):\n self.db.execute(\"CREATE SEQUENCE item_id\")\n self.db.execute(\n '''CREATE TABLE bulks_wait\n (id INTEGER PRIMARY KEY DEFAULT NEXTVAL('item_id'),\n infobip_id varchar(80) NULL,\n username varchar(80) NOT NULL,\n bulk_name varchar(120) NOT NULL,\n insert_time INTEGER NOT NULL,\n send_time INTEGER NOT NULL,\n abon_number varchar(80) NOT NULL,\n viber_alpha varchar(80) NOT NULL,\n viber_message varchar(1000) NOT NULL,\n viber_validity_time INTEGER NOT NULL,\n viber_photo varchar(512) NULL,\n viber_btn_text varchar(45) NULL,\n viber_btn_ancour varchar(512) NULL,\n sms_alpha varchar(80) NOT NULL,\n sms_message varchar(1000) NOT NULL,\n sms_validity_time INTEGER NOT NULL,\n infobip_status varchar(80) NULL,\n channel varchar(80) NULL,\n status INTEGER NOT NULL)'''\n )\n self.db.execute(\"CREATE INDEX send_time ON bulks_wait(send_time)\")\n self.db.execute(\"CREATE INDEX status ON bulks_wait(status)\")\n self.db.execute(\"CREATE INDEX infobip_id ON bulks_wait(infobip_id)\")\n self.db.execute(\"CREATE SEQUENCE user_id\")\n self.db.execute('''\n CREATE TABLE users\n (id INTEGER PRIMARY KEY DEFAULT NEXTVAL('user_id'),\n login varchar(120) NOT NULL,\n pass varchar(512) NOT NULL,\n name varchar(120) NULL)\n ''')\n # self.db.execute('''\n # CREATE OR REPLACE FUNCTION update_id()\n # RETURNS trigger AS\n # $BODY$\n # BEGIN\n # IF (NEW.id IS NULL) THEN\n # NEW.id := nextval('item_id');\n # RETURN NEW;\n # END IF;\n # END;\n # $BODY$\n # LANGUAGE plpgsql;\n # ''')\n # self.db.execute('''\n # CREATE TRIGGER update_id_trigger BEFORE INSERT ON bulks_wait\n\t # FOR EACH ROW EXECUTE PROCEDURE update_id();\n # ''')\n\n @tornado.gen.coroutine\n def getCountSend(self):\n cursor = yield self.db.execute( \"SELECT COUNT(id) FROM bulks_wait WHERE status = 1\" )\n return cursor.fetchall()[0][0]\n\n @tornado.gen.coroutine\n def getMessagesWaitSend(self, limit=500):\n \"\"\"Выбирает сообщения с базы на отправку\"\"\"\n try:\n cursor = yield self.db.execute(\n '''SELECT\n id,\n infobip_id,\n username,\n bulk_name,\n insert_time,\n send_time,\n abon_number,\n viber_alpha,\n viber_message,\n viber_validity_time,\n viber_photo,\n viber_btn_text,\n viber_btn_ancour,\n sms_alpha,\n sms_message,\n sms_validity_time,\n infobip_status,\n channel,\n status\n FROM bulks_wait\n WHERE send_time <= EXTRACT(EPOCH FROM NOW())::INT AND status = 0\n ORDER BY id ASC\n LIMIT ''' + str(limit) + \" OFFSET 0;\"\n )\n msgs = self.messageFactory(cursor)\n return msgs\n except Exception as ex:\n print(ex)\n\n @tornado.gen.coroutine\n def setMessages(self, messages):\n \"\"\"Кладем сообщения в базу\"\"\"\n try:\n if type(messages) is list:\n data = []\n logging.info(\"Start INSERT \" + str(len(messages)) + \" messages!\")\n for message in messages:\n if message.abon_number:\n if message.id() is None :\n query = yield self.db.mogrify(\"( nextval('item_id'),%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\", message.getList()[1:])\n else:\n query = yield self.db.mogrify(\"( %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\", message.getList())\n data.append(query.decode(\"utf8\"))\n args_str = ','.join(data)\n logging.info(\"Start INSERT \" + str(len(data)) + \" messages!\")\n start = time.time()\n print(data[:3])\n print(\"Execution start\")\n yield self.db.execute(\"INSERT INTO bulks_wait VALUES \" + args_str + \" ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status, infobip_id = EXCLUDED.infobip_id, infobip_status = EXCLUDED.infobip_status, channel = EXCLUDED.channel\")\n print(\"Execution End \"+ str(time.time() - start ))\n\n else:\n new_str = messages.getList()\n logging.info(\"Start INSERT report from Infobip for Message with #ID: \" + str(messages.getList()[0]))\n print(new_str)\n yield self.db.execute(\"INSERT INTO bulks_wait VALUES %s ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status, infobip_id = EXCLUDED.infobip_id, infobip_status = EXCLUDED.infobip_status, channel = EXCLUDED.channel\", (new_str,))\n\n except psycopg2.Error as ex:\n print(ex)\n\n @tornado.gen.coroutine\n def getReportsByInfobipID(self, id):\n \"\"\"Вернет отчет по доставленному сообщению на Infobip\"\"\"\n try:\n cursor = yield self.db.execute(\n \"\"\"SELECT\n id,\n infobip_id,\n username,\n bulk_name,\n insert_time,\n send_time,\n abon_number,\n viber_alpha,\n viber_message,\n viber_validity_time,\n viber_photo,\n viber_btn_text,\n viber_btn_ancour,\n sms_alpha,\n sms_message,\n sms_validity_time,\n infobip_status,\n channel,\n status\n FROM bulks_wait\n WHERE infobip_id = %s\"\"\", (id,)\n )\n message = self.messageFactory(cursor)\n logging.info('getReportsByInfobipID: ' + str(message[0].infobip_id))\n return message[0]\n except psycopg2.Error as ex:\n print(ex)\n\n @tornado.gen.coroutine\n def getUserBulks(self, user):\n \"\"\"Вернет количество рассылок юзера\"\"\"\n try:\n cursor = yield self.db.execute(\n \"\"\"SELECT\n bulk_name,\n send_time,\n COUNT(id) as count_bulks,\n (CASE\n WHEN (COUNT(*) FILTER (WHERE status = 0)) != 0 THEN 'wait'\n WHEN (COUNT(*) FILTER (WHERE status = 1 or status = 2)) != 0 THEN 'now'\n WHEN (COUNT(*) FILTER (WHERE status = 3 or status = 4 or status = 5 or status = 6)) != 0 THEN 'complete'\n END) as state\n FROM bulks_wait\n WHERE username = %s\n GROUP BY bulk_name, send_time\n ORDER BY send_time;\"\"\", (user,))\n return cursor.fetchall()\n except Exception as ex:\n print(ex)\n\n @tornado.gen.coroutine\n def getBulkItem(self, bulk, time):\n \"\"\"Вернет рассылку по названию и времени старта\"\"\"\n try:\n cursor = yield self.db.execute(\n \"\"\"SELECT\n bulk_name,\n COUNT(id) AS AllMessages,\n SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) AS Delivered,\n SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS InProcess,\n SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) + SUM(CASE WHEN status = 5 THEN 1 ELSE 0 END) + SUM(CASE WHEN status = 6 THEN 1 ELSE 0 END) AS Undelivered,\n (CASE\n WHEN (COUNT(*) FILTER (WHERE status = 0)) != 0 THEN 'Рассылка запланирована'\n WHEN (COUNT(*) FILTER (WHERE status = 1 or status = 2)) != 0 THEN 'Выполняется доставка'\n WHEN (COUNT(*) FILTER (WHERE status = 3 or status = 4 or status = 5 or status = 6)) != 0 THEN 'Рассылка завершена'\n END) AS state,\n send_time,\n MAX(insert_time),\n CASE\n WHEN viber_photo IS NOT NULL THEN 'С картинкой' ELSE 'Без картинки'\n END AS Image,\n viber_alpha,\n (SELECT viber_message FROM bulks_wait WHERE bulk_name = %s LIMIT 1) as viber_mess,\n CASE\n WHEN viber_photo IS NOT NULL THEN viber_photo ELSE NULL\n END AS ImagePath,\n CASE\n WHEN viber_btn_ancour IS NOT NULL THEN viber_btn_ancour ELSE 'Без картинки'\n END AS ImageUrl,\n viber_validity_time,\n sms_alpha,\n (SELECT sms_message FROM bulks_wait WHERE bulk_name = %s LIMIT 1) as sms_mess,\n sms_validity_time,\n SUM(CASE WHEN status = 4 AND channel = 'VIBER' THEN 1 ELSE 0 END) AS count_viber,\n SUM(CASE WHEN status = 4 AND channel = 'SMS' THEN 1 ELSE 0 END) AS count_sms\n FROM bulks_wait\n WHERE bulk_name = %s AND send_time= %s\n GROUP BY bulk_name,\n send_time,\n Image,\n viber_alpha,\n ImagePath,\n ImageUrl,\n viber_validity_time,\n sms_alpha,\n sms_validity_time\"\"\", (bulk, bulk, bulk, time,)\n )\n return cursor.fetchall()\n except Exception as ex:\n print(ex)\n\n def messageFactory(self, cursor):\n msgs_lst = []\n for row in cursor.fetchall():\n id = None\n message = Message(row[0])\n for iField, field in enumerate(cursor.description):\n if field[0] == 'id': id = row[iField]\n if field[0] == 'infobip_id': message.infobip_id = row[iField]\n if field[0] == 'username': message.username = row[iField]\n if field[0] == 'bulk_name': message.bulk_name = row[iField]\n if field[0] == 'insert_time': message.insert_time = row[iField]\n if field[0] == 'send_time': message.send_time = row[iField]\n if field[0] == 'abon_number': message.abon_number = row[iField]\n if field[0] == 'viber_alpha': message.viber_alpha = row[iField]\n if field[0] == 'viber_message': message.viber_message = row[iField]\n if field[0] == 'viber_validity_time': message.viber_validity_time = row[iField]\n if field[0] == 'viber_photo': message.viber_photo = row[iField]\n if field[0] == 'viber_btn_text': message.viber_btn_text = row[iField]\n if field[0] == 'viber_btn_ancour': message.viber_btn_ancour = row[iField]\n if field[0] == 'sms_alpha': message.sms_alpha = row[iField]\n if field[0] == 'sms_message': message.sms_message = row[iField]\n if field[0] == 'sms_validity_time': message.sms_validity_time = row[iField]\n if field[0] == 'infobip_status': message.infobip_status = row[iField]\n if field[0] == 'channel': message.channel = row[iField]\n if field[0] == 'status': message.status = row[iField]\n msgs_lst.append(message)\n return msgs_lst\n\n @tornado.gen.coroutine\n def getFinishReports(self):\n try:\n cursor = yield self.db.execute(\"SELECT infobip_id FROM bulks_wait WHERE status = 2 AND (viber_validity_time + sms_validity_time) + insert_time < EXTRACT(EPOCH FROM NOW())::INT\")\n row = cursor.fetchall()[0]\n print(row)\n return row\n except psycopg2.Error as ex:\n print(ex)\n\n @tornado.gen.coroutine\n def authenticate(self, login, password):\n try:\n cursor = yield self.db.execute(\"SELECT * FROM users WHERE login = %s\", (login,))\n row = cursor.fetchall()\n if not row:\n print(\"No such user in system!!!\")\n logging.warning(\"No such user in system!!!\")\n return None\n pass_from_base = row[0][2].encode('utf8')\n if bcrypt.hashpw(password.encode('utf8'), pass_from_base) == pass_from_base:\n logging.info(\"User \" + str(row[0][1]) + ' enter in system!!!')\n return True\n else:\n logging.warning('Not correct password for user: ' + str(row[0][1]))\n return None\n except Exception as ex:\n print(ex)\n\n @tornado.gen.coroutine\n def exportCSV(self, name_bulk, time):\n try:\n cursor = yield self.db.execute(\"SELECT * FROM bulks_wait WHERE bulk_name = %s AND send_time = %s\", (name_bulk, time))\n row = cursor.fetchall()\n return row\n except Exception as ex:\n print(ex)\n","sub_path":"modules/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":14703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"365752842","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n__author__ = \"Marius Pozniakovas, Tomas Kučejevas\"\n__email__ = \"pozniak.marius@gmail.com\"\n\nimport os\nimport virtual_machine as VM\nimport memory as me\n\nclass RM:\n\n def __init__(self):\n \n #paging\n self._ptr = 0\n \n #command reading\n self._ic = 0\n\n #mode\n self._mode = 0\n \n #interrupts\n self._ti = 10\n self._si = 0\n self._pi = 0\n self._ioi = 0\n\n #channel registers\n self._ch1 = 0\n self._ch2 = 0\n self._ch3 = 0\n\n #random usage registers\n self._ra = 0\n self._rb = 0\n self._rc = 0\n\n #true/false register\n self._c = 0\n\n print('RM created.')\n self.mem = me.Memory()\n RM.menu(self)\n\n def menu(self):\n '''function that takes care of menu and then splits the workflow'''\n err = None\n \n while True:\n os.system('cls')\n\n print('------ Main menu -------')\n print('Command line \\t\\t 1')\n print('Read from HDD \\t\\t 2')\n print('Print registers \\t 3')\n print('Exit \\t\\t\\t q')\n print(\"Last input: \", err)\n print('--------------------------')\n\n menu_choice = input('Input your choice: ')\n\n if menu_choice == '1':\n err = 'Input'\n vm = VM.VM(self)\n vm.collect_input()\n\n elif menu_choice == '2':\n print('read from hdd')\n err = 'HDD'\n #break\n\n elif menu_choice == '3':\n os.system('cls')\n err = 'Memory'\n print('------ Registers -------')\n print('Paging')\n print('---')\n print('PTR \\t\\t\\t ', self._ptr)\n print('----------------------------')\n print('Mode')\n print('---')\n print('MODE \\t\\t\\t ', self._mode)\n print('----------------------------')\n print('Command Reading')\n print('---')\n print('IC \\t\\t\\t ', self._ic)\n print('----------------------------')\n print('Interrupts')\n print('---')\n print('TI \\t\\t\\t ', self._ti)\n print('SI \\t\\t\\t ', self._si)\n print('PI \\t\\t\\t ', self._pi)\n print('IOI \\t\\t\\t ', self._ioi)\n print('----------------------------')\n print('Random Usage')\n print('---')\n print('RA \\t\\t\\t ', self._ra)\n print('RB \\t\\t\\t ', self._rb)\n print('RC \\t\\t\\t ', self._rc)\n print('C \\t\\t\\t ', self._c)\n print('----------------------------')\n print('Channel Usage')\n print('---')\n print('CH1 \\t\\t\\t ', self._ch1)\n print('CH2 \\t\\t\\t ', self._ch2)\n print('CH3 \\t\\t\\t ', self._ch3)\n print('----------------------------')\n _input = input('Press enter to exit to main menu\\n')\n #break\n\n elif menu_choice == 'q':\n err = 'exiting'\n break\n\n else:\n err = 'Wrong Input' \n\n def setRA(self, RA):\n self._ra = RA\n\n def setRB(self, RB):\n self._rb = RB\n\n def setRC(self, RC):\n self._rc = RC\n\n def getRA(self):\n return self._ra\n\n def getRB(self):\n return self._rb\n\n def getRC(self):\n return self._rc\n\n def getC(self):\n return self._c\n\n #------------------\n #functions\n def _add(self):\n '''RC = RA + RB'''\n if(self._c == 0):\n self._rc = int(self._ra) + int(self._rb)\n self.mem.check_size(self._rc)\n else:\n print(\"C != 0, aborting operation\")\n return\n\n def _sub(self):\n '''RC = RA - RB'''\n if(self._c == 0):\n self._rc = int(self._ra) - int(self._rb)\n self.mem.check_size(self._rc)\n else:\n print(\"C != 0, aborting operation\")\n return\n\n def _cmp(self):\n ''' RA == RB ---> RC = 0\n RA < RB ---> RC = 1\n RA > RB ---> RC = 2 '''\n if self._ra == self._rb:\n self._rc = 0\n\n elif self._ra < self._rb:\n self._rc = 1\n\n elif self._ra > self._rb:\n self._rc = 2\n \n return\n \n def _rmw(self):\n '''TODO'''\n return\n\n def _rmi(self):\n '''TODO'''\n return\n\n def _jp(self):\n '''TODO'''\n return\n\n def _je(self):\n '''TODO'''\n return\n \n def _jg(self):\n '''TODO'''\n return\n\n def _halt(self):\n print('Halting')\n return\n\n def _out(self):\n print('RC =', self._rc)\n return\n\n def _rdw(self, a, b):\n self._ra = a\n self._rb = b\n self._c = 1\n return\n \n def _rdi(self, a, b):\n self._ra = a\n self._rb = b\n self._c = 0\n return\n","sub_path":"real_machine.py","file_name":"real_machine.py","file_ext":"py","file_size_in_byte":5171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"21087664","text":"from flask import Flask,render_template,request,redirect\nimport requests\nimport simplejson as json\nimport numpy as np\nfrom pandas import *\nimport pandas\nfrom datetime import date, timedelta\nfrom bokeh.plotting import figure, show\nfrom bokeh.io import output_notebook\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import *\nfrom bokeh.embed import components\nfrom bokeh.util.string import encode_utf8\n#from bokeh.resources import INLINE\n\napp = Flask(__name__)\n\napp.vars={}\n\n\n@app.route('/index',methods=['GET','POST'])\ndef index():\n\tif request.method == 'GET':\n\t\treturn render_template('index.html')\n\telse:\n\t\tapp.vars['ticker'] = request.form['ticker']\n\tprint(app.vars['ticker'])\n\ttry:\n\t\tr = requests.get(\"https://www.quandl.com/api/v3/datasets/WIKI/\"+app.vars['ticker']+\".json?auth_token=8XNJ9GnZjgoLQzcRH_87\")\n\texcept requests.exceptions.ConnectionError as e:\n\t\tprint(\"Connection timed out. Try again\")\n\t\treturn redirect('/timeout')\n\tapp.vars['D'] = json.loads(r.text)\n\treturn redirect('/main')\n\n@app.route('/main')\ndef main():\n\tif 'dataset' in app.vars['D']:\n\t\tprint('valid')\n\t\treturn redirect('/plot')\n\tprint('invalid')\n\treturn redirect('/error')\n\n#####################################\n\n@app.route('/plot')\ndef plot_display():\n\ttoday = date.today()\n\tif today.month == 1:\n\t\tnew_month = 12\n\t\tnew_year = today.year-1\n\telse:\n\t\tnew_month = today.month-1\n\t\tnew_year = today.year\n\tm_onemonth = today.replace(month=new_month, year = new_year)\n\n\tdata = np.array(app.vars['D']['dataset']['data'])[:,1:].astype(float)\n\tdates = np.array(app.vars['D']['dataset']['data'])[:,0].astype('M8[D]')\n\tc_header = np.array(app.vars['D']['dataset']['column_names']).astype(str)\n\n\tS = Series(data.T.tolist(), index = c_header[1:]).to_dict()\n\n\tDF = DataFrame(S, index=dates).sort_index(ascending=False)\n\n\tx = DF[today:m_onemonth].index\n\ty = DF[today:m_onemonth][\"Close\"][::-1]\n\n\tp = figure(title=app.vars['ticker']+\" closing price previous month\", plot_height=300, plot_width = 600, x_axis_type=\"datetime\")\n\tp.line(x,y,color = \"#2222aa\", line_width = 3)\n\t\n\t#js_res=INLINE.render_js()\n\t#css_res=INLINE.render_css()\n\n\tscript, div = components(p)#, INLINE)\n\tprint(div)\n\t\n\treturn render_template('plot.html',ticker=app.vars['ticker'], div=div, script=script)#, js_resources=js_res, css_resources=css_res)\n\t#return encode_utf8(html)\n\n@app.route('/error')\ndef error_display():\n\treturn render_template('error.html', ticker=app.vars['ticker'])\n\n@app.route('/timeout')\ndef TO_display():\n\treturn render_template('timeout.html')\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n","sub_path":"stocks.py","file_name":"stocks.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"456203986","text":"import calendar\nimport datetime\n\nyob = 1980\nytoday = datetime.datetime.now().year + 10\n\nfor y in range(ytoday - yob + 1):\n currenty = y + yob\n currentday = datetime.datetime(currenty, 4, 5)\n print('%s: %s' % (currenty, calendar.day_name[currentday.weekday()]))\n","sub_path":"disme/dayofdob.py","file_name":"dayofdob.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"652209481","text":"import os\nimport nose\nimport shutil\nimport yaml\nfrom xxxpythonPackageNamexxx import xxxmodule_namexxx, cl_utils\nfrom xxxpythonPackageNamexxx.utKit import utKit\n\nfrom dryxPython.projectsetup import setup_main_clutil\n\nsu = setup_main_clutil(\n arguments={},\n docString=__doc__,\n logLevel=\"DEBUG\",\n options_first=False,\n projectName=\"xxxpythonPackageNamexxx\",\n tunnel=False\n)\narguments, settings, log, dbConn = su.setup()\n\n# load settings\nstream = file(\n \"/Users/Dave/.config/xxxpythonPackageNamexxx/xxxpythonPackageNamexxx.yaml\", 'r')\nsettings = yaml.load(stream)\nstream.close()\n\n# SETUP AND TEARDOWN FIXTURE FUNCTIONS FOR THE ENTIRE MODULE\nmoduleDirectory = os.path.dirname(__file__)\nutKit = utKit(moduleDirectory)\nlog, dbConn, pathToInputDir, pathToOutputDir = utKit.setupModule()\nutKit.tearDownModule()\n\n\nclass test_xxxmodule_namexxx():\n\n def test_xxxmodule_namexxx_function(self):\n kwargs = {}\n kwargs[\"log\"] = log\n kwargs[\"settings\"] = settings\n # xt-kwarg_key_and_value\n\n testObject = xxxmodule_namexxx(**kwargs)\n testObject.get()\n\n # x-print-testpage-for-pessto-marshall-web-object\n\n # x-class-to-test-named-worker-function\n","sub_path":"python_module/tests/test_%%module_name%%.py","file_name":"test_%%module_name%%.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"249186908","text":"# https://www.geeksforgeeks.org/find-the-longest-substring-with-k-unique-characters-in-a-given-string/\n\n\ndef is_valid_substr(entity_count, k):\n return k >= len([val for val in entity_count.values() if val > 0])\n\n\ndef longest_k_unique_characters_substr(s, k):\n if not s or len(set([c for c in s])) < k:\n return -1\n\n entity_count = {s[0]: 1}\n longest_substr, substr_start, start = 0, -1, 0\n for end in range(1, len(s)):\n entity_count[s[end]] = entity_count.get(s[end], 0) + 1\n\n while not is_valid_substr(entity_count, k):\n entity_count[s[start]] -= 1\n start += 1\n\n if longest_substr < end - start + 1:\n longest_substr = end - start + 1\n substr_start = start # for print substring\n\n return longest_substr\n\n\nif __name__ == '__main__':\n T = int(input())\n\n for _ in range(T):\n s = input()\n k = int(input())\n\n print(longest_k_unique_characters_substr(s, k))\n","sub_path":"Problems/geeksforgeeks/Longest_K_unique_characters_substring.py","file_name":"Longest_K_unique_characters_substring.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"156571739","text":"from random import sample\nfrom itertools import count\n\ndef lead(move, fr, path = None):\n\tif path == None:\n\t\tpath = []\n\n\tts = move[fr]\n\tpath.append(fr)\n\n\tdiff = list(set(ts) - set(path))\n\tshuf = sample(diff, len(diff))\n\n\treturn lead(move, shuf[-1], path) if shuf else path\n\ndef num(move, n, m):\n\tk = count(1)\n\tnum = { (i, j) : next(k) for i in range(n) for j in range(m) }\n\treturn { num[k] : [ num[v] for v in vs ] for k, vs in move.items() }\n","sub_path":"lab6/lead.py","file_name":"lead.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"629285449","text":"import glob\nimport json\nimport os\nimport traceback\nimport boto3\nfrom re import search\nimport re\nimport logging\nfrom botocore.exceptions import ClientError\nfrom s3_upload import upload_file\n\n\n# Directory variables (root dir, data dir, etc.)\nimport pandas\n\nDATA_DIR = os.path.join(os.getcwd(), 'data')\nDIR = os.getcwd()\n\n#Path to input file(s)\nfile_list = [\"/Users/joshua.geissler/Documents/GitHub/updated-py-template/sample_1.csv\", \n\"/Users/joshua.geissler/Downloads/sample_4.csv\", \n\"https://discover-s3-testing.s3.amazonaws.com/sample_2.csv\", \n\"https://discover-s3-testing.s3.amazonaws.com/random/sample_3.csv\"]\n\ndef main():\n # This script will be executed in a container in a batch environment.\n\n # ######### Parameters ##########\n # Do not pass variables on the command line, read all the required parameters\n # from the ENV variables. Discover UI will collect the parameters needed and set them as ENV variables\n # at run time.\n\n # Example: Read a float value for threshold and default to 0.75 if missing\n # threshold = float(os.getenv(\"AD_THRESHOLD\", 0.75))\n\n message = os.getenv(\"AD_MESSAGE\", \"Running a Sample Python Script on Discover\")\n print(message)\n\n df = pandas.read_csv(os.path.join(DATA_DIR, 'icd10cm_codes_2020.csv'))\n\n # Discover UI uses 'results.json' file to display the output to use\n # For information on results.json format see: ???\n output_results = {\"data\": [], \"data_type\": \"generated\"}\n\n # Results object\n results_dict = {}\n\n for input_file in file_list:\n #boolean variable to track if input_file is local\n local = True\n\n #Check whether file is in s3, if not assume its local\n if search(\"s3.amazonaws.com\", input_file):\n local = False\n #Use Regex to find the bucket and key matches\n Regex = re.search('https://(.+?).s3.amazonaws.com/(.*)', input_file)\n\n #s3 bucket name\n bucket_name = Regex.group(1)\n #Path to file inside bucket\n key = Regex.group(2)\n\n #Initialize S3 and set bucket\n s3 = boto3.resource('s3')\n my_bucket = s3.Bucket(bucket_name)\n\n path, filename = os.path.split(key)\n my_bucket.download_file(key, filename)\n\n #Set input_file to reference new local copy of the file\n input_file = os.path.join(os.getcwd(), filename)\n\n DIR = os.getcwd()\n\n else:\n DIR = os.path.dirname(input_file)\n\n df_in = pandas.read_csv(input_file, header=None, names=['code'])\n\n for c in df_in['code']:\n # lookup the code in data file\n if c in list(df['code']):\n results_dict[c] = [df.loc[df.code == c].description.values[0]]\n else:\n results_dict[c] = \"***NOT FOUND***\"\n\n # Create results dataframe from results_dict\n results_df = pandas.DataFrame(results_dict).transpose()\n\n # Save results file to csv file\n print(f'Saving results to {DIR} directory ...')\n\n # extract the input filename for generating related result files\n input_filename = os.path.splitext(os.path.basename(input_file))[0]\n\n output_filename = f'{input_filename}_result.csv'\n results_df.to_csv(os.path.join(DIR, output_filename), header=False)\n\n # Note: Use filename to display the content of a file, and link to generate a link to download results\n output_results[\"data\"].append({\n \"title\": \"Results\",\n # \"filename\": output_filename,\n \"link\": output_filename,\n })\n\n #Upload Results to S3 if the file originated from there\n if not local:\n #if the file is inside of any folders within the S3 bucket we have to add the path and \"/\"\n if path:\n upload_file(input_file, bucket_name, path + \"/\" + output_filename)\n else:\n upload_file(input_file, bucket_name, output_filename)\n\n with open(os.path.join(DIR, \"results.json\"), \"w+\") as f:\n print(\"Writing results.json file\")\n json.dump(output_results, f)\n f.close()\n\n\nif __name__ == '__main__':\n try:\n main()\n except Exception as e:\n tb = traceback.format_exc()\n\n with open(os.path.join(os.getcwd(), \"results.json\"), \"w+\") as f:\n print(\"Writing errors in results.json file\")\n json.dump({\n \"data_type\": \"generated\",\n \"data\": [\n {\"error\": str(tb), \"title\": \"Error\"}\n ]\n }, f)\n f.close()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"401988051","text":"import json\nimport requests\nimport datetime as dt\nimport ics\nimport threading\nimport time\n\n\ndef threaded(func):\n def wrapper(*args, **kwargs):\n threading.Thread(target=func, args=args, kwargs=kwargs).start()\n\n return wrapper\n\n\nclass Schedule:\n def __init__(self):\n print('> Schedule: OK')\n self.db = None\n self.__updating__ = False\n self.last_update = ''\n self.update()\n self.__updater__()\n\n @threaded\n def __updater__(self):\n while True:\n current_time = str(dt.datetime.now()).split(' ')[1].split('.')[0]\n if '19:55:00' > current_time > '19:50:00':\n print('$ Trying to start planned update at ' + current_time + ' $')\n if self.__updating__ is False:\n print('$ Planned update started $')\n self.update()\n else:\n print('$ Cancel (Updating already in process $')\n time.sleep(180)\n\n @threaded\n def update(self):\n self.__updating__ = True\n self.db = None\n self.last_update = str(dt.datetime.now()).split(' ')[1].split('.')[0]\n print('$ Schedule updating started')\n self.db = self._fill_schedule()\n print('$ Schedule updated')\n self.__updating__ = False\n\n def get_group_schedule(self, title):\n if self.db is not None:\n for group in self.db:\n if group['title'].lower() == title.lower():\n return group['schedule']\n return None\n\n @staticmethod\n def _get_json(url):\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 '\n '(KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}\n response = requests.get(url, headers=headers)\n return json.loads(response.text)\n\n @staticmethod\n def _get_group_list():\n groups = Schedule._get_json('https://urfu.ru/api/schedule/groups/')\n group_db = []\n for e in groups:\n group_db.append({'id': e['id'],\n 'title': e['title']})\n return group_db\n\n def _fill_schedule(self):\n schedule = []\n i = 0\n for group in Schedule._get_group_list():\n group_schedule = self._get_schedule(group['id'])\n schedule.append({'title': group['title'],\n 'schedule': group_schedule})\n i += 1\n if i % 100 == 0:\n print('$ ' + str(i) + ' groups scrapped')\n\n return schedule\n\n @staticmethod\n def _get_schedule(group_id):\n date = str(dt.date.today()).replace('-', '')\n url = 'https://urfu.ru/api/schedule/groups/calendar/' + str(group_id) + '/' + date\n\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 '\n '(KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}\n response = requests.get(url, headers=headers)\n calendar = ics.Calendar(response.text)\n\n schedule = []\n for event in calendar.events:\n begin_date, begin_time = tuple(str(event.begin).split('+')[0].split('T'))\n begin_time = str(begin_time)[:5:]\n end_time = str(event.end).split('+')[0].split('T')[1][:5:]\n weekday = Schedule._get_weekday(begin_date)\n name = event.name\n begin_date_iso = Schedule._iso_date(begin_date)\n location = event.location\n description = event.description\n\n flag = False\n for e in schedule:\n if e[\"begin_date\"] == begin_date_iso:\n e[\"weekday\"] = weekday\n e[\"events\"].append({\n \"location\": location,\n \"begin_time\": begin_time,\n \"end_time\": end_time,\n \"name\": name\n })\n flag = True\n continue\n if flag:\n continue\n\n schedule.append({\"begin_date\": begin_date_iso,\n \"weekday\": weekday,\n \"events\": [\n {\n \"location\": location,\n \"begin_time\": begin_time,\n \"end_time\": end_time,\n \"name\": name\n }\n ]\n })\n schedule.sort(key=lambda x: x['begin_date'])\n for day in schedule:\n day['events'].sort(key=lambda x: x['begin_time'])\n return schedule\n\n @staticmethod\n def _iso_date(date):\n year, month, day = tuple(str(date).split('-'))\n iso_date = str(day) + '.' + str(month) + '.' + str(year)\n return str(iso_date)\n\n @staticmethod\n def _get_weekday(date):\n year, month, day = tuple(str(date).split('-'))\n d = dt.date(int(year), int(month), int(day))\n weekday_n = d.isoweekday()\n if weekday_n == 1:\n return 'Пн'\n elif weekday_n == 2:\n return 'Вт'\n elif weekday_n == 3:\n return 'Ср'\n elif weekday_n == 4:\n return 'Чт'\n elif weekday_n == 5:\n return 'Пт'\n elif weekday_n == 6:\n return 'Сб'\n elif weekday_n == 7:\n return 'Вс'\n","sub_path":"core/schedule_grabber.py","file_name":"schedule_grabber.py","file_ext":"py","file_size_in_byte":5518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"241397237","text":"#!/usr/bin/env python\nimport env\n\nimport os\nimport os.path\n\nfrom config_descr.PROJECT import g_available_platform\n\nfrom common.shared_logger import g_logger\nfrom common.config import get_global_property\nfrom internal.report_builder import StepReporter\nfrom common.exceptions import CommonException\nfrom common import descr_argument_parser\nfrom common.description import Description\nimport common.tempcache as tempcache\nimport common.execution as execution\n\nfrom internal import fs\nimport internal.svn.command as svn\n\n\ndef get_context_description():\n return Description({\n 'config_path': {\n 'default': os.path.join(get_global_property(\"framework_dir\"), \"Sources\", \"Internal\", \"DAVAConfig.h\"),\n 'help': 'path to config file to restore',\n 'type': str\n },\n 'vcs': {\n 'default': 'git',\n 'help': 'version control system that is used to store config',\n 'choices': env.g_supported_vcs\n },\n })\n\n\ndef __restore_from_cache(config_dir, config_name):\n g_logger.warning(\"trying to restore %s from cache\" % config_name)\n config_path = os.path.join(config_dir, config_name)\n backup_config_path = tempcache.get_cache_path(config_name)\n if os.path.isfile(backup_config_path):\n fs.copy_replace_file(backup_config_path, config_path)\n else:\n g_logger.error(\"failed to restore %s from cache\" % config_path)\n\n\ndef __restore_from_git(config_dir, config_name):\n g_logger.info(\"__restore_from_git(%s, %s)\" % (config_dir, config_name))\n execution.verbose_call_in(config_dir, ['git', 'checkout', config_name])\n\n\ndef __restore_from_svn(config_dir, config_name):\n g_logger.info(\"__restore_from_svn(%s, %s)\" % (config_dir, config_name))\n svn.revert(config_dir, config_name)\n\n\ng_vcs_restore_functions = {\n 'cache': __restore_from_cache,\n 'svn': __restore_from_svn,\n 'git': __restore_from_git\n}\n\n\ndef get_input_context(*argv, **kwargs):\n parser = descr_argument_parser.DescrArgumentParser(description='Set ios specific properties')\n parser.add_descr(get_context_description())\n return parser.get_context(*argv, **kwargs)\n\n\ndef do(context):\n g_logger.info(context)\n\n with StepReporter('restore config header'):\n if os.path.isfile(context['config_path']):\n config_dir, config_name = os.path.split(context['config_path'])\n\n if context['vcs'] is not None:\n if context['vcs'] in g_vcs_restore_functions:\n g_vcs_restore_functions[context['vcs']](config_dir, config_name)\n return\n else:\n g_logger.warning(\"unsupported vcs, will try to restore from backup\")\n __restore_from_cache(config_dir, config_name)\n\n else:\n raise CommonException(\"%s does not exist\" % context['config_path'])\n\n\nif __name__ == '__main__':\n do(get_input_context())\n","sub_path":"Scripts/project/building/restore_config.py","file_name":"restore_config.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"614622545","text":"import numpy as np\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport os\nimport requests\n\n\npath = os.path.dirname(os.getcwd()) + '\\\\Sources\\\\'\ndest_codes_path = path + 'transformed\\\\airport_codes.csv'\n\n\ndef parse_to_csv(url):\n page = requests.get(url)\n soup = BeautifulSoup(page.content, \"html.parser\")\n data = soup.find_all(\"tr\")\n code = \"\"\n for i in data:\n code += str(i)\n code += \"
\"\n df = pd.DataFrame(np.concatenate(pd.read_html(code)),columns=['IATA','ICAO','Location','Airport', 'Country'])\n\n df = df[['IATA','ICAO']]\n print(df)\n df.to_csv(dest_codes_path, index=False, header=True, mode='w')\n\n\n\nif __name__ == \"__main__\":\n if os.path.exists(dest_codes_path):\n print(\"File already exists\")\n else:\n parse_to_csv(\"http://www.flugzeuginfo.net/table_airportcodes_country-location_en.php\")\n","sub_path":"Py/airport_iata_icao.py","file_name":"airport_iata_icao.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"592830575","text":"from flask_restful import Resource, reqparse\nfrom models.stall import StallModel\n\n\nclass Stall(Resource):\n\tparser = reqparse.RequestParser()\n\tparser.add_argument('cam_id',\n\t\ttype = str,\n\t\trequired = True,\n\t\thelp = 'Cam Identifier'\n\t\t)\n\tparser.add_argument('status',\n\t\ttype=int,\n\t\trequired = True,\n\t\thelp = 'Stall Status'\n\t\t)\n\tparser.add_argument('rt_time',\n\t\ttype = int,\n\t\trequired = True,\n\t\thelp = 'Time stamp of when modified'\n\t\t)\n\t\n\tdef get(self,lot_id,stall_id):\n\t\titem = StallModel.find_by_stall_id(lot_id,stall_id)\n\t\tif item: \n\t\t\treturn item.json()\n\t\treturn {'message': 'Item not found'}, 404\n\n\tdef put(self,lot_id,stall_id):\n\t\tdata = Stall.parser.parse_args()\n\t\titem = StallModel.find_by_stall_id(lot_id,stall_id)\n\t\t\n\t\tif item is None:\n\t\t\titem = StallModel(lot_id,stall_id,**data)\n\t\telse: \n\t\t\titem.status = data['status']\n\t\t\n\t\titem.save_to_db()\n\n\t\treturn item.json()\n\t\nclass Cam_Status(Resource):\n\tdef get(self,lot_id,cam_id):\n\t\treturn {'Cam_Status': [item.json() for item in StallModel.query.filter_by(lot_id=lot_id,cam_id=cam_id)]}\n\nclass Lot_Status(Resource):\n\tdef get(self,lot_id):\n\t\treturn {'Lot_Status': [item.json() for item in StallModel.query.filter_by(lot_id=lot_id)]}\n\n","sub_path":"resources/stall.py","file_name":"stall.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"589198662","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 10 15:19:02 2014\nDo the LSA using the gensim toolkit\nsave the LSA information\nthe texts is built in form of:\n [[the id which contains the word1],[the id which contains the word2]...]\nthis versions is for words analysis\n@author: mountain\n\"\"\"\nfrom gensim import corpora\nfrom LSA import LSA\nimport json\nfrom read_and_write import write_dict_into_GB18030\n\n\n\nf=file(r'../../result/pre/words_id_dict_further.json')\n#f=file(r'E:/BD/bddac/result/pre/test.json')\ndictword=json.load(f,encoding = \"GB18030\", strict=False)\n\nf=file(r'../../result/pre/id_num_mapping.json')\nidnum=json.load(f,encoding = \"GB18030\", strict=False)\n\nword_num={}\ntexts=[]\nfor i,k in enumerate(dictword):\n word_num[k]=i\n tmp=[]\n for s in idnum:\n for ele in dictword[k]:\n if idnum[s]==ele:\n tmp.append(s)\n texts.append(tmp)\n\nword_doc_path='../../result/word/word_doc.json'\nwrite_dict_into_GB18030(word_doc_path,texts) \n\nword2num_path = '../../result/word2num.json'\nwrite_dict_into_GB18030(word2num_path, word_num)\n\ndictionary,corpus,tfidf,corpus_tfidf,lsi,corpus_lsi=LSA(texts)\n\n#save the dictionary according to the texts\nfname='../../result/word/dict.txt'\ndictionary.save_as_text(fname)\n\n#save the corpus, corpus=[[(id,id_occured_times_in_word) for id occured in word] for word in texts]\nword_docid_path='../../result/word/word_docid.txt'\ncorpora.MmCorpus.serialize(word_docid_path, corpus) \n#aa=list(corpora.MmCorpus(word_docid_path))\n\n#save the tfidf_model which can be used later for mapping a corpus to a tf-idf_copus\ntfidf_model='../../result/word/tfidf_model.txt'\ntfidf.save(tfidf_model)\n\n#save the corpus_tfidf, list(corpus_tfidf)=[[(id,tf_idf) for id occured in word] for word in texts]\nword_tfidf_path='../../result/word/doc_tfidf.txt'\ncorpora.MmCorpus.serialize(word_tfidf_path, corpus_tfidf)\n#bb=list(corpora.MmCorpus(word_tfidf_path))\n\n#save the lsi_model\nlsi_model='../../result/word/lsimodel.txt'\nlsi.save(lsi_model)\n#lsi = models.LsiModel.load('/tmp/model.lsi')\n\n#save the corpus_lsi,list(corpus_lsi)=[[ftr of the word after lsi] for word in texts]\ncorpora.MmCorpus.serialize('../../result/word/word_ftr_aft_lsi.txt', corpus_lsi)\n \n","sub_path":"src/feature-extraction/Lsa_word.py","file_name":"Lsa_word.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"265358549","text":"from typing import List\n\nclass Solution:\n def findErrorNums(self, nums: List[int]) -> List[int]:\n\n res = []\n val_dict = {}\n\n for i in nums:\n if val_dict.get(i) != None:\n res.append(i)\n else: val_dict[i] = 1\n\n for i in range(1, len(nums) +1 ):\n if i not in val_dict.keys():\n res.append(i)\n break\n return res","sub_path":"leetcode/data_structure/hash/set_mismatch.py","file_name":"set_mismatch.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"636085449","text":"from controller import Robot, Camera, Motor, Accelerometer, GPS, TouchSensor\nimport os\n#import Config\n#import original\nimport sys\n\ntry:\n pythonVersion = 'python%d%d' % (sys.version_info[0], sys.version_info[1])\n libraryPath = os.path.join(os.environ.get(\"WEBOTS_HOME\"), 'projects', 'robots', 'robotis', 'darwin-op', 'libraries',\n pythonVersion)\n libraryPath = libraryPath.replace('/', os.sep)\n sys.path.append(libraryPath)\n from managers import RobotisOp2GaitManager, RobotisOp2MotionManager\nexcept ImportError:\n sys.stderr.write(\"Warning: 'managers' module not found.\\n\")\n sys.exit(0)\n\nclass Walk():\n def __init__(self):\n self.robot = Robot() # Initialize the Robot class to control the robot \n self.mTimeStep = int(self.robot.getBasicTimeStep()) # Get the current simulation time mTimeStep of each simulation step\n self.HeadLed = self.robot.getLED('HeadLed') # Get head LED light\n self.EyeLed = self.robot.getLED('EyeLed') # Get head LED light\n self.HeadLed.set(0xff0000) # Turn on the head LED light and set a color\n self.EyeLed.set(0xa0a0ff) # Light up the eye LED lights and set a color\n self.mAccelerometer = self.robot.getAccelerometer('Accelerometer') # Get the accelerometer\n self.mAccelerometer.enable(self.mTimeStep)# Activate the sensor and update the value with mTimeStep as the cycle\n\n self.fup = 0\n self.fdown = 0 # Define two class variables for later judging whether the robot has fallen down\n \n self.mGyro = self.robot.getGyro('Gyro') # Get the gyroscope\n self.mGyro.enable(self.mTimeStep) # Activate the gyroscope and update the value with mTimeStep as the cycle\n\n self.camera = self.robot.getCamera('Camera') # Get the Camera\n self.camera.enable(self.mTimeStep)# Activate the Camera and update the value with mTimeStep as the cycle\n \n self.accelerometer = self.robot.getDevice('Accelerometer') # Get the Accelerometer\n self.accelerometer.enable(self.mTimeStep)# Activate the Accelerometer and update the value with mTimeStep as the cycle\n \n self.gps = self.robot.getGPS('gps')# Get the GPS\n self.gps.enable(self.mTimeStep)# Activate the GPS and update the value with mTimeStep as the cycle\n \n \n self.positionSensors = [] # Initialize the joint angle sensor\n self.positionSensorNames = ('ShoulderR', 'ShoulderL', 'ArmUpperR', 'ArmUpperL',\n 'ArmLowerR', 'ArmLowerL', 'PelvYR', 'PelvYL',\n 'PelvR', 'PelvL', 'LegUpperR', 'LegUpperL',\n 'LegLowerR', 'LegLowerL', 'AnkleR', 'AnkleL',\n 'FootR', 'FootL', 'Neck', 'Head') # Initialize each sensor name\n\n # Acquire and activate each sensor, update the value with mTimeStep as the cycle\n for i in range(0, len(self.positionSensorNames)):\n self.positionSensors.append(self.robot.getPositionSensor(self.positionSensorNames[i] + 'S'))\n self.positionSensors[i].enable(self.mTimeStep)\n \n\n self.mKeyboard = self.robot.getKeyboard() # Initialize keyboard reading class\n self.mKeyboard.enable(self.mTimeStep) # Read from the keyboard with mTimeStep as the cycle\n\n self.mMotionManager = RobotisOp2MotionManager(self.robot) # Initialize the robot action group controller\n self.mGaitManager = RobotisOp2GaitManager(self.robot, \"config.ini\") # Initialize the robot gait controller\n \n \n def myStep(self):\n ret = self.robot.step(self.mTimeStep)\n if ret == -1:\n exit(0)\n \n def wait(self, ms):\n startTime = self.robot.getTime()\n s = ms / 1000.0\n while s + startTime >= self.robot.getTime():\n self.myStep()\n\n def run(self):\n \n print(\"-------Walk example of ROBOTIS OP2-------\")\n print(\"This example illustrates Gait Manager\")\n print(\"Press the space bar to start/stop walking\")\n print(\"Use the arrow keys to move the robot while walking\")\n \n self.myStep() # Simulate a step size and refresh the sensor reading\n\n self.mMotionManager.playPage(9) #Perform the 9th action of the action group,initialize the standing posture, and prepare to walk\n self.wait(200) # Wait 200ms\n\n self.isWalking = False # The robot does not enter the walking state at the beginning\n\n initialgps = self.gps.getValues() # store the starting GPS Location of the Robot in X,Y,Z Axis\n print(\"Starting Location:\",initialgps) # printing the statement \n\n \n\n while True:\n self.checkIfFallen() # Determine whether to fall\n self.mGaitManager.setXAmplitude(0.0) # Advance to 0\n self.mGaitManager.setAAmplitude(0.0) # Turn to 0\n key = 0 # The initial keyboard reading defaults to 0\n key = self.mKeyboard.getKey() # Read input from keyboard\n if key == 32: # If a space is read, change the walking state\n if (self.isWalking): # If the current robot is walking, stop the robot\n self.mGaitManager.stop()\n self.isWalking = False\n self.wait(200)\n else: # If the robot is currently stopped, it will start walking\n self.mGaitManager.start()\n self.isWalking = True\n self.wait(200)\n elif key == 315: # \n self.mGaitManager.setXAmplitude(1.0)\n print(\"GPS:\",self.gps.getValues())\n print(\"Total Distance traveled in Terms of X Coordinate in metres:\",abs(self.gps.getValues()[0]-initialgps[0]))\n #print(\"GPS Y:\",self.gps.getValues()[1]-initialgps[1])\n print(\"Total Distance traveled in Terms of Z Coordinate in metres:\",abs(self.gps.getValues()[2]-initialgps[2]))\n print(\"Speed:\",self.gps.getSpeed())\n \n elif key == 317: \n self.mGaitManager.setXAmplitude(-1.0)\n print(\"GPS:\",self.gps.getValues())\n print(\"Total Distance traveled in Terms of X Coordinate in metres :\",abs(self.gps.getValues()[0]-initialgps[0]))\n #print(\"GPS Y:\",self.gps.getValues()[1]-initialgps[1])\n print(\"Total Distance traveled in Terms of Z Coordinate in metres :\",abs(self.gps.getValues()[2]-initialgps[2]))\n print(\"Speed:\",self.gps.getSpeed())\n \n elif key == 316: \n self.mGaitManager.setAAmplitude(-0.5)\n print(\"GPS:\",self.gps.getValues())\n print(\"Total Distance traveled in Terms of X Coordinate in metres:\",abs(self.gps.getValues()[0]-initialgps[0]))\n #print(\"GPS Y:\",self.gps.getValues()[1]-initialgps[1])\n print(\"Total Distance traveled in Terms of Z Coordinate in metres:\",abs(self.gps.getValues()[2]-initialgps[2]))\n print(\"Speed:\",self.gps.getSpeed())\n \n elif key == 314: \n self.mGaitManager.setAAmplitude(0.5)\n print(\"GPS:\",self.gps.getValues())\n print(\"Total Distance traveled in Terms of X Coordinatei n metres:\",abs(self.gps.getValues()[0]-initialgps[0]))\n #print(\"GPS Y:\",self.gps.getValues()[1]-initialgps[1])\n print(\"Total Distance traveled in Terms of Z Coordinate in metres:\",abs(self.gps.getValues()[2]-initialgps[2]))\n print(\"Speed:\",self.gps.getSpeed())\n \n self.mGaitManager.step(self.mTimeStep) # The gait generator generates a step-length movement\n self.myStep() # Simulate a step size\n \n \n def checkIfFallen(self):\n \n acc = self.mAccelerometer.getValues() # Obtain the corresponding values of the three axes through the acceleration sensor\n acc_tolerance = 80.0\n acc_step = 100 # Counter upper limit\n \n if (acc[1] < 512.0 - acc_tolerance): # The value of the y-axis will decrease when you face down on the ground\n self.fup = self.fup + 1 # Counter plus 1\n else:\n self.fup = 0 # Counter reset\n\n if (acc[1] > 512.0 + acc_tolerance): # The value of the y-axis will increase when you fall back down\n self.fdown = self.fdown + 1 # Counter plus 1\n else:\n self.fdown = 0 # Counter reset\n\n if (acc[0] < 512.0 - acc_tolerance):\n self.fright = self.fright + 1\n else:\n self.fright = 0\n\n if (acc[0] > 512.0 + acc_tolerance):\n self.fleft = self.fleft + 1\n else:\n self.fleft = 0\n\n # the robot face is down\n if (self.fup > acc_step): # The counter exceeds the upper limit, that is, the falling time exceeds acc_step simulation steps\n print(\"1\")\n self.mMotionManager.playPage(10) # Perform face-down and stand-up movements\n self.mMotionManager.playPage(9) # Resume walking position\n self.fup = 0\n\n # the back face is down\n elif (self.fdown > acc_step) :\n print(\"2\")\n self.mMotionManager.playPage(11) # Perform back-to-ground and stand-up movements\n self.mMotionManager.playPage(9) # Resume walking position\n self.fdown = 0 # Counter reset\n\n # the back face is down\n elif (self.fright > acc_step) :\n print(\"3\")\n self.mMotionManager.playPage(13)\n self.fright = 0\n\n # the back face is down\n elif (self.fleft > acc_step) :\n print(\"4\")\n self.mMotionManager.playPage(12)\n self.fleft = 0\n\n \n def auto_run(self):\n self.myStep() # Simulate a step to refresh the sensor reading \n self.mMotionManager.playPage(9) # Perform action group 9, initialize standing position, and prepare to walk \n self.wait(200) # Wait 200ms \n self.isWalking = False # Initially, the robot did not enter the walking state \n initialgps = self.gps.getValues() # store the starting GPS Location of the Robot in X,Y,Z Axis\n print(\"Starting Location:\",initialgps) # printing the statement \n while True:\n self.checkIfFallen() # Determine whether to fall\n self.mGaitManager.start() # Gait generator enters walking state \n self.mGaitManager.setXAmplitude(1.0) # Set robot forward \n self.mGaitManager.step(self.mTimeStep) # Gait generator generates a step action \n self.myStep() # Simulate one step \n print(\"GPS:\",self.gps.getValues())\n print(\"Total Distance traveled in Terms of X Coordinate:\",self.gps.getValues()[0]-initialgps[0])\n #print(\"GPS Y:\",self.gps.getValues()[1]-initialgps[1])\n print(\"Total Distance traveled in Terms of Z Coordinate::\",self.gps.getValues()[2]-initialgps[2])\n print(\"Speed:\",self.gps.getSpeed())\n\n\nif __name__ == '__main__':\n walk = Walk() \n walk.run() ","sub_path":"python_walk_getup.py","file_name":"python_walk_getup.py","file_ext":"py","file_size_in_byte":11148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"601871896","text":"from flask import render_template, redirect, url_for, request\nfrom datetime import datetime\nfrom . import app\nfrom .forms import TaskForm\nfrom .models import db, Task, tasks_schema\n\n\n@app.route('/', methods=['get', 'post'])\ndef index():\n form = TaskForm()\n return render_template('index.html', form=form)\n\n\n@app.route('/task_list', methods=['get'])\ndef task_list():\n tasks = sorted(Task.query.all(), key=lambda task: task.id)\n return tasks_schema.dumps(tasks)\n\n\n@app.route('/complete_tasks', methods=['post'])\ndef complete_tasks():\n tasks = Task.query.all() # from database\n results = tasks_schema.load(request.get_json()) # from front-end\n\n # Making sure everything aligns to compare:\n assert len(tasks) == len(results)\n tasks.sort(key=lambda task: task.id)\n results.sort(key=lambda task: task.id)\n\n for task, result in zip(tasks, results):\n if result.completed != task.completed:\n model_instance = Task.query.filter_by(id=task.id).first()\n\n if not task.completed:\n model_instance.finished_at = datetime.utcnow()\n else:\n model_instance.finished_at = None\n\n model_instance.completed = not model_instance.completed\n db.session.commit()\n\n return redirect('/') # maybe these will go away\n\n\n@app.route('/new_task', methods=['post'])\ndef new_task():\n data = request.form.get('description')\n\n new_task = Task(\n description=data,\n completed=False,\n created_at=datetime.utcnow(),\n finished_at=None\n )\n\n db.session.add(new_task)\n db.session.commit()\n\n return redirect('/') # maybe these will go away\n\n\n@app.route('/delete_task/', methods=['post'])\ndef delete_task(id):\n to_delete = Task.query.filter_by(id=id).delete()\n db.session.commit()\n\n return redirect('/') # maybe these will go away\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"570443825","text":"from PPOutils import *\n\n# Initialize Actor, Critic, Memory\n# Lines 1 to 2 in the DeepMimic Pseudocode \nactor = actorNet()\ncritic = criticNet()\nmemory = Memory()\noptimizerActor = optim.Adam(actor.parameters(), lr=lrActor)\noptimizerCritic = optim.Adam(critic.parameters(), lr=lrCritic)\n\n\nfor i in range(numIterations): # Line 3\n \n # Lines 4 to 13\n memory.fill(actor,env) # Collects samples as side-effect,\n # Returns logarithmic Probability of\n # all actions in the samples\n actorOld = actor # Line 14\n\n for u in range(numUpdates): # Line 15\n sars = memory.sample() # Line 16\n\n # Update Value function , Lines 17 to 21\n y_i = TdResiduals(sars)\n update(critic.Loss(y_i,sars), optimizerCritic)\n\n # Lines 22 to 26\n Adv = gae(y_i)\n # i[0] : state of current sample, i[1] : Action of current sample\n ratios = [(actor(tensor(np.transpose(i[0]))).log_prob(i[1])- i [6]).exp() for i in sars]\n # Use of logarithmic probabilities for numerical stability\n \n update(actor.Loss(Adv,ratios,epsilon),optimizerActor) # Line 27\n \n print(str(i) +\" / \" + str(numIterations))\ntestRun(actor, env)\n\n\n","sub_path":"PPO/rug/PPO.py","file_name":"PPO.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"559365856","text":"import cv2 as cv\nimport numpy as np\nimport glob\nimport time\n\nfrom feature_extractors import CHOG, Hog, LocalBinaryPatterns\nfrom landmark_predictor import extract_samples, predict\n\n################################################# ds 2k, ext = LocalBinaryPatterns is the bé####################################\n# OPEN_KERNEL_SIZE = (5,5)\n# WINDOW_SIZE = 50\n# LBP_PATCH_SIZE = 50 #for lbp\n\n# BLUR_SIZE = 3 #good for ds 2k \n# num_random = 100\n\n\n# #ext = LocalBinaryPatterns(8,3, cell_count = 8, patchSize= LBP_PATCH_SIZE)\n# ext = CHOG(radius = 20, pixel_distance= 1, block_count = 1, bin_count = 9)\n\n# center_points, true_features = extract_samples ('training2k_align', extractor = ext, blur_size = BLUR_SIZE )\n\n# smp_img = cv.imread('./training2k/egfr_F_R_oly_2X_3.tif', cv.IMREAD_GRAYSCALE) # sample image used for aligning predicted images\n# smp_img = cv.medianBlur(smp_img,BLUR_SIZE)\n\n# mask = np.zeros(smp_img.shape[:2], dtype=\"uint8\") \n# ROI_BORDER_SIZE = 250\n# mask = cv.rectangle(mask, (ROI_BORDER_SIZE,ROI_BORDER_SIZE),(smp_img.shape[1]-ROI_BORDER_SIZE, smp_img.shape[0]-ROI_BORDER_SIZE), 255, -1)\n\n# #predict (smp_img, './predict2k\\egfr_F_R_oly_2X_7.tif', center_points, true_features, window_size= WINDOW_SIZE, candidate_method = \"keypoint_on_bin_img\", extractor= ext, mask_roi= mask, blur_size= BLUR_SIZE, open_kernel_size = OPEN_KERNEL_SIZE, debug= True)\n# for name in glob.glob('./predict2k/*.tif'):#for each tif\n# print(\"Processing \", name)\n# predict(smp_img, name, center_points, true_features, window_size= WINDOW_SIZE, candidate_method = \"keypoint_on_bin_img\", extractor= ext, mask_roi= mask, blur_size= BLUR_SIZE, open_kernel_size = OPEN_KERNEL_SIZE, debug= False)\n\n################################################# ds nature####################################\nPATCH_SIZE = 60\nlbp = LocalBinaryPatterns(16,3, cell_count = 8, patchSize= PATCH_SIZE)\n# hog = Hog(winSize = (16,16), blockSize = (8, 8), blockStride=(2,2), cellSize=(4,4))\n\n# chog = CHOG(radius = 30, pixel_distance= 1, block_count = 1, bin_count = 9)\nBLUR_SIZE = 9\nOPEN_KERNEL_SIZE = (5,5)\nWINDOW_SIZE = 60\n\nstart_time = time.time()\ncenter_points, true_features = extract_samples ('../KeypointMatching/training_nature_fine_align', extractor = lbp, blur_size = BLUR_SIZE )\nprint (\"ex run time: %.2f seconds\" % (time.time() - start_time))\n\n\nsmp_img = cv.imread('../KeypointMatching/training_nature_fine_align/011.bmp', cv.IMREAD_GRAYSCALE) # sample image used for aligning predicted images\nsmp_img = cv.medianBlur(smp_img, BLUR_SIZE)\nmask = np.zeros(smp_img.shape[:2], dtype=\"uint8\") \nROI_BORDER_SIZE = 150\nmask = cv.rectangle(mask, (ROI_BORDER_SIZE,ROI_BORDER_SIZE),(smp_img.shape[1]-ROI_BORDER_SIZE, smp_img.shape[0]-ROI_BORDER_SIZE), 255, -1)\n#mask = cv.rectangle(mask, (top_border,left),(smp_img.shape[1]-ROI_BORDER_SIZE, smp_img.shape[0]-ROI_BORDER_SIZE), 255, -1)\npredict (smp_img, '../KeypointMatching/predict_nature/107.bmp', center_points, true_features, window_size= WINDOW_SIZE, candidate_method = \"keypoint\", extractor= lbp, mask_roi= mask, blur_size= BLUR_SIZE, open_kernel_size = OPEN_KERNEL_SIZE, debug= True)\n# for name in glob.glob('../KeypointMatching/predict_nature/*.bmp'):#for each tif\n# print(\"Processing \", name)\n# predict (smp_img, name, center_points, true_features, window_size= WINDOW_SIZE, candidate_method = \"keypoint\", extractor= chog, mask_roi= mask, blur_size= BLUR_SIZE, open_kernel_size = OPEN_KERNEL_SIZE, debug= False)\n\n#####################################################################################\n\n","sub_path":"iMorph_src/test_prediction.py","file_name":"test_prediction.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"99085078","text":"import sys\nimport requests\nimport csv\nfrom bs4 import BeautifulSoup\nimport phonenumbers\nimport re\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nimport pyap\nimport time\nfrom geotext import GeoText\np = re.compile(r'^(\\s+)?(Mr(\\.)?|Mrs(\\.)?)?(?P.+)(\\s+)(?P.+)$', re.IGNORECASE)\n\ndocterNameArray=[]\nfp=open('perio-UAE.csv',\"w\")\ncolumn=['first_name','last_name','address','pincode','city','Country','email','phoneNumber','web']\ncsvwriter = csv.writer(fp)\ncsvwriter.writerow(column)\nurl=\"https://www.perio.org/?q=locator-advanced\"\ndriver = webdriver.Chrome(executable_path='chromedriver')\ndriver.get(url)\ndriver.find_element_by_xpath('//*[@id=\"block-system-main\"]/div/div/div[1]/div/div/form[3]/select').click()\ndriver.find_element_by_xpath('//*[@id=\"block-system-main\"]/div/div/div[1]/div/div/form[3]/select/option[77]').click()\ndriver.find_element_by_xpath('//*[@id=\"block-system-main\"]/div/div/div[1]/div/div/form[3]/input[2]').click()\nptag=2\nlinks=driver.find_elements_by_tag_name('a')\nfor link in links:\n\tif(link.get_attribute('target')==\"_blank\"):\n\t\tintialData=driver.find_element_by_xpath('//*[@id=\"block-system-main\"]/div/div/div[1]/div/div/p['+str(ptag)+']').text\n\t\tsplitInitialData=intialData.split('\\n')\n\t\tdname=splitInitialData[0]\n\t\taddress=splitInitialData[1]\n\t\tphoneNumber=\"\"\n\t\tif(len(splitInitialData)>2):\n\t\t\tphoneNumber=splitInitialData[2]\n\t\ttry:\n\t\t\turl=link.get_attribute('href')\n\t\t\tresult=requests.get(url)\n\t\t\tsrc = result.content\n\t\t\tsoup = BeautifulSoup(src, \"lxml\")\n\t\t\tlink=soup.find('div',{'class':'row'})\n\t\t\tweb=\"\"\n\t\t\temail=\"\"\n\t\t\temail=link.find('a')\n\t\t\tif(email!=None):\n\t\t\t\temail=email.text\n\t\t\tweb=link.find('a',{\"target\":\"_blank\"})\n\t\t\tif(web!=None):\n\t\t\t\tweb=web.text\n\t\t\t\n\t\texcept:\n\t\t\tNoAction=0\n\t\t\t\n\t\tfinally:\n\t\t\t# driver2.close()\n\t\t\tif('(Dr.)' in dname):\n\t\t\t\tdname=dname.replace(\"Dr.\",\"\")\n\n\t\t\tif('Dr.' in dname):\n\t\t\t\tdname=dname.replace(\"Dr.\",\"\")\n\n\t\t\tif('Prof.' in dname):\n\t\t\t\tdname=dname.replace(\"Dr.\",\"\")\n\n\t\t\tm = p.match(dname)\n\t\t\tfirst_name=\"\"\n\t\t\tlast_name=\"\"\n\t\t\tif(m != None):\n\t\t\t\tfirst_name = m.group('FIRST_NAME')\n\t\t\t\tlast_name = m.group('LAST_NAME')\n\n\t\t\tphoneNumber=re.sub('[^0-9]+', '',phoneNumber)\n\t\t\tif(len(phoneNumber)>=8):\n\t\t\t\tphoneNumber=phonenumbers.format_number(phonenumbers.parse(phoneNumber, 'AE'), phonenumbers.PhoneNumberFormat.NATIONAL)\n\t\t\t\tphoneNumber='+971'+phoneNumber[1:len(phoneNumber)]\n\n\t\t\tif(')' in phoneNumber):\n\t\t\t\tphoneNumber=re.sub('[^0-9]+', '',phoneNumber)\n\t\t\t\tphoneNumber='+'+phoneNumber\n\t\t\tprint(phoneNumber,email,web)\n\t\t\tplaces = GeoText(address)\n\t\t\tcity=places.cities\n\t\t\tplace=\"\"\n\t\t\tif(city!=[]):\n\t\t\t\tplace=city[0]\n\n\t\t\tpincode=\"\"\n\t\t\treg = re.compile('^.*(?P\\d{5}).*$')\n\t\t\tmatch = reg.match(address)\n\n\t\t\tif(match):\n\t\t\t\tpincode=match.groupdict()['zipcode']\n\n\n\t\t\tif(dname not in docterNameArray):\n\t\t\t\tdocterNameArray.append(dname)\n\t\t\t\tcolumn=[first_name,last_name,address,pincode,place,'UAE',email,phoneNumber,web]\n\t\t\t\tcsvwriter = csv.writer(fp)\n\t\t\t\tcsvwriter.writerow(column)\n\n\t\t\tprint(dname)\n\t\t\t\t\t\t# driver2.close()\n\t\tptag=ptag+1\n","sub_path":"perio-India.py","file_name":"perio-India.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"115284118","text":"import pygame\nimport math\nimport random\n\nGREEN = (38, 122, 44)\n\nclass Zombie:\n def __init__(self, health, camPosX, camPosY, player):\n self.moveSpeed = 0.01\n self.senseRange = 5000\n self.health = health\n self.xPos = camPosX + random.randint(-1000,1000)\n self.yPos = camPosY + random.randint(-1000,1000)\n #self.xPos = 100\n #self.xPos = 100\n self.player = player\n\n def drawEntity(self, game_display, camPosX, camPosY):\n pygame.draw.rect(game_display, GREEN, [self.xPos+camPosX-55, self.yPos+camPosY-91, 5, 5])\n\n def move(self):\n i = 2\n distance = math.sqrt((self.player.xPos - self.xPos) ** 2 + (self.player.yPos - self.yPos) ** 2)\n if distance < self.senseRange:\n yDelta = (self.player.yPos - self.yPos)\n xDelta = (self.player.xPos - self.xPos)\n if distance < 200:\n i = 3\n if random.randint(0,i) == i:\n yDelta = (self.player.yPos - self.yPos)\n xDelta = (self.player.xPos - self.xPos)\n self.xPos += xDelta * self.moveSpeed\n self.yPos += yDelta * self.moveSpeed\n else:\n self.xPos += random.randint(-20,20) * self.moveSpeed\n self.yPos += random.randint(-20,20) * self.moveSpeed\n","sub_path":"enemies.py","file_name":"enemies.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"344357885","text":"class Node:\n def __init__(self, value=None, next_node=None):\n self.value = value\n self.next_node = next_node\n\n def get_value(self):\n return self.value\n\n def get_next(self):\n return self.next_node\n\n def set_next(self, new_next):\n self.next_node = new_next\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def add_to_head(self, value):\n node = Node(value)\n\n if self.head is not None:\n node.set_next(self.head)\n\n self.head = node\n\n def contains(self, value):\n if not self.head:\n return False\n\n current = self.head\n\n while current:\n if current.get_value() == value:\n return True\n\n current = current.get_next()\n\n return False\n\n def reverse_list(self, node, prev):\n #Loop through list and create connection map with lists of nodes\n if not self.head:\n return\n \n current = self.head\n connections = []\n while current:\n if current.get_next():\n connections.append([current, current.get_next()])\n current = current.get_next()\n \n counter = 0\n for pair in connections[-1::-1]:\n if counter == 0:\n self.head = pair[1]\n pair[1].set_next(pair[0])\n counter += 1\n\n\n","sub_path":"reverse/reverse.py","file_name":"reverse.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"237121664","text":"from tkinter import *\r\nfrom PIL import Image, ImageTk\r\nfrom tkmacosx import Button as button\r\n\r\n\r\n#place an image on the grid\r\ndef display_logo(url, row, column,columnspan):\r\n img = Image.open(url)\r\n #resize image\r\n img = img.resize((int(img.size[0]/4.5),int(img.size[1]/4.5)))\r\n img = ImageTk.PhotoImage(img)\r\n img_label = Label(image=img, bg=\"white\")\r\n img_label.image = img\r\n img_label.grid(column=column, row=row,columnspan=columnspan, rowspan=2, sticky=NW, padx=20, pady=40)\r\n\r\ndef display_icon(url, row, column, stick):\r\n icon = Image.open(url)\r\n #resize image\r\n icon = icon.resize((25,25))\r\n icon = ImageTk.PhotoImage(icon)\r\n icon_label = Button(image=icon, width=25, height=25)\r\n icon_label.image = icon\r\n icon_label.grid(column=column, row=row, sticky=stick)\r\n\r\n\r\n#place a tebox on the pages\r\ndef display_textbox(content, ro, col, root):\r\n text_box = Text(root, height=10, width=30, padx=10, pady=10)\r\n text_box.insert(1.0, content)\r\n text_box.tag_configure(\"center\", justify=\"center\")\r\n text_box.tag_add(\"center\", 1.0, \"end\")\r\n text_box.grid(column=col, row=ro, sticky=SW, padx=25, pady=25)\r\n\r\n#Detect Images inside the PDF document\r\n#Thank you sylvain of Stackoverflow\r\n#https://stackoverflow.com/questions/2693820/extract-images-from-pdf-without-resampling-in-python\r\ndef extract_images(page):\r\n images = []\r\n if '/XObject' in page['/Resources']:\r\n xObject = page['/Resources']['/XObject'].getObject()\r\n\r\n for obj in xObject:\r\n if xObject[obj]['/Subtype'] == '/Image':\r\n size = (xObject[obj]['/Width'], xObject[obj]['/Height'])\r\n data = xObject[obj].getData()\r\n mode = \"\"\r\n if xObject[obj]['/ColorSpace'] == '/DeviceRGB':\r\n mode = \"RGB\"\r\n else:\r\n mode = \"CMYK\"\r\n img = Image.frombytes(mode, size, data)\r\n images.append(img)\r\n return images\r\n\r\ndef resize_img(img):\r\n width, height = int(img.size[0]), int(img.size[1])\r\n if width > height:\r\n height = int( 300/width* height)\r\n width = 300\r\n elif height > width:\r\n width = int( 250/height * width)\r\n height = 250\r\n else:\r\n width, height = 250, 250\r\n\r\n img = img.resize((width,height))\r\n return img\r\n\r\ndef display_images(img):\r\n img = resize_img(img)\r\n img = ImageTk.PhotoImage(img)\r\n img_label = Label(image=img, bg=\"white\")\r\n img_label.image = img\r\n img_label.grid(row=5, column=6, rowspan=4, columnspan=2)\r\n return img_label\r\n\r\ndef delete_color_option():\r\n value_inside = StringVar(root)\r\n # Set the default value of the variable\r\n value_inside.set(\"Delete a Color\")\r\n delete_option = OptionMenu(root, value_inside, *hexadecimal)\r\n delete_option.grid(column=6, row=3, sticky=NE)\r\n\r\n delete_btn = Button(root, text=\"Delete\", command=lambda:delete_color(value_inside), \r\n font=(\"Raleway\",12), highlightbackground=\"#20bebe\", \r\n bg=\"#20bebe\", fg=\"black\", height=1, width=15)\r\n delete_btn.grid(column=7, row=3, sticky=NW)\r\n\r\n\r\n##########################################\r\n\r\n\r\n\r\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"620568410","text":"words = [\n[\"BMW\",\"Volkswaagen\"],\n[\"Honda\",\"Toyota\"],\n[\"Amazon\",\"Facebook\"],\n[\"Tokopedia\",\"Bukalapak\"],\n[\"Apple\",\"Microsoft\"],\n[\"Starbucks\",\"Kopimana\"],\n[\"Coca Cola\",\"Pepsi\"],\n[\"Vietnam\",\"Cambodia\"],\n[\"Italy\",\"Spain\"],\n[\"Sweden\",\"Finland\"],\n[\"India\",\"Bangladesh\"],\n[\"Australia\",\"New Zealand\"],\n[\"Japan\",\"South Korea\"],\n[\"Mayonnaise\",\"Ketchup\"],\n[\"Cake\",\"Pie\"],\n[\"Taco\",\"Burrito\"],\n[\"Pizza\",\"Bagel\"],\n[\"Milkshake\",\"Ice cream\"],\n[\"Salt\",\"Pepper\"],\n[\"Doctor\",\"Nurse\"],\n[\"Developer\",\"Manager\"],\n[\"Designer\",\"CEO\"],\n[\"Agent\",\"Soldier\"],\n[\"Paris\",\"Milan\"],\n[\"Walk\",\"Run\"],\n[\"Golf\",\"Tennis\"],\n[\"Yak\",\"Bison\"],\n[\"Eagle\",\"Dove\"],\n[\"Flamingo\",\"Pelican\"],\n[\"Sheep\",\"Ox\"],\n]","sub_path":"wordlist.py","file_name":"wordlist.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"587583929","text":"from setuptools import setup\nfrom setuptools import find_packages\n\nversion = '1.6.4'\n\ndesc = 'A transmogrifier blueprint for updating dexterity objects'\nlong_desc = open('README.rst').read() + '\\n\\n' + open('CHANGES.rst').read()\ntests_require = [\n 'ftw.builder',\n 'plone.app.intid',\n 'plone.app.testing',\n 'plone.app.dexterity',\n 'plone.namedfile[blobs]',\n 'plone.directives.form',\n 'plone.formwidget.contenttree',\n 'z3c.relationfield',\n 'unittest2',\n]\n\n\nsetup(\n name='transmogrify.dexterity',\n version=version,\n description=desc,\n long_description=long_desc,\n classifiers=[\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords='',\n author='4teamwork AG',\n author_email='mailto:info@4teamwork.ch',\n url='https://github.com/collective/transmogrify.dexterity/',\n license='GPL2',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['transmogrify'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n 'collective.transmogrifier',\n 'plone.app.textfield',\n 'plone.app.transmogrifier',\n 'plone.dexterity',\n 'plone.namedfile',\n 'plone.supermodel',\n 'plone.uuid',\n 'z3c.form',\n ],\n tests_require=tests_require,\n extras_require=dict(tests=tests_require),\n entry_points=\"\"\"\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n)\n","sub_path":"pypi_install_script/transmogrify.dexterity-1.6.4.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"578797312","text":"#!/usr/bin/python3\n\nimport sys\nimport csv\nimport datetime\nimport psycopg2\n\nimport numpy as np\n\nimport pandas as pd\n\ntry:\n conn = psycopg2.connect(\"dbname='soccer'\")\nexcept:\n print(\"Can't connect to database.\")\n sys.exit()\n\ntoday = datetime.datetime.now()\nstart = today.strftime(\"%F\")\nend = today + datetime.timedelta(days=6)\n\nselect_games = \"\"\"\nselect\nt.club_name as team_name,\no.club_name as opponent_name,\n\ntf.exp_factor*sft.offensive as etg,\nof.exp_factor*sfo.offensive as eog\n\nfrom club.games g\njoin club.teams t\n on (t.club_id,t.year)=(g.home_team_id,g.year)\njoin club._schedule_factors sft\n on (sft.team_id,sft.year)=(g.home_team_id,g.year)\njoin club.teams o\n on (o.club_id,o.year)=(g.away_team_id,g.year)\njoin club._schedule_factors sfo\n on (sfo.team_id,sfo.year)=(g.away_team_id,g.year)\njoin club._factors tf on\n tf.level='offense_home'\njoin club._factors of on\n of.level='defense_home'\nwhere\n not(g.date='LIVE')\nand g.league_key = 'english+premier+league'\nand g.competition='Prem'\nand g.date::date >= current_date\nand g.home_goals is null\nand g.away_goals is null\nand g.club_id=g.home_team_id\norder by g.club_name asc,g.date::date asc\n;\n\"\"\"\n\ncur = conn.cursor()\ncur.execute(select_games)\n\ngames = cur.fetchall()\n\nselect_table = \"\"\"\nselect\ng.club_name as team,\nsum(\ncase when g.club_id=g.home_team_id\n and (home_goals > away_goals) then 1\n when club_id=away_team_id\n and (home_goals < away_goals) then 1\nelse 0\nend) as w,\nsum(\ncase when (home_goals=away_goals) then 1\nelse 0\nend) as d,\nsum(\ncase when club_id=home_team_id\n and (home_goals < away_goals) then 1\n when club_id=away_team_id\n and (home_goals > away_goals) then 1\nelse 0\nend) as l,\n\nsum(\ncase when g.club_id=g.home_team_id then home_goals\n else away_goals\nend) as gf,\nsum(\ncase when g.club_id=g.home_team_id then away_goals\n else home_goals\nend) as ga\n--sum(\n--case when g.club_id=g.home_team_id then home_goals-away_goals\n-- else away_goals-home_goals\n--end) as gd\n\nfrom club.games g\nwhere\n not(g.date='LIVE')\nand g.league_key = 'english+premier+league'\nand g.competition='Prem'\nand g.year=2016\nand g.date::date <= current_date\nand g.home_goals is not null\nand g.away_goals is not null\ngroup by g.club_name\norder by g.club_name asc\n;\n\"\"\"\n\ncur.execute(select_table)\ntable = pd.DataFrame(cur.fetchall(),\n columns=['team','w','d','l','gf','ga'])\n\nteam = []\nw = []\nd = []\nl = []\ngf = []\nga = []\n\nfor i,game in enumerate(games):\n\n tg = np.random.poisson(lam=game[2])\n og = np.random.poisson(lam=game[3]) \n \n team.extend([game[0],game[1]])\n gf.extend([tg, og])\n ga.extend([og, tg])\n# gd.extend([tg-og, og-tg])\n \n if (tg > og):\n w.extend([1,0])\n d.extend([0,0])\n l.extend([0,1])\n elif (tg == og):\n w.extend([0,0])\n d.extend([1,1])\n l.extend([0,0])\n else:\n w.extend([0,1])\n d.extend([0,0])\n l.extend([1,0])\n\nsim = {'team' : team,\n 'w' : w,\n 'd' : d,\n 'l' : l,\n 'gf' : gf,\n 'ga' : ga}\n\nros = pd.DataFrame(sim,\n columns = ['team','w','d','l','gf','ga'])\n\ndf = pd.concat([table, ros], axis=0)\n\nseason = df.groupby(['team']).agg({'w' : sum,\n 'd' : sum,\n 'l' : sum,\n 'gf' : sum,\n 'ga' : sum})\n\nseason['gd'] = season['gf']-season['ga']\nseason['pts'] = 3*season['w']+season['d']\n\nfinal = season.sort(['pts', 'gd', 'gf'], ascending=[0, 0, 0])\n\nfinal['i'] = final['pts']*1000000+(final['gd']+100)*1000+final['gf']\n\nfinal['rank'] = final['i'].rank(ascending=0, method='min')\n\nfinal.drop(['i'],inplace=True,axis=1)\nprint(final)\n","sub_path":"club/sim_leagues/sim_poisson.py","file_name":"sim_poisson.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"346896191","text":"\"\"\"NBoost Proxy Class\"\"\"\n\nfrom typing import Tuple, Callable\nfrom numbers import Number\nfrom copy import deepcopy\nimport socket\nfrom nboost.models.rerank.base import RerankModel\nfrom nboost.models.qa.base import QAModel\nfrom nboost.models import resolve_model\nfrom nboost.server import SocketServer\nfrom nboost.helpers import dump_json\nfrom nboost.session import Session\nfrom nboost import hooks, defaults\nfrom nboost.exceptions import *\n\n\nclass Proxy(SocketServer):\n \"\"\"The proxy object is the core of NBoost.\"\"\"\n def __init__(self, search_path: type(defaults.search_path) = defaults.search_path,\n rerank: type(defaults.rerank) = defaults.rerank,\n model: type(defaults.model) = defaults.model,\n model_dir: type(defaults.model_dir) = defaults.model_dir,\n qa: type(defaults.qa) = defaults.qa,\n qa_model: type(defaults.qa_model) = defaults.qa_model,\n qa_model_dir: type(defaults.qa_model_dir) = defaults.qa_model_dir,\n data_dir: type(defaults.data_dir) = defaults.data_dir, **kwargs):\n super().__init__(**kwargs)\n self.kwargs = kwargs\n self.averages = {}\n self.search_path = search_path\n self.rerank = rerank\n self.qa = qa\n\n self.status = deepcopy(self.get_session().cli_configs)\n self.status['search_path'] = search_path\n self.status['description'] = 'NBoost, for neural boosting.'\n\n if self.rerank:\n self.model = resolve_model(\n data_dir=data_dir,\n model_dir=model_dir,\n model_cls=model, **kwargs) # type: RerankModel\n self.status['model_class'] = type(self.model).__name__\n self.status['model_dir'] = model_dir\n\n if self.qa:\n self.qa_model = resolve_model(\n data_dir=data_dir,\n model_dir=qa_model_dir,\n model_cls=qa_model,\n **kwargs) # type: QAModel\n self.status['qa_model_class'] = type(self.qa_model).__name__\n self.status['qa_model_dir'] = qa_model_dir\n\n def update_averages(self, **stats: Number):\n for key, value in stats.items():\n self.averages.setdefault(key, {'count': 0, 'sum': 0})\n item = self.averages[key]\n item['count'] += 1\n item['sum'] += value\n self.status['average_' + key] = item['sum'] / item['count']\n\n def get_session(self):\n return Session(**self.kwargs)\n\n def loop(self, client_socket: socket.socket, address: Tuple[str, str]):\n \"\"\"Main ioloop for reranking server results to the client\"\"\"\n server_socket = self.set_socket()\n session = self.get_session()\n prefix = 'Request (%s:%s): ' % address\n\n try:\n hooks.on_client_request(session, client_socket, self.search_path)\n self.logger.debug(prefix + 'search request.')\n\n if self.rerank:\n hooks.on_rerank_request(session)\n\n hooks.on_server_request(session)\n\n if self.rerank:\n hooks.on_rerank_response(session, self.model)\n\n if self.qa:\n hooks.on_qa(session, self.qa_model)\n\n if session.debug:\n hooks.on_debug(session)\n\n hooks.on_client_response(session, client_socket)\n\n except FrontendRequest:\n self.logger.info(prefix + 'frontend request')\n hooks.on_frontend_request(client_socket, session)\n\n except StatusRequest:\n self.logger.info(prefix + 'status request')\n hooks.on_status_request(client_socket, session, self.status)\n\n except UnknownRequest:\n path = session.get_request_path('url.path')\n self.logger.info(prefix + 'unknown path %s', path)\n hooks.on_unhandled_request(client_socket, server_socket, session)\n\n except MissingQuery:\n self.logger.warning(prefix + 'missing query')\n hooks.on_unhandled_request(client_socket, server_socket, session)\n\n except UpstreamServerError as exc:\n self.logger.error(prefix + 'server status %s' % exc)\n hooks.on_client_response(session, client_socket)\n\n except InvalidChoices as exc:\n self.logger.warning(prefix + '%s', exc.args)\n hooks.on_unhandled_request(client_socket, server_socket, session)\n\n except Exception as exc:\n # for misc errors, send back json error msg\n self.logger.error(prefix + str(exc), exc_info=True)\n hooks.on_proxy_error(client_socket, exc)\n\n finally:\n self.update_averages(**session.stats)\n client_socket.close()\n server_socket.close()\n\n def run(self):\n \"\"\"Same as socket server run() but logs\"\"\"\n self.logger.info(dump_json(self.status, indent=4).decode())\n super().run()\n\n def close(self):\n \"\"\"Close the proxy server and model\"\"\"\n self.logger.info('Closing model...')\n self.model.close()\n super().close()\n","sub_path":"nboost/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":5089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"365178706","text":"import csv\nimport random\n\nnamelist = ['park', 'komori', 'sonehara','nobusawa','li','shimizu']\n# test = []\nv = open('C:\\\\Users\\\\i3_OWNER\\'s\\\\Documents\\\\pytest\\\\Weekly_Gift.csv')\nr = csv.reader(v)\nrow0 = next(r)\nfor i in random.sample(namelist, 3):\n row0.append(i)\nprint(row0)\n\n# for i in range(3):\n # B = random.randrange(0, len(namelist)-1)\n# B = random.sample(namelist, 3)\n# # if B in test:\n# row0.append(namelist[B])\n# print(row0)\n","sub_path":"practice/tcs/final/automake.py","file_name":"automake.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"137148883","text":"# -*- coding:utf-8 -*- \n'''\n__author__:liubin \n\n'''\n\nimport unittest\nimport requests\nimport logging\n\n\nclass AddEventTest(unittest.TestCase):\n '''添加发布会'''\n\n def __init__(self, *args, **kwargs):\n super(AddEventTest, self).__init__(*args, **kwargs)\n self.logger = logging.getLogger(__name__)\n\n print(self.logger)\n\n def setUp(self):\n\n self.base_url = \"http://127.0.0.1:8000/api/add_event/\"\n\n @unittest.skip(\"I don't want to run this case.\")\n def test_add_event_all_null(self):\n '''参数为空'''\n self.logger.info(\"传入参数都为空\")\n payload = {'eid':'','':'','limit':'','address':\"\",'start_time':''}\n r = requests.post(self.base_url,data=payload)\n self.result = r.json()\n self.logger.info(\"获得结果\")\n self.assertEqual(self.result['status'],10021)\n self.assertEqual(self.result['message'],'parameter error')\n\n @unittest.skip(\"I don't want to run this case.\")\n def test_add_event_eid_exist(self):\n '''发布会id 已经存在'''\n\n payload = {'eid': 1, 'name': '一加4 发布会', 'limit': 2000,\n 'address': \"深圳宝体\", 'start_time': '2017'}\n r = requests.post(self.base_url, data=payload)\n self.result = r.json()\n self.assertEqual(self.result['status'], 10022)\n self.assertEqual(self.result['message'], 'event id already exists')\n\n def test_add_event_name_exist(self):\n ''' 名称已经存在'''\n\n payload = {'eid': 10, 'name': '红米Pro发布会', 'limit': 2000,\n 'address': \"北京水立方\", 'start_time': '2017'}\n r = requests.post(self.base_url, data=payload)\n self.result = r.json()\n self.assertEqual(self.result['status'], 10023)\n self.assertEqual(self.result['message'], 'event name already exists')\n\n @unittest.skip(\"I don't want to run this case.\")\n def test_add_event_data_type_error(self):\n ''' 日期格式错误'''\n\n payload = {'eid': 11, 'name': '一加4 手机发布会', 'limit': 2000,\n 'address': \"北京水立方\", 'start_time': '2017'}\n r = requests.post(self.base_url, data=payload)\n self.result = r.json()\n self.assertEqual(self.result['status'], 10024)\n self.assertIn('start_time format error.', self.result['message'])\n\n @unittest.skip(\"I don't want to run this case.\")\n def test_add_event_success(self):\n ''' 添加成功'''\n\n payload = {'eid': 11, 'name': '一加4 手机发布会', 'limit': 2000,\n 'address': \"北京水立方\", 'start_time': '2017-05-10 12:00:00'}\n r = requests.post(self.base_url, data=payload)\n self.result = r.json()\n self.assertEqual(self.result['status'], 200)\n self.assertEqual(self.result['message'], 'add event success')\n\n\n def tearDown(self):\n\n print(self.result)\n","sub_path":"src/interface/add_event_test.py","file_name":"add_event_test.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"227995954","text":"class Query:\n def __init__(self, db):\n self.db = db\n self.builds = []\n self.tables = []\n\n def add(self, table):\n D = self.db.describe(table)\n self.builds.append([])\n self.tables.append(table)\n index = len(self.tables) - 1\n for r in D:\n self.builds[index].append(r[0])\n\n def remove(self, table, field):\n self.builds[self.tables.index(table)].remove(field)\n\n def build(self):\n string = \"\"\n for i,t in enumerate(self.tables):\n for f in self.builds[i]:\n string += t + \".\" + f + \",\"\n return string[:-1]\n\n def getFields(self):\n fields = []\n for i,t in enumerate(self.tables):\n for f in self.builds[i]:\n fields.append(f)\n return fields\n","sub_path":"code/stock/streams/mysql/Query.py","file_name":"Query.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"227128909","text":"from django import template\r\nfrom django.urls import reverse\r\nfrom django.utils.safestring import mark_safe\r\nregister = template.Library()\r\n\r\n@register.filter\r\ndef type_list(list, req):\r\n\tvalue = req.get('type')\r\n\tfor x , y in list:\r\n\t\tif value == 'homeservice':\r\n\t\t\treturn \"အိမ်သို့ ပင့်ဆောင်နိုင်သော ဆရာဝန်များ\"\r\n\t\telif x == value:\r\n\t\t\treturn \"ဆက်သွယ်နိုင်သော %sများ\"%y\r\n\treturn \"အမျိုးအစားအားလုံး\"\r\n\r\n@register.filter\r\ndef services_title(name):\r\n\ttitle = name.get('type')\r\n\tif title == \"hotline\":\r\n\t\treturn \"Call Center\"\r\n\telif title == \"homeservice\":\r\n\t\treturn \"home service\"\r\n\telif title == \"public\":\r\n\t\treturn \"Public Clinic\"\r\n\telif title == \"fever\":\r\n\t\treturn \"fever clinic\"\r\n\telif title == \"tele\":\r\n\t\treturn \"tele consulation\"\r\n\telif title:\r\n\t\treturn title\r\n\telse:\r\n\t\treturn \"All Service\"\r\n\r\n@register.filter\r\ndef township_list(list, value):\r\n\ttownship = value.get('township')\r\n\tif township is not None:\r\n\t\tfor x , y in list:\r\n\t\t\tif township == \"\":\r\n\t\t\t\treturn \"မြို့နယ်အားလုံး\"\r\n\t\t\telif x == township:\r\n\t\t\t\treturn \"ရွေးချယ်လိုက်သော \"+y + \"မြို့နယ်\"\r\n\telse:\r\n\t\treturn \"မြို့နယ်အားလုံး\"\r\n","sub_path":"charity/templatetags/charity_tag.py","file_name":"charity_tag.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"377874946","text":"#%% Imports\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom matplotlib import cm\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import scale\nimport pickle\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport tables\n\nout = './PCA/'\ncmap = cm.get_cmap('Spectral')\n\nnp.random.seed(0)\nfile1 = open(r'.\\bioresponse.pkl', 'rb')\ndata1 = pickle.load(file1)\nfile1.close()\ninstances = data1.data\nX = data1.data\nlabels = data1.target\nX_trainset, X_test, Y_trainset, Y_test = train_test_split(X, labels, test_size=0.3, random_state=42, shuffle=True, stratify=labels)\nX_train_unscaled, Y_train, X_val, Y_val = train_test_split(X_trainset, Y_trainset, test_size=0.2, random_state=42, shuffle=True, stratify =Y_trainset)\nn_samples, n_features = instances.shape\nn_digits = len(np.unique(data1.target))\nsample_size = 300\nX_train = scale(X_train_unscaled)\ninstances_letter = scale(X_trainset) #same as StandardScaler().fit_transform(data1.data)\nlabels_letter = Y_trainset\n#X_val = scale(X_val)\nX_test= scale(X_test)\nX_scaled = scale(X_trainset)\nX_train = scale(X)\nY_train = labels\nfrom collections import defaultdict\nfrom helpers import reconstructionError\n\nclusters = [2,3,4,5,6,10]\ndims = [2,40,80,170,480,670,860,990,1150,1287,1378,1453,1516,1617,1772]\n#raise\n\ntmp = defaultdict(dict)\nfor i in dims:\n pca = PCA(n_components=i, random_state=10)\n pca.fit(X_scaled)\n tmp[i] = reconstructionError(pca, X_scaled)\nprint(tmp)\ntmp1 =pd.DataFrame(tmp,index=[0]).T\ntmp1.to_csv(out+'bio_recon_error.csv')\n\n#%% data for 1\npca = PCA(random_state=5)\npca.fit(instances_letter)\ntmp = pd.Series(data = pca.explained_variance_,index = range(1,1777))\ntmp.to_csv(out+'bio_variance.csv')\ntmp.plot(title='Eigen value distribution')\nplt.ylabel('Eigen value')\nplt.xlabel('Principal components')\nplt.grid(True)\nplt.show()\ntmp = pd.Series(data = pca.explained_variance_ratio_.cumsum(),index = range(1,1777))\ntmp.plot(title='Percentage of variance explained')\nplt.ylabel('Percentage of variance explained')\nplt.xlabel('Number of components')\nplt.grid(True)\nplt.axhline(y=0.9, color='r', linestyle='dashed')\nplt.show()\ntmp.to_csv(out+'bio_ratio.csv')\n\n\n#%% data for 3\n# Set this from chart 2 and dump, use clustering script to finish up\ndim = 319\npca = PCA(n_components=dim,random_state=10)\nfeatures_letter = pca.fit_transform(X_train)\nletterdf = pd.DataFrame(np.hstack((features_letter,np.atleast_2d(Y_train).T)))\ncols = list(range(letterdf.shape[1]))\ncols[-1] = 'Class'\nletterdf.columns = cols\nletterdf.to_csv(out+'vis_bio_DS.csv')\nletterdf.to_hdf(out+'datasets.hdf','bio',complib='blosc',complevel=9)\n\n\n\n","sub_path":"Project_code/2_PCA.py","file_name":"2_PCA.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"195591","text":"from mt_git import step\n\n\ndef execute(exe_config):\n\n git_conf = exe_config.get('git', {})\n for command, param in git_conf.items():\n print('executing GIT.{}'.format(command))\n getattr(step, command)(git_conf, param)\n\n\ndef get_default_config(install_type):\n return {\n 'name': 'git',\n 'config': {\n 'install': install_type,\n 'configure_ignore': True,\n 'set_sublime_as_merge': True,\n 'setup_credentials': {\n 'user.name': 'Your Name Here',\n 'user.email': 'your_email@youremail.com'\n }\n }\n }","sub_path":"mt-git/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"389140240","text":"import os\nimport subprocess\n\n#head -n 1 programs.txt | tail -1\n\n# ^-- add to this\n\nuser = os.getenv(\"SUDO_USER\")\nif user is None:\n print(\"\\n Execute as \\033[1;31;48msudo\\033[1;37;48m\\n\")\n exit()\n\ndef cmd_exists(cmd):\n return subprocess.call(\"type \" + cmd, shell=True, \n stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0\n\n###################################################################\n\n# \tADD REPOSITORIES\n\n###################################################################\n\nos.system(\"sudo apt-get update -y && sudo apt-get upgrade -y && sudo apt-get dist-upgrade -y\")\n\nrepository = \"\"\ncount = 1\nlines = 0\n\nwith open('repositories.txt') as f:\n\tlines = sum(1 for _ in f)\n\nwhile count <= lines: \n\trepository = os.popen(\"head -n \"+str(count)+\" repositories.txt | tail -1\").read()\n\tos.system(\"sudo add-apt-repository -y ppa:\" + repository)\n\tcount = count + 1\n\n###################################################################\n\n# \tINSTALL PROGRAMS\n\n###################################################################\n\nos.system(\"sudo apt-get update -y && sudo apt-get upgrade -y && sudo apt-get dist-upgrade -y\")\n\nprogram = \"\"\nlines = 0\nprograms = 1\ncount = 1\n\nwith open('programs.txt') as f:\n\tlines = sum(1 for _ in f)\n\nwhile count <= lines: \n\n\tprogram = os.popen(\"head -n \"+str(count)+\" programs.txt | tail -1\").read()\n\n\tif cmd_exists(program):\n\n\t\tprint(\"\\nAlready Installed!\\n\")\n\t\t\n\t\tcount = count + 1\n\n\telse:\n\n\t\tos.system(\"sudo apt-get install -y \" + program)\n\n\t\tcount = count + 1\n\n###################################################################\n\n# \tINSTALL PIP\n\n###################################################################\n\npipprogram = \"\"\nlines = 0\nprograms = 1\ncount = 1\n\nwith open('pip.txt') as f:\n\tlines = sum(1 for _ in f)\n\nwhile count <= lines: \n\n\tpipprogram = os.popen(\"head -n \"+str(count)+\" pip.txt | tail -1\").read()\n\n\tif cmd_exists(pipprogram):\n\n\t\tprint(\"\\nAlready Installed!\\n\")\n\t\t\n\t\tcount = count + 1\n\n\telse:\n\n\t\tos.system(\"sudo pip install \" + pipprogram)\n\n\t\tcount = count + 1\n\n###################################################################\n\n# \tINSTALL PIP3\n\n###################################################################\n\npip3program = \"\"\nlines = 0\nprograms = 1\ncount = 1\n\nwith open('pip3.txt') as f:\n\tlines = sum(1 for _ in f)\n\nwhile count <= lines: \n\n\tpip3program = os.popen(\"head -n \"+str(count)+\" pip3.txt | tail -1\").read()\n\n\tif cmd_exists(pip3program):\n\n\t\tprint(\"\\nAlready Installed!\\n\")\n\t\t\n\t\tcount = count + 1\n\n\telse:\n\n\t\tos.system(\"sudo pip3 install \" + pip3program)\n\n\t\tcount = count + 1\n\n\n###################################################################\n\n# \tINSTALL EASY_INSTALL\n\n###################################################################\n\nesprogram = \"\"\nlines = 0\nprograms = 1\ncount = 1\n\nwith open('easy_install.txt') as f:\n\tlines = sum(1 for _ in f)\n\nwhile count <= lines: \n\n\tesprogram = os.popen(\"head -n \"+str(count)+\" easy_install.txt | tail -1\").read()\n\n\tif cmd_exists(esprogram):\n\n\t\tprint(\"\\nAlready Installed!\\n\")\n\t\t\n\t\tcount = count + 1\n\n\telse:\n\n\t\tos.system(\"sudo easy_install -U \" + esprogram)\n\n\t\tcount = count + 1\n\n\n###################################################################\n\n# \tINSTALL GEM\n\n###################################################################\n\ngemprogram = \"\"\nlines = 0\nprograms = 1\ncount = 1\n\nwith open('gem.txt') as f:\n\tlines = sum(1 for _ in f)\n\nwhile count <= lines: \n\n\tgemprogram = os.popen(\"head -n \"+str(count)+\" gem.txt | tail -1\").read()\n\n\tif cmd_exists(gemprogram):\n\n\t\tprint(\"\\nAlready Installed!\\n\")\n\t\t\n\t\tcount = count + 1\n\n\telse:\n\n\t\tos.system(\"sudo gem install \" + gemprogram)\n\n\t\tcount = count + 1\n\n###################################################################\n\n# \tINSTALL CUSTOM\n\n###################################################################\n\nos.system(\"sudo bash custom.sh\")\n\nos.system(\"sudo apt-get update -y && sudo apt-get upgrade -y && sudo apt-get dist-upgrade -y\")\n\nprint(\"Done!\")\n\n###################################################################\n\n# \tCLEAN UP\n\n###################################################################\n\nos.system(\"sudo apt-get -y remove\")\nos.system(\"sudo apt-get -y autoremove\")\nos.system(\"sudo apt-get -y clean\")\nos.system(\"sudo apt-get -y autoclean\")\n","sub_path":"installprograms.py","file_name":"installprograms.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"619757698","text":"dia_list = [.5, .75, 1, 1.25, 1.5, 2]\r\nprice_per_ft_list = [0.41, 0.494, .822, .956, 1.048, 1.45]\r\nk_90_elbow = 0.3\r\nd_mold = 1.25\r\nd_hx = 1\r\nk_list = []\r\n\r\n\r\n\r\ndef compare_diameters (d_connect, d):\r\n d_big = max(d_connect,d)\r\n d_small = min(d_connect, d)\r\n return d_big, d_small\r\n\r\ndef k_reducer(d_big, d_small):\r\n d_1 = d_big\r\n d_2 = d_small\r\n check = d_2/d_1\r\n if 0.25 < check < 1:\r\n k_red = 0.5-0.167*(d_2/d_1)-0.125*((d_2/d_1)**2)-.208*((d_2/d_1)**3)\r\n else:\r\n k_red = 1000\r\n return k_red\r\n\r\ndef k_expansion (d_big, d_small):\r\n d_1 = d_small\r\n d_2 = d_big\r\n check = d_2/d_1\r\n if 1 < check < 5:\r\n k_exp = ((d_2/d_1)**2-1)\r\n else:\r\n k_exp = 1000\r\n return k_exp\r\n\r\ndef full_k (k_red_mold, k_exp_mold, k_red_hx, k_exp_hx, k_90_elbow, d_mold, d, d_hx):\r\n if (d > d_hx and d > d_mold) or (d < d_hx and d < d_mold):\r\n k = 3*k_90_elbow+k_red_mold+k_exp_mold+k_red_hx+k_exp_hx\r\n elif (d == d_hx):\r\n k = 3*k_90_elbow+k_red_mold+k_exp_mold\r\n elif (d == d_mold):\r\n k = 3*k_90_elbow+k_red_hx+k_exp_hx\r\n else:\r\n print('oops')\r\n return k\r\n\r\nfor i in dia_list:\r\n d = i\r\n d_big_mold, d_small_mold = compare_diameters(d_mold,d)\r\n k_red_mold = k_reducer(d_big_mold, d_small_mold)\r\n k_exp_mold = k_expansion(d_big_mold, d_small_mold)\r\n d_big_hx, d_small_hx = compare_diameters(d_hx, d)\r\n k_red_hx = k_reducer(d_big_hx, d_small_hx)\r\n k_exp_hx = k_expansion(d_big_hx, d_small_hx)\r\n k = full_k(k_red_mold, k_exp_mold, k_red_hx, k_exp_hx, k_90_elbow, d_mold, d, d_hx)\r\n k_list.append(k)\r\n \r\nprint(k_list)\r\n ","sub_path":"pipes.py","file_name":"pipes.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"247878641","text":"from petisco.controller.errors.http_error import HttpError\n\n\nclass InvalidTokenHttpError(HttpError):\n def __init__(\n self,\n message: str = \"Access token is missing or invalid.\",\n code: int = 401,\n suffix=\"\",\n ):\n if suffix:\n message = message + \" \" + suffix\n\n super(InvalidTokenHttpError, self).__init__(message, code)\n","sub_path":"petisco/controller/errors/invalid_token_http_error.py","file_name":"invalid_token_http_error.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"104487674","text":"from __future__ import division\nimport sys\n\ndef reader(corpus_file):\n\tline = corpus_file.readline()\n\twhile line:\n\t\tfield = line.strip().split()\n\t\tif field:\n\t\t\tyield field\n\t\tline = corpus_file.readline()\n\ndef sentence_reader(input_file):\n\tline = input_file.readline()\n\tsentence = []\n\twhile line:\n\t\tword = line.strip()\n\t\tif word:\n\t\t\tsentence.append(word)\n\t\telse:\n\t\t\tyield sentence\n\t\t\tsentence = []\n\t\tline = input_file.readline()\n\nclass hmm(object):\n\tdef __init__(self):\n\t\tself.emissions = {}\n\t\tself.transitions = {}\n\t\tself.unigram = {}\n\t\tself.bigram = {}\n\t\tself.tags = []\n\t\tself.all_status = ['O','I-GENE']\n\n\tdef train(self, counts_file):\n\t\tfreq_counts = reader(counts_file)\n\t\tfor freq in freq_counts:\n\t\t\tif freq:\n\t\t\t\tif freq[1] == 'WORDTAG':\n\t\t\t\t\ttmp = {}\n\t\t\t\t\ttmp[freq[2]] = int(freq[0])\n\t\t\t\t\tif freq[-1] in self.emissions:\n\t\t\t\t\t\tself.emissions[freq[-1]].update(tmp)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.emissions[freq[-1]] = tmp\n\t\t\t\telif freq[1] == '1-GRAM':\n\t\t\t\t\tself.unigram[freq[-1]] = int(freq[0])\n\t\t\t\telif freq[1] == '2-GRAM':\n\t\t\t\t\ttmp = {}\n\t\t\t\t\ttmp[freq[-1]] = int(freq[0])\n\t\t\t\t\tif freq[2] in self.bigram:\n\t\t\t\t\t\tself.bigram[freq[2]].update(tmp)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.bigram[freq[2]] = tmp\n\t\t\t\telse:\n\t\t\t\t\ttmp = {}\n\t\t\t\t\ttmp[freq[-1]] = int(freq[0])\n\t\t\t\t\tif freq[2] in self.transitions:\n\t\t\t\t\t\tif freq[3] in self.transitions[freq[2]]:\n\t\t\t\t\t\t\tself.transitions[freq[2]][freq[3]].update(tmp)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.transitions[freq[2]][freq[3]] = tmp\n\t\t\t\t\telse:\n\t\t\t\t\t\ttmp2 = {}\n\t\t\t\t\t\ttmp2[freq[3]] = tmp\n\t\t\t\t\t\tself.transitions[freq[2]] = tmp2\n\t\tfor i in self.emissions:\n\t\t\tfor j in self.emissions[i]:\n\t\t\t\tself.emissions[i][j] /= self.unigram[j]\n\t\tfor word in self.emissions:\n\t\t\tif 'O' not in self.emissions[word]:\n\t\t\t\tself.emissions[word]['O'] = 0.0\n\t\t\telif 'I-GENE' not in self.emissions[word]:\n\t\t\t\tself.emissions[word]['I-GENE'] = 0.0\n\t\tfor i in self.transitions:\n\t\t\tfor j in self.transitions[i]:\n\t\t\t\tfor k in self.transitions[i][j]:\n\t\t\t\t\tself.transitions[i][j][k] /= self.bigram[i][j]\n\n\tdef make_tags(self,pi,bp,n):\n\t\tif n == 1:\n\t\t\tmaxVal = -1.0\n\t\t\ttmpTag = ''\n\t\t\tfor step,i,j in pi.keys():\n\t\t\t\ttmp = pi[(step,i,j)]*self.transitions['*'][j]['STOP']\n\t\t\t\tif tmp > maxVal:\n\t\t\t\t\tmaxVal = tmp\n\t\t\t\t\ttmpTag = j\n\t\t\tself.tags.append([tmpTag])\n\t\telse:\n\t\t\tmaxVal = -1.0\n\t\t\tfor i in self.all_status:\n\t\t\t\tfor j in self.all_status:\n\t\t\t\t\ttmp = pi[(n-1,i,j)]*self.transitions[i][j]['STOP']\n\t\t\t\t\tif tmp>maxVal:\n\t\t\t\t\t\tmaxVal = tmp\n\t\t\t\t\t\tp = i\n\t\t\t\t\t\tq = j\n\t\t\ttmpTags = [p,q]\n\t\t\tl = [q,p]\n\t\t\tk = n-1\n\t\t\twhile k>1:\n\t\t\t\tr = bp[(k,p,q)]\n\t\t\t\tl.append(r)\n\t\t\t\tq = p\n\t\t\t\tp = r\n\t\t\t\tk -= 1\n\t\t\tl.reverse()\n\t\t\tself.tags.append(l)\n\n\tdef viterbi(self, sentence):\n\t\tn = len(sentence)\n\t\trare_words = []\n\t\tpi = {}\n\t\tbp = {}\n\t\tfor word in sentence:\n\t\t\tif word not in self.emissions:\n\t\t\t\trare_words.append('_RARE_')\n\t\t\telse:\n\t\t\t\trare_words.append(word)\n\t\tstep = 0\n\t\twhile steppi[(step,i,j)]:\n\t\t\t\t\t\t\t\tpi[(step,i,j)] = tmp\n\t\t\t\t\t\t\t\tbp[(step,i,j)] = k\n\t\t\tstep += 1\n\t\tself.make_tags(pi,bp,n)\n\t\t\t\n\t\t\n\tdef tag(self,input_file):\n\t\tsentences = sentence_reader(input_file)\n\t\tfor sentence in sentences:\n\t\t\tself.viterbi(sentence)\n\nif __name__ == '__main__':\n\tinput_file = open(sys.argv[1],'r')\n\tinput_file1 = open(sys.argv[1],'r')\n\tcounts_file = open(sys.argv[2],'r')\n\toutput_file = open(sys.argv[3],'w')\n\n\ttagger = hmm()\n\ttagger.train(counts_file)\n\ttagger.tag(input_file)\n\t\n\tsentences = sentence_reader(input_file1)\n\tfor sentence,tags in zip(sentences, tagger.tags):\n\t\tfor word, tag in zip(sentence, tags):\n\t\t\toutput_file.write(word+' '+tag+'\\n')\n\t\toutput_file.write('\\n')\n\t\t\n","sub_path":"2-python-practice/4-hmm/hmm/trigramHmm.py","file_name":"trigramHmm.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"129681691","text":"import torch\nimport os\nimport config\nimport numpy as np\nfrom PIL import Image\nfrom torchvision.utils import save_image\n\n\ndef gradient_penalty(critic, real, fake, device):\n BATCH_SIZE, C, H, W = real.shape\n alpha = torch.rand((BATCH_SIZE, 1, 1, 1)).repeat(1, C, H, W).to(device)\n interpolated_images = real * alpha + fake.detach() * (1 - alpha)\n interpolated_images.requires_grad_(True)\n\n # Calculate critic scores\n mixed_scores = critic(interpolated_images)\n\n # Take the gradient of the scores with respect to the images\n gradient = torch.autograd.grad(\n inputs=interpolated_images,\n outputs=mixed_scores,\n grad_outputs=torch.ones_like(mixed_scores),\n create_graph=True,\n retain_graph=True,\n )[0]\n gradient = gradient.view(gradient.shape[0], -1)\n gradient_norm = gradient.norm(2, dim=1)\n gradient_penalty = torch.mean((gradient_norm - 1) ** 2)\n return gradient_penalty\n\n\ndef save_checkpoint(model, optimizer, filename=\"my_checkpoint.pth.tar\"):\n print(\"=> Saving checkpoint\")\n checkpoint = {\n \"state_dict\": model.state_dict(),\n \"optimizer\": optimizer.state_dict(),\n }\n torch.save(checkpoint, filename)\n\n\ndef load_checkpoint(checkpoint_file, model, optimizer, lr):\n print(\"=> Loading checkpoint\")\n checkpoint = torch.load(checkpoint_file, map_location=config.DEVICE)\n # model.load_state_dict(checkpoint)\n model.load_state_dict(checkpoint[\"state_dict\"])\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\n\n # If we don't do this then it will just have learning rate of old checkpoint\n # and it will lead to many hours of debugging \\:\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = lr\n\n\ndef plot_examples(low_res_folder, gen):\n files = os.listdir(low_res_folder)\n\n gen.eval()\n for file in files:\n image = Image.open(\"test_images/\" + file)\n with torch.no_grad():\n upscaled_img = gen(\n config.test_transform(image=np.asarray(image))[\"image\"]\n .unsqueeze(0)\n .to(config.DEVICE)\n )\n save_image(upscaled_img, f\"saved/{file}\")\n gen.train()\n","sub_path":"ML/Pytorch/GANs/ESRGAN/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"495853531","text":"import numpy as np\n\nclass Metrics():\n def __init__(self):\n pass\n\n def accuracy_score(self, y_true, y_pred):\n \"\"\"Calculate the accuracy score for the data passed\n\n Args:\n y_true (numpy array): the real data\n y_pred (numpy array): the predicted data\n\n Returns:\n float: the accuracy score for the data passed\n \"\"\"\n sample_length = y_true.shape[0]\n return (np.sum(y_true == y_pred) / sample_length)\n\n def shuffle(self, X, y):\n indices = np.arange(X.shape[0])\n np.random.shuffle(indices)\n return X[indices], y[indices]\n\n def k_fold(self, X, y, k, classifier):\n X, y = self.shuffle(X, y)\n\n subset_size = round(X.shape[0] / k)\n X_subsets = [X[i:i+subset_size, :] for i in range(0, X.shape[0], subset_size)]\n y_subsets = [y[i:i+subset_size] for i in range(0, y.shape[0], subset_size)]\n\n train_accuracy_list = np.array([])\n test_accuracy_list = np.array([])\n print(\"___________________________K-fold___________________________\")\n for i in range(k):\n X_test = X_subsets[i]\n y_test = y_subsets[i]\n\n X_train = np.array([])\n y_train = np.array([])\n for j in range(k):\n if i != j:\n X_train = np.append(X_train, X_subsets[j])\n y_train = np.append(y_train, y_subsets[j])\n X_train = X_train.reshape(y_train.shape[0], X.shape[1])\n\n classifier.fit(X_train,y_train)\n y_test_pred = classifier.predict(X_test)\n y_train_pred = classifier.predict(X_train)\n\n test_accuracy = self.accuracy_score(y_test, y_test_pred)\n train_accuracy = self.accuracy_score(y_train, y_train_pred)\n\n train_accuracy_list = np.append(train_accuracy_list, train_accuracy)\n test_accuracy_list = np.append(test_accuracy_list, test_accuracy)\n print(\"___________________________Iteração {}___________________________\".format(i+1))\n print('Acurácia para dados de treino: {}'.format(train_accuracy))\n print('Acurácia para dados de teste: {}'.format(test_accuracy))\n print('\\n')\n print('Acurácia geral de treino: {}'.format(train_accuracy_list.mean()))\n print('Acurácia geral de teste: {}'.format(test_accuracy_list.mean()))\n ","sub_path":"Atividade 4/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"49645411","text":"import unittest\nimport numpy as np\nfrom jigsolver import Border, Piece, Puzzle\nfrom jigsolver.metrics import dissimilarity\n\nclass PieceTestCase(unittest.TestCase):\n def setUp(self):\n # creating very simple pieces\n A = np.zeros((2, 2, 3)).astype(int)\n B = A.copy()\n\n A[:, 0] = 1\n A[:, 1] = 2\n A = Piece(A)\n\n B[:, 0] = 5\n B[:, 1] = 1\n B = Piece(B)\n\n self.A=A\n self.B=B\n\n def test_piece_size_should_return_size(self):\n picture = np.array([\n [[1, 1, 1], [1, 2, 3], [4, 5, 6]],\n [[0, 1, 2], [5, 3, 0], [0, 1, 4]],\n [[8, 5, 1], [4, 5, 0], [8, 5, 1]]\n ])\n piece = Piece(picture, 0)\n self.assertEqual(piece.size, 3)\n\n def test_piece_with_rectangular_picture_should_raise_error(self):\n picture = np.zeros((4, 5, 3)) # RGB picture of shape 4×5\n with self.assertRaises(AssertionError):\n piece = Piece(picture, 0)\n\n def test_piece_without_colored_picture_should_raise_error(self):\n picture = np.zeros((3, 3, 2))\n with self.assertRaises(AssertionError):\n piece = Piece(picture, 0)\n\n def test_piece_without_three_dimensional_picture_should_raise_error(self):\n picture = np.zeros((5, 5))\n with self.assertRaises(AssertionError):\n piece = Piece(picture, 0)\n\n def test_piece_dissimilarity(self):\n\n diss = [0] * len(Border)\n diss[Border.TOP.value] = 51\n diss[Border.BOTTOM.value] = 51\n diss[Border.RIGHT.value] = 54\n diss[Border.LEFT.value] = 0\n\n #Testing of the symetry\n\n self.assertListEqual(dissimilarity(self.A, self.B), diss)\n\n diss[Border.TOP.value], diss[Border.BOTTOM.value] = diss[Border.BOTTOM.value], diss[Border.TOP.value]\n diss[Border.LEFT.value], diss[Border.RIGHT.value] = diss[Border.RIGHT.value], diss[Border.LEFT.value]\n\n self.assertListEqual(dissimilarity(self.B, self.A), diss)\n\n\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/piece_test.py","file_name":"piece_test.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"583099360","text":"'''\n题目:打印出所有的\"水仙花数\",所谓\"水仙花数\"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个\"水仙花数\",因为153=1的三次方+5的三次方+3的三次方。\n\n程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。\n'''\n\narr = list()\n\nfor i in range(100,1000):\n a = int(i/100) % 10\n b = int(i/10) % 10\n c = int(i/1) % 10\n if i == a**3 + b**3 + c**3:\n arr.append(i)\n\nprint('水仙花数:' + str(arr))\n","sub_path":"case_20/sub_13.py","file_name":"sub_13.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"417123385","text":"from __future__ import annotations\n\nfrom typing import Callable\nfrom typing import cast\nfrom typing import NamedTuple\nfrom typing import Sequence\n\nimport numpy as np\n\nfrom optuna.logging import get_logger\nfrom optuna.study import Study\nfrom optuna.study._study_direction import StudyDirection\nfrom optuna.trial import FrozenTrial\nfrom optuna.trial import TrialState\nfrom optuna.visualization._plotly_imports import _imports\nfrom optuna.visualization._utils import _check_plot_args\n\n\nif _imports.is_successful():\n from optuna.visualization._plotly_imports import go\n\n_logger = get_logger(__name__)\n\n\nclass _ValuesInfo(NamedTuple):\n values: list[float]\n stds: list[float] | None\n label_name: str\n\n\nclass _OptimizationHistoryInfo(NamedTuple):\n trial_numbers: list[int]\n values_info: _ValuesInfo\n best_values_info: _ValuesInfo | None\n\n\ndef _get_optimization_history_info_list(\n study: Study | Sequence[Study],\n target: Callable[[FrozenTrial], float] | None,\n target_name: str,\n error_bar: bool,\n) -> list[_OptimizationHistoryInfo]:\n _check_plot_args(study, target, target_name)\n if isinstance(study, Study):\n studies = [study]\n else:\n studies = list(study)\n\n info_list: list[_OptimizationHistoryInfo] = []\n for study in studies:\n trials = study.get_trials(states=(TrialState.COMPLETE,))\n label_name = target_name if len(studies) == 1 else f\"{target_name} of {study.study_name}\"\n if target is not None:\n values = [target(t) for t in trials]\n # We don't calculate best for user-defined target function since we cannot tell\n # which direction is better.\n best_values_info: _ValuesInfo | None = None\n else:\n values = [cast(float, t.value) for t in trials]\n if study.direction == StudyDirection.MINIMIZE:\n best_values = list(np.minimum.accumulate(values))\n else:\n best_values = list(np.maximum.accumulate(values))\n best_label_name = (\n \"Best Value\" if len(studies) == 1 else f\"Best Value of {study.study_name}\"\n )\n best_values_info = _ValuesInfo(best_values, None, best_label_name)\n info_list.append(\n _OptimizationHistoryInfo(\n trial_numbers=[t.number for t in trials],\n values_info=_ValuesInfo(values, None, label_name),\n best_values_info=best_values_info,\n )\n )\n\n if len(info_list) == 0:\n _logger.warning(\"There are no studies.\")\n\n if sum(len(info.trial_numbers) for info in info_list) == 0:\n _logger.warning(\"There are no complete trials.\")\n info_list.clear()\n\n if not error_bar:\n return info_list\n\n # When error_bar=True, a list of 0 or 1 element is returned.\n if len(info_list) == 0:\n return []\n all_trial_numbers = [number for info in info_list for number in info.trial_numbers]\n max_num_trial = max(all_trial_numbers) + 1\n\n def _aggregate(label_name: str, use_best_value: bool) -> tuple[list[int], _ValuesInfo]:\n # Calculate mean and std of values for each trial number.\n values: list[list[float]] = [[] for _ in range(max_num_trial)]\n assert info_list is not None\n for trial_numbers, values_info, best_values_info in info_list:\n if use_best_value:\n assert best_values_info is not None\n values_info = best_values_info\n for trial_number, value in zip(trial_numbers, values_info.values):\n values[trial_number].append(value)\n trial_numbers_union = [i for i in range(max_num_trial) if len(values[i]) > 0]\n value_means = [np.mean(v).item() for v in values if len(v) > 0]\n value_stds = [np.std(v).item() for v in values if len(v) > 0]\n return trial_numbers_union, _ValuesInfo(value_means, value_stds, label_name)\n\n eb_trial_numbers, eb_values_info = _aggregate(target_name, False)\n eb_best_values_info: _ValuesInfo | None = None\n if target is None:\n _, eb_best_values_info = _aggregate(\"Best Value\", True)\n return [_OptimizationHistoryInfo(eb_trial_numbers, eb_values_info, eb_best_values_info)]\n\n\ndef plot_optimization_history(\n study: Study | Sequence[Study],\n *,\n target: Callable[[FrozenTrial], float] | None = None,\n target_name: str = \"Objective Value\",\n error_bar: bool = False,\n) -> \"go.Figure\":\n \"\"\"Plot optimization history of all trials in a study.\n\n Example:\n\n The following code snippet shows how to plot optimization history.\n\n .. plotly::\n\n import optuna\n\n\n def objective(trial):\n x = trial.suggest_float(\"x\", -100, 100)\n y = trial.suggest_categorical(\"y\", [-1, 0, 1])\n return x ** 2 + y\n\n\n sampler = optuna.samplers.TPESampler(seed=10)\n study = optuna.create_study(sampler=sampler)\n study.optimize(objective, n_trials=10)\n\n fig = optuna.visualization.plot_optimization_history(study)\n fig.show()\n\n Args:\n study:\n A :class:`~optuna.study.Study` object whose trials are plotted for their target values.\n You can pass multiple studies if you want to compare those optimization histories.\n target:\n A function to specify the value to display. If it is :obj:`None` and ``study`` is being\n used for single-objective optimization, the objective values are plotted.\n\n .. note::\n Specify this argument if ``study`` is being used for multi-objective optimization.\n target_name:\n Target's name to display on the axis label and the legend.\n error_bar:\n A flag to show the error bar.\n\n Returns:\n A :class:`plotly.graph_objs.Figure` object.\n \"\"\"\n\n _imports.check()\n\n info_list = _get_optimization_history_info_list(study, target, target_name, error_bar)\n return _get_optimization_history_plot(info_list, target_name)\n\n\ndef _get_optimization_history_plot(\n info_list: list[_OptimizationHistoryInfo],\n target_name: str,\n) -> \"go.Figure\":\n layout = go.Layout(\n title=\"Optimization History Plot\",\n xaxis={\"title\": \"Trial\"},\n yaxis={\"title\": target_name},\n )\n\n traces = []\n for trial_numbers, values_info, best_values_info in info_list:\n if values_info.stds is None:\n error_y = None\n else:\n error_y = {\"type\": \"data\", \"array\": values_info.stds, \"visible\": True}\n traces.append(\n go.Scatter(\n x=trial_numbers,\n y=values_info.values,\n error_y=error_y,\n mode=\"markers\",\n name=values_info.label_name,\n )\n )\n\n if best_values_info is not None:\n traces.append(\n go.Scatter(\n x=trial_numbers,\n y=best_values_info.values,\n name=best_values_info.label_name,\n )\n )\n if best_values_info.stds is not None:\n upper = np.array(best_values_info.values) + np.array(best_values_info.stds)\n traces.append(\n go.Scatter(\n x=trial_numbers,\n y=upper,\n mode=\"lines\",\n line=dict(width=0.01),\n showlegend=False,\n )\n )\n lower = np.array(best_values_info.values) - np.array(best_values_info.stds)\n traces.append(\n go.Scatter(\n x=trial_numbers,\n y=lower,\n mode=\"none\",\n showlegend=False,\n fill=\"tonexty\",\n fillcolor=\"rgba(255,0,0,0.2)\",\n )\n )\n\n return go.Figure(data=traces, layout=layout)\n","sub_path":"optuna/visualization/_optimization_history.py","file_name":"_optimization_history.py","file_ext":"py","file_size_in_byte":8014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"593290042","text":"\"\"\"\n 百度输入法词库爬虫\n\"\"\"\nimport random\nimport string\nimport scrapy\nfrom baiduSpder.items import CategoryItem\nfrom baiduSpder.bdict_decoder import BaiduPinyinBDict\n\nclass BaiduBaikeSpider(scrapy.Spider):\n \"\"\"\n 百度输入法词库爬虫\n \"\"\"\n\n name = \"baidu_baike_spider\"\n\n dictDecoder = BaiduPinyinBDict()\n dict_ids = [\"158\", \"317\", \"162\", \"159\", \"163\", \"165\", \"160\", \"161\"]\n dict_names = {\"158\": \"理工行业\", \"317\": \"人文社会\", \"162\": \"电子游戏\", \"159\": \"生活百科\",\n \"163\": \"娱乐休闲\", \"165\": \"人名\", \"160\": \"文化艺术\", \"161\":\"体育运动\"}\n item_names = {\"name\":1}\n\n\n user_agent_list = [\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1\",\n \"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5\",\n \"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24\"\n ]\n\n def randomHeaders(self):\n headers = {\n \"User-Agent\": random.choice(self.user_agent_list),\n \"Cookie\": \"bid=%s\" % \"\".join(random.sample(string.ascii_letters + string.digits, 11)),\n }\n return headers\n\n def start_requests(self):\n for cid in self.dict_ids:\n url = \"https://shurufa.baidu.com/dict_list?cid=\" + cid\n request = scrapy.Request(url, headers=self.randomHeaders())\n request.meta['cat'] = self.dict_names[cid]\n yield request\n\n\n def parse(self, response):\n category2 = response.xpath('//*[@id=\"cid_\"]/a[@data-stats=\"webDictListPage.category2\"]')\n\n for cat in category2:\n url = \"https://shurufa.baidu.com\" + cat.xpath('@href').extract()[0]\n name = cat.xpath('text()').extract()[0].replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n request = scrapy.Request(url, headers=self.randomHeaders(), callback=self.parse_items)\n request.meta['base_url'] = url\n request.meta['cat1'] = name\n request.meta['cat2'] = '无'\n request.meta['cat'] = response.meta['cat']\n yield request\n\n categories = response.xpath('//*[@id=\"cid_\"]/div[@class=\"tag_list popup_button\"]')\n\n for cat in categories:\n cat2_name = cat.xpath('//a[@data-stats=\"webDictListPage.category2\"]/text()').extract()[0].replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n cat3 = cat.xpath('//a[@data-stats=\"webDictListPage.category3\"]')\n for c in cat3:\n url = \"https://shurufa.baidu.com\" + c.xpath('@href').extract()[0]\n name = c.xpath('text()').extract()[0].replace(\"\\n\",\"\").replace(\"\\r\",\"\")\n request = scrapy.Request(url, headers=self.randomHeaders(), callback=self.parse_items)\n request.meta['cat1'] = cat2_name\n request.meta['cat2'] = name\n request.meta['cat'] = response.meta['cat']\n yield request\n \n url = \"https://shurufa.baidu.com\" + cat.xpath('//a[@data-stats=\"webDictListPage.category2\"]/@href').extract()[0]\n request = scrapy.Request(url, headers=self.randomHeaders(), callback=self.parse_items)\n request.meta['cat1'] = cat2_name\n request.meta['cat2'] = '无'\n request.meta['cat'] = response.meta['cat']\n yield request\n \n def parse_items(self, response):\n categories = response.xpath('//*[@id=\"dict-list-page\"]/div/div/div/div[3]/table//tr')\n for cat in categories:\n cat3 = cat.xpath('td[1]/a/@title').extract()[0]\n\n if cat3 in self.item_names.keys():\n continue\n else:\n inner_id = cat.xpath('td[5]/a/@dict-innerid').extract()[0]\n dic_download_url = (\"https://shurufa.baidu.com/\"\n \"dict_innerid_download?innerid=\") + inner_id\n self.item_names[cat3] = 1\n request = scrapy.Request(dic_download_url,\n headers=self.randomHeaders(), callback=self.parse_bdict)\n request.meta['inner_id'] = inner_id\n request.meta['cat1'] = response.meta['cat1']\n request.meta['cat2'] = response.meta['cat2']\n request.meta['cat3'] = cat3.replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n request.meta['cat'] = response.meta['cat']\n yield request\n\n #翻页\n next_page_url = response.xpath(('//*[@id=\"dict-list-page\"]/div/div/div/div[4]'\n '/a[@class=\"last paging-right\"]/@href')).extract()[0]\n\n if next_page_url:\n next_url = \"https://shurufa.baidu.com/\" + next_page_url\n request = scrapy.Request(next_url, headers=self.randomHeaders(),callback=self.parse_items)\n request.meta[\"cat1\"] = response.meta['cat1']\n request.meta[\"cat2\"] = response.meta['cat2']\n request.meta['cat'] = response.meta['cat']\n yield request\n\n def parse_bdict(self, response):\n words = self.dictDecoder.convert_words(response.body)\n for word in words:\n item = CategoryItem()\n item[\"word\"] = word\n item['category3'] = response.meta['cat3']\n item['category2'] = response.meta['cat2']\n item['category1'] = response.meta['cat1']\n item['category'] = response.meta['cat']\n yield item\n\n\n\n\n","sub_path":"baiduSpder/spiders/baidu_baike_spider.py","file_name":"baidu_baike_spider.py","file_ext":"py","file_size_in_byte":7264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"338664290","text":"# for i in 'hello world':\n# if i == 'a':\n# break\n# else:\n# print('char a not in string')\n\na = [1,4,5,78,4,5,5]\nfor i in a:\n if not str(i).isdigit():\n raise AssertionError('FAIL: str in list')\nelse:\n print('no str in list')\n","sub_path":"for_else.py","file_name":"for_else.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"413918999","text":"from common.arangodb import get_db\nfrom migrations.base import Migration\n\n\nclass InitialMigration(Migration):\n migration_id = 'add_type_index_014'\n tasks = ['add_type_index']\n\n def add_type_index(self):\n db = get_db()\n\n db['root'].add_hash_index(fields=[\"type\"], unique=False)\n","sub_path":"server/server/migrations/migrations/add_type_index_014.py","file_name":"add_type_index_014.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"323867506","text":"def companyBotStrategy(trainingData):\n avg_time = 0\n corr_count = 0\n for i in range(len(trainingData)):\n if trainingData[i][1] == 1:\n avg_time += trainingData[i][0]\n corr_count += 1\n \n if corr_count == 0:\n return 0\n \n avg_time /= corr_count\n \n return avg_time\n\nprint(companyBotStrategy([[1, 1], [3, 0], [3, 1], [2, 1]]))","sub_path":"codefights/company-challenges/companyBotStrategy.py","file_name":"companyBotStrategy.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"8186764","text":"# Uses python3\nimport sys\n\ndef sort_weights_values(weights, values):\n # Sort weights and values in non-increasing order computed from value per unit weight\n value_per_weight = list()\n n = len(values)\n for i in range(n):\n value_per_weight.append(values[i] / weights[i])\n\n zipped = zip(value_per_weight, values, weights)\n sorted_zipped = sorted(zipped, reverse = True)\n value_per_weight, values, weights = zip(*sorted_zipped)\n return values, weights\n\n\ndef get_optimal_value(capacity, weights, values):\n value = 0.\n values, weights = sort_weights_values(weights, values)\n for i, weight in enumerate(weights):\n if capacity <= 0:\n return value\n min_weight = min(capacity, weight)\n value += min_weight * values[i] / weights[i]\n capacity -= min_weight\n\n return value\n\n\nif __name__ == \"__main__\":\n data = list(map(int, sys.stdin.read().split()))\n n, capacity = data[0:2]\n values = data[2:(2 * n + 2):2]\n weights = data[3:(2 * n + 2):2]\n opt_value = get_optimal_value(capacity, weights, values)\n print(\"{:.10f}\".format(opt_value))\n","sub_path":"algorithmic-toolbox/assignment-2/fractional_knapsack.py","file_name":"fractional_knapsack.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"429086395","text":"import logging\nimport unittest\n\n\n\"\"\"MinAvgTwoSlice (https://codility.com/demo/take-sample-test/min_avg_two_slice/)\n\nAnalysis:\n - Reference http://codesays.com/2014/solution-to-min-avg-two-slice-by-codility/\n\"\"\"\n\n__author__ = 'au9ustine'\nlogging.basicConfig(format='%(message)s', level=logging.DEBUG)\n\n\ndef solution(A):\n min_avg_val = (A[0] + A[1]) / 2.0\n i_min = 0\n for i in xrange(len(A)-2):\n if (A[i] + A[i+1]) / 2.0 < min_avg_val:\n min_avg_val = (A[i] + A[i+1]) / 2.0\n i_min = i\n if (A[i] + A[i+1] + A[i+2]) / 3.0 < min_avg_val:\n min_avg_val = (A[i] + A[i+1] + A[i+2]) / 3.0\n i_min = i\n if (A[-1] + A[-2]) / 2.0 < min_avg_val:\n min_avg_val = (A[-1] + A[-2]) / 2.0\n i_min = len(A)-2\n return i_min\n\nclass SolutionTest(unittest.TestCase):\n\n def setUp(self):\n self.data = [\n ([4, 2, 2, 5, 1, 5, 8], 1),\n ]\n\n def test_solution(self):\n for input_data, expected in self.data:\n actual = solution(input_data)\n self.assertEquals(expected, actual)\n\nif __name__ == \"__main__\":\n unittest.main(failfast=True)","sub_path":"lessons/lesson03_prefix_sums/MinAvgTwoSlice.py","file_name":"MinAvgTwoSlice.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"534427591","text":"from django.shortcuts import render\nfrom .apps import WebappConfig \n\n# Create your views here.\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom .apps import WebappConfig\n\nclass call_model(APIView):\n\n \n #def get(self,request):\n # if request.method == 'GET':\n # params = request.GET.get('sentence') \n # # sentence = 'I am very happy'\n # response = WebappConfig.predictor.predict(params)\n\n # return JsonResponse(response[0],safe=False)\n\n def get(self,request):\n if request.method == 'GET':\n params = request.GET.get('sentence') \n predict = WebappConfig.predictor.predict(params)\n \n response =dict()\n #response_default=dict()\n response1=dict()\n response2=dict()\n response3=dict()\n\n response1[\"name\"] = str(predict[0][0])\n response1[\"confidence\"] = float(predict[0][1])\n\n response2[\"name\"] = str(predict[1][0])\n response2[\"confidence\"] = float(predict[1][1])\n\n response3[\"name\"] = str(predict[2][0])\n response3[\"confidence\"] = float(predict[2][1])\n\n l=[response1,response2,response3]\n\n #response[\"name\"] = str(predict[0][0])\n #response[\"confidence\"] = float(predict[0][1])\n response[\"intent\"] = response1 \n response[\"intent_ranking\"]=l\n return JsonResponse(response)\n\n\n\n\n\n\n","sub_path":"api_bert/webapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"456458695","text":"import os\r\nfile_list = os.listdir()\r\nanswer = 0\r\nfold_names = ''\r\nfor i in range(0, len(file_list)):\r\n path = './' + file_list[i]\r\n valid = False\r\n if os.path.isdir(path):\r\n for letter in file_list[i]:\r\n if letter == ' ':\r\n valid = True\r\n if valid:\r\n answer += 1\r\n fold_names += file_list[i] + ', '\r\nprint('Папок, состоящих из более чем одного слова', answer)\r\nhelp = fold_names.split(',')\r\ndel help[-1]\r\nfold_names = ', '.join(help)\r\nprint('Эти папки: ', fold_names)\r\n","sub_path":"hw13/hw13.py","file_name":"hw13.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"451828895","text":"import numpy as np\nimport math\nfrom physics_sim import PhysicsSim\n\nclass Task():\n \"\"\"Task (environment) that defines the goal and provides feedback to the agent.\"\"\"\n def __init__(self, init_pose=None, init_velocities=None,\n init_angle_velocities=None, runtime=5., target_pos=None):\n \"\"\"Initialize a Task object.\n Params\n ======\n init_pose: initial position of the quadcopter in (x,y,z) dimensions and the Euler angles\n init_velocities: initial velocity of the quadcopter in (x,y,z) dimensions\n init_angle_velocities: initial radians/second for each of the three Euler angles\n runtime: time limit for each episode\n target_pos: target/goal (x,y,z) position for the agent\n \"\"\"\n # Simulation\n self.sim = PhysicsSim(init_pose, init_velocities, init_angle_velocities, runtime)\n self.action_repeat = 3\n\n self.state_size = self.action_repeat * 6\n self.action_low = 0\n self.action_high = 900\n self.action_size = 4\n self.init_pose = init_pose\n self.success = False\n self.takeoff = False\n\n # Goal\n self.target_pos = target_pos if target_pos is not None else np.array([0., 0., 10.])\n\n def get_reward(self):\n \"\"\"Uses current pose of sim to return reward.\"\"\"\n #original reward function: reward = 1.-.3*(abs(self.sim.pose[:3] - self.target_pos)).sum()\n thrusts = self.sim.get_propeler_thrust(self.sim.prop_wind_speed)\n linear_forces = self.sim.get_linear_forces(thrusts)\n distance = np.linalg.norm(self.target_pos - self.sim.pose[:3])\n #speed = math.sqrt(np.square(self.sim.find_body_velocity()).sum())\n #with 300x300x300m env, the max distance from one corner to another is 519\n max_distance = 519\n #Focus quadcopter on not crashing but first rewarding an upward linear force until at the height of the target\n if self.sim.pose[2] < self.target_pos[2]:\n #velocity_discount = 1/speed\n reward = np.tanh(linear_forces[2])\n #after getting to the correct z-coordinate, move to the correct y-coordinate\n elif self.sim.pose[1] < self.target_pos[1]:\n #velocity_discount = 1/speed\n reward = 1 + np.tanh(linear_forces[1])\n #finally, after getting rewards for the x and y coordinates, give reward for distance\n #at this stage, the drone will have overshot the x and y coordinates, but it would be in a better area to\n #start searching for the x coordinate\n elif distance > 1 and self.sim.pose[2] > self.target_pos[2] and self.sim.pose[1] > self.target_pos[1] :\n reward = 2 + (1-math.pow((distance/300),.04))\n elif distance < 1:\n self.success = True\n reward = 100\n #possible reward for hover: np.exp(-np.square(linear_forces[2]))\n return reward\n\n def step(self, rotor_speeds):\n \"\"\"Uses action to obtain next state, reward, done.\"\"\"\n reward = 0\n pose_all = []\n for _ in range(self.action_repeat):\n done = self.sim.next_timestep(rotor_speeds) # update the sim pose and velocities\n reward += self.get_reward()\n pose_all.append(self.sim.pose)\n next_state = np.concatenate(pose_all)\n return next_state, reward, done\n\n def reset(self):\n \"\"\"Reset the sim to start a new episode.\"\"\"\n self.sim.reset()\n self.takeoff = False\n self.success = False\n state = np.concatenate([self.sim.pose] * self.action_repeat)\n return state\n","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":3603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"385843554","text":"# -*- coding: utf-8 -*-\nimport fileinput\n\nimport hashlib\nimport re\nimport os\n\nfrom file_manager.models import ExtractedFile\n\ndef md5(fname):\n hash_md5 = hashlib.md5()\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\n\ndef read_file(file_name):\n with open(file_name, 'rb') as f:\n return f.readlines()\n\n\ndef write_file(file_name, data):\n with open(file_name, 'wb') as f:\n f.writelines(data)\n\ndef save_file_to_db(file_name):\n file_hash = md5(file_name)\n if not ExtractedFile.objects.filter(file_hash=file_hash).exists():\n f = ExtractedFile()\n f.file.path = file_name.split('/')[-1]\n f.source_IP = '.'.join(file_name.split('/')[-1].split('-').split('.')[:-1])\n f.file_hash = file_hash\n f.save()\ndef clean_pcap_files(file_name):\n lines = read_file(file_name)\n for i, l in enumerate(lines):\n if l == b'\\r\\n':\n processed_file_path = '/home/razieh/code/BSC/separated_files/' + file_name.split('/')[-1]\n write_file(processed_file_path, lines[i + 1::])\n os.remove(file_name)\n if os.path.getsize(processed_file_path) == 0:\n os.remove(processed_file_path)\n save_file_to_db(processed_file_path)\n break\n\n\nfor file in fileinput.input():\n if file.startswith('192.168.0.101'):\n os.remove(file)\n continue\n clean_pcap_files(re.sub(r'\\s', '', file))\n","sub_path":"file_manager/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"155696655","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import with_statement\nimport unittest\nimport robot\nfrom os import remove\n\n\nclass TestUsers(unittest.TestCase):\n old_users_file = 'test_old_users.txt'\n new_users_file = 'test_new_users.txt'\n old_users = ['john ', 'ray ', 'pete ']\n new_users = ['john ', 'ray ', 'pete ', 'mat ']\n\n def setUp(self):\n \"\"\"Create old and new users files\"\"\"\n with open(self.old_users_file, 'w') as f:\n f.write('\\n'.join(self.old_users))\n f.write('\\n')\n with open(self.new_users_file, 'w') as f:\n f.write('\\n'.join(self.new_users))\n\n def tearDown(self):\n \"\"\"Delete test old and new users files\"\"\"\n remove(self.old_users_file)\n remove(self.new_users_file)\n\n def test_load_user_list(self):\n old_users_list = robot.load_user_list(self.old_users_file)\n old_users = set([u.strip() for u in self.old_users])\n self.assertEqual(old_users_list, old_users)\n\n def test_get_user(self):\n user = robot.get_user(self.new_users_file, self.old_users_file)\n new_users = [u.strip() for u in self.new_users]\n self.assertIn(user, new_users)\n\n def test_get_user_fail(self):\n with open(self.old_users_file, 'a') as f:\n f.write('mat\\n')\n user = robot.get_user(self.new_users_file, self.old_users_file)\n self.assertEqual(user, None)\n\n def test_save_user(self):\n robot.save_user(self.old_users_file, 'mat')\n old_users_list = robot.load_user_list(self.old_users_file)\n self.assertIn('mat', old_users_list)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"310815583","text":"from django.test import TestCase\n\nfrom academy.apps.accounts.models import User\nfrom academy.apps.students.models import Training, Student\nfrom academy.website.accounts.forms import StudentForm\n\n\nclass AccountsTestForm(TestCase):\n\n def test_student_form(self):\n training = Training.objects.create(batch=1)\n user = User.objects.create_user(\n 'username', 'user@gmail.com', '123qwead', is_active=True\n )\n self.assertEqual(user.email, 'user@gmail.com')\n\n data = {\n 'user': user.id,\n 'training': training.id\n }\n form = StudentForm(data=data)\n self.assertTrue(form.is_valid())\n form.save()\n\n student = Student.objects.first()\n self.assertEqual(student.user, user)\n self.assertEqual(student.training, training)\n","sub_path":"tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"468816257","text":"import traceback\nfrom uuid import uuid4\nfrom django.http.response import JsonResponse\nfrom xpms_common import trace\nfrom utilities import common\nfrom utilities.http import post, post_job, is_request_timeout, get_response, get_nested_value\nfrom config_vars import RULE_SERVICE_URI, LIST_OPERATORS_SERVICE_METHOD, RULES_ENDPOINT, RULES_COLLECTION, SERVICE_NAME\nfrom jsonschema import Draft3Validator\nimport json\nfrom jrules_lib.rule_manager import RuleManager\nfrom connections.mongodb import MongoDbConn\n\ntracer = trace.Tracer.get_instance(SERVICE_NAME)\n\n\ndef rules_config():\n data = dict()\n data[\"solution_id\"] = 'R1'\n data[\"request_id\"] = \"1234\"\n resp = post(RULE_SERVICE_URI + LIST_OPERATORS_SERVICE_METHOD, data)\n return JsonResponse(resp)\n\n\nrules_schema = {\n \"$schema\": \"http://json-schema.org/schema#\",\n \"type\": \"object\",\n \"properties\": {\n \"rule\": {\n \"type\": \"object\"\n },\n \"rule_type\": {\n \"type\": \"string\"\n },\n \"rule_name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\"rule\", \"rule_type\", \"rule_name\"]\n}\n\n\ndef create_rules(payload, solution_id, config):\n job_id = None\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n if is_rule_valid(payload):\n data = {\"solution_id\": solution_id, \"data\": payload}\n response = post_job(config['EP'], data)\n if 'job_id' in response:\n job_id = response[\"job_id\"]\n if not is_request_timeout(response):\n status, result = get_response(response)\n if status:\n rule_id = get_nested_value(response, config[\"DATA\"])\n return {\"status\": \"success\", \"data\": str(rule_id),\n \"msg\": \"Successfully created rule.\",\n 'job_id':job_id}\n else:\n return result\n else:\n return {\"status\": \"failure\", \"msg\": \"Request timed out.\",\n 'job_id':job_id}\n else:\n return {\"status\": \"failure\", \"msg\": \"Invalid rule format.\",\n 'job_id': job_id}\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n if job_id:\n return {\"status\": \"failure\", \"msg\": str(e), \"data\": \"\",\n 'job_id':job_id}\n else:\n return {\"status\": \"failure\", \"msg\": str(e), \"data\": \"\"}\n finally:\n context.end_span()\n\n\ndef get_rules(solution_id, config):\n job_id = None\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n data = {\"solution_id\": solution_id, \"data\": {\"filter_obj\": {}}}\n response = post_job(config[\"EP\"], data)\n if 'job_id' in response:\n job_id = response[\"job_id\"]\n if not is_request_timeout(response):\n status, result = get_response(response)\n if status:\n resp = get_nested_value(response, config[\"DATA\"])\n return {\"status\": \"success\", \"data\": resp,\n \"msg\": \"Successfully retrieved rules\", 'job_id':job_id}\n else:\n return result\n else:\n return {\"status\": \"failure\", \"msg\": \"request timed out\",\n 'job_id': job_id}\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n if job_id:\n return {\"status\": \"failure\", \"data\": [], \"msg\": str(e),\n 'job_id': job_id}\n else:\n return {\"status\": \"failure\", \"data\": [], \"msg\": str(e)}\n finally:\n context.end_span()\n\n\ndef rules_execution_test(solution_id, payload, config):\n job_id = None\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n data = {\"solution_id\": solution_id, \"data\": payload}\n response = post_job(config[\"EP\"], data)\n if 'job_id' in response:\n job_id = response[\"job_id\"]\n if not is_request_timeout(response):\n status, result = get_response(response)\n if status:\n resp = get_nested_value(response, config[\"DATA\"])\n return {\"status\": \"success\", \"data\": resp,\n \"msg\": \"test successful\", 'job_id':job_id}\n else:\n return result\n else:\n return {\"status\": \"failure\", \"msg\": \"Request timed out\",\n 'job_id': job_id}\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n if job_id:\n return {\"status\": \"failure\", \"msg\": str(e), 'job_id':job_id}\n else:\n return {\"status\": \"failure\", \"msg\": str(e)}\n finally:\n context.end_span()\n\ndef is_rule_valid(rule):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n return Draft3Validator(rules_schema).is_valid(rule)\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n return False\n finally:\n context.end_span()\n\n\ndef process_rules(request):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n solution_id = common.get_solution_from_session(request)\n if request.method == \"GET\":\n return get_rule(solution_id)\n elif request.method == \"POST\":\n data = json.loads(request.body.decode())\n if \"rule_id\" in data:\n msg = \"Rule Updated Successfully\"\n else:\n msg = \"Rule Added Successfully\"\n response = update_rule(solution_id,data)\n if response[\"status\"] == \"success\":\n return {\"status\": \"success\", \"msg\":msg, \"rule_id\" : response[\"rule_id\"]}\n else:\n return response\n elif request.method == \"DELETE\":\n data = json.loads(request.body.decode())\n response = delete_rule(solution_id,data[\"rule_id\"])\n if response[\"status\"] == \"success\":\n return {\"status\": \"success\", \"msg\":\"Rule Deleted Successfully\"}\n else:\n return response\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n return {\"status\": \"failure\", \"msg\": str(e)}\n finally:\n context.end_span()\n\n\ndef get_rule(solution_id,rule_id=None):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n rules = RuleManager()\n if rule_id:\n payload = dict(solution_id=solution_id,rule_id=rule_id)\n result = rules.process(\"getRule\", payload)\n key = \"rule\"\n else:\n payload = dict()\n error = 'Invalid response'\n payload[\"solution_id\"] = solution_id\n result = rules.process(\"getRules\", payload)\n key = \"rules\"\n if 'status' in result:\n if 'code' in result['status']:\n if result['status']['code'] == 200:\n if 'metadata' in result and key in result['metadata']:\n rules = result['metadata'][key]\n if isinstance(rules,list) and len(rules) > 0:\n for r in rules:\n r.pop('_id', False)\n if isinstance(rules, dict):\n rules.pop('_id', False)\n error = None\n else:\n error = result['msg']\n\n res = {\"status\": \"success\", \"data\": rules}\n if error is not None:\n res['error'] = error\n\n return res\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n return {\"status\" : \"failure\", \"msg\" : str(e)}\n finally:\n context.end_span()\n\n\ndef update_rule(solution_id,rule):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n rules = RuleManager()\n rule[\"solution_id\"] = solution_id\n result = rules.process(\"saveRule\",rule)\n status = result[\"status\"]\n if status[\"success\"]:\n rule_id = get_nested_value(result,\"metadata.rule_id\")\n where_clause = dict(solution_id=solution_id, rule_id=rule_id)\n MongoDbConn.update(RULES_COLLECTION,where_clause,rule)\n response = {\"status\":\"success\",\"rule_id\":rule_id}\n else:\n response = {\"status\":\"failure\",\"msg\":status[\"msg\"]}\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n response = {\"status\": \"failure\",\"msg\":str(e)}\n context.end_span()\n return response\n\n\ndef delete_rule(solution_id,rule_id):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n payload = dict(solution_id=solution_id,rule_id=rule_id)\n rules = RuleManager()\n result = rules.process(\"deleteRule\",payload)\n if result[\"status\"][\"success\"] is True:\n MongoDbConn.remove(RULES_COLLECTION,dict(solution_id=solution_id,rule_id=rule_id))\n response = {\"status\":\"success\"}\n else:\n response = {\"status\":\"failure\",\"msg\":result[\"status\"][\"msg\"]}\n return response\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n return {\"status\":\"failure\",\"msg\":str(e)}\n finally:\n context.end_span()\n\n\ndef get_config(request):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n solution_id = common.get_solution_from_session(request)\n rules = RuleManager()\n result = rules.process(\"getOperators\",solution_id)\n if result and result[\"status\"][\"success\"]:\n config = result[\"metadata\"][\"data\"]\n return {\"status\":\"success\",\"config\":config}\n else:\n return {\"status\": \"success\",\"msg\":\"error while retrieving config from rules\"}\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n return {\"status\":\"failure\",\"msg\":str(e)}\n finally:\n context.end_span()\n\n\ndef get_rule_info(solution_id,rule_id):\n rule = RuleManager()\n payload = dict(solution_id=solution_id, rule_id=rule_id)\n rule_info = rule.process(RULES_ENDPOINT[\"get_rule\"], payload)\n return rule_info\n\n\ndef execute_rules(request):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n rules = RuleManager()\n data = json.loads(request.body.decode())\n data[\"solution_id\"] = common.get_solution_from_session(request)\n rule = data[\"rule\"]\n transform_rule = False\n if \"rule_type\" in rule.keys() and rule[\"rule_type\"] == \"T\":\n transform_rule = True\n document_variables = [k for k in data[\"source\"].keys()]\n data[\"source\"].update(format_source_data(rule[\"rule\"]))\n else:\n data[\"source\"] = data[\"source\"][\"source\"]\n result = rules.process(\"execute\",data)\n if result[\"status\"][\"success\"]:\n exec_result = result[\"metadata\"][\"result\"][\"facts\"]\n if transform_rule:\n final_result = []\n formatted_result = reformat_attribute_dict(exec_result[\"result\"],\"\",[])\n for item in formatted_result:\n if list(item.keys())[0] not in document_variables:\n final_result.append(item)\n exec_result[\"result\"] = final_result\n if \"src\" in exec_result.keys():\n exec_result.pop(\"src\")\n return {\"status\":\"success\",\"result\":exec_result}\n else:\n return {\"status\":\"failure\",\"msg\":result[\"status\"][\"msg\"]}\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n return {\"status\": \"failure\", \"msg\": str(e)}\n finally:\n context.end_span()\n\n\ndef execute_custom_rules(request):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n if request.method == \"POST\":\n payload = json.loads(request.body.decode())\n payload[\"solution_id\"] = common.get_solution_from_session(request)\n rules = RuleManager()\n exec_result = rules.process(\"executeCustomCode\",payload)\n if exec_result[\"status\"][\"success\"]:\n output = exec_result[\"metadata\"][\"result\"]\n return {\"status\":\"success\",\"result\":output}\n else:\n return {\"status\": \"failure\",\"msg\":exec_result[\"msg\"]}\n # TODO raise specific exception\n except Exception as e:\n return {\"status\":\"failure\",\"error\":str(e),\"msg\":\"Internal Error occurred\"}\n finally:\n context.end_span()\n\n\ndef format_source_data(rule):\n source_dict = {}\n for action in rule['actions']:\n assign_variables = action[\"attr\"][\"rval\"]\n if action[\"op\"] == \"split\":\n for attribute in assign_variables.values():\n attribute_dict = format_hierarchy_rules(attribute)\n source_dict = add_attribute_dict(attribute_dict, source_dict)\n else:\n source_dict.update(format_hierarchy_rules(assign_variables))\n return source_dict\n\n\ndef format_hierarchy_rules(attr):\n attribute_list = attr.split('.')\n attribute_dict = {}\n first_rec = True\n for rec in reversed(attribute_list):\n if first_rec:\n attribute_dict[rec] = \"\"\n first_rec = False\n else:\n attribute_dict = {}\n attribute_dict[rec] = previous_dict\n previous_dict = attribute_dict\n return attribute_dict\n\n\ndef add_attribute_dict(attribute,source):\n attribute_key = next(iter(attribute))\n source_key = [key for key in source.keys()]\n if attribute_key in source_key:\n add_attribute_dict(attribute[attribute_key],source[attribute_key])\n else:\n source[attribute_key] = attribute[attribute_key]\n return source\n\ndef reformat_attribute_dict(data, attribute=\"\", attribute_list=[]):\n\n if isinstance(data, dict):\n for k in data:\n reformat_attribute_dict(data[k], attribute + '.' + k if attribute else k, attribute_list)\n else:\n attribute_list.append({attribute:data})\n\n return attribute_list\n\n\n\ndef process_custom_rules(request,type):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n solution_id = common.get_solution_from_session(request)\n if request.method == \"GET\":\n return(get_custom_rules(solution_id,type))\n elif request.method == \"POST\":\n data = json.loads(request.body.decode())\n response = update_custom_rule(solution_id,data)\n if response[\"status\"] == \"success\":\n return {\"status\": \"success\", \"msg\":\"Custom rule added Successfully\"}\n else:\n return response\n elif request.method == \"DELETE\":\n data = json.loads(request.body.decode())\n response = delete_custom_rule(solution_id, data)\n if response[\"status\"] == \"success\":\n return {\"status\": \"success\", \"msg\":\"Custom rule deleted Successfully\"}\n else:\n return response\n\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n return {\"status\": \"failure\", \"msg\": str(e)}\n finally:\n context.end_span()\n\n\ndef update_custom_rule(solution_id,data):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n rules = RuleManager()\n data[\"solution_id\"] = solution_id\n result = rules.process(\"saveCustomRule\",data)\n status = result[\"status\"]\n if status[\"success\"]:\n response = {\"status\":\"success\"}\n else:\n response = {\"status\":\"failure\",\"msg\":status[\"msg\"]}\n # TODO raise specific exception\n except Exception as e:\n response = {\"status\": \"failure\",\"msg\":str(e)}\n context.end_span()\n return response\n\n\ndef get_custom_rules(solution_id,type):\n context = tracer.get_context(request_id=str(uuid4()), log_level=\"INFO\")\n context.start_span(component=__name__)\n try:\n data = {\"solution_id\" : solution_id,\"type\":type}\n rules = RuleManager()\n result = rules.process(\"getCustomRules\",data)\n if result and result[\"status\"][\"success\"]:\n rules = result[\"metadata\"][\"rules\"]\n return {\"status\":\"success\",\"custom_rules\":rules}\n else:\n return {\"status\": \"success\",\"msg\":\"error while retrieving custom rules\"}\n # TODO raise specific exception\n except Exception as e:\n context.log(message=str(e), obj={\"tb\": traceback.format_exc()})\n return {\"status\":\"failure\",\"msg\":str(e)}\n finally:\n context.end_span()\n\n\ndef delete_custom_rule(solution_id,data):\n try:\n data[\"solution_id\"] = solution_id\n rules = RuleManager()\n result = rules.process(\"deleteCustomRules\",data)\n status = result[\"status\"]\n if status[\"success\"]:\n response = {\"status\":\"success\"}\n else:\n response = {\"status\":\"failure\",\"msg\":status[\"msg\"]}\n except Exception as e:\n response = {\"status\": \"failure\",\"msg\":str(e)}\n return response","sub_path":"services/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":18342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"347340870","text":"import weakref\n\n\nclass Card:\n pool = weakref.WeakValueDictionary()\n\n def __new__(cls, value, suit):\n obj = cls.pool.get(value + suit)\n if obj is None:\n obj = super().__new__(cls)\n obj.value, obj.suit = value, suit\n cls.pool[value + suit] = obj\n\n return obj\n\n def __repr__(self):\n return ''.format(self.value, self.suit)\n\n\ndef run():\n c1 = Card('1', 't')\n c2 = Card('1', 't')\n c3 = Card('2', 'j')\n\n print(len(Card.pool)) # 2\n del c1\n print(len(Card.pool)) # 2\n del c2\n print(len(Card.pool)) # 1\n del c3\n print(len(Card.pool)) # 0\n\n\nclass CommonPool(type):\n def __new__(mcs, name, bases, attrs):\n attrs['pool'] = weakref.WeakValueDictionary() # 创建的class具备pool\n return super().__new__(mcs, name, bases, attrs)\n\n @staticmethod\n def _serialize_param(cls, *args, **kwargs):\n args_list = list(map(str, args))\n args_list.extend([str(kwargs), cls.__name__])\n key = ''.join(args_list)\n return key\n\n def __call__(cls, *args, **kwargs):\n key = CommonPool._serialize_param(cls, *args, **kwargs)\n obj = cls.pool.get(key)\n\n if obj is None:\n obj = super().__call__() # super class is type, that can return object of class\n cls.pool[key] = obj\n return obj\n\n\nclass CommonCard(object, metaclass=CommonPool):\n def __call__(self, *args, **kwargs):\n print('CommonCard call')\n\n\ndef run_common_card():\n c1 = CommonCard(1, 2, h=1)\n c1()\n\n c2 = CommonCard(1, 2, h=1)\n c3 = CommonCard(3, 4, w=1)\n\n print(c1 == c2, c1 is c2)\n print(c2 != c3, c2 is not c3)\n\n print(len(CommonCard.pool)) # 2\n\n\ndef main():\n run()\n\n print('*' * 40)\n\n run_common_card()\n\n print('*' * 40)\n\n\ndef test():\n a = list(map(str, (1, 2, 3)))\n print(a)\n\n a = str({'a': 1, 'b': 2})\n print(a)\n\n a = str((1, 2, 3))\n print(a)\n\n\nif __name__ == '__main__':\n main()\n test()\n","sub_path":"pattern/structural/flyweight.py","file_name":"flyweight.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"357812011","text":"__author__ = 'Jan Voigt'\r\n\r\nimport numpy as np\r\nimport csv as csv\r\nfrom pylab import *\r\n#from operator import add\r\nimport matplotlib.pyplot as plt\r\n\r\nx1List = [] # ln(c)\r\ny1List = [] # EMK Dotierseite\r\n\r\nf = open(\"EMK_dotierseite_ln(c)_alle.txt\")\r\n\r\nfor line in f:\r\n line = line.rstrip()\r\n parts = line.split()\r\n x1List.append(float(parts[0]))\r\n y1List.append(float(parts[1]))\r\n\r\nx2List = [] # ln(c)\r\ny2List = [] # EMK_Messseite\r\n\r\ng = open(\"EMK_Messseite_ln(c)_alle.txt\")\r\n\r\nfor line in g:\r\n line = line.rstrip()\r\n parts = line.split()\r\n x2List.append(float(parts[0]))\r\n y2List.append(float(parts[1]))\r\n\r\ndef generate_offset(off,list):\r\n offset_list= []\r\n for i in range(0,len(list),1):\r\n offset_list.append(list[i]+off)\r\n return offset_list\r\n\r\ndef geraden_gl(list):\r\n offset_list= []\r\n for i in range(0,len(list),1):\r\n offset_list.append(list[i]*46-9.8)\r\n return offset_list\r\n\r\nx3List = [-0.05,-0.04,-0.03,-0.02,-0.01,0.0,0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09]\r\ny3List = geraden_gl(x3List)\r\n\r\n#plt.plot(radius, area, label='Circle')\r\nplt.plot(x3List, y3List, linestyle='-', color='g', linewidth=2.0, label='Fit der $alpha$-Phase')\r\nplt.plot(x2List, y2List, 'ro', label='Mess-Seite')\r\nplt.plot(x1List, y1List, 'bs', label='Dotier-Seite')\r\nplt.xlabel('ln(c)')\r\nplt.ylabel('Emk in mV')\r\n#plt.title('$C_p$ von Tantal im ges. Temperaturbereich')\r\nplt.legend(loc=\"best\")\r\nplt.show()\r\n","sub_path":"legacy/emklnc.py","file_name":"emklnc.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"170829916","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('author/', views.getauthor, name='author'),\n path('article/', views.getsingle, name=\"single_post\"),\n path('login/', views.user_login, name='user_login'),\n path('success', views.success, name='user_success'),\n path('logout', views.user_logout, name='user_logout'),\n path('signup', views.signup, name='signup'),\n path('create', views.create, name='create'),\n]","sub_path":"djangoblog/blogapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"373517980","text":"from string import ascii_lowercase as letters\nfrom math import factorial\nimport re\n\ninfile = open('B-large.in')\noutfile = open('output.txt', mode='w')\n\n\ndef read_int_list() -> [int]:\n \"\"\"\n :rtype : [int]\n \"\"\"\n return list(map(int, infile.readline().split()))\n\n\ndef read_int() -> int:\n \"\"\"\n :rtype : int\n \"\"\"\n return int(infile.readline())\n\n\nfor c in range(read_int()):\n N = read_int()\n line = infile.readline()\n words = line.strip().split()\n ans = 1\n full = {}\n lefts = set()\n rights = set()\n inner = set()\n for i in range(len(words)):\n word = words[i]\n left = word[0]\n right = word[-1]\n match = re.match(left+\"+(.*?)\"+right+\"*$\", word)\n word_inner = match.group(1)\n if word_inner:\n already = set()\n current = \"\"\n for letter in word_inner:\n if letter != current:\n current = letter\n if letter in already:\n ans = 0\n break\n already.add(letter)\n word_inner = set(word_inner)\n if word_inner & inner:\n ans = 0\n break\n inner |= word_inner\n\n if left == right:\n if word_inner:\n ans = 0\n break\n full[left] = full.get(left, 0) + 1\n\n if left != right:\n if left in lefts or right in rights:\n ans = 0\n break\n lefts.add(left)\n rights.add(right)\n if lefts==rights:\n print(line)\n print(c+1)\n if lefts == rights and lefts or inner & lefts or inner & rights or inner & set(full.keys()):\n ans = 0\n if ans != 0:\n free = len(words)\n for letter in letters:\n if letter in lefts and letter in rights:\n free -= 1\n for letter in full:\n ans *= factorial(full[letter])\n ans = ans % 1000000007\n free -= full[letter]\n if not (letter in lefts or letter in rights):\n free += 1\n ans *= factorial(free)\n ans = ans % 1000000007\n print(full, free)\n\n print(\"Case #%i: %s\" % (c + 1, ans), file=outfile)\n\ninfile.close()\noutfile.close()\n","sub_path":"solutions_5669245564223488_1/Python/alexmojaki/jam.py","file_name":"jam.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"272349622","text":"from flask import Flask, request\nfrom flask import jsonify\nfrom flask_pymongo import PyMongo\nfrom flask_cors import CORS\nfrom config import config\n\nimport uuid\n\napp = Flask(__name__)\nCORS(app)\n\n# connect to MongoDB\napp.config[\"MONGO_URI\"] = config[\"URI_DB\"]\nmongodb_client = PyMongo(app)\ndb = mongodb_client.db\n\n#service 1\n@app.route(\"/auth/login\", methods=[\"POST\"])\ndef login():\n #get request data\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n\n #validate data (exists? y/n)\n user = db.users.find_one({\"username\": username})\n if not user:\n return jsonify({\n \"status\": \"warning\",\n \"message\": \"Usuario no encontrado\"\n })\n \n if user[\"password\"] == password:\n response = {\n \"status\": \"OK\",\n \"username\": user[\"username\"],\n \"name\": user[\"name\"],\n \"last_name\": user[\"last_name\"],\n \"email\": user[\"email\"]\n }\n else:\n response = {\n \"status\": \"warning\",\n \"message\": \"Los datos ingresados son incorrectos\"\n }\n return jsonify(response)\n\n@app.route(\"/user\", methods=[\"POST\"])\ndef create_user():\n #get request data\n data_user = request.get_json()\n\n #uuid\n uuid_number = uuid.uuid1()\n\n # complement user data\n data_user[\"uuid\"] = str(uuid_number)\n data_user[\"status\"] = \"ACTIVE\"\n\n #save user data\n user = db.users.insert(data_user)\n\n if user:\n response = {\n \"name\": data_user[\"name\"],\n \"last_name\": data_user[\"last_name\"],\n \"phone_number\": data_user[\"phone_number\"],\n \"email\": data_user[\"phone_number\"],\n \"uuid\": data_user[\"uuid\"],\n \"status\": data_user[\"status\"]\n }\n else:\n response = {\n \"status\": \"error\",\n \"message\": \"No se ha podido guardar los datos.\"\n }\n return jsonify(response)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"410272710","text":"import requests\nimport praw\nimport time\n\ngfycat_api = 'https://api.gfycat.com/v1/gfycats/'\n\nreddit = praw.Reddit(client_id='',\n client_secret='',\n password='',\n user_agent='gfycat by /u/DevouringOne and /u/jadenx2',\n username='NBA_MOD')\n\nsubreddit = reddit.subreddit('nba_mods')\n\nfor submission in subreddit.stream.submissions(skip_existing=True):\n if 'streamable' in submission.url:\n title = submission.title\n\n data = {'fetchUrl': submission.url, 'title': title}\n response = requests.post(gfycat_api, data=str(data).encode('utf-8')) # This line is where the gfycat is created\n\n gfyname = response.json()['gfyname']\n\n is_ready = requests.get(gfycat_api + gfyname)\n\n while is_ready.status_code is not 200:\n time.sleep(15)\n is_ready = requests.get(gfycat_api + gfyname)\n print(\"Trying again... response code: {}\".format(is_ready.status_code))\n\n print(\"Response code: {} - gfycat mirror is ready\".format(is_ready.status_code))\n\n reply = \"Here is a [Gfycat mirror of this Streamable link](https://gfycat.com/{0})\".format(gfyname)\n\n for comment in submission.comments:\n if comment.stickied and comment.author == 'NBA_MOD':\n mirror = comment.reply(reply)\n mirror.mod.distinguish()\n print(\"Mirror posted\")\n","sub_path":"reddit-nba-bot/gfycat_bot.py","file_name":"gfycat_bot.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"588210994","text":"\"\"\"Test Axis event stream.\n\npytest --cov-report term-missing --cov=axis.event_stream tests/test_event_stream.py\n\"\"\"\n\nimport pytest\nfrom unittest.mock import Mock\n\nfrom axis.event_stream import EventManager\n\nfrom .event_fixtures import (\n FIRST_MESSAGE,\n AUDIO_INIT,\n DAYNIGHT_INIT,\n FENCE_GUARD_INIT,\n GLOBAL_SCENE_CHANGE,\n LIGHT_STATUS_INIT,\n LOITERING_GUARD_INIT,\n MOTION_GUARD_INIT,\n OBJECT_ANALYTICS_INIT,\n PIR_INIT,\n PIR_CHANGE,\n PORT_0_INIT,\n PORT_ANY_INIT,\n PTZ_MOVE_INIT,\n PTZ_MOVE_START,\n PTZ_MOVE_END,\n PTZ_PRESET_INIT_1,\n PTZ_PRESET_INIT_2,\n PTZ_PRESET_INIT_3,\n PTZ_PRESET_AT_1_TRUE,\n PTZ_PRESET_AT_1_FALSE,\n PTZ_PRESET_AT_2_TRUE,\n PTZ_PRESET_AT_2_FALSE,\n PTZ_PRESET_AT_3_TRUE,\n PTZ_PRESET_AT_3_FALSE,\n RELAY_INIT,\n RULE_ENGINE_REGION_DETECTOR_INIT,\n STORAGE_ALERT_INIT,\n VMD3_INIT,\n VMD4_ANY_INIT,\n VMD4_ANY_CHANGE,\n)\n\n\n@pytest.fixture\ndef event_manager(axis_device) -> EventManager:\n \"\"\"Returns mocked event manager.\"\"\"\n axis_device.enable_events(Mock())\n return axis_device.event\n\n\n@pytest.mark.parametrize(\n \"input,expected\",\n [\n (FIRST_MESSAGE, {}),\n (\n PIR_INIT,\n {\n \"operation\": \"Initialized\",\n \"topic\": \"tns1:Device/tnsaxis:Sensor/PIR\",\n \"source\": \"sensor\",\n \"source_idx\": \"0\",\n \"type\": \"state\",\n \"value\": \"0\",\n },\n ),\n (\n PIR_CHANGE,\n {\n \"operation\": \"Changed\",\n \"topic\": \"tns1:Device/tnsaxis:Sensor/PIR\",\n \"source\": \"sensor\",\n \"source_idx\": \"0\",\n \"type\": \"state\",\n \"value\": \"1\",\n },\n ),\n (\n RULE_ENGINE_REGION_DETECTOR_INIT,\n {\n \"operation\": \"Initialized\",\n \"source\": \"VideoSource\",\n \"source_idx\": \"0\",\n \"topic\": \"tns1:RuleEngine/MotionRegionDetector/Motion\",\n \"type\": \"State\",\n \"value\": \"0\",\n },\n ),\n (\n STORAGE_ALERT_INIT,\n {\n \"operation\": \"Initialized\",\n \"source\": \"disk_id\",\n \"source_idx\": \"NetworkShare\",\n \"topic\": \"tnsaxis:Storage/Alert\",\n \"type\": \"overall_health\",\n \"value\": \"-3\",\n },\n ),\n (\n VMD4_ANY_INIT,\n {\n \"operation\": \"Initialized\",\n \"topic\": \"tnsaxis:CameraApplicationPlatform/VMD/Camera1ProfileANY\",\n \"type\": \"active\",\n \"value\": \"0\",\n },\n ),\n (\n VMD4_ANY_CHANGE,\n {\n \"operation\": \"Changed\",\n \"topic\": \"tnsaxis:CameraApplicationPlatform/VMD/Camera1ProfileANY\",\n \"type\": \"active\",\n \"value\": \"1\",\n },\n ),\n ],\n)\ndef test_parse_event_xml(event_manager, input: bytes, expected: dict):\n \"\"\"Verify that first message doesn't do anything.\"\"\"\n assert event_manager.parse_event_xml(input) == expected\n\n\n@pytest.mark.parametrize(\n \"input,expected\",\n [\n (\n AUDIO_INIT,\n {\n \"topic\": \"tns1:AudioSource/tnsaxis:TriggerLevel\",\n \"source\": \"channel\",\n \"source_idx\": \"1\",\n \"class\": \"sound\",\n \"type\": \"Sound\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n (\n DAYNIGHT_INIT,\n {\n \"topic\": \"tns1:VideoSource/tnsaxis:DayNightVision\",\n \"source\": \"VideoSourceConfigurationToken\",\n \"source_idx\": \"1\",\n \"class\": \"light\",\n \"type\": \"DayNight\",\n \"state\": \"1\",\n \"tripped\": True,\n },\n ),\n (\n FENCE_GUARD_INIT,\n {\n \"topic\": \"tnsaxis:CameraApplicationPlatform/FenceGuard/Camera1Profile1\",\n \"source\": \"\",\n \"source_idx\": \"Camera1Profile1\",\n \"class\": \"motion\",\n \"type\": \"Fence Guard\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n (\n LIGHT_STATUS_INIT,\n {\n \"topic\": \"tns1:Device/tnsaxis:Light/Status\",\n \"source\": \"id\",\n \"source_idx\": \"0\",\n \"class\": \"light\",\n \"type\": \"Light\",\n \"state\": \"OFF\",\n \"tripped\": False,\n },\n ),\n (\n LOITERING_GUARD_INIT,\n {\n \"topic\": \"tnsaxis:CameraApplicationPlatform/LoiteringGuard/Camera1Profile1\",\n \"source\": \"\",\n \"source_idx\": \"Camera1Profile1\",\n \"class\": \"motion\",\n \"type\": \"Loitering Guard\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n (\n MOTION_GUARD_INIT,\n {\n \"topic\": \"tnsaxis:CameraApplicationPlatform/MotionGuard/Camera1ProfileANY\",\n \"source\": \"\",\n \"source_idx\": \"Camera1ProfileANY\",\n \"class\": \"motion\",\n \"type\": \"Motion Guard\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n (\n OBJECT_ANALYTICS_INIT,\n {\n \"topic\": \"tnsaxis:CameraApplicationPlatform/ObjectAnalytics/Device1Scenario1\",\n \"source\": \"\",\n \"source_idx\": \"Device1Scenario1\",\n \"class\": \"motion\",\n \"type\": \"Object Analytics\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n (\n PIR_INIT,\n {\n \"topic\": \"tns1:Device/tnsaxis:Sensor/PIR\",\n \"source\": \"sensor\",\n \"source_idx\": \"0\",\n \"class\": \"motion\",\n \"type\": \"PIR\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n (\n PORT_0_INIT,\n {\n \"topic\": \"tns1:Device/tnsaxis:IO/Port\",\n \"source\": \"port\",\n \"source_idx\": \"1\",\n \"class\": \"input\",\n \"type\": \"Input\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n (\n PORT_ANY_INIT,\n {\n \"topic\": \"tns1:Device/tnsaxis:IO/Port\",\n \"source\": \"port\",\n \"source_idx\": \"\",\n \"class\": \"input\",\n \"type\": \"Input\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n (\n PTZ_MOVE_INIT,\n {\n \"topic\": \"tns1:PTZController/tnsaxis:Move/Channel_1\",\n \"source\": \"PTZConfigurationToken\",\n \"source_idx\": \"1\",\n \"class\": \"ptz\",\n \"type\": \"is_moving\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n (\n PTZ_PRESET_INIT_1,\n {\n \"topic\": \"tns1:PTZController/tnsaxis:PTZPresets/Channel_1\",\n \"source\": \"PresetToken\",\n \"source_idx\": \"1\",\n \"class\": \"ptz\",\n \"type\": \"on_preset\",\n \"state\": \"1\",\n \"tripped\": True,\n },\n ),\n (\n RELAY_INIT,\n {\n \"topic\": \"tns1:Device/Trigger/Relay\",\n \"source\": \"RelayToken\",\n \"source_idx\": \"3\",\n \"class\": \"output\",\n \"type\": \"Relay\",\n \"state\": \"inactive\",\n \"tripped\": False,\n },\n ),\n (\n VMD3_INIT,\n {\n \"topic\": \"tns1:RuleEngine/tnsaxis:VMD3/vmd3_video_1\",\n \"source\": \"areaid\",\n \"source_idx\": \"0\",\n \"class\": \"motion\",\n \"type\": \"VMD3\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n (\n VMD4_ANY_INIT,\n {\n \"topic\": \"tnsaxis:CameraApplicationPlatform/VMD/Camera1ProfileANY\",\n \"source\": \"\",\n \"source_idx\": \"Camera1ProfileANY\",\n \"class\": \"motion\",\n \"type\": \"VMD4\",\n \"state\": \"0\",\n \"tripped\": False,\n },\n ),\n ],\n)\ndef test_create_event(event_manager, input: bytes, expected: tuple):\n \"\"\"Verify that a new audio event can be managed.\"\"\"\n event_manager.update(input)\n\n event = next(iter(event_manager.values()))\n assert event.topic == expected[\"topic\"]\n assert event.source == expected[\"source\"]\n assert event.id == expected[\"source_idx\"]\n assert event.CLASS == expected[\"class\"]\n assert event.TYPE == expected[\"type\"]\n assert event.state == expected[\"state\"]\n if event.BINARY:\n assert event.is_tripped is expected[\"tripped\"]\n\n\n@pytest.mark.parametrize(\"input\", [[], [{\"operation\": \"unsupported\"}, {}]])\ndef test_do_not_create_event(event_manager, input: list):\n \"\"\"Verify the different controls in pre_processed_raw.\"\"\"\n event_manager.update(input)\n assert len(event_manager.values()) == 0\n\n\ndef test_vmd4_change(event_manager):\n \"\"\"Verify that a VMD4 event change can be managed.\"\"\"\n event_manager.update(VMD4_ANY_INIT)\n event_manager.update(VMD4_ANY_CHANGE)\n\n event = next(iter(event_manager.values()))\n assert event.state == \"1\"\n\n\ndef test_pir_init(event_manager):\n \"\"\"Verify that a new PIR event can be managed.\"\"\"\n event_manager.update(PIR_INIT)\n assert event_manager.values()\n\n event = next(iter(event_manager.values()))\n assert event.state == \"0\"\n assert not event.is_tripped\n\n mock_callback = Mock()\n event.register_callback(mock_callback)\n assert event.observers\n\n event_manager.update(PIR_CHANGE)\n assert event.state == \"1\"\n assert event.is_tripped\n assert mock_callback.called\n\n event.remove_callback(mock_callback)\n assert not event.observers\n\n\ndef test_ptz_preset(event_manager):\n \"\"\"Verify that a new PTZ preset event can be managed.\"\"\"\n event_manager.update(PTZ_PRESET_INIT_1)\n event_manager.update(PTZ_PRESET_INIT_2)\n event_manager.update(PTZ_PRESET_INIT_3)\n\n events = iter(event_manager.values())\n\n event_1 = next(events)\n assert event_1.topic == \"tns1:PTZController/tnsaxis:PTZPresets/Channel_1\"\n assert event_1.source == \"PresetToken\"\n assert event_1.id == \"1\"\n assert event_1.CLASS == \"ptz\"\n assert event_1.TYPE == \"on_preset\"\n assert event_1.state == \"1\"\n\n event_2 = next(events)\n assert event_2.id == \"2\"\n assert event_2.state == \"0\"\n\n event_3 = next(events)\n assert event_3.id == \"3\"\n assert event_3.state == \"0\"\n\n for event in (event_1, event_2, event_3):\n mock_callback = Mock()\n event.register_callback(mock_callback)\n\n event_manager.update(PTZ_PRESET_AT_1_FALSE)\n assert event_1.state == \"0\"\n assert not event_1.is_tripped\n assert event_2.state == \"0\"\n assert not event_2.is_tripped\n assert event_3.state == \"0\"\n assert not event_3.is_tripped\n\n event_manager.update(PTZ_PRESET_AT_2_TRUE)\n assert event_1.state == \"0\"\n assert not event_1.is_tripped\n assert event_2.state == \"1\"\n assert event_2.is_tripped\n assert event_3.state == \"0\"\n assert not event_3.is_tripped\n\n event_manager.update(PTZ_PRESET_AT_2_FALSE)\n assert event_1.state == \"0\"\n assert not event_1.is_tripped\n assert event_2.state == \"0\"\n assert not event_2.is_tripped\n assert event_3.state == \"0\"\n assert not event_3.is_tripped\n\n event_manager.update(PTZ_PRESET_AT_3_TRUE)\n assert event_1.state == \"0\"\n assert not event_1.is_tripped\n assert event_2.state == \"0\"\n assert not event_2.is_tripped\n assert event_3.state == \"1\"\n assert event_3.is_tripped\n\n event_manager.update(PTZ_PRESET_AT_3_FALSE)\n assert event_1.state == \"0\"\n assert not event_1.is_tripped\n assert event_2.state == \"0\"\n assert not event_2.is_tripped\n assert event_3.state == \"0\"\n assert not event_3.is_tripped\n\n event_manager.update(PTZ_PRESET_AT_1_TRUE)\n assert event_1.state == \"1\"\n assert event_1.is_tripped\n assert event_2.state == \"0\"\n assert not event_2.is_tripped\n assert event_3.state == \"0\"\n assert not event_3.is_tripped\n\n\ndef test_ptz_move(event_manager):\n \"\"\"Verify that a new PTZ move event can be managed.\"\"\"\n event_manager.update(PTZ_MOVE_INIT)\n\n event = next(iter(event_manager.values()))\n assert event.topic == \"tns1:PTZController/tnsaxis:Move/Channel_1\"\n assert event.source == \"PTZConfigurationToken\"\n assert event.id == \"1\"\n assert event.CLASS == \"ptz\"\n assert event.TYPE == \"is_moving\"\n assert event.state == \"0\"\n\n mock_callback = Mock()\n event.register_callback(mock_callback)\n\n event_manager.update(PTZ_MOVE_START)\n assert event.state == \"1\"\n assert event.is_tripped\n assert mock_callback.called\n\n event_manager.update(PTZ_MOVE_END)\n assert event.state == \"0\"\n assert not event.is_tripped\n assert mock_callback.called\n\n event.remove_callback(mock_callback)\n assert not event.observers\n\n\ndef test_unsupported_event(event_manager):\n \"\"\"Verify that unsupported events aren't created.\"\"\"\n event_manager.signal = Mock()\n event_manager.update(GLOBAL_SCENE_CHANGE)\n event_manager.signal.assert_not_called()\n\n event = next(iter(event_manager.values()))\n assert event.BINARY is False\n assert not event.TOPIC\n assert not event.CLASS\n assert not event.TYPE\n assert event.topic == \"tns1:VideoSource/GlobalSceneChange/ImagingService\"\n assert event.source == \"Source\"\n assert event.id == \"0\"\n assert event.state == \"0\"\n\n\ndef test_initialize_event_already_exist(event_manager):\n \"\"\"Verify that initialize with an already existing event doesn't create.\"\"\"\n event_manager.signal = Mock()\n event_manager.update(VMD4_ANY_INIT)\n assert len(event_manager.values()) == 1\n event_manager.signal.assert_called_once()\n\n event_manager.update(VMD4_ANY_INIT)\n assert len(event_manager.values()) == 1\n event_manager.signal.assert_called_once()\n","sub_path":"tests/test_event_stream.py","file_name":"test_event_stream.py","file_ext":"py","file_size_in_byte":14506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"170103916","text":"import numba\n\n@numba.jit(nopython=True)\ndef dist(x, y):\n \"\"\"Calculate the distance\"\"\"\n dist = 0\n for i in range(len(x)):\n dist += (x[i] - y[i]) ** 2\n return dist\n\n@numba.jit(nopython=True)\ndef find_labels(points, centers):\n \"\"\"Assign points to a cluster.\"\"\"\n labels = []\n min_dist = np.inf\n min_label = 0\n for i in range(len(points)):\n for j in range(len(centers)):\n distance = dist(points[i], centers[j])\n if distance < min_dist:\n min_dist, min_label = distance, j\n labels.append(min_label)\n return labels\n\n\ndef compute_centers(points, labels):\n \"\"\"Calculate the cluster centres.\"\"\"\n n_centers = len(set(labels))\n n_dims = len(points[0])\n\n centers = [[0 for i in range(n_dims)] for j in range(n_centers)]\n counts = [0 for j in range(n_centers)]\n\n for label, point in zip(labels, points):\n counts[label] += 1\n centers[label] = [a + b for a, b in zip(centers[label], point)]\n\n return [[x / count for x in center] for center, count in zip(centers, counts)]\n\n\ndef kmeans(points, n_clusters):\n \"\"\"Calculates the cluster centres repeatedly until nothing changes.\"\"\"\n centers = points[-n_clusters:].tolist()\n while True:\n old_centers = centers\n labels = find_labels(points, centers)\n centers = compute_centers(points, labels)\n if centers == old_centers:\n break\n return labels\n","sub_path":"docs/performance/nb_kmeans.py","file_name":"nb_kmeans.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"599636290","text":"import uuid\nimport datetime\n\nfrom flask import request, jsonify\nfrom flask_restplus import Resource\nfrom marshmallow import Schema, fields\nimport bcrypt\nfrom app.api import user_ns\n\nfrom app.utils.required_params import required_params\nfrom app.handler.user import UserHandler\nfrom app.handler.session import SessionHandler\n\n\n\nclass UserCreateApiSchema(Schema):\n\n user_id = fields.Str(required=True)\n password = fields.Str(required=True)\n\n@user_ns.route('')\nclass CreateUser(Resource):\n @required_params(UserCreateApiSchema())\n def post(self):\n try:\n user_handler = UserHandler()\n\n params = dict()\n\n params['user_id'] = request.get_json().get('user_id')\n params['password'] = bcrypt.hashpw(request.get_json().get('password').encode('utf-8'), bcrypt.gensalt()).decode('utf-8')\n\n user_info = user_handler.read_filter(filter_col={'user_id': params['user_id'], 'deleted': False})\n # 중복 체크\n if user_info is not None:\n return {'message': 'exists Account'}, 409\n else:\n params['user_uuid'] = str(uuid.uuid4())\n user_handler.create(params)\n except Exception as e:\n return {'message': 'fail'}, 500\n else:\n return {'message': 'create user success', 'data': {'user_uuid': params['user_uuid']}}, 200\n\n\nclass UserDeleteApiSchema(Schema):\n\n session_id = fields.Str(required=True)\n\n\n@user_ns.route('')\nclass DeleteUser(Resource):\n @required_params(UserDeleteApiSchema())\n def delete(self):\n try:\n session_handler = SessionHandler()\n user_handler = UserHandler()\n\n session_id = request.get_json().get('session_id')\n\n session_info = session_handler.read_filter(filter_col={'session_id': session_id})\n\n if session_info is not None:\n if session_info.logout_time is None:\n if session_info.relation_user.deleted is False:\n date = datetime.datetime.now()\n # 세션 로그아웃 처리\n session_handler.update(session_id, date)\n user_handler.update_user_status(session_info.relation_user.user_id, date)\n else:\n return {'message': 'already deleted'}, 409\n else:\n return {'message': 'session expired'}, 401\n else:\n return {'message': 'not exists session'}, 404\n\n except Exception as e:\n return {'message': 'fail'}, 500\n else:\n return {'message': 'delete user success'}, 200\n\n\n@user_ns.route('/')\nclass GetUser(Resource):\n def get(self, user_uuid):\n\n try:\n session_handler = SessionHandler()\n user_handler = UserHandler()\n\n session_list = list()\n result = dict()\n\n session_info = session_handler.read_all_filter(filter_col={'user_uuid': user_uuid})\n user_info = user_handler.read_filter(filter_col={'id': user_uuid})\n\n if user_info is None:\n return {'message': 'not exists account'}, 404\n else:\n for row in session_info:\n s_dict = dict()\n s_dict['session_id'] = row.session_id\n s_dict['create_time'] = str(row.create_time.strftime(\"%Y-%m-%d-%H:%M:%S\"))\n s_dict['logout_time'] = None if row.logout_time is None else str(row.logout_time.strftime(\"%Y-%m-%d-%H:%M:%S\"))\n session_list.append(s_dict)\n\n result['session_list'] = session_list\n\n result['user_info'] = dict()\n\n result['user_info']['user_uuid'] = user_info.id\n result['user_info']['user_id'] = user_info.user_id\n result['user_info']['create_time'] = str(user_info.create_time.strftime(\"%Y-%m-%d-%H:%M:%S\"))\n if user_info.deleted is True:\n result['user_info']['deleted_time'] = str(user_info.deleted_time.strftime(\"%Y-%m-%d-%H:%M:%S\"))\n\n except Exception as e:\n return {'message': 'fail'}, 500\n else:\n return {'message': 'success', 'data': result}, 200\n\n\n","sub_path":"app/api/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"394844595","text":"\nfrom collections import Counter\n\ndata = [x.rstrip() for x in open(\"input.txt\").readlines()]\nsums = [0, 0]\n\nfor i in data:\n a = [j for i, j in Counter(i).most_common()]\n if 2 in a:\n sums[0] += 1\n if 3 in a:\n sums[1] += 1\n\nprint(sums[0] * sums[1])\n\nfor i in data:\n for j in data:\n diffs = 0\n for indx, char in enumerate(i):\n if char != j[indx]:\n diffs += 1\n if diffs == 1:\n answer = [char for indx, char in enumerate(i) if j[indx] == char]\n print(\"\".join(answer))\n break\n","sub_path":"python/day2/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"268459529","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom product_list import ProductList\nclass ProductScreen:\n\tdef click_ok(self):\n\t\tmessage_box = QMessageBox()\n\t\ttypedName = self.txtName.text().strip()\n\t\ttypedYear = self.txtYear.text().strip()\n\t\tif len(typedName)==0 or len(typedYear) == 0:\n\t\t\tmessage_box.setText('Please input information')\n\t\t\tmessage_box.exec_()\n\t\telse:\n\t\t\tself.dict_product[\"name\"] = typedName\n\t\t\tself.dict_product[\"year\"] = typedYear\n\t\t\tself.products.append(self.dict_product)\n\t\t\tself.txtName.setText('')\n\t\t\tself.txtYear.setText('')\n\t\"\"\"\t\n\tdef __init__(self):\t\t\n\t\tself.window = QWidget()\n\t\tself.window.resize(800, 600)\n\t\tself.window.setWindowTitle('This is Product Screen')\n\n\t\tvbox = QVBoxLayout()\n\t\tvbox.setSpacing(10)\n\n\t\tself.txtName = QLineEdit()\n\t\tself.txtName.setPlaceholderText(\"Enter product's name\")\n\t\tself.txtYear = QLineEdit()\n\t\tself.txtYear.setPlaceholderText('Year')\n\n\t\tvbox.addWidget(self.txtName)\n\t\tvbox.addWidget(self.txtYear)\n\t\t#vbox.addStretch(2)\n\t\tbtn_save = QPushButton(\"Add product\")\n\t\tbtn_save.clicked.connect(self.click_ok)\n\t\tvbox.addWidget(btn_save)\n\n\t\tbtn_show_list = QPushButton(\"Show product List\")\n\t\tvbox.addWidget(btn_show_list)\n\t\tbtn_show_list.clicked.connect(self.btn_show_list)\n\n\t\tself.window.setLayout(vbox)\n\t\tself.window.show()\n\t\tself.products = []\n\t\tself.product_list = None\n\t\"\"\"\n\tdef __init__(self):\t\t\n\t\tself.window = QWidget()\n\t\tself.window.resize(800, 600)\n\t\tself.window.setWindowTitle('This is Product Screen')\n\t\tself.dict_product = {}\n\n\t\tself.gridLayout = QGridLayout()\n\t\tself.gridLayout.setSpacing(10)\n\n\t\tself.gridLayout.addWidget(QLabel(\"Name\"), 0, 0)\n\t\tself.txtName = QLineEdit()\n\t\tself.txtName.setPlaceholderText(\"Enter product's name\")\n\t\tself.gridLayout.addWidget(self.txtName, 0, 1)\n\n\t\tself.gridLayout.addWidget(QLabel(\"Year\"), 1, 0)\n\t\tself.txtYear = QLineEdit()\n\t\tself.txtYear.setPlaceholderText('Year')\n\t\tself.gridLayout.addWidget(self.txtYear, 1, 1)\n\n\t\tself.gridLayout.addWidget(QLabel(\"Status\"), 2, 0)\n\t\tself.comboStatus = QComboBox()\n\t\tself.status = [\"Old\", \"New\"]\n\t\tself.comboStatus.addItems(self.status)\n\t\tself.comboStatus.currentIndexChanged.connect(self.select_status)\n\t\tself.gridLayout.addWidget(self.comboStatus, 2, 1)\n\n\t\t#vbox.addStretch(2)\n\t\tbtn_save = QPushButton(\"Add product\")\n\t\tbtn_save.clicked.connect(self.click_ok)\n\t\tself.gridLayout.addWidget(btn_save, 3, 0)\n\n\t\tbtn_show_list = QPushButton(\"Show product List\")\n\t\tself.gridLayout.addWidget(btn_show_list, 3, 1)\n\t\tbtn_show_list.clicked.connect(self.btn_show_list)\n\n\t\tself.window.setLayout(self.gridLayout)\n\t\tself.window.show()\n\t\tself.products = []\n\t\tself.product_list = None\n\tdef select_status(self, index):\n\t\tself.dict_product['status'] = self.status[index]\n\tdef btn_show_list(self):\n\t\tif self.product_list == None:\n\t\t\tself.product_list = ProductList(self, self.products)","sub_path":"buoiso05/product_screen.py","file_name":"product_screen.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"114813343","text":"\nimport os\nimport multiprocessing as mp\nimport threading\nimport sqlite3\n\nimport global_var\nfrom utils_v2 import ClearIxpAsSet, ClearIxpPfxDict, ClearSibRel, CompressAsPath, CompressAsPathToMin, IsIxpIp, IsIxpAs, GetAsStrOfIpByRv, GetSibRel, GetIxpPfxDict, GetIxpAsSet, \\\n GetPfx2ASByRv, ClearIp2AsDict\nfrom gen_ip2as_command import PreGetSrcFilesInDirs\nfrom get_ip2as_from_bdrmapit import InitBdrCache_2, ConnectToBdrMapItDb_2, ConstrBdrCache_2, CloseBdrMapItDb_2, \\\n GetIp2ASFromBdrMapItDb_2\n\ndef ResolveTraceWartsPerMonth(year, month):\n os.chdir(str(year) + '/' + str(month).zfill(2) + '/')\n for root,dirs,files in os.walk('.'):\n for filename in files: #例:cdg-fr.20180125\n print(filename)\n if filename.endswith('.gz'):\n os.system('gunzip ' + filename)\n os.system('sc_analysis_dump ' + filename[0:-3] + ' > ' + filename[0:-9]) \n\ndef GetLinksFromTrace(trace_list, all_trace_links_set, all_possi_trace_links_set):\n pre_hop = ''\n ixp_flag = False\n for i in range(0, len(trace_list)):\n cur_hop = trace_list[i]\n if cur_hop.__contains__('<'):\n ixp_flag = True\n continue\n if (not pre_hop) or (pre_hop == '*') or (pre_hop == '?') or \\\n (cur_hop == '*') or (cur_hop == '?'): # or (set(pre_hop.split('_')) & set(cur_hop.split('_'))):\n pre_hop = cur_hop\n ixp_flag = False\n continue\n for pre_elem in pre_hop.split('_'):\n for cur_elem in cur_hop.split('_'):\n if pre_elem == cur_elem:\n continue\n link = pre_elem + ' ' + cur_elem\n if link == '3491 58593':\n print(1)\n if link.__contains__('<'):\n print('')\n if ixp_flag:\n all_possi_trace_links_set.add(link)\n else:\n all_trace_links_set.add(link)\n pre_hop = cur_hop\n ixp_flag = False\n return\n\n#bdrmapit_date_cursor_dict = dict()\ndef CheckBdrmapitPerDb(ip, as_str, date, bdrmapit_vote_dict):\n # global bdrmapit_date_cursor_dict\n # if date not in bdrmapit_date_cursor_dict.keys():\n # return None\n # select_sql = \"SELECT asn FROM annotation WHERE addr=\\'%s\\'\" %ip\n # bdrmapit_date_cursor_dict[date].execute(select_sql)\n # result = bdrmapit_date_cursor_dict[date].fetchall() \n # if result:\n # res = str(result[0][0]) \n res = GetIp2ASFromBdrMapItDb_2(date, ip)\n if res:\n if res in as_str.split('_'):\n return res\n if res not in bdrmapit_vote_dict.keys():\n bdrmapit_vote_dict[res] = 0\n bdrmapit_vote_dict[res] += 1\n return None\n\ndef NextDate(date):\n year = int(date[:4])\n month = int(date[4:])\n if year == 2020 and month == 4: #last one\n return None\n if month < 12:\n return str(year) + str(month + 1).zfill(2)\n return str(year + 1) + '01'\n\ndef PrevDate(date):\n year = int(date[:4])\n month = int(date[4:])\n if year == 2018 and month == 1:\n return None\n if month > 1:\n return str(year) + str(month - 1).zfill(2)\n return str(year - 1) + '12'\n\ndef FurtherCheckBdrmapit(ip, as_str, as_bdrmapit, date): \n bdrmapit_vote_dict = dict()\n bdrmapit_vote_dict[as_bdrmapit] = 1\n for cur_date in [date, NextDate(date), PrevDate(date)]:\n if not cur_date:\n continue\n res = CheckBdrmapitPerDb(ip, as_str, date, bdrmapit_vote_dict)\n if res:\n return res\n sorted_list = sorted(bdrmapit_vote_dict.items(), key=lambda d:d[1], reverse = True)\n if sorted_list[0][1] == 1: #no bdrmapit result conform, use bgp-map\n return as_str\n else:\n return sorted_list[0][0]\n\nbgp_ip_as_cache = dict()\ndef GetAsOfIpByBGPAndBdrmapit(ip, dbname):\n global bgp_ip_as_cache\n as_str = ''\n if ip in bgp_ip_as_cache.keys():\n as_str = bgp_ip_as_cache[ip]\n else:\n as_str = GetAsStrOfIpByRv(ip) #moas之间以'_'隔开\n bgp_ip_as_cache[ip] = as_str\n as_bdrmapit = GetIp2ASFromBdrMapItDb_2(dbname, ip)\n if as_bdrmapit != '':\n if as_str:\n if as_bdrmapit not in as_str.split('_'):\n as_str = FurtherCheckBdrmapit(ip, as_str, as_bdrmapit, dbname.split('.')[1][:6])\n else:\n as_str = as_bdrmapit\n return as_str\n\ndef ChgTrace2ASPath_2(trace_file_name, w_filename, all_trace_links_set, all_possi_trace_links_set, all_trace_paths_set): #不将trace分类,考虑IXP,只用ribs map\n ConnectToBdrMapItDb_2(trace_file_name, '../back/bdrmapit_' + trace_file_name + '.db')\n ConstrBdrCache_2(trace_file_name)\n wf = None\n if w_filename:\n #print(w_filename)\n wf = open(w_filename, 'w')\n with open(trace_file_name, 'r') as rf:\n data_list = rf.read().strip('\\n').split('\\n')\n line_num = 0\n for curline in data_list:\n if not curline.startswith('T'):\n continue\n elems = curline.strip('\\n').split('\\t')\n as_path = ''\n for i in range(13, len(elems)):\n curhops = elems[i]\n if curhops.__contains__('q'):\n as_path = as_path + ' *'\n else:\n #curhops: \"210.171.224.41,1.210,1;210.171.224.41,1.216,1\"\n hopelems = curhops.split(';')\n hop_as_list = []\n for elem in hopelems:\n #elem: \"210.171.224.41,1.210,1\"\n temp = elem.split(',')\n #先检查ip是否是ixp的ip\n #temp[0]: \"210.171.224.41\"\n is_ixp_ip = False\n #print(\"temp[0]: %s\" %temp[0])\n if IsIxpIp(temp[0]):\n is_ixp_ip = True #从打印来看挺多的\n #2021.4.26修改\n as_str = GetAsOfIpByBGPAndBdrmapit(temp[0], trace_file_name)\n if as_str:\n for asn in as_str.split('_'):\n if IsIxpAs(asn):\n is_ixp_ip = True\n break\n #if not is_ixp_ip and as_str not in hop_as_list:\n if as_str not in hop_as_list:\n hop_as_list.append(as_str)\n else:\n if '?' not in hop_as_list:\n hop_as_list.append('?')\n if is_ixp_ip:\n hop_as_list = ['<>'] #2021.1.30 做标记,暂时先这样做\n break #有一个ixp ip就记当前位置为ixp ip\n \n if len(hop_as_list) == 0: #2021.1.27这里原来没有这一步,有bug,应该考虑过滤掉IXP后没有ip和AS的情况\n print('NOTE: hop not exist')\n elif len(hop_as_list) == 1:\n # if hop_as_list[0] == '3491_58593':\n # print(curhops)\n # print(curline)\n # print(trace_file_name)\n as_path = as_path + ' ' + hop_as_list[0]\n else:\n as_path = as_path + ' {' + ' '.join(hop_as_list) + '}'\n if wf:\n wf.write(curline + '\\n')\n wf.write(as_path + '\\n')\n else:\n GetLinksFromTrace(CompressAsPathToMin(CompressAsPath(as_path)).split(' '), all_trace_links_set, all_possi_trace_links_set)\n all_trace_paths_set.add(CompressAsPathToMin(CompressAsPath(as_path)))\n line_num += 1 \n if line_num % 100000 == 0:\n print(line_num)\n #wf.close()\n InitBdrCache_2(trace_file_name)\n CloseBdrMapItDb_2(trace_file_name)\n if wf:\n wf.close()\n\ndef ChgTrace2ASPath_2WithPadding(trace_file_name, w_filename, get_link_flag, all_trace_path_set = None, all_trace_links_set = None, all_possi_trace_links_set = None): #不将trace分类,考虑IXP,只用ribs map\n # ConnectToBdrMapItDb_2(trace_file_name, '../back/bdrmapit_' + trace_file_name + '.db') #20210807临时补丁\n # ConstrBdrCache_2(trace_file_name) #20210807临时补丁\n #wf = open(w_filename, 'w')\n with open('back_as_' + trace_file_name, 'r') as rf_back: #20210807临时补丁\n bdrmapit_result_list = rf_back.read().strip('\\n').split('\\n') #20210807临时补丁\n with open(trace_file_name, 'r') as rf:\n data_list = rf.read().strip('\\n').split('\\n')\n line_num = 0\n for curline in data_list:\n if not curline.startswith('T'):\n continue\n bdrmapit_line_list = bdrmapit_result_list[line_num].strip(' ').split(' ') #20210807临时补丁\n elems = curline.strip('\\n').split('\\t')\n as_path = ''\n for i in range(13, len(elems)):\n curhops = elems[i]\n as_bdrmapit = bdrmapit_line_list[i - 13] #20210807临时补丁\n if curhops.__contains__('q'):\n as_path = as_path + ' *'\n else:\n #curhops: \"210.171.224.41,1.210,1;210.171.224.41,1.216,1\"\n hopelems = curhops.split(';')\n hop_as_list = []\n for elem in hopelems:\n #elem: \"210.171.224.41,1.210,1\"\n temp = elem.split(',')\n #先检查ip是否是ixp的ip\n #temp[0]: \"210.171.224.41\"\n is_ixp_ip = False\n #print(\"temp[0]: %s\" %temp[0])\n if IsIxpIp(temp[0]):\n is_ixp_ip = True #从打印来看挺多的\n #2021.4.26修改\n as_str = ''\n #print(cur_map_method)\n as_str = GetAsStrOfIpByRv(temp[0]) #moas之间以'_'隔开\n #as_bdrmapit = GetIp2ASFromBdrMapItDb_2(trace_file_name, temp[0]) #20210807临时补丁\n if as_bdrmapit != '':\n if as_str:\n if as_bdrmapit not in as_str.split('_'):\n as_str = as_str + '_' + as_bdrmapit\n else:\n as_str = as_bdrmapit\n if as_str:\n for asn in as_str.split('_'):\n if IsIxpAs(asn):\n is_ixp_ip = True\n break\n #if not is_ixp_ip and as_str not in hop_as_list:\n if as_str not in hop_as_list:\n hop_as_list.append(as_str)\n else:\n if '?' not in hop_as_list:\n hop_as_list.append('?')\n if is_ixp_ip:\n hop_as_list = ['<>'] #2021.1.30 做标记,暂时先这样做\n break #有一个ixp ip就记当前位置为ixp ip\n \n if len(hop_as_list) == 0: #2021.1.27这里原来没有这一步,有bug,应该考虑过滤掉IXP后没有ip和AS的情况\n print('NOTE: hop not exist')\n elif len(hop_as_list) == 1:\n as_path = as_path + ' ' + hop_as_list[0]\n else:\n as_path = as_path + ' {' + ' '.join(hop_as_list) + '}'\n #wf.write(as_path + '\\n')\n if get_link_flag:\n GetLinksFromTrace(CompressAsPathToMin(CompressAsPath(as_path)).split(' '), all_trace_links_set, all_possi_trace_links_set)\n else:\n all_trace_path_set.add(CompressAsPathToMin(CompressAsPath(as_path)))\n line_num += 1 \n #wf.close()\n # InitBdrCache_2(trace_file_name) #20210807临时补丁\n # CloseBdrMapItDb_2(trace_file_name) #20210807临时补丁\n\ndef ChgTrace2ASPathPerMonth(year, month, vp):\n print(vp + ' begin')\n all_trace_links_set = set()\n all_possi_trace_links_set = set()\n for root,dirs,files in os.walk('.'):\n for filename in files: #例:cdg-fr.20180125\n if not filename.startswith('back_'):\n if not filename.startswith(vp):\n continue\n w_filename = 'as_' + filename\n if os.path.exists(w_filename) and os.path.getsize(w_filename) > 0:\n continue\n print(filename)\n ChgTrace2ASPath_2(filename, w_filename, all_trace_links_set, all_possi_trace_links_set, None)\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_trace_links_from_' + vp, 'w') as wf:\n wf.write(','.join(list(all_trace_links_set)))\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_possi_trace_links_from_' + vp, 'w') as wf:\n wf.write(','.join(list(all_possi_trace_links_set)))\n print(vp + ' end')\n\ndef GetPathOrLinksPerMonth(year, month, vp, get_link_flag):\n print(vp + ' begin')\n all_trace_links_set = set()\n all_possi_trace_links_set = set()\n all_trace_path_set = set()\n for root,dirs,files in os.walk('.'):\n for filename in files: #例:cdg-fr.20180125 \n if not filename.startswith('back_'):\n if not filename.startswith(vp):\n continue\n w_filename = 'as_' + filename\n if os.path.exists(w_filename) and os.path.getsize(w_filename) > 0:\n continue\n print(filename)\n if get_link_flag:\n ChgTrace2ASPath_2WithPadding(filename, w_filename, True, None, all_trace_links_set, all_possi_trace_links_set)\n else:\n ChgTrace2ASPath_2WithPadding(filename, w_filename, False, all_trace_path_set, None, None)\n if get_link_flag:\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_trace_links_from_' + vp, 'w') as wf:\n wf.write(','.join(list(all_trace_links_set)))\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_possi_trace_links_from_' + vp, 'w') as wf:\n wf.write(','.join(list(all_possi_trace_links_set)))\n else:\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_trace_path_from_' + vp, 'w') as wf:\n wf.write('\\n'.join(list(all_trace_path_set)))\n print(vp + ' end')\n\ndef GetPathOrLinksPerMonth_Ori(vp, only_stat_trace_flag):\n print(vp + ' begin')\n global bgp_ip_as_cache\n #global bdrmapit_date_cursor_dict\n #bdrmapit_date_db_dict = dict()\n all_trace_links_set = set()\n all_possi_trace_links_set = set()\n all_trace_path_set = set()\n\n for year in range(2018,2021):\n for month in range(1, 13):\n if (year == 2020 and month > 4): #2016年4月前peeringdb数据不准,2020年5月后的数据不全\n continue\n date = str(year) + str(month).zfill(2)\n GetSibRel(year, month)\n GetIxpPfxDict(year, month)\n GetIxpAsSet() #这条语句需要放在GetSibRel()之后,因为需要sib_dict,也就是as2org_dict\n GetPfx2ASByRv(year, month)\n bgp_ip_as_cache.clear()\n for root,dirs,files in os.walk('.'):\n for filename in files: #例:cdg-fr.20180125\n (cur_vp, cur_date) = filename.split('.')\n if cur_vp != vp or date != cur_date[:6]:\n continue\n w_filename = 'as_' + filename\n if os.path.exists(w_filename) and os.path.getsize(w_filename) > 0:\n continue\n print(filename)\n if only_stat_trace_flag: #其实可以一次把as file写下来,同时统计trace和link。但是原来为了快,只统计了trace和link,现在还是需要写as file\n ChgTrace2ASPath_2(filename, None, all_trace_links_set, all_possi_trace_links_set, all_trace_path_set)\n else:\n ChgTrace2ASPath_2(filename, w_filename, None, None, None)\n ClearIp2AsDict()\n ClearIxpAsSet()\n ClearIxpPfxDict()\n ClearSibRel()\n \n #for key in bdrmapit_date_cursor_dict.keys():\n # bdrmapit_date_cursor_dict[key].close()\n # bdrmapit_date_db_dict[key].close()\n\n if only_stat_trace_flag:\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_trace_links_2_from_' + vp, 'w') as wf:\n wf.write(','.join(list(all_trace_links_set)))\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_possi_trace_links_2_from_' + vp, 'w') as wf:\n wf.write(','.join(list(all_possi_trace_links_set)))\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_trace_path_2_from_' + vp, 'w') as wf:\n wf.write('\\n'.join(list(all_trace_path_set)))\n print(vp + ' end')\n\ndef TmpPerProc(year, month, vp):\n global bgp_ip_as_cache\n #global bdrmapit_date_cursor_dict\n #bdrmapit_date_db_dict = dict()\n all_trace_links_set = set()\n all_possi_trace_links_set = set()\n all_trace_path_set = set()\n\n GetSibRel(year, month)\n GetIxpPfxDict(year, month)\n date = str(year) + str(month).zfill(2)\n bgp_ip_as_cache.clear()\n for root,dirs,files in os.walk('.'):\n for filename in files: #例:cdg-fr.20180125\n (cur_vp, cur_date) = filename.split('.')\n if cur_vp != vp or date != cur_date[:6]:\n continue\n # w_filename = 'as_' + filename\n # if os.path.exists(w_filename) and os.path.getsize(w_filename) > 0:\n # continue\n print(filename)\n ChgTrace2ASPath_2(filename, None, all_trace_links_set, all_possi_trace_links_set, all_trace_path_set)\n ClearSibRel()\n ClearIxpPfxDict()\n\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_trace_links_2_from_' + vp + '_' + date, 'w') as wf:\n wf.write(','.join(list(all_trace_links_set)))\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_possi_trace_links_2_from_' + vp + '_' + date, 'w') as wf:\n wf.write(','.join(list(all_possi_trace_links_set)))\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_trace_path_2_from_' + vp + '_' + date, 'w') as wf:\n wf.write('\\n'.join(list(all_trace_path_set)))\n\ndef GetPathOrLinksPerMonth_Ori_MultiProc(vp, flag):\n print(vp + ' begin')\n proc_list = []\n all_trace_links_set = set()\n all_possi_trace_links_set = set()\n all_trace_path_set = set()\n\n for year in range(2018,2021):\n for month in range(1, 13):\n if (year == 2020 and month > 4): #2016年4月前peeringdb数据不准,2020年5月后的数据不全\n continue\n proc_list.append(mp.Process(target=TmpPerProc, args=(year, month, vp)))\n #RunBdrmapitPermonthAllVps(year, month)\n for proc in proc_list:\n proc.start()\n for proc in proc_list:\n proc.join()\n \n output = os.popen('ls ' + global_var.par_path + global_var.other_middle_data_dir + 'all_trace_links_2_from_' + vp + '_*')\n data = output.read()\n for filename in data.strip('\\n').split('\\n'):\n with open(filename, 'r') as rf: \n tmp_set = set(rf.read().strip(',').split(','))\n all_trace_links_set |= tmp_set\n os.system('rm -f %s' %filename)\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_trace_links_2_from_' + vp, 'w') as wf:\n wf.write(','.join(list(all_trace_links_set)))\n output = os.popen('ls ' + global_var.par_path + global_var.other_middle_data_dir + 'all_possi_trace_links_2_from_' + vp + '_*')\n data = output.read()\n for filename in data.strip('\\n').split('\\n'):\n with open(filename, 'r') as rf:\n tmp_set = set(rf.read().strip(',').split(','))\n all_possi_trace_links_set |= tmp_set\n os.system('rm -f %s' %filename)\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_possi_trace_links_2_from_' + vp, 'w') as wf:\n wf.write(','.join(list(all_possi_trace_links_set)))\n output = os.popen('ls ' + global_var.par_path + global_var.other_middle_data_dir + 'all_trace_path_2_from_' + vp + '_*')\n data = output.read()\n for filename in data.strip('\\n').split('\\n'):\n with open(filename, 'r') as rf:\n tmp_set = set(rf.read().strip(',').split(','))\n all_trace_path_set |= tmp_set\n os.system('rm -f %s' %filename)\n with open(global_var.par_path + global_var.other_middle_data_dir + 'all_trace_path_2_from_' + vp, 'w') as wf:\n wf.write(','.join(list(all_trace_path_set)))\n \n \n #for key in bdrmapit_date_cursor_dict.keys():\n # bdrmapit_date_cursor_dict[key].close()\n # bdrmapit_date_db_dict[key].close()\n print(vp + ' end')\n\ndef GetPathOrLinksPerMonth_Ori_Debug(year, month, vp):\n all_trace_links_set = set()\n all_possi_trace_links_set = set()\n all_trace_path_set = set()\n GetSibRel(year, month)\n GetIxpPfxDict(year, month)\n date = str(year) + str(month).zfill(2)\n for root,dirs,files in os.walk('.'):\n for filename in files: #例:cdg-fr.20180125\n (cur_vp, cur_date) = filename.split('.')\n if cur_vp != vp or date != cur_date[:6]:\n continue\n # w_filename = 'as_' + filename\n # if os.path.exists(w_filename) and os.path.getsize(w_filename) > 0:\n # continue\n #print(filename)\n ChgTrace2ASPath_2(filename, None, all_trace_links_set, all_possi_trace_links_set, all_trace_path_set)\n ClearSibRel()\n ClearIxpPfxDict()\n\n\ndef TmpGetIpsOfTraceByIp(obj_ip, files): \n output = os.popen('grep ' + obj_ip + ' ' + files)\n data = output.readline()\n info_suc = dict()\n info_prev = dict()\n dbname = 'mty-tx'\n db_pathname = '../back/bdrmapit_mty-mx.20200216.db'\n ConnectToBdrMapItDb_2(dbname, db_pathname)\n ConstrBdrCache_2(dbname)\n while data:\n elems = data.strip('\\n').split('\\t')\n dst_ip = elems[2]\n suc_ip = ''\n prev_ip = ''\n for i in range(13, len(elems)):\n if elems[i].__contains__(obj_ip):\n if not prev_ip:\n if i > 0:\n prev_ip = elems[i - 1].split(',')[0]\n else:\n prev_ip = 'N'\n if i < len(elems) - 1:\n suc_ip = elems[i + 1].split(',')[0]\n if suc_ip != obj_ip:\n break\n else:\n suc_ip = ''\n else:\n break\n if suc_ip not in info_suc.keys():\n info_suc[suc_ip] = [0, []]\n info_suc[suc_ip][0] += 1\n info_suc[suc_ip][1].append(dst_ip)\n if prev_ip not in info_prev.keys():\n info_prev[prev_ip] = 0\n info_prev[prev_ip] += 1\n data = output.readline()\n sort_list_suc = sorted(info_suc.items(), key=lambda d:d[1][0], reverse = True)\n sort_list_prev = sorted(info_prev.items(), key=lambda d:d[1], reverse = True)\n print('next ip:')\n for elem in sort_list_suc:\n (key, val) = elem \n if key != '' and key != 'q':\n print('%s (%s): %d' %(key, GetAsOfIpByBGPAndBdrmapit(key, dbname), val[0]))\n else:\n print('%s (): %d' %(key, val[0]))\n if key == '':\n dst_as_dict = dict()\n for elem in val[1]:\n as_str = GetAsOfIpByBGPAndBdrmapit(elem, dbname)\n if as_str:\n if as_str not in dst_as_dict.keys():\n dst_as_dict[as_str] = 0\n dst_as_dict[as_str] += 1\n sort_list_local = sorted(dst_as_dict.items(), key=lambda d:d[1], reverse = True)\n print('\\t', end='')\n for sub_elem in sort_list_local:\n (asn, num) = sub_elem\n print('%s(%d)' %(asn, num), end=',')\n print('')\n print('prev ip:')\n for elem in sort_list_prev:\n (key, val) = elem \n if key != '':\n print('%s (%s): %d' %(key, GetAsOfIpByBGPAndBdrmapit(key, dbname), val))\n else:\n print('%s (): %d' %(key, val))\n InitBdrCache_2(dbname)\n CloseBdrMapItDb_2(dbname)\n\ndef IndexCompressPathToPath(vp, no_use_flag):\n comp_ori_dict = dict()\n for root,dirs,files in os.walk('.'):\n for filename in files: #例:cdg-fr.20180125\n if not filename.startswith('as_' + vp):\n continue\n print(filename)\n with open(filename, 'r') as rf:\n curline_ip = rf.readline()\n while curline_ip:\n curline_trace = rf.readline()\n trace = curline_trace.strip('\\n').strip('\\t').strip(' ')\n compress_trace = CompressAsPath(trace)\n if compress_trace not in comp_ori_dict.keys():\n comp_ori_dict[compress_trace] = set()\n comp_ori_dict[compress_trace].add(trace)\n curline_ip = rf.readline()\n print(vp + ' done')\n with open(global_var.par_path + global_var.other_middle_data_dir + 'compress_trace_to_ori_trace_' + vp, 'w') as wf:\n for (comp, trace_set) in comp_ori_dict.items():\n wf.write(comp + ':' + ','.join(list(trace_set)) + '\\n')\n\nif __name__ == '__main__':\n PreGetSrcFilesInDirs()\n os.chdir(global_var.all_trace_par_path + global_var.all_trace_download_dir + 'result/')\n thread_list = []\n\n #Debug\n # tmp_set1 = set()\n # tmp_set2 = set()\n # with open('/mountdisk1/ana_c_d_incongruity/other_middle_data/temp', 'r') as rf:\n # curline = rf.readline()\n # while curline:\n # GetLinksFromTrace(curline.strip('\\n').split(' '), tmp_set1, tmp_set2)\n # curline = rf.readline() \n \n # for year in range(2018,2021):\n # for month in range(1, 13):\n # if (year == 2020 and month > 4): #2016年4月前peeringdb数据不准,2020年5月后的数据不全\n # continue\n # thread_list.append(mp.Process(target=GetPathOrLinksPerMonth_Ori_Debug, args=(year, month, 'mty-mx')))\n # for thread in thread_list:\n # thread.start()\n # for thread in thread_list:\n # thread.join()\n #TmpGetIpsOfTraceByIp('63.223.15.174', 'mty-mx.20*')\n #TmpGetIpsOfTraceByIp('63.223.15.178', 'mty-mx.20*')\n # print('done')\n # vps = set()\n # for root,dirs,files in os.walk('.'):\n # for filename in files:\n # vps.add(filename.split('.')[0])\n # #print(vps)\n # tmp = {'ams2-nl', 'arn-se', 'bcn-es', 'bjl-gm', 'bma-se', 'bwi-us', 'cdg-fr', 'cjj-kr', 'dfw-us', 'dub-ie', 'eug-us', 'fnl-us', 'hel-fi', 'hkg-cn', 'hlz-nz', 'iad-us', 'jfk-us', 'lej-de', 'mel-au', 'mty-mx', 'nrt-jp', 'ord-us', 'osl-no', 'per-au', 'pna-es', 'pry-za', 'rno-us', 'sao-br', 'scl-cl', 'sea-us', 'sjc2-us', 'tpe-tw', 'wbu-us', 'yow-ca', 'yyz-ca', 'zrh2-ch'}\n # print(vps.difference(tmp))\n # while True:\n # pass\n\n # for year in range(2018,2021):\n # for month in range(1, 13):\n # if (year == 2020 and month > 4): #2016年4月前peeringdb数据不准,2020年5月后的数据不全\n # continue\n # date = str(year) + str(month).zfill(2)\n # tmp_db_name = '../back/bdrmapit_%s.db' %date\n # if os.path.exists(tmp_db_name) and os.path.getsize(tmp_db_name) > 0:\n # # bdrmapit_date_db_dict[date] = sqlite3.connect('../back/bdrmapit_%s.db' %date)\n # # if bdrmapit_date_db_dict[date]:\n # # bdrmapit_date_cursor_dict[date] = bdrmapit_date_db_dict[date].cursor()\n # ConnectToBdrMapItDb_2(date, tmp_db_name)\n # #InitBdrCache_2(date)\n # ConstrBdrCache_2(date)\n\n vps = set()\n for root,dirs,files in os.walk('.'):\n for filename in files:\n if filename.startswith('as_'):\n continue\n vps.add(filename.split('.')[0])\n for vp in vps:\n #for vp in ['cbg-uk']:\n #GetPathOrLinksPerMonth_Ori_MultiProc(vp, True)\n # 2019.01 trace get\n # #ChgTrace2ASPathPerMonth(year, month, vp)\n # #thread_list.append(threading.Thread(target=ChgTrace2ASPathPerMonth,args=(year, month, vp)))\n # #thread_list.append(mp.Process(target=ChgTrace2ASPathPerMonth, args=(year, month, vp)))\n #thread_list.append(mp.Process(target=GetPathOrLinksPerMonth, args=(year, month, vp, False)))\n #3 days/month trace get \n #thread_list.append(mp.Process(target=GetPathOrLinksPerMonth_Ori, args=(vp, False)))\n thread_list.append(mp.Process(target=IndexCompressPathToPath, args=(vp, False)))\n for thread in thread_list:\n thread.start()\n for thread in thread_list:\n thread.join()\n # ClearIp2AsDict()\n # ClearIxpAsSet()\n # ClearIxpPfxDict()\n # ClearSibRel()\n \n # for year in range(2018,2021):\n # for month in range(1, 13):\n # if (year == 2020 and month > 4): #2016年4月前peeringdb数据不准,2020年5月后的数据不全\n # continue\n # date = str(year) + str(month).zfill(2)\n # tmp_db_name = '../back/bdrmapit_%s.db' %date\n # if os.path.exists(tmp_db_name) and os.path.getsize(tmp_db_name) > 0:\n # CloseBdrMapItDb_2(date)\n # InitBdrCache_2(date) \n","sub_path":"deal_all_trace.py","file_name":"deal_all_trace.py","file_ext":"py","file_size_in_byte":29583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"642602940","text":"from .db import db\nfrom datetime import datetime\n\n\nclass Reaction(db.Model):\n __tablename__ = 'reactions'\n\n id = db.Column(db.Integer, primary_key=True)\n type = db.Column(db.String(255), nullable=False)\n user_id = db.Column(db.Integer, db.ForeignKey(\"users.id\"), nullable=False)\n message_id = db.Column(db.Integer, db.ForeignKey(\"messages.id\", ondelete=\"CASCADE\"), nullable=False)\n created_at = db.Column(db.DateTime, default=lambda: datetime.now(), nullable=False)\n updated_at = db.Column(db.DateTime, default=lambda: datetime.now(), nullable=False)\n message = db.relationship(\"Message\", back_populates=\"reactions\")\n user = db.relationship(\"User\", back_populates=\"reactions\")\n\n def to_dict(self):\n return {\n \"id\": self.id,\n \"type\": self.type,\n \"message_id\": self.message_id,\n \"user_id\": self.user_id,\n # \"created_at\": self.created_at,\n \"user\": {\n \"username\": self.user.username,\n }\n }\n","sub_path":"app/models/reaction.py","file_name":"reaction.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"333162710","text":"# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport math\n\nimport numpy as np\nimport paddle\nfrom paddle import ParamAttr\nimport paddle.nn as nn\nimport paddle.nn.functional as F\nfrom paddle.nn import Conv2d, BatchNorm, Linear, Dropout\nfrom paddle.nn import AdaptiveAvgPool2d, MaxPool2d, AvgPool2d\nfrom paddle.nn.initializer import MSRA\nfrom paddlehub.module.module import moduleinfo\nfrom paddlehub.module.cv_module import ImageClassifierModule\n\n\nclass ConvBNLayer(nn.Layer):\n \"\"\"Basic conv bn layer.\"\"\"\n\n def __init__(self,\n num_channels: int,\n filter_size: int,\n num_filters: int,\n stride: int,\n padding: int,\n channels: int = None,\n num_groups: int = 1,\n act: str = 'relu',\n name: str = None):\n super(ConvBNLayer, self).__init__()\n\n self._conv = Conv2d(\n in_channels=num_channels,\n out_channels=num_filters,\n kernel_size=filter_size,\n stride=stride,\n padding=padding,\n groups=num_groups,\n weight_attr=ParamAttr(initializer=MSRA(), name=name + \"_weights\"),\n bias_attr=False)\n\n self._batch_norm = BatchNorm(\n num_filters,\n act=act,\n param_attr=ParamAttr(name + \"_bn_scale\"),\n bias_attr=ParamAttr(name + \"_bn_offset\"),\n moving_mean_name=name + \"_bn_mean\",\n moving_variance_name=name + \"_bn_variance\")\n\n def forward(self, inputs: paddle.Tensor):\n y = self._conv(inputs)\n y = self._batch_norm(y)\n return y\n\n\nclass DepthwiseSeparable(nn.Layer):\n \"\"\"Depthwise and pointwise conv layer.\"\"\"\n\n def __init__(self,\n num_channels: int,\n num_filters1: int,\n num_filters2: int,\n num_groups: int,\n stride: int,\n scale: float,\n name: str = None):\n super(DepthwiseSeparable, self).__init__()\n\n self._depthwise_conv = ConvBNLayer(\n num_channels=num_channels,\n num_filters=int(num_filters1 * scale),\n filter_size=3,\n stride=stride,\n padding=1,\n num_groups=int(num_groups * scale),\n name=name + \"_dw\")\n\n self._pointwise_conv = ConvBNLayer(\n num_channels=int(num_filters1 * scale),\n filter_size=1,\n num_filters=int(num_filters2 * scale),\n stride=1,\n padding=0,\n name=name + \"_sep\")\n\n def forward(self, inputs: paddle.Tensor):\n y = self._depthwise_conv(inputs)\n y = self._pointwise_conv(y)\n return y\n\n\n@moduleinfo(\n name=\"mobilenet_v1_imagenet_ssld\",\n type=\"cv/classification\",\n author=\"paddlepaddle\",\n author_email=\"\",\n summary=\"mobilenet_v1_imagenet_ssld is a classification model, \"\n \"this module is trained with Imagenet dataset.\",\n version=\"1.1.0\",\n meta=ImageClassifierModule)\nclass MobileNetV1(nn.Layer):\n \"\"\"MobileNetV1\"\"\"\n\n def __init__(self, class_dim: int = 1000, load_checkpoint: str = None):\n super(MobileNetV1, self).__init__()\n self.block_list = []\n\n self.conv1 = ConvBNLayer(\n num_channels=3, filter_size=3, channels=3, num_filters=int(32), stride=2, padding=1, name=\"conv1\")\n\n conv2_1 = self.add_sublayer(\n \"conv2_1\",\n sublayer=DepthwiseSeparable(\n num_channels=int(32),\n num_filters1=32,\n num_filters2=64,\n num_groups=32,\n stride=1,\n scale=1,\n name=\"conv2_1\"))\n self.block_list.append(conv2_1)\n\n conv2_2 = self.add_sublayer(\n \"conv2_2\",\n sublayer=DepthwiseSeparable(\n num_channels=int(64),\n num_filters1=64,\n num_filters2=128,\n num_groups=64,\n stride=2,\n scale=1,\n name=\"conv2_2\"))\n self.block_list.append(conv2_2)\n\n conv3_1 = self.add_sublayer(\n \"conv3_1\",\n sublayer=DepthwiseSeparable(\n num_channels=int(128),\n num_filters1=128,\n num_filters2=128,\n num_groups=128,\n stride=1,\n scale=1,\n name=\"conv3_1\"))\n self.block_list.append(conv3_1)\n\n conv3_2 = self.add_sublayer(\n \"conv3_2\",\n sublayer=DepthwiseSeparable(\n num_channels=int(128),\n num_filters1=128,\n num_filters2=256,\n num_groups=128,\n stride=2,\n scale=1,\n name=\"conv3_2\"))\n self.block_list.append(conv3_2)\n\n conv4_1 = self.add_sublayer(\n \"conv4_1\",\n sublayer=DepthwiseSeparable(\n num_channels=int(256),\n num_filters1=256,\n num_filters2=256,\n num_groups=256,\n stride=1,\n scale=1,\n name=\"conv4_1\"))\n self.block_list.append(conv4_1)\n\n conv4_2 = self.add_sublayer(\n \"conv4_2\",\n sublayer=DepthwiseSeparable(\n num_channels=int(256),\n num_filters1=256,\n num_filters2=512,\n num_groups=256,\n stride=2,\n scale=1,\n name=\"conv4_2\"))\n self.block_list.append(conv4_2)\n\n for i in range(5):\n conv5 = self.add_sublayer(\n \"conv5_\" + str(i + 1),\n sublayer=DepthwiseSeparable(\n num_channels=int(512),\n num_filters1=512,\n num_filters2=512,\n num_groups=512,\n stride=1,\n scale=1,\n name=\"conv5_\" + str(i + 1)))\n self.block_list.append(conv5)\n\n conv5_6 = self.add_sublayer(\n \"conv5_6\",\n sublayer=DepthwiseSeparable(\n num_channels=int(512),\n num_filters1=512,\n num_filters2=1024,\n num_groups=512,\n stride=2,\n scale=1,\n name=\"conv5_6\"))\n self.block_list.append(conv5_6)\n\n conv6 = self.add_sublayer(\n \"conv6\",\n sublayer=DepthwiseSeparable(\n num_channels=int(1024),\n num_filters1=1024,\n num_filters2=1024,\n num_groups=1024,\n stride=1,\n scale=1,\n name=\"conv6\"))\n self.block_list.append(conv6)\n\n self.pool2d_avg = AdaptiveAvgPool2d(1)\n\n self.out = Linear(\n int(1024),\n class_dim,\n weight_attr=ParamAttr(initializer=MSRA(), name=\"fc7_weights\"),\n bias_attr=ParamAttr(name=\"fc7_offset\"))\n\n if load_checkpoint is not None:\n model_dict = paddle.load(load_checkpoint)[0]\n self.set_dict(model_dict)\n print(\"load custom checkpoint success\")\n\n else:\n checkpoint = os.path.join(self.directory, 'mobilenet_v1_ssld_imagenet.pdparams')\n if not os.path.exists(checkpoint):\n os.system(\n 'wget https://paddlehub.bj.bcebos.com/dygraph/image_classification/mobilenet_v1_ssld_imagenet.pdparams -O '\n + checkpoint)\n model_dict = paddle.load(checkpoint)[0]\n self.set_dict(model_dict)\n print(\"load pretrained checkpoint success\")\n\n def forward(self, inputs: paddle.Tensor):\n y = self.conv1(inputs)\n for block in self.block_list:\n y = block(y)\n y = self.pool2d_avg(y)\n y = paddle.reshape(y, shape=[-1, 1024])\n y = self.out(y)\n return y\n","sub_path":"modules/image/classification/mobilenet_v1_imagenet_ssld/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":8514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"648433032","text":"def hint(a, b):\n c = ''\n for i in range(len(a)):\n if a[i] == b[i]:\n c += a[i].replace(b[i], b[i].upper())\n elif a[i] in b:\n c += a[i]\n else:\n c += '.'\n return c\n","sub_path":"10 - Strings/Lingo.py","file_name":"Lingo.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"178314995","text":"from flectra import models, fields, api\nfrom pprint import pprint\n\nclass pindah_kelas(models.TransientModel):\n _name = 'siswa_ocb11.pindah_kelas'\n\n siswa_id = fields.Many2one('res.partner', string=\"Siswa\", domain=[('is_siswa','=',True)], required=True)\n induk = fields.Char('Induk',related='siswa_id.induk')\n tahunajaran_id = fields.Many2one('siswa_ocb11.tahunajaran', string=\"Tahun Ajaran\", default=lambda self: self.env['siswa_ocb11.tahunajaran'].search([('active','=',True)]), required=True)\n # tahunajaran_id = fields.Many2one('siswa_ocb11.tahunajaran', string=\"Tahun Ajaran\")\n rombel_asal_id = fields.Many2one('siswa_ocb11.rombel', string=\"Rombel\" , compute='_compute_rombel_asal', store=True)\n # rombel_tujuan_id = fields.Many2one('siswa_ocb11.rombel', string=\"Pindah ke\", required=True, domain=lambda self: [('jenjang_id', '=', self.rombel_asal_id.jenjang_id.id)])\n rombel_tujuan_id = fields.Many2one('siswa_ocb11.rombel', string=\"Pindah ke\", required=True, )\n\n @api.depends('siswa_id')\n def _compute_rombel_asal(self):\n # if self.siswa_id:\n for rec in self:\n if rec.siswa_id:\n # set rombel asal\n tahunajaran = rec.tahunajaran_id\n rombel_asal = rec.siswa_id.rombels.search([('siswa_id','=',rec.siswa_id.id),('tahunajaran_id','=',tahunajaran.id)])\n rec.rombel_asal_id = rec.siswa_id.active_rombel_id.id\n \n @api.onchange('rombel_asal_id')\n def rombel_asal_change(self):\n if self.rombel_asal_id:\n domain = {'rombel_tujuan_id':[\n ('jenjang_id','=',self.rombel_asal_id.jenjang_id.id),\n ('id','!=',self.rombel_asal_id.id)\n ]}\n return {'domain':domain, 'value':{'rombel_tujuan_id':[]}}\n \n def action_pindah_kelas(self):\n # update rombel\n self.env['siswa_ocb11.rombel_siswa'].search([\n ('siswa_id','=',self.siswa_id.id),\n ('tahunajaran_id','=',self.tahunajaran_id.id)\n ]).write({\n 'rombel_id' : self.rombel_tujuan_id.id\n })\n siswa = self.env['res.partner'].search([('id','=',self.siswa_id.id)])\n print('recompute rombel siswa')\n siswa._compute_rombel()\n\n # update rombel siswa dashboard\n rombel_dashboards = self.env['siswa_ocb11.rombel_dashboard'].search([\n ('tahunajaran_id', '=', self.tahunajaran_id.id),\n ('rombel_id', 'in', [self.rombel_tujuan_id.id, self.rombel_asal_id.id])\n ])\n\n # pprint(rombel_dashboards)\n for rbd in rombel_dashboards:\n print('loop rombel dashboard')\n rbd.lets_compute_jumlah_siswa()\n \n # reload page\n return {\n 'type': 'ir.actions.client',\n 'tag': 'reload',\n }\n","sub_path":"siswa_ocb11/wizards/pindah_kelas.py","file_name":"pindah_kelas.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"135782219","text":"from Robot import *\nfrom Supervisor import *\nfrom time import time, sleep\nfrom subprocess import Popen, PIPE\nfrom math import radians, sin, cos, atan2\n\n# Rueda izquierda esta bien. Cuando pones IN1 High y IN2 LOW, el motor va hacia adelante.\nM1IN1 = 19 # Left Motor Driver Pin M1IN1 - Purple Wire\nM1IN2 = 26 # Left Motor Driver Pin M1IN2 - Orange Wire\nM2IN1 = 16 # Right Motor Driver Pin M2IN1 - Purple Wire\nM2IN2 = 20 # Right Motor Driver Pin M2IN2 - Orange Wire\nE1A = 12 # Right Encoder A Output - Yellow Wire\nE1B = 13 # Right Encoder B Output - White Wire\nE2A = 5 # Left Encoder A Output - Yellow Wire\nE2B = 6 # Left Encoder B Output - White Wire\nGarI = 8 # Motor garra derecha - Green Wire\nGarD = 7 # Motor garra izquierda - Green Wire\nGRot = 25 # Motor que rota las garras - Green wire\nTRIG = 27 # Trigger pin for all ultrasonics - White Wire\nECHO1 = 24 # Echo pin for Right US - Purple Wire\nECHO2 = 23 # Echo pin for Center US - Purple Wire\nECHO3 = 22 # Echo pin for Left US - Purple Wire\n\nmilky = Robot(0.06, 0.29, 48*74.83, 0, 180, 100, 100)\nmilky.setMotors(M1IN1, M1IN2, M2IN1, M2IN2)\nmilky.setEncoders(E1A, E1B, E2A, E2B)\nmilky.setIMU()\nmilky.setUltrasonics(TRIG,ECHO1,ECHO2,ECHO3)\n\nclock = time()\nmilky.stateEstimate.yawOffset = milky.imu.getFirstYaw(50)\nprint(time() - clock)\nprint(\"CENTRO: \", milky.stateEstimate.yawOffset)\nnavigation = Supervisor(milky)\ni = 0\noldClock = time()\nnewClock = 0\ndelta = 0\nwhile(True):\n\tdistances = milky.getUSDistances()\n\tprint(\"Distancias: \",distances)\nsleep(0.2)\nwhile(False):\n\tnewClock = time()\n\tdelta = newClock - oldClock\n\tprint(str(i))\n\tprint(\"x = \" + str(milky.stateEstimate.x) + \"; y = \" + str(milky.stateEstimate.y) + \"; thetha = \" + str(milky.stateEstimate.theta))\n\tprint(\"Delta: \" + str(delta))\n\t#yawIMU = milky.imu.getYaw()\n\t#print(\"Yaw IMU: \" + str(yawIMU))\n\t#thetaIMU = yawIMU - yawOffset\n\t#print(\"Theta IMU: \" + str(thetaIMU))\n\tnavigation.execute(delta)\n\ti += 1\n\toldClock = newClock\n\tprint(str(milky.leftEncoder.ticks) + \";\" + str(milky.rightEncoder.ticks))\n\tsleep(0.1)\n\npi = pigpio.pi()\n\npi.set_PWM_dutycycle(19, 0)\npi.set_PWM_dutycycle(26, 0)\npi.set_PWM_dutycycle(20, 0)\npi.set_PWM_dutycycle(16, 0)\npi.stop()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"505324460","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\nimport numpy as np\n\ndf = pd.read_csv('Position_salaries.csv')\n\nX = df.iloc[:, 1:2].values\ny = df.iloc[:, 2].values\n\n# # A CURVE APPEARS TO FIT THE DATA BETTER THAN A STRAIGHT LINE \n# plt.scatter(X, y)\n# plt.show()\n\n# FIT TRANSFORMED POLYNOMIAL DATA TO THE LINEAR REGRESSION MODEL\npoly_reg = PolynomialFeatures(degree=4)\nX_poly = poly_reg.fit_transform(X)\n\nlin_reg = LinearRegression()\nlin_reg.fit(X_poly, y)\n\n# PREDICT RANDOM VALUES\ninput_value = np.array([6.7])\ninput_value = np.resize(input_value, (len(input_value), 1))\n\npred = lin_reg.predict(poly_reg.transform(input_value))\n# print(pred)\n\n# VISUALIZE \ndummy_X_values = np.arange(0, 10.1, 0.1)\ndummy_X_values = np.resize(dummy_X_values, (len(dummy_X_values), 1))\n\nplt.scatter(X, y)\nplt.plot(dummy_X_values, lin_reg.predict(poly_reg.fit_transform(dummy_X_values)), color='red')\nplt.show()","sub_path":"regression/polynomial_regression/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"261051798","text":"# Асинхронный парсер для создания карты сайта\nimport asyncio\nimport aiohttp\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\nimport time\nfrom logs import Logger\n\nmain_list = []\nsocial = ['vk', 'facebook', 'linkedin', 'twitter', 'callto', 'skype', 'tel', '#', 'mailto']\n\nlog = Logger(onprint=True)\n\nasync def connection(session, url):\n \"\"\" делает запрос, ожидает ответа и сра��у же поднимается в случае статуса не-200 \"\"\"\n\n log.info(f'set connection\\nurl - {url}')\n\n resp = await session.request(method=\"GET\", url=url)\n resp.raise_for_status()\n html = await resp.text()\n return html\n\nasync def soup_d(html):\n \"\"\" Создает объект BeautifulSoup \"\"\"\n soup = BeautifulSoup(html, 'html.parser')\n return soup\n\nasync def parse_response(html, hostname):\n \"\"\" Парсит страницу HTML которая возвращается от сервера\n чистит ссылки от мусора и добавляет их в локальный список\n \"\"\"\n log.debug('begin parse')\n soup = await soup_d(html)\n local_list = []\n all_links = soup.find_all('a')\n\n for link in all_links:\n # забирает href\n l = link.get('href')\n log.onprint = False\n log.debug(f'link - {l}')\n\n if l:\n # убираю аргументы из ссылок\n if '?' in l:\n l = l[:l.find('?')]\n log.debug(f'delete arguments {l}')\n\n if hostname in l:\n # отделить домен\n l = l.split(hostname)\n l = l[-1]\n log.debug(f'delete domain {l}')\n\n for s in social:\n # удалить ссылки на соцсеточки\n if s in l :\n l = 'zero'\n\n # сохраняю в список\n if l not in local_list and l != 'zero' and len(l) > 1:\n local_list.append(l)\n log.debug(f'append to local list - {l}')\n return local_list\n\nasync def parse_local_list(local_list):\n \"\"\" берет ссылки из локального списка, и добавляет их в основной список\n \"\"\"\n for link in local_list:\n if link not in main_list:\n main_list.append(link)\n log.debug(f'append to main list - {link}')\n\nasync def make_links(url, session):\n \"\"\" \n Основной цикл для организации взаимодействия всех корутин\n Проблема с которой столкнулся\n начинает парсить ссылки на документы\n /images/image/img.png\n пришлось обработать три варианта возникновения такой проблемы\n их наверняка больше, и это вызовет ошибку при дальнейшей работе\n пытался решить эту проблему так же как и в parse_response\n for s in social:\n но итерация проходила только в первом случае, потом прерывалась\n пришлось сделать хардкодом\n \"\"\"\n log.debug(f'set session with {url}')\n # parsed_url = urlparse(url)\n root_domain = urlparse(url).netloc\n # domain = parsed_url.geturl()\n\n try:\n # обработка ссылок на документы и картинки\n if 'png' in url or 'pdf' in url or 'jpg' in url:\n html = None\n else:\n html = await connection(session, url)\n except Exception as error:\n log.onprint=True\n log.error(f'{error}')\n log.onprint=False\n html = None\n\n if html:\n # запись в локальный список\n local_list = await parse_response(html, root_domain)\n # запись из локального списка в главный\n await parse_local_list(local_list)\n\nasync def main(url):\n \"\"\" объединение всех функций в одну, чтобы можно было легко импортировать \"\"\"\n start = time.time()\n log.debug(f'started')\n\n async with aiohttp.ClientSession() as session:\n # установка соединения\n # делаю список ссылок из главной страницы в основной список\n await make_links(url, session)\n\n tasks = []\n for m in main_list:\n # из основного списка, прикрепляю домен к укороченным ссылкам\n # создаю и запускаю таски\n url2 = f'{url}{m}'\n tasks.append(\n asyncio.ensure_future(make_links(url2, session))\n )\n await asyncio.gather(*tasks)\n\n end = time.time()\n log.onprint=True\n log.info(f'work time - {end - start}')\n\nif __name__ == \"__main__\":\n print('This module should be imported. It used in async_main.py')","sub_path":"async_parse.py","file_name":"async_parse.py","file_ext":"py","file_size_in_byte":5276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"136901767","text":"from django.shortcuts import render\n# Create your views here.\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n'''\n \nimport matplotlib.pyplot as plt\nfrom nltk.corpus import twitter_samples\nfrom nltk.tokenize import TweetTokenizer\nimport string\nimport re \nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom random import shuffle\nfrom nltk import classify\nimport nltk.classify\nimport numpy as np\nfrom textblob import TextBlob\nimport re\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import confusion_matrix, classification_report,accuracy_score\nfrom nltk import classify\nfrom sklearn import tree\n\nglobal filename\nglobal pos_tweets, neg_tweets, all_tweets;\npos_tweets_set = []\nneg_tweets_set = []\nglobal classifier\nglobal msg_train, msg_test, label_train, label_test\nglobal svr_acc,random_acc,decision_acc\nglobal test_set ,train_set\n\n\nstopwords_english = stopwords.words('english')\nstemmer = PorterStemmer()\n'''\n##vamsi writings\n#\n#from reviews.trailvm import label_data\n\ndef label_data():\n rows=pd.read_csv('C:/Users/Ganesh vamsi/Desktop/ninc/kfc/owndataset2 - owndataset.csv',header=0,index_col=False,delimiter=',')\n labels=[]\n for cell in rows['stars']:\n if cell>=4:\n labels.append('2')\n elif cell==3:\n labels.append('1')\n else:\n labels.append('0')\n rows['new_labels']=labels\n \n return rows\n\n\n\ndef home(request):\n rows=label_data()\n #y=rows.new_labels\n #X=rows.drop('review',axis=1)\n \n print(rows.head(5))\n X=rows.review\n y=rows.new_labels\n print('X isssss',X)\n print(\"Y issssssssssssssssssss\",y)\n X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=42)\n print('X_test',len(X_test))\n print('Y_train',len(y_train))\n return render(request,'index.html')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'''\nemoticons_happy = set([\n ':-)', ':)', ';)', ':o)', ':]', ':3', ':c)', ':>', '=]', '8)', '=)', ':}',\n ':^)', ':-D', ':D', '8-D', '8D', 'x-D', 'xD', 'X-D', 'XD', '=-D', '=D',\n '=-3', '=3', ':-))', \":'-)\", \":')\", ':*', ':^*', '>:P', ':-P', ':P', 'X-P',\n 'x-p', 'xp', 'XP', ':-p', ':p', '=p', ':-b', ':b', '>:)', '>;)', '>:-)',\n '<3'\n ])\n \n# Sad Emoticons\nemoticons_sad = set([\n ':L', ':-/', '>:/', ':S', '>:[', ':@', ':-(', ':[', ':-||', '=L', ':<',\n ':-[', ':-<', '=\\\\', '=/', '>:(', ':(', '>.<', \":'-(\", \":'(\", ':\\\\', ':-c',\n ':c', ':{', '>:\\\\', ';('\n ])\n\n \n# all emoticons (happy + sad)\nemoticons = emoticons_happy.union(emoticons_sad)\n\ndef clean_tweets(tweet):\n # remove stock market tickers like $GE\n tweet = re.sub(r'\\$\\w*', '', tweet)\n \n # remove old style retweet text \"RT\"\n tweet = re.sub(r'^RT[\\s]+', '', tweet)\n \n # remove hyperlinks\n tweet = re.sub(r'https?:\\/\\/.*[\\r\\n]*', '', tweet)\n \n # remove hashtags\n # only removing the hash # sign from the word\n tweet = re.sub(r'#', '', tweet)\n \n # tokenize tweets\n tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True, reduce_len=True)\n tweet_tokens = tokenizer.tokenize(tweet)\n #word not in emoticons and # remove emoticons ##in line 89\n tweets_clean = [] \n for word in tweet_tokens:\n if (word not in stopwords_english and # remove stopwords\n word not in string.punctuation): # remove punctuation\n #tweets_clean.append(word)\n stem_word = stemmer.stem(word) # stemming word\n tweets_clean.append(stem_word)\n \n return tweets_clean\n\ndef bag_of_words(tweet):\n words = clean_tweets(tweet)\n words_dictionary = dict([word, True] for word in words) \n return words_dictionary\n\ndef text_processing(tweet):\n \n #Generating the list of words in the tweet (hastags and other punctuations removed)\n def form_sentence(tweet):\n tweet_blob = TextBlob(tweet)\n return ' '.join(tweet_blob.words)\n new_tweet = form_sentence(tweet)\n \n #Removing stopwords and words with unusual symbols\n def no_user_alpha(tweet):\n tweet_list = [ele for ele in tweet.split() if ele != 'user']\n clean_tokens = [t for t in tweet_list if re.match(r'[^\\W\\d]*$', t)]\n clean_s = ' '.join(clean_tokens)\n clean_mess = [word for word in clean_s.split() if word.lower() not in stopwords.words('english')]\n return clean_mess\n no_punc_tweet = no_user_alpha(new_tweet)\n \n #Normalizing the words in tweets \n def normalization(tweet_list):\n lem = WordNetLemmatizer()\n normalized_tweet = []\n for word in tweet_list:\n normalized_text = lem.lemmatize(word,'v')\n normalized_tweet.append(normalized_text)\n return normalized_tweet\n \n \n return normalization(no_punc_tweet)\n\ndef upload():\n\n all_tweets = twitter_samples.strings('tweets.20150430-223406.json')\n for tweet in pos_tweets:\n pos_tweets_set.append((bag_of_words(tweet), 'pos'))\n for tweet in neg_tweets:\n neg_tweets_set.append((bag_of_words(tweet), 'neg'))\n \n text.insert(END,\"NLTK Total No Of Tweets Found : \"+str(len(pos_tweets_set)+len(neg_tweets_set))+\"\\n\") \n \ndef readNLTK():\n global msg_train, msg_test, label_train, label_test\n global test_set ,train_set\n \n train_tweets = pd.read_csv('dataset/train_tweets.csv')\n test_tweets = pd.read_csv('dataset/test_tweets.csv')\n \n X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=42)\n train_tweets = train_tweets[['label','tweet']]\n test = test_tweets['tweet']\n train_tweets['tweet_list'] = train_tweets['tweet'].apply(text_processing)\n test_tweets['tweet_list'] = test_tweets['tweet'].apply(text_processing)\n train_tweets[train_tweets['label']==1].drop('tweet',axis=1).head()\n X = train_tweets['tweet']\n y = train_tweets['label']\n test = test_tweets['tweet']\n test_set = pos_tweets_set[:1000] + neg_tweets_set[:1000]\n train_set = pos_tweets_set[1000:] + neg_tweets_set[1000:]\n msg_train, msg_test, label_train, label_test = train_test_split(train_tweets['tweet'], train_tweets['label'], test_size=0.2)\n text.insert(END,\"Training Size : \"+str(len(train_set))+\"\\n\\n\")\n text.insert(END,\"Test Size : \"+str(len(test_set))+\"\\n\\n\") \n\ndef runDecision():\n global decision_acc\n pipeline = Pipeline([\n ('bow',CountVectorizer(analyzer=text_processing)), ('tfidf', TfidfTransformer()), ('classifier', RandomForestClassifier())])\n pipeline.fit(msg_train,label_train)\n predictions = pipeline.predict(msg_test)\n text.delete('1.0', END)\n text.insert(END,\"Decision Tree Accuracy Details\\n\\n\")\n text.insert(END,str(classification_report(predictions,label_test))+\"\\n\")\n decision_acc = accuracy_score(predictions,label_test)\n text.insert(END,\"Decision Tree Accuracy : \"+str(decision_acc)+\"\\n\\n\")\n\ndef detect():\n text.delete('1.0', END)\n filename = filedialog.askopenfilename(initialdir=\"test\")\n test = []\n with open(filename, \"r\") as file:\n for line in file:\n line = line.strip('\\n')\n line = line.strip()\n test.append(line)\n for i in range(len(test)):\n tweet = bag_of_words(test[i])\n result = classifier.classify(tweet)\n prob_result = classifier.prob_classify(tweet)\n negative = prob_result.prob(\"neg\")\n positive = prob_result.prob(\"pos\")\n msg = 'Neutral'\n if positive > negative:\n if positive >= 0.80:\n msg = 'High Positive'\n elif positive > 0.60 and positive < 0.80:\n msg = 'Moderate Positive'\n else:\n msg = 'Neutral'\n else:\n if negative >= 0.80:\n msg = 'High Negative'\n elif positive > 0.60 and positive < 0.80:\n msg = 'Moderate Negative'\n else:\n msg = 'Neutral'\n text.insert(END,test[i]+\" == tweet classified as \"+msg+\"\\n\") \n \n \n\ndef graph():\n height = [decision_acc]\n bars = ('Decision Tree Accuracy')\n y_pos = np.arange(len(bars))\n plt.bar(y_pos, height)\n plt.xticks(y_pos, bars)\n plt.show()\n\n\nfont1 = ('times', 14, 'bold')\nuploadButton = Button(main, text=\"Load NLTK Dataset\", command=upload)\nuploadButton.place(x=50,y=100)\nuploadButton.config(font=font1) \n\nreadButton = Button(main, text=\"Read NLTK Tweets Data\", command=readNLTK)\nreadButton.place(x=50,y=150)\nreadButton.config(font=font1) \n\ndecisionButton = Button(main, text=\"Run Decision Tree Algorithm\", command=runDecision)\ndecisionButton.place(x=50,y=300)\ndecisionButton.config(font=font1)\n\ndetectButton = Button(main, text=\"Detect Sentiment Type\", command=detect)\ndetectButton.place(x=50,y=350)\ndetectButton.config(font=font1)\n\ngraphButton = Button(main, text=\"Accuracy Graph\", command=graph)\ngraphButton.place(x=50,y=400)\ngraphButton.config(font=font1) \n'''","sub_path":"reviews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"259030433","text":"#!/usr/bin/env python3\n\"\"\"\nbuilds an identity block as described in Deep Residual Learning for Image\nRecognition (2015)\nhttps://arxiv.org/pdf/1512.03385.pdf\n\"\"\"\nimport tensorflow.keras as K\n\n\ndef identity_block(A_prev, filters):\n \"\"\"\n builds an identity block as described in Deep Residual Learning for Image\n :param A_prev: the output from the previous layer\n :param filters: a tuple or list containing F11, F3, F12, respectively:\n F11 is the number of filters in the first 1x1 convolution\n F3 is the number of filters in the 3x3 convolution\n F12 is the number of filters in the second 1x1 convolution\n :return: the activated output of the identity block\n \"\"\"\n # left side of the image\n # https://www.dropbox.com/s/ydsblgks4ce2073/\n # Identity%20Block%20resnet.png?dl=0\n F11, F3, F12 = filters\n\n init = K.initializers.he_normal()\n\n # conv2d 1x1 + 1(S)\n conv2d_ = K.layers.Conv2D(\n filters=F11,\n kernel_size=[1, 1],\n kernel_initializer=init,\n padding='same',\n )\n\n conv2d = conv2d_(A_prev)\n\n # batch_normalization\n batch_normalization_ = K.layers.BatchNormalization(\n axis=-1,\n )\n\n batch_normalization = batch_normalization_(conv2d)\n\n # activation layer using relu\n activation_ = K.layers.Activation(\n activation='relu'\n )\n\n activation = activation_(batch_normalization)\n\n # conv 3x3 + 1(S)\n conv2d_1_ = K.layers.Conv2D(\n filters=F3,\n kernel_size=[3, 3],\n kernel_initializer=init,\n padding='same',\n )\n\n conv2d_1 = conv2d_1_(activation)\n\n # batch_normalization\n batch_normalization_1_ = K.layers.BatchNormalization(\n axis=-1,\n )\n\n batch_normalization_1 = batch_normalization_1_(conv2d_1)\n\n # activation layer using relu\n activation_1_ = K.layers.Activation(\n activation='relu'\n )\n\n activation_1 = activation_1_(batch_normalization_1)\n\n # conv 1x1 + 1(S)\n conv2d_2_ = K.layers.Conv2D(\n filters=F12,\n kernel_size=[1, 1],\n kernel_initializer=init,\n padding='same',\n )\n\n conv2d_2 = conv2d_2_(activation_1)\n\n # batch_normalization\n batch_normalization_2_ = K.layers.BatchNormalization(\n axis=-1,\n )\n\n batch_normalization_2 = batch_normalization_2_(conv2d_2)\n\n # Add layer.\n # https://keras.io/api/layers/merging_layers/add/\n add_ = K.layers.Add()\n\n add = add_([batch_normalization_2, A_prev])\n\n # activation layer using relu\n activation_2_ = K.layers.Activation(\n activation='relu'\n )\n\n activation_2 = activation_2_(add)\n\n return activation_2\n","sub_path":"supervised_learning/0x08-deep_cnns/2-identity_block.py","file_name":"2-identity_block.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"346688067","text":"# -*- coding:utf-8 -*-\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport time\n\ncap = cv2.VideoCapture(\"video1.mp4\")\n#cap = cv2.VideoCapture(\"video2.mp4\")\n#cap = cv2.VideoCapture(\"video3.mp4\")\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n\ncoef_angular_positivo = []\ncoef_angular_negativo = []\ncoef_linear_positivo = []\ncoef_linear_negativo = []\n\nmediana_x = 0\nmediana_y = 0\n\nwhile True:\n ret, video = cap.read()\n\n lista_xi = []\n lista_yi = []\n\n x_ponto_fuga = []\n y_ponto_fuga = []\n\n avg_x=0\n avg_y=0\n\n rgb = cv2.cvtColor(video, cv2.COLOR_BGR2RGB)\n gray = cv2.cvtColor(video, cv2.COLOR_BGR2GRAY)\n hsv = cv2.cvtColor(video, cv2.COLOR_BGR2HSV)\n\n edges = cv2.Canny(gray, 50, 150, apertureSize=3)\n\n#====================================================================\n #threshold para o video 1:\n ret, limiarizada = cv2.threshold(gray, 230, 255, cv2.THRESH_BINARY)\n\n#====================================================================\n\n#====================================================================\n #threshold para o video 2:\n #ret, limiarizada = cv2.threshold(gray,240,255,cv2.THRESH_BINARY)\n#====================================================================\n\n#====================================================================\n #threshold para o video 3:\n #ret, limiarizada = cv2.threshold(gray,230,255,cv2.THRESH_BINARY) \n#====================================================================\n lines = cv2.HoughLines(limiarizada,1, np.pi/180, 200)\n\n for line in lines:\n for rho,theta in line:\n m = np.cos(theta)\n b = np.sin(theta)\n \n# time.sleep(0.5)\n\n#====================================================================\n# if para o video 1:\n if 0.7 > m > 0.6:\n coef_angular_positivo.append(m)\n coef_linear_positivo.append(b)\n x0 = m*rho\n y0 = b*rho\n x1 = int(x0 + 1000*(-b))\n y1 = int(y0 + 1000*(m))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(m))\n line = cv2.line(video,(x1,y1),(x2,y2),(0,255,0),3)\n \n elif -0.7 > m > -0.8:\n coef_angular_negativo.append(m)\n coef_linear_negativo.append(b)\n x0 = m*rho\n y0 = b*rho\n x3 = int(x0 + 1000*(-b))\n y3 = int(y0 + 1000*(m))\n x4 = int(x0 - 1000*(-b))\n y4 = int(y0 - 1000*(m))\n line = cv2.line(video,(x3,y3),(x4,y4),(0,255,0),3)\n \n try:\n h1 = coef_linear_positivo[len(coef_linear_positivo)-1]\n m1 = coef_angular_positivo[len(coef_angular_positivo)-1]\n\n h2 = coef_linear_negativo[len(coef_linear_negativo)-1]\n m2 = coef_angular_negativo[len(coef_angular_negativo)-1]\n \n xi = ((x1*y2 - y1*x2)*(x3 - x4) - (x1-x2)*(x3*y4 - y3*x4))/((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4))#((h2-h1)/(m1-m2))\n yi = ((x1*y2 - y1*x2)*(y3 - y4) - (y1-y2)*(x3*y4 - y3*x4))/((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4))#(m1*xi) + h1\n\n lista_xi.append(xi)\n lista_yi.append(yi)\n\n x_ponto_fuga.append(xi)\n y_ponto_fuga.append(yi)\n \n except:\n pass\n else:\n pass\n\n\n try:\n avg_x = int(np.mean(x_ponto_fuga))\n avg_y = int(np.mean(y_ponto_fuga))\n cv2.circle(video, (avg_x,avg_y), 3, (255,0,0), 5)\n except:\n pass\n cv2.imshow('video', video)\n# cv2.imshow('mask', mask)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n\n\n# termo_xi = int(np.round(len(lista_xi)/2))\n# termo_yi = int(np.round(len(lista_yi)/2))\n\n# print(termo_yi)\n# print(termo_xi)\n \n# print(termo_xi)\n# print(termo_yi)\n# for i in lista_xi:\n# print(lista_xi[int(np.mean(len(lista_xi)))])\n# print(lista_xi[termo_xi])\n# print(lista_yi[termo_yi])\n\n# xi = lista_xi[termo_xi]\n# yi = lista_yi[termo_yi]\n# print(lista_xi[termo_xi])\n# print(lista_yi[termo_yi])\n\n# print(xi)\n# print(yi)\n\n#====================================================================\n# if para o video 2:\n #if 0.05 < m < 0.2 or -0.05> m > -0.2: \n # print(m)\n # x0 = m*rho\n # y0 = b*rho\n # x1 = int(x0 + 1000*(-b))\n # y1 = int(y0 + 1000*(m))\n # x2 = int(x0 - 1000*(-b))\n # y2 = int(y0 - 1000*(m))\n # cv2.line(video,(x1,y1),(x2,y2),(0,255,0),10)\n #else:\n # pass\n\n#====================================================================\n\n#================================== VIDEO 3 NAO ESTÁ DANDO MUITO CERTO (REVER) ==========================================\n\n# if para o video 3:\n #if 0.6 < m < 0.7 or 0.75 < m < 0.78:\n # print(m)\n # x0 = m*rho\n # y0 = b*rho\n # x1 = int(x0 + 1000*(-b))\n # y1 = int(y0 + 1000*(m))\n # x2 = int(x0 - 1000*(-b))\n # y2 = int(y0 - 1000*(m))\n # cv2.line(video,(x1,y1),(x2,y2),(0,255,0),10)\n #else:\n # pass\n\n# lower_white = np.array([0, 0, 150])\n# higher_white = np.array([255, 30, 255])\n\n# mask = cv2.inRange(hsv, lower_white, higher_white)\n #cv2.imshow('threshold', video)","sub_path":"Atividades_Robot/AT3-Feito/atividade3.py","file_name":"atividade3.py","file_ext":"py","file_size_in_byte":5949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"527647448","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2018/6/11 21:23\n# @Author : merlinhuang\n# @File : daemon_random.py\n\n\n\"\"\"\nrandom模块用于生成伪随机数\n\"\"\"\nimport random\n\n#### 基本方法\n\n# 初始化随机数生成器。如果未提供a或者a=None,则使用系统时间为种子。如果a是一个整数,则作为新的种子。\n# random.seed(a=None, version=2)\n\n# 返回当前生成器的内部状态\n# random.getstate()\n\n# 传入一个先前利用getstate方法获得的状态对象,使得生成器恢复到这个状态。\n# random.setstate(state)\n\n# 返回一个不大于 2**K 的Python整数(十进制),比如k = 10,则结果是0 ~ 2^10之间的整数。\n# random.getrandbits(k)\nprint(random.getrandbits(2))\n\n\n#### 针对整数的方法\n\n# [0, stop) 内的一个整数\n# random.randrange(stop)\nprint(random.randrange(10))\n# range的范围内随机选择一个整数,前开后闭\n# random.randrange(start, stop[, step])\nprint(random.randrange(2, 101, 2)) # 2 - 100的偶数\n\n# 返回一个a <= N <= b的随机整数N, 等同于randrange(a, b+1)\n# random.randint(a, b)\nprint(random.randint(1, 4))\n\n\n#### 针对序列类型的方法\n\n# 从非空序列seq中随机选取一个元素. 如果seq为空则弹出IndexError异常.\n# random.choice(seq)\nseq1 = [1, 3, 5, 7, 9]\nprint(random.choice(seq1))\nstring = ['win', 'lose', 'draw']\nprint(random.choice(string))\n\n# 3.6版本新增, 从population集群中随机抽取K个元素。weights是相对权重列表,cum_weights是累计权重,两个参数不能同时存在。\n# random.choices(population, weights=None, *, cum_weights=None, k=1)\n\n\n# 随机打乱序列x内元素的排列顺序,俗称“洗牌”。只能用于可变的序列\n# random.shuffle(x[, random])\nseq2 = [1, 3, 5, 7, 9]\nrandom.shuffle(seq2)\nprint(seq2)\n\n# 从population样本或集合中随机抽取K个不重复的元素形成新的序列。常用于不重复的随机抽样。返回的是一个新的序列,不会破坏原有序列,\n# 如果k大于population的长度,则弹出ValueError异常。\n# random.sample(population, k)\nseq3 = (1, 3, 5, 7, 9, 1, 3, 4)\nseq4 = random.sample(seq3, 6)\nprint(seq4)\nprint(seq3)\n\nseq5 = random.sample(range(10000), k=10)\nprint(seq5)\n\n\n#### 真值分布\n\n# 返回一个介于左闭右开[0.0, 1.0)区间的浮点数\n# random.random()\nprint(random.random())\nprint(random.random())\n\n# 返回一个介于a和b之间的浮点数x, a =< x < b。如果a>b,则是b到a之间的浮点数。这里的a和b都有可能出现在结果中\n# random.uniform(a, b)\nprint(random.uniform(1.0, 1.1))\nprint(random.uniform(3, 1))\n\n\n# 返回一个low <= N <=high的三角形分布的随机数。参数mode指明众数出现位置\n# random.triangular(low, high, mode)\n\n# β分布。返回的结果在0~1之间。\n# random.betavariate(alpha, beta)\n\n\n# 指数分布\n# random.expovariate(lambd)\n\n# 伽马分布\n# random.gammavariate(alpha, beta)\n\n# 高斯分布\n# random.gauss(mu, sigma)\n\n\n# 对数正态分布\n# random.lognormvariate(mu, sigma)\n\n\n# 正态分布\n# random.normalvariate(mu, sigma)\n\n# 卡帕分布\n# random.vonmisesvariate(mu, kappa)\n\n# 帕累托分布\n# random.paretovariate(alpha)\n\n\n# 可选择的生成器\n# class random.SystemRandom([seed])\n# 使用os.urandom()方法生成随机数的类,由操作系统提供源码,不一定所有系统都支持\n\n\n# 生成一个包含大写字母A-Z和数字0-9的随机4位验证码的程序\nimport random\n\ncheckcode = ''\n# 4个长度\nfor i in range(4):\n current = random.randrange(0, 4)\n # 取字母,3/4概率\n if current != i:\n # 65 - 90 对应A-Z\n # temp = chr(random.randint(65,90))\n # 97 - 122 对应a-z\n temp = chr(random.randint(97, 122))\n # 取数字,1/4概率\n else:\n temp = random.randint(0, 9)\n checkcode += str(temp)\nprint(checkcode)\n\n\n# 生成指定长度字母数字随机序列的代码\n\nimport random, string\n\ndef gen_random_string(length):\n # 数字的个数随机产生\n num_of_numeric = random.randint(1,length-1)\n # 剩下的都是字母\n num_of_letter = length - num_of_numeric\n # 随机生成数字,循环项: random.choice(string.digits)\n numerics = [random.choice(string.digits) for i in range(num_of_numeric)]\n print(numerics)\n # 随机生成字母,循环项: random.choice(string.ascii_letters)\n letters = [random.choice(string.ascii_letters) for i in range(num_of_letter)]\n print(letters)\n # 结合两者\n all_chars = numerics + letters\n # 洗牌\n random.shuffle(all_chars)\n # 生成最终字符串\n result = ''.join([i for i in all_chars])\n return result\n\nif __name__ == '__main__':\n print(gen_random_string(18))","sub_path":"venv/python_package/daemon_random.py","file_name":"daemon_random.py","file_ext":"py","file_size_in_byte":4693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"33196888","text":"import logging\n\nfrom ingestors.base import Ingestor\n\nlog = logging.getLogger(__name__)\n\n\nclass IgnoreIngestor(Ingestor):\n MIME_TYPES = [\n 'application/x-pkcs7-mime',\n 'application/pkcs7-mime',\n 'application/pkcs7-signature',\n 'application/x-pkcs7-signature'\n ]\n EXTENSIONS = [\n 'json',\n 'yml',\n 'yaml',\n 'exe',\n 'dll',\n 'ini',\n 'class',\n 'psd', # adobe photoshop\n 'indd', # adobe indesign\n 'sql',\n 'avi',\n 'mpg',\n 'mpeg',\n 'mkv',\n 'dat',\n 'log',\n 'pbl',\n 'p7m',\n ]\n NAMES = [\n '.DS_Store',\n 'Thumbs.db',\n '.gitignore'\n ]\n SCORE = 2\n\n def ingest(self, file_path):\n log.info(\"[%s] will be ignored but stored.\", self.result)\n\n @classmethod\n def match(cls, file_path, result=None):\n if result.file_name in cls.NAMES:\n return cls.SCORE\n return super(IgnoreIngestor, cls).match(file_path, result=result)\n","sub_path":"ingestors/ignore.py","file_name":"ignore.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"371030734","text":"#!/usr/bin/python3\n\nimport sys\nimport os\nimport re\nimport glob\n\ncodonDict = {\"F\" : \"TTC\",\n \"L\" : \"CTG\",\n \"I\" : \"ATC\",\n \"M\" : \"ATG\",\n \"V\" : \"GTG\",\n \"S\" : \"AGC\",\n \"P\" : \"CCC\",\n \"T\" : \"ACC\",\n \"A\" : \"GCC\",\n \"Y\" : \"TAC\",\n \"*\" : \"TGA\",\n \"H\" : \"CAC\",\n \"Q\" : \"CAG\",\n \"N\" : \"AAC\",\n \"K\" : \"AAG\",\n \"D\" : \"GAC\",\n \"E\" : \"GAG\",\n \"C\" : \"TGC\",\n \"W\" : \"TGG\",\n \"R\" : \"AGA\",\n \"G\" : \"GGC\",\n \"X\" : \"NNN\",\n \"U\" : \"NNN\"\n}\n\nprint(len(codonDict))\n \noutDir = \"nucleotide_fastas\"\n\nif not os.path.isdir(outDir):\n os.makedirs(outDir)\n\nIDPattern = re.compile(\"^>.+$\")\nseqPattern = re.compile(\"^[^>][A-Z*-]+$\")\n \nfor inFasta in glob.glob(\"./*_orthologues.fa\"):\n inFasta = os.path.basename(inFasta)\n print(inFasta)\n protFasta = open(inFasta, \"r\")\n nucFasta = open(\"{}/{}\".format(outDir, inFasta), \"w\")\n for idx, line in enumerate(protFasta):\n print(idx)\n line = line.rstrip()\n if IDPattern.match(line):\n sequence = protFasta.readline().rstrip()\n if not seqPattern.match(sequence):\n print(sequence)\n sys.exit(\"Error, sequence not in expected format\")\n nucleotide = \"\"\n for aminoAcid in sequence:\n if not aminoAcid in codonDict:\n print(aminoAcid)\n sys.exit(\"Error, unknown amino acid\")\n codon = codonDict[aminoAcid]\n nucleotide = nucleotide + codon\n nucFasta.write(line + \"\\n\")\n nucFasta.write(nucleotide + \"\\n\")\n elif seqPattern.match(line):\n print(line)\n sys.exit(\"Error, sequence should not match here\")\n else:\n print(line)\n sys.exit(\"Line in unexpected format\")\n protFasta.close()\n nucFasta.close()\n","sub_path":"reverse_translate.py","file_name":"reverse_translate.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"115978227","text":"file = open('data.txt', 'r')\nv = file.read()\n\nreplac_symbols = [\",\", \"-\", \".\"]\nfor x in replac_symbols:\n v = v.replace(x, \" \")\n\nv = v.split()\n\nz_words = []\nz_count = []\nz = 0\n\nfor word in v:\n word_exists = [x == word for x in z_words]\n if sum(word_exists) == 0:\n z_words.append(word)\n z_count.append(1)\n z += 1\n else:\n el = -1\n for k in range(z):\n if z_words[k]:\n el = k\n \n if el > -1:\n z_count[el] += 1\n\nfor x in range(z):\n \"{} ({})\".format(z_words[x], z_count[x])\n\nfile.close()","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"137756275","text":"import numpy as np\nimport array\nimport itertools\nimport sys\nimport pysam\nimport argparse\nfrom collections import Counter\n\nfrom . import utilities\nfrom . import fastq\nfrom . import fasta\nfrom . import adapters\nfrom . import annotation\nfrom . import sam\nfrom .sw_cython import *\n\nempty_alignment = {\n 'score': -1e6,\n 'path': [],\n 'query_mappings': [],\n 'target_mappings': [],\n 'insertions': set(),\n 'deletions': set(),\n 'mismatches': set(),\n}\n\ndef first_query_index(alignment_path):\n for q, t in alignment_path:\n if q != GAP:\n return q\n\n return None\n\ndef first_target_index(alignment_path):\n for q, t in alignment_path:\n if t != GAP:\n return t\n\n return None\n\ndef last_query_index(alignment_path):\n for q, t in alignment_path[::-1]:\n if q != GAP:\n return q\n\n return None\n\ndef last_target_index(alignment_path):\n for q, t in alignment_path[::-1]:\n if t != GAP:\n return t\n\n return None\n\ndef last_n_query_pairs(alignment_path, n):\n ''' Returns (q, t) pairs for the last n elements of alignment_path for which\n q is not a gap.\n '''\n pairs = []\n\n for q, t in alignment_path[::-1]:\n if q != GAP:\n pairs.append((q, t))\n if len(pairs) == n:\n break\n \n pairs = pairs[::-1]\n\n return pairs\n\ndef make_char_pairs(index_pairs, query, target):\n char_pairs = []\n for q, t in index_pairs:\n if q == GAP:\n q_char = '-'\n else:\n q_char = query[q]\n if t == GAP:\n t_char = '-'\n else:\n t_char = target[t]\n char_pairs.append((q_char, t_char))\n return char_pairs\n\ndef print_local_alignment(alignment, fh=sys.stdout):\n query = alignment['query']\n target = alignment['target']\n path = alignment['path']\n if path == []:\n fh.write('{0}\\n\\n{1}\\n'.format(query, target))\n return\n\n def index_to_char(seq, index):\n if index == GAP:\n return '-'\n else:\n if index >= len(seq):\n raise ValueError(index, len(seq), seq)\n return seq[index]\n \n first_q = first_query_index(path)\n first_t = first_target_index(path)\n last_q = last_query_index(path)\n last_t = last_target_index(path)\n\n left_query = query[:first_q]\n left_target = target[:first_t]\n right_query = query[last_q + 1:]\n right_target = target[last_t + 1:]\n\n left_length = max(first_q, first_t)\n left_query = '{:>{length}s} '.format(left_query, length=left_length)\n left_target = '{:>{length}s} '.format(left_target, length=left_length)\n \n query_string = [left_query]\n target_string = [left_target]\n\n for q, t in path:\n query_string.append(index_to_char(query, q))\n target_string.append(index_to_char(target, t))\n\n query_string.extend([' ', right_query])\n target_string.extend([' ', right_target])\n\n fh.write('query\\t{0}\\n'.format(''.join(query_string)))\n fh.write('target\\t{0}\\n'.format(''.join(target_string)))\n\ntrimmed_annotation_fields = [\n ('original_name', 's'),\n ('insert_length', '04d'),\n ('adapter_seq', 's'),\n ('adapter_qual', 's'),\n]\n\nTrimmedAnnotation = annotation.Annotation_factory(trimmed_annotation_fields)\nNO_DETECTED_OVERLAP = -2\n\ndef generate_alignments(query,\n target,\n alignment_type,\n match_bonus=2,\n mismatch_penalty=-1,\n indel_penalty=-5,\n max_alignments=1,\n min_score=-np.inf,\n ):\n if alignment_type == 'local':\n force_query_start = False\n force_target_start = False\n force_either_start = False\n force_edge_end = False\n elif alignment_type == 'barcode':\n force_query_start = True\n force_target_start = True\n force_either_start = False\n force_edge_end = True\n elif alignment_type == 'overlap':\n force_query_start = False\n force_target_start = False\n force_either_start = True\n force_edge_end = True\n elif alignment_type == 'unpaired_adapter':\n force_query_start = True\n force_target_start = False\n force_either_start = False\n force_edge_end = True\n elif alignment_type == 'IVT':\n force_query_start = True\n force_target_start = False\n force_either_start = False\n force_edge_end = False\n elif alignment_type == 'global':\n force_query_start = True\n force_target_start = True\n force_either_start = False\n force_edge_end = True\n\n query_bytes = query.encode()\n target_bytes = target.encode()\n\n matrices = generate_matrices(query_bytes,\n target_bytes,\n match_bonus,\n mismatch_penalty,\n indel_penalty,\n force_query_start,\n force_target_start,\n force_either_start,\n )\n cells_seen = set()\n if force_edge_end:\n possible_ends = propose_edge_ends(matrices['scores'], cells_seen, min_score, max_alignments=max_alignments)\n else:\n possible_ends = propose_all_ends(matrices['scores'], cells_seen, min_score)\n\n alignments = []\n for end_row, end_col in possible_ends:\n alignment = backtrack_cython(query_bytes,\n target_bytes,\n matrices,\n cells_seen,\n end_row,\n end_col,\n force_query_start,\n force_target_start,\n force_either_start,\n )\n if alignment != None:\n alignment['query'] = query\n alignment['target'] = target\n alignments.append(alignment)\n if len(alignments) == max_alignments:\n break\n else:\n pass\n\n return alignments\n\ndef propose_edge_ends(score_matrix,\n cells_seen,\n min_score=None,\n max_alignments=1,\n ):\n num_rows, num_cols = score_matrix.shape\n if max_alignments == 1:\n max_row = np.argmax(score_matrix[:, num_cols - 1])\n max_row_score = score_matrix[max_row, num_cols -1]\n max_col = np.argmax(score_matrix[num_rows - 1, :])\n max_col_score = score_matrix[num_rows - 1, max_col]\n if max_row_score > max_col_score:\n sorted_edge_cells = [(max_row, num_cols - 1)]\n else:\n sorted_edge_cells = [(num_rows - 1, max_col)]\n else:\n right_edge = [(i, num_cols - 1) for i in range(num_rows)]\n # Note: range(num_cols - 1) prevents including the corner twice\n bottom_edge = [(num_rows - 1, i) for i in range(num_cols - 1)]\n edge_cells = right_edge + bottom_edge\n sorted_edge_cells = sorted(edge_cells,\n key=lambda cell: score_matrix[cell],\n reverse=True,\n )\n for cell in sorted_edge_cells:\n if min_score != None and score_matrix[cell] < min_score:\n break\n\n if cell in cells_seen:\n continue\n\n yield cell\n\ndef propose_all_ends(score_matrix, cells_seen, min_score):\n sorted_indices = score_matrix.ravel().argsort()[::-1]\n for index in sorted_indices:\n cell = np.unravel_index(index, score_matrix.shape)\n\n try:\n if score_matrix[cell] < min_score:\n break\n except TypeError:\n print(score_matrix[cell], min_score)\n raise\n\n if cell in cells_seen:\n continue\n\n yield cell\n\ndef global_alignment(query, target, **kwargs):\n al, = generate_alignments(query, target, 'global', **kwargs)\n return al\n\ndef infer_insert_length(R1, R2, before_R1, before_R2, solid=False):\n ''' Infer the length of the insert represented by R1 and R2 by performing\n a semi-local alignment of R1 and the reverse complement of R2 with\n the expected adapter sequences prepended to each read.\n '''\n extended_R1 = before_R1 + R1.seq\n extended_R2 = utilities.reverse_complement(before_R2 + R2.seq)\n alignment, = generate_alignments(extended_R1,\n extended_R2, \n 'overlap',\n 2,\n -1,\n -5,\n 1,\n 0,\n )\n #print_local_alignment(extended_R1, extended_R2, alignment['path'])\n\n R1_start = len(before_R1)\n R2_start = len(R2.seq) - 1\n R1_start_in_R2 = alignment['query_mappings'][len(before_R1)]\n R2_start_in_R1 = alignment['target_mappings'][len(R2.seq) - 1]\n \n # Since R1 is the query and R2 is the target, bases in R1 that aren't in\n # R2 are called insertions, and bases in R2 that aren't in R1 are called\n # deletions.\n # An indel in the insert is non-physical.\n if R2_start_in_R1 != SOFT_CLIPPED:\n illegal_insertion = any(R1_start <= i <= R2_start_in_R1 for i in alignment['insertions'])\n else:\n illegal_insertion = any(R1_start <= i for i in alignment['insertions'])\n\n if R1_start_in_R2 != SOFT_CLIPPED:\n illegal_deletion = any(R1_start_in_R2 <= d <= R2_start for d in alignment['deletions'])\n else:\n illegal_deletion = any(d <= R2_start for d in alignment['deletions'])\n \n if illegal_insertion or illegal_deletion:\n return 'illegal', 500, -1\n\n if len(alignment['path']) == 0:\n return 'illegal', 500, -1\n\n if R1_start_in_R2 != SOFT_CLIPPED and R2_start_in_R1 != SOFT_CLIPPED:\n length_from_R1 = R2_start_in_R1 - R1_start + 1\n length_from_R2 = R2_start - R1_start_in_R2 + 1\n else:\n # overlap alignment forces the alignment to start with either the\n # beginning of R1 or R2 and end with either the end of R1 or R2. \n # Making it to this else branch means that either the first base of R1 or\n # the first base of R2 or both wasn't aligned. This either means that\n # the insert is longer than the read length or a pathological alignment\n # has been produced in which only adapter bases are involved in the \n # alignment. Flag the second case as illegal.\n\n try:\n first_R1_index, first_R2_index = alignment['path'][0]\n except IndexError:\n print(R1)\n print(R2)\n print(alignment)\n raise\n length_from_R1 = (first_R1_index - R1_start + 1) + (len(R2.seq) - 1)\n\n last_R1_index, last_R2_index = alignment['path'][-1]\n length_from_R2 = (R2_start - last_R2_index + 1) + (len(R1.seq) - 1)\n \n if first_R1_index == 0 or last_R2_index == 0:\n return 'illegal', 500, -1 \n\n if length_from_R1 < -1 or length_from_R2 < -1:\n # Negative insert lengths are non-physical. Even though I don't\n # understand it, -1 is relatively common so is tolerated.\n return 'illegal', 500, -1\n\n insert_length = length_from_R1\n\n if 2 * len(alignment['path']) - alignment['score'] > .2 * len(alignment['path']):\n status = 'bad'\n else:\n status = 'good'\n \n if status == 'good' and (length_from_R1 != length_from_R2):\n if solid and not(alignment['insertions'] or alignment['deletions']):\n pass\n else:\n # This shouldn't be possible without an illegal indel.\n #print('length from R1', length_from_R1)\n #print('length from R2', length_from_R2)\n #print(diagnostic(R1, R2, before_R1, before_R2, alignment)\n return 'illegal', 500, -1\n \n #print_diagnostic(R1, R2, before_R1, before_R2, alignment)\n\n return status, insert_length, alignment\n\ndef print_diagnostic(R1, R2, before_R1, before_R2, alignment, fh=sys.stdout):\n extended_R1 = (before_R1.lower() + R1.seq).decode()\n extended_R2 = (utilities.reverse_complement(before_R2.lower() + R2.seq)).decode()\n #fh.write(R1.name + '\\n')\n #fh.write(R1.qual + '\\n')\n #fh.write(R2.qual + '\\n')\n #fh.write('{0}\\t{1}\\t{2}\\n'.format(alignment['score'], len(alignment['path']) * .2, alignment['score'] - len(alignment['path']) * 2))\n #fh.write(str(alignment['path']) + '\\n')\n print_local_alignment(extended_R1, extended_R2, alignment['path'], fh=fh)\n #fh.write(str(alignment['insertions']) + '\\n')\n #fh.write(str(alignment['deletions']) + '\\n')\n #fh.write(str(sorted(alignment['mismatches'])) + '\\n')\n #for q, t in sorted(alignment['mismatches']):\n # fh.write('\\t{0}\\t{1}\\n'.format(extended_R1[q], extended_R2[t]))\n\ndef align_read(read, targets, alignment_type, min_path_length, max_alignments=1):\n alignments = []\n\n for r, is_reverse in ((read, False),\n (read.reverse_complement(), True),\n ):\n seq = r.seq\n qual = r.qual\n\n qual = array.array('B', fastq.decode_sanger(qual))\n\n for i, (target_name, target_seq) in enumerate(targets):\n for alignment in generate_alignments(seq, target_seq, alignment_type, max_alignments=max_alignments):\n path = alignment['path']\n\n if len(path) >= min_path_length and alignment['score'] / (2. * len(path)) > 0.8:\n al = pysam.AlignedSegment()\n al.seq = seq\n al.query_qualities = qual\n al.is_reverse = is_reverse\n\n char_pairs = make_char_pairs(path, seq, target_seq)\n\n cigar = sam.aligned_pairs_to_cigar(char_pairs)\n clip_from_start = first_query_index(path)\n if clip_from_start > 0:\n cigar = [(sam.BAM_CSOFT_CLIP, clip_from_start)] + cigar\n clip_from_end = len(seq) - 1 - last_query_index(path)\n if clip_from_end > 0:\n cigar = cigar + [(sam.BAM_CSOFT_CLIP, clip_from_end)]\n al.cigar = cigar\n \n if al.query_length != al.infer_query_length():\n raise ValueError('CIGAR implies different query length - {0}: {1}, {2}'.format(al.query_name, al.query_length, al.infer_query_length()))\n\n read_aligned, ref_aligned = zip(*char_pairs)\n md = sam.alignment_to_MD_string(ref_aligned, read_aligned)\n al.set_tag('MD', md)\n\n al.set_tag('AS', alignment['score'])\n al.tid = i\n al.query_name = read.name\n al.next_reference_id = -1\n al.reference_start = first_target_index(path)\n\n \n alignments.append(al)\n\n return alignments\n\ndef align_reads(target_fasta_fn,\n reads,\n bam_fn,\n min_path_length=15,\n error_fn='/dev/null',\n alignment_type='overlap',\n ):\n ''' Aligns reads to targets in target_fasta_fn by Smith-Waterman, storing\n alignments in bam_fn and yielding unaligned reads.\n '''\n targets_dict = {r.name: r.seq for r in fasta.reads(target_fasta_fn)}\n targets = sorted(targets_dict.items())\n\n names = [name for name, seq in targets]\n lengths = [len(seq) for name, seq in targets]\n header = pysam.AlignmentHeader.from_references(names, lengths)\n alignment_sorter = sam.AlignmentSorter(bam_fn, header)\n\n statistics = Counter()\n \n with alignment_sorter:\n for read in reads:\n statistics['input'] += 1\n\n alignments = align_read(read, targets, alignment_type, min_path_length)\n \n if alignments:\n statistics['aligned'] += 1\n\n sorted_alignments = sorted(alignments, key=lambda m: m.get_tag('AS'), reverse=True)\n grouped = utilities.group_by(sorted_alignments, key=lambda m: m.get_tag('AS'))\n _, highest_group = next(grouped)\n primary_already_assigned = False\n for alignment in highest_group:\n if len(highest_group) == 1:\n alignment.mapping_quality = 2\n else:\n alignment.mapping_quality = 1\n\n if not primary_already_assigned:\n primary_already_assigned = True\n else:\n alignment.is_secondary = True\n\n alignment_sorter.write(alignment)\n else:\n statistics['unaligned'] += 1\n\n yield read\n\n with open(error_fn, 'w') as error_fh:\n for key in ['input', 'aligned', 'unaligned']:\n error_fh.write('{0}: {1:,}\\n'.format(key, statistics[key]))\n\ndef stitch_read_pair(R1, R2, before_R1='', before_R2=''): \n status, insert_length, alignment = infer_insert_length(R1, R2, before_R1, before_R2)\n R2_rc = R2.reverse_complement()\n\n overlap_start = max(0, insert_length - len(R1))\n just_R1 = R1[:overlap_start]\n overlap_R1 = R1[overlap_start:insert_length]\n\n overlap_start = max(0, len(R2) - insert_length)\n overlap_R2 = R2_rc[overlap_start:overlap_start + len(overlap_R1)]\n just_R2 = R2_rc[overlap_start + len(overlap_R1):]\n\n overlap_seq = []\n overlap_qual = []\n for R1_s, R1_q, R2_s, R2_q in zip(overlap_R1.seq,\n overlap_R1.qual,\n overlap_R2.seq,\n overlap_R2.qual,\n ):\n if R1_q > R2_q:\n s, q = R1_s, R1_q\n else:\n s, q = R2_s, R2_q\n\n overlap_seq.append(s)\n overlap_qual.append(q)\n\n overlap = fastq.Read('', ''.join(overlap_seq), ''.join(overlap_qual))\n\n stitched = just_R1 + overlap + just_R2\n return stitched\n","sub_path":"Cassiopeia/ProcessingPipeline/process/sequencing/sw.py","file_name":"sw.py","file_ext":"py","file_size_in_byte":18383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"12672674","text":"#coding:utf-8\n\n'''\nCreated on 2018年4月5日\n\n@author: win7\n'''\nimport cognitive_face as CF\nimport os\n\ndef run_main():\n key = '762e85b7f4c24c4b81f7b7f60211a31a'\n CF.Key.set(key)\n image_path = './images/big-bang-theory-group.jpg'\n face_list = CF.face.detect(image_path)\n print(face_list)\n print('检测出{}张人脸'.format(len(face_list)))\n return ''\n \n\n\nif __name__ == '__main__':\n run_main()","sub_path":"计算机视觉/imagebasic/image008.py","file_name":"image008.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"565037886","text":"from django.conf.urls import url\nfrom mathtutor import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'mathtutor/registration/login.html'}, name=\"login\"),\n url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/'}, name=\"logout\"),\n url(r'^noaccess/$', views.noaccess, name='noaccess'),\n url(r'^accounts/profile/$', views.parent_survey, name=\"info\"),\n url(r'^accounts/grid/$', views.dashboard, name='dashboard'),\n url(r'^post-surveys/$', views.post_surveys, name=\"post_surveys\"),\n url(r'^lore/(?P[a-z]*)/$', views.quiz_or_practice, name=\"quiz_or_practice\"),\n url(r'^(?P[a-z]*)/quizes/$', views.list_quizes, name=\"list_quizes\"),\n url(r'^learn/(?P[a-z]*)/(?P[a-z]*)/$', views.practice, name=\"practice\"),\n url(r'^learn/(?P[a-z]*)/(?P[a-z]*)/(?P\\d+)/$', views.practice, name=\"practice_item\"),\n url(r'^(?P\\d+)/glossary/$', views.glossary, name=\"glossary\"),\n url(r'^glossary-item/(?P\\d+)/$', views.glossary, name=\"glossary_item\"),\n]\n\n\n\n","sub_path":"mathtutor/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"528641770","text":"\n\n\nfrom TextScrape.PrinceRevolution.Scrape import Scrape\n\nimport ScrapePlugins.RunBase\n\n\nclass Runner(ScrapePlugins.RunBase.ScraperBase):\n\tloggerPath = \"Main.PrRev.Run\"\n\n\tpluginName = \"PRevScrape\"\n\n\n\tdef _go(self):\n\n\t\tself.log.info(\"Checking Prince Revolution for updates\")\n\t\tscraper = Scrape()\n\t\tscraper.crawl()\n\n\ndef test():\n\timport logSetup\n\tlogSetup.initLogging()\n\tscrp = Runner()\n\tscrp.go()\n\t# scrp.retreiveItemFromUrl(scrp.startUrl)\n\t# new = gdp.GDocExtractor.getDriveFileUrls('https://drive.google.com/folderview?id=0B-x_RxmzDHegRk5iblp4alZmSkU&usp=sharing')\n\n\nif __name__ == \"__main__\":\n\ttest()\n\n","sub_path":"TextScrape/PrinceRevolution/Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"262445334","text":"#programa que pida una nota al usuario\n#la muestra 7 veces en pantalla\n#Declaracion\nnota=0\n\n#input\nnota=input(\"introduce una nota:\")\n\nfor i in range(7):\n print(nota)\n#fin_for\n","sub_path":"DAMIAN_COLOMA/rango4.py","file_name":"rango4.py","file_ext":"py","file_size_in_byte":179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"264266796","text":"# Copyright (c) 2021-2021 Björn Andersson \n# Copyright (c) 2021-2021 Sundarrajan Gopalakrishnan <>\n#\n# This work is licensed under the MIT license, see the file LICENSE for details.\n\nimport json, rpc, struct, math, time,sys, traceback,string,ast\nimport numpy as np\nfrom scipy.spatial import distance as dist\nfrom matplotlib import pyplot as plt\nimport plotille\nfrom mirobot import Mirobot\n\nclass remote_control():\n '''\n A class to execute remote procedure calls\n \n ...\n\n Attributes\n ----------\n CAMERA_ONE_PORT : str\n portname for camera one\n CAMERA_TWO_PORT : str\n portname for camera two\n MIROBOT_ONE_PORT : str\n portname for mirobot one\n MIROBOT_TWO_PORT : str\n portname for mirobot two\n prev_cx : list (float)\n List containing cx values for all readings, used for stabalizing data.\n prev_cy : list (float)\n List containing cy values for all readings, used for stabalizing data.\n prev_area : list (int)\n List containing blob area values for all readings, used for stabalizing data.\n prev_rotation_angle : list (float)\n List containing blob rotation for all readings, used for stabalizing data.\n color : list (string)\n List containing string representation of all the blobs.\n is_cube_list: list (bool)\n List containing information if the blob is a cube or a domino.\n True if a cube, False if a domino.\n april_tags : dict\n Dictionary containing data about the april tags, recieved by the OpenMV.\n mirobot_one_timer : (time.time() / 60)\n time in minutes since epoch\n mirobot_two_timer : (time.time() / 60 ) \n time in minutes since epoch\n HOMING_TIMEOUT : (int) \n sets time in minutes until the robot needs to be homed again.\n '''\n def __init__(self):\n self.CAMERA_ONE_PORT = \"/dev/ttyACM_OpenMV1\"\n self.CAMERA_TWO_PORT = \"/dev/ttyACM_OpenMV2\"\n self.MIROBOT_ONE_PORT = \"/dev/ttyUSB_Mirobot1\"\n self.MIROBOT_TWO_PORT = \"/dev/ttyUSB_Mirobot2\"\n self.MIROBOT_ONE_TIMER_LOG = \"/home/pi/mirobot/timers/mirobot_one_timer.txt\"\n self.MIROBOT_TWO_TIMER_LOG = \"/home/pi/mirobot/timers/mirobot_two_timer.txt\"\n self.HOMING_TIMEOUT = 10 # Change this to appropiate timing\n self.prev_cx = [-1] * 25\n self.prev_cy = [-1] * 25\n self.prev_area = [-1] * 25\n self.prev_rotation_angle = [-1] * 25\n self.color = []\n self.is_cube_list = []\n self.april_tags = {}\n\n\n def get_camera(self, port):\n '''Returns the rpc interface representing the openMV camera connected to the port.\n \n Paramters\n ----------\n port (str): a string representation of the port connected to the camera\n \n Returns\n ----------\n interface (rpc.rpc_usb_vcp_master): Interface to interact with openMV\n '''\n return rpc.rpc_usb_vcp_master(port)\n\n def exe_get_data(self, interface):\n '''\n Called from fill_data().\n Makes a remote call to the OpenMV to get data from the image processing.\n Stores the april tags data in the and updates the list of values.\n\n Parameters\n ----------\n interface (rpc.rpc_usb_vcp_master): Interface to interact with openMV\n\n Returns\n ----------\n None\n \n '''\n try:\n result = interface.call(\"get_data\", send_timeout=10000, recv_timeout=10000) \n\n if result is not None and len(result):\n e = struct.unpack('{}s'.format(len(result)), result)\n \n for element in e:\n string_element = str(bytes(element).decode(\"utf8\"))\n if \"apriltag\" in string_element:\n y = string_element.split(\"apriltag\")[0]\n data = ast.literal_eval(y)\n self.update_data(data)\n apriltag_str = string_element.split(\"apriltag\")[1]\n self.april_tags = ast.literal_eval(apriltag_str)\n else:\n print(\"No data...\")\n\n except:\n traceback.print_exc(file=sys.stdout)\n\n def update_data(self, data):\n '''\n Called from exe_get_data().\n Updates the data lists (prev_cx, prev_cy, area, prev_rotation_angle, color)\n Making use of an exponential filter the data is beining normalized.\n\n Parameters\n ----------\n data (list) : list containing blob data\n\n Returns\n ----------\n None\n '''\n w=0.10\n\n window_size = len(data)\n cx = [0] * window_size\n cy = [0] * window_size\n area = [0] * window_size\n rotation_angle = [0] * window_size\n\n for blob_count,blob_list in enumerate(data):\n for count, element in enumerate(blob_list):\n if(count == 0):\n if(self.prev_cx[blob_count] == -1):\n self.prev_cx[blob_count] = element\n cx[blob_count] = int((w * element) + ((1-w) * self.prev_cx[blob_count]))\n self.prev_cx[blob_count] = cx[blob_count]\n elif(count == 1):\n if(self.prev_cy[blob_count] == -1):\n self.prev_cy[blob_count] = element\n cy[blob_count] = int((w * element) + ((1-w) * self.prev_cy[blob_count]))\n self.prev_cy[blob_count] = cy[blob_count]\n elif(count == 2):\n if(self.prev_area[blob_count] == -1):\n self.prev_area[blob_count] = element\n area[blob_count] = int((w * element) + ((1-w) * self.prev_area[blob_count]))\n self.prev_area[blob_count] = area[blob_count]\n elif(count == 3):\n corner_list = self.order_points(np.array(element))\n \n # Finding cube or domino brick\n c_ax = corner_list[0][0]\n c_ay = corner_list[0][1]\n c_bx = corner_list[1][0]\n c_by = corner_list[1][1]\n c_cx = corner_list[3][0]\n c_cy = corner_list[3][1]\n \n side_ab = math.hypot(c_bx - c_ax, c_by - c_ay)\n side_ac = math.hypot(c_cx - c_ax, c_cy - c_ay) \n difference = side_ac - side_ab\n \n if(abs(difference) > (side_ab/3) or abs(difference) > (side_ac/3)):\n self.is_cube_list.append(False)\n else:\n self.is_cube_list.append(True)\n\n angle = self.get_angle_of_rotation(corner_list.tolist())\n if(self.prev_rotation_angle[blob_count] == -1):\n self.prev_rotation_angle[blob_count] = angle\n rotation_angle[blob_count] = int((w * angle) + ((1-w) * self.prev_rotation_angle[blob_count]))\n self.prev_rotation_angle[blob_count] = rotation_angle[blob_count]\n elif(count == 4):\n self.color.append(element)\n \n def order_points(self, pts):\n '''\n Sorts the corners in a (top left, top right, bottom right, bottom left) order.\n\n This function was borrowed from pyimagesearch.com \n https://www.pyimagesearch.com/2016/03/21/ordering-coordinates-clockwise-with-python-and-opencv/\n\n\n Parameters\n ----------\n pts : tuple of (x,y) coordinates to be sorted.\n \n Returns\n ----------\n sorted list of corners : [top left, top right, bottom right, bottom left]\n\n '''\n # sort the points based on their x-coordinates\n xSorted = pts[np.argsort(pts[:, 0]), :]\n # grab the left-most and right-most points from the sorted\n # x-roodinate points\n leftMost = xSorted[:2, :]\n rightMost = xSorted[2:, :]\n\t # now, sort the left-most coordinates according to their\n\t # y-coordinates so we can grab the top-left and bottom-left\n\t # points, respectively\n leftMost = leftMost[np.argsort(leftMost[:, 1]), :]\n (tl, bl) = leftMost\n\t # now that we have the top-left coordinate, use it as an\n\t # anchor to calculate the Euclidean distance between the\n\t # top-left and right-most points; by the Pythagorean\n\t # theorem, the point with the largest distance will be\n\t # our bottom-right point\n D = dist.cdist(tl[np.newaxis], rightMost, \"euclidean\")[0]\n (br, tr) = rightMost[np.argsort(D)[::-1], :]\n\t # return the coordinates in top-left, top-right,\n\t # bottom-right, and bottom-left order\n return np.array([tl, tr, br, bl], dtype=\"float32\")\n \n def get_angle_of_rotation(self, corners):\n '''\n Calculates the angle of rotation for a blob in degrees,\n\n Parameters\n ----------\n corners : list of tuples of (x,y) coordinates.\n \n Returns\n ----------\n degrees : the rotation of the blob in degrees.\n '''\n ctx,cty = corners[0]\n crx,cry = corners[1] \n\n angle = math.atan2(cry - cty, crx - ctx)\n degrees = abs(angle * (180 / math.pi) )\n return degrees\n \n def rescale(self, x_camera, y_camera, tag_corners, offset_positive_x=20, offset_positive_y=0, offset_negative_x=20, offset_negative_y=5):\n '''\n Transforms the coordinates from camera frame to robot frame.\n Camera coordinate system and robot coordinate system is reversed,\n thus will the x-axis of the camera be the y-axis of the robot, and the\n y-axis of the camera will be the x-axis of the robot.\n\n The center of the robot is not exactly the center of the plate, and because of \n that there is a need to calibrate the offset for positive roboy_y and negative\n robot_y differently.\n\n We have calibrated the offset to work for a major part of the working space. \n But for perfection theese values need to be tuned.\n\n Standard values are:\n offset_positive_x = 20\n offset_positive_y = 0\n offset_negative_x = 20\n offset_negative_y =5\n\n Parameters\n ----------\n x_camera (float) : The cameras x position\n y_camera (float) : The cameras y position\n tag_corners : The corners of the april tags, used to transform between image and robot frame.\n\n Positive offset used for blobs found in the positive (left) side of the robot x-axis.\n offset_positive_x (int) : Desired offset for the x-axis of the robot.\n offset_positive_y (int) : Desired offset for the y-axis of the robot.\n\n Negative offset used for blobs found in the negative (right) side of the robot y-axis.\n offset_negative_x (int) : Desired offset for the x-axis of the robot.\n offset_negative_y (int) : Desired offset for the y-axis of the robot.\n \n Returns\n ----------\n x, y (float) : translated coordinates in the robot frame.\n\n '''\n robot_y = self.rescale_x(x_camera, tag_corners)\n robot_x = self.rescale_y(y_camera, tag_corners)\n \n if (offset_positive_x == 0 and offset_positive_y == 0) or (offset_negative_x == 0 and offset_negative_y == 0):\n return robot_x, robot_y\n elif robot_y < 0:\n if offset_negative_x < 0:\n robot_x = robot_x - offset_negative_x\n elif offset_negative_x > 0:\n robot_x = robot_x + offset_negative_x \n if offset_negative_y < 0:\n robot_y = robot_y - offset_negative_y\n elif offset_negative_y > 0:\n robot_y = robot_y + offset_negative_y \n return robot_x, robot_y\n elif robot_y > 0:\n if offset_positive_x < 0:\n robot_x = robot_x - offset_positive_x\n elif offset_negative_x > 0:\n robot_x = robot_x + offset_positive_x \n if offset_negative_y < 0:\n robot_y = robot_y - offset_positive_y\n elif offset_negative_y > 0:\n robot_y = robot_y + offset_positive_y \n return robot_x, robot_y \n \n def rescale_x(self, val, tag_corners):\n '''\n Translates the image x coordinate into robot x coordinate.\n \n Parameters\n ----------\n val (float) : the value to convert\n tag_corners (list) : list of the april tag corners\n \n Returns\n ----------\n (int) The transformed coordinate.\n '''\n out_min = -129 \n out_max = 123\n\n in_min = tag_corners[0][0] * 2\n in_max = tag_corners[1][0] * 2\n \n if (in_min - in_max) != 0:\n return out_min + (val - in_min) * ((out_max - out_min) / (in_max - in_min))\n else:\n raise ZeroDivisionError\n \n def rescale_y(self, val, tag_corners):\n '''\n Translate the image y coordinate into robot y coordinate.\n\n Parameters\n ----------\n val (float) : the value to convert\n tag_corners (list) : list of the april tag corners\n \n Returns\n ----------\n (int) The transformed coordinate. \n '''\n out_min = 104\n out_max = 294\n \n in_min = tag_corners[0][1] * 2\n in_max = tag_corners[3][1] * 2\n \n if (in_min - in_max) != 0: \n return out_min + (val - in_min) * ((out_max - out_min) / (in_max - in_min))\n else:\n raise ZeroDivisionError\n \n def get_tag_corners(self):\n ''' \n Get cx and cy for all april tags and store them in a list\n\n Returns\n ----------\n A sorted list of the april tag corners.\n '''\n center_list = []\n for tag_id,tag in self.april_tags.items():\n center_list.append((tag.get('cx'),tag.get('cy')))\n \n # The four corners of a april tag\n tag_corners = (self.order_points(np.array(center_list))).tolist()\n return tag_corners\n \n def draw(self, cx_list, cy_list):\n '''\n Plots the blocks into a coordinate system in the terminal.\n\n Returns\n ----------\n None\n '''\n cx = np.array(cx_list)\n cy = []\n\n for element in cy_list:\n cy.append(element * -1)\n \n cy_converted = np.array(cy)\n\n fig = plotille.Figure()\n fig.width = 40\n fig.height = 10\n fig.set_x_limits(min_=0, max_=350)\n fig.set_y_limits(min_=-180, max_=0)\n fig.scatter(cx,cy_converted)\n\n print(fig.show(legend=False))\n \n def init_robot(self, port=None):\n '''Initializing the robot before use with the homing routine\n Parameters:\n portname (str): a string representation of the port used by the Mirobot\n \n Returns:\n None\n '''\n if port:\n with Mirobot(portname = port, debug=True) as m:\n m.home_simultaneous()\n self.set_homing_timer(port)\n else:\n print(\"Must spesify a valid port.\")\n \n def go_to_resting_point(self, port=None, speed=750):\n '''\n Moves the Mirobot to its resting point.\n Needed for the OpenMV camera to be able to calibrate.\n\n (cx = 133, cy = 0, cz = 80, rx = 0, ry = 0, rz = 0)\n\n Parameters\n ----------\n port (str) : The protname connected to the robot being operated on.\n\n speed (int) : The speed of movement of the robot. Ranges from 0 - 2000.\n Not recommended to run below 500. Default set to 750.\n '''\n\n need_homing = self.check_homing_timer(port)\n if need_homing:\n print(\"Please home robot before further work.\")\n return \n\n if port:\n with Mirobot(portname = port, debug=True) as m:\n m.unlock_shaft()\n m.go_to_cartesian_lin(133,0,80,0,0,0, speed)\n else:\n print(\"Must spesify a valid port.\")\n \n def go_to_zero(self, port=None, speed=750):\n '''\n Moves the Mirobot to its zero position\n '''\n need_homing = self.check_homing_timer(port)\n if need_homing:\n print(\"Please home robot before further work.\")\n return \n\n if port:\n with Mirobot(portname = port, debug=True) as m:\n m.unlock_shaft()\n m.send_msg(\"M21 G90 G1 X0 Y0 Z0 A0 B0 C0\")\n # m.go_to_zero()\n else:\n print(\"Must spesify a valid port.\")\n \n def pick_up_cartesian(self, x, y, z, rx=0, ry=0, rz=0, port=None, speed=750, is_cube=True):\n '''\n Moves the robot to the given cartesian coordinates and picks up the\n object using the suction cup. Then moves to the zero position and releases \n the object.\n\n Parameters:\n x (float) : float value for the mirobots x coordinate\n y (float) : float value for the mirobots y coordinate\n z (float) : float value for the mirobots z coordinate\n rx (float) : float value for the mirobots rx coordinate\n ry (float) : float value for the mirobots ry coordinate\n rz (float) : float value for the mirobots rz coordinate\n\n port (str) : The protname connected to the robot being operated on.\n\n speed (int) : The speed of movement of the robot. Ranges from 0 - 2000.\n Not recommended to run below 500. Default set to 750.\n \n is_cube (bool) : True if a cube, false if a rectangle.\n \n Returns\n I dont know - have to find out...\n '''\n need_homing = self.check_homing_timer(port)\n if need_homing:\n print(\"Please home robot before further work.\")\n return \n \n X_MIN, X_MAX, Y_MIN, Y_MAX, Z_MIN, Z_MAX = self.get_soft_limits(is_cube)\n \n if (not x < X_MIN or not x > X_MAX or not y < Y_MIN or not y > Y_MAX \n or not z < Z_MIN or not z > Z_MAX):\n \n with Mirobot(portname=port, debug=True) as m:\n try:\n m.unlock_shaft() \n time.sleep(1)\n m.go_to_cartesian_lin(x,y,z,rx,ry,rz, speed)\n # Suction cup on\n m.send_msg('M3S1000')\n time.sleep(1)\n m.go_to_zero()\n # Suction cup off\n m.send_msg('M3S0')\n time.sleep(1)\n except KeyboardInterrupt:\n print()\n print(\"You sucessfully stopped the robot.\")\n print(\"Press the reset button to end the program.\")\n print(\"Home the robot before further operations.\")\n print()\n m.send_msg('!')\n else:\n print(\"Can't operate on theese coordinates.\")\n\n def set_homing_timer(self, portname):\n '''\n Sets the timer for when the robot was last homed.\n\n Paramters\n ----------\n portname (str) : The port connected to the robot\n \n Returns\n ----------\n None\n '''\n if portname == self.MIROBOT_ONE_PORT:\n with open(self.MIROBOT_ONE_TIMER_LOG, 'w', encoding = 'utf-8') as f:\n mirobot_one_timer = str( ( time.time() / 60 ) )\n f.write(mirobot_one_timer)\n \n if portname == self.MIROBOT_TWO_PORT:\n with open(self.MIROBOT_TWO_TIMER_LOG, 'w', encoding = 'utf-8') as f:\n mirobot_two_timer = str( ( time.time() / 60 ) )\n f.write(mirobot_two_timer)\n\n def check_homing_timer(self, portname):\n '''\n Checks how long time since the robot was last homed.\n\n Parameters\n ----------\n portname (str) : The port connected to the robot.\n \n Returns\n ----------\n False if no need to home robot\n True if need to home robot\n '''\n minutes_since_epoch = time.time() / 60\n\n if portname == self.MIROBOT_ONE_PORT:\n mirobot_one_timer = 0.0\n \n with open(self.MIROBOT_ONE_TIMER_LOG, 'r', encoding = 'utf-8') as f:\n mirobot_one_timer = float( f.read() )\n \n if (minutes_since_epoch - mirobot_one_timer < self.HOMING_TIMEOUT):\n return False\n elif (minutes_since_epoch - mirobot_one_timer >= self.HOMING_TIMEOUT):\n return True\n\n if portname == self.MIROBOT_TWO_PORT:\n \n mirobot_two_timer = 0.0\n \n with open(self.MIROBOT_TWO_TIMER_LOG, 'r', encoding = 'utf-8') as f:\n mirobot_two_timer = float( f.read() )\n \n if (minutes_since_epoch - mirobot_two_timer < self.HOMING_TIMEOUT):\n return False\n elif (minutes_since_epoch - mirobot_two_timer >= self.HOMING_TIMEOUT):\n return True\n\n def get_soft_limits(self, is_cube):\n '''\n Gets the soft limits for the robots working space.\n Only Z_MIN is different depending on which object\n is to be picked up.\n\n !!!\n Z_MIN for a domino brick has not been set. This must be tested and\n corrected! Currently it is set to the same as a cube for saftey.\n\n Parameters\n is_cube (bool) : True if a cube, False if a rectangle.\n\n Returns\n X_MIN (int), X_MAX (int), Y_MIN (int), Y_MAX (int), Z_MIN (int), Z_MAX (int)\n '''\n X_MIN = 133\n X_MAX = 290\n Y_MIN = -125\n Y_MAX = 125\n Z_MIN = 100\n Z_MAX = 231\n\n if is_cube:\n Z_MIN = 58\n return X_MIN, X_MAX, Y_MIN, Y_MAX, Z_MIN, Z_MAX\n \n elif not is_cube:\n # Please spesify the correct value for Z_MIN\n Z_MIN = 58\n return X_MIN, X_MAX, Y_MIN, Y_MAX, Z_MIN, Z_MAX\n \n def fill_data_list(self, interface):\n '''\n Storing the values of a 25 frames to be processed.\n\n parameters\n interface (rpc.rpc_usb_vcp_master) : The openMV camera used.\n \n Returns\n None \n '''\n for i in range(25):\n self.exe_get_data(interface) \n\n def clear_data_list(self):\n '''\n Clears the data_list before next call\n\n Returns\n ----------\n None\n '''\n self.data_list.clear()\n\n def find_mode(self, sample):\n #c = Counter(sample)\n return max(set(sample), key=sample.count)\n\n def find_mean(self, sample):\n #c = Counter(sample)\n return int(sum(sample) / len(sample))\n\n def median(self, items):\n if len(items) % 2:\n return select_nth(len(items)//2, items)\n else:\n left = select_nth((len(items)-1) // 2, items)\n right = select_nth((len(items)+1) // 2, items)\n\n return (left + right) / 2\n \n def select_nth(self, n, items):\n pivot = items[0]\n\n lesser = [item for item in items if item < pivot]\n if len(lesser) > n:\n return select_nth(n, lesser)\n n -= len(lesser)\n\n numequal = items.count(pivot)\n if numequal > n:\n return pivot\n n -= numequal\n\n greater = [item for item in items if item > pivot]\n return select_nth(n, greater)\n\n","sub_path":"remote_call.py","file_name":"remote_call.py","file_ext":"py","file_size_in_byte":24594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"315879114","text":"import networkx as nx\nimport itertools as IT\nimport matplotlib.pyplot as plt\n\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n#\n# root=TreeNode(1)\n# root.right=TreeNode(2)\n# root.right.right=TreeNode(3)\n\nclass BinaryTree(object):\n def __init__(self, data):\n self.data = data\n self.right = None\n self.left = None\n self.name = None\n def edgelist(self, counter = IT.count().next):\n self.name = counter() if self.name is None else self.name\n for node in (self.left, self.right):\n if node:\n node.name = counter() if node.name is None else node.name\n yield (self.name, node.name)\n for node in (self.left, self.right):\n if node:\n for n in node.edgelist(counter):\n yield n\n\ntree = [BinaryTree(i) for i in range(5)]\ntree[0].left = tree[1]\ntree[0].right = tree[2]\ntree[2].left = tree[3]\ntree[2].right = tree[4]\n\nedgelist = list(tree[0].edgelist())\nprint(edgelist)\n\nG = nx.Graph(edgelist)\nnx.draw_spectral(G)\n# plt.show()\n","sub_path":"plotTree.py","file_name":"plotTree.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"501299714","text":"# -*- coding: utf-8 -*-\n\nimport functools\n\nfrom flask import request, make_response, jsonify\n\nfrom flask_utils.tools import Signer\n\n\ndef sign_required(signer=Signer, status=200, default=''):\n \"\"\"\n 装饰器,用来装饰class-based view的method方法(get, post, etc.)\n :param signer: 签名类,必须有validate方法\n :param status: 整型,http状态码\n :param default: 签名失败的返回值\n \"\"\"\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n\n nonlocal default\n\n if request.method == 'GET':\n params = request.args\n elif request.method == 'POST':\n params = request.json\n else:\n return func(*args, **kwargs)\n\n if signer.validate(params):\n resp = func(*args, **kwargs)\n else:\n if isinstance(default, dict):\n default = jsonify(default)\n resp = make_response(default, status)\n\n return resp\n return wrapper\n return decorator\n","sub_path":"flask_utils/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"128912122","text":"import contextlib\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, Session, scoped_session\n\nfrom .base_class import Base\n# noinspection PyUnresolvedReferences\nfrom app.db_models.user import User\nfrom app.db_models.expense import Expense\nfrom app.core import Config\n\nengine = create_engine(Config.database_url, connect_args={\"check_same_thread\": False})\ndb_session = scoped_session(\n sessionmaker(autocommit=False, autoflush=False, bind=engine)\n)\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\n\ndef get_db() -> Session:\n try:\n db = SessionLocal()\n yield db\n finally:\n db.close()\n\n\ndef create_all():\n Base.metadata.create_all(bind=engine)\n\n\ndef reset_db():\n with contextlib.closing(engine.connect()) as con:\n trans = con.begin()\n for table in reversed(Base.metadata.sorted_tables):\n con.execute(table.delete())\n trans.commit()\n","sub_path":"app/db/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"47310864","text":"#cd Google Drive/project/A_database/python\r\n#python 35 via spyder console\r\nimport urllib\r\nimport re\r\nimport json\r\n\r\nuni = []\r\nwebsite = []\r\nfilename = 'uni_ph.txt'\r\n\r\ndef input_page(filename):\r\n try:\r\n with open(filename) as source:\r\n raw_list=source.readlines()\r\n for i in range(len(raw_list)-1): ##-1 so index not out of bounds\r\n split = raw_list[i].split(',') ##erratic data so get only the right link\r\n uni.append(split[0])\r\n website.append(split[1])\r\n website[i]=website[i][1:-2] ##further remove unnecessary characters\r\n print(uni[i])\r\n except Exception as e:\r\n print('failed in input_page module:', str(e))\r\n return(uni, website)\r\n\r\ndef parse_goog(uni):\r\n try:\r\n for i in len(uni):\r\n for j in uni[i]:\r\n terms = j.rstrip(\" \")\r\n print(terms)\r\n # url = \"http://www.bloomberg.com/markets/watchlist/recent-ticker/\"+symlist[i]+\":PM\"\r\n # htmltext = urllib.urlopen(url)\r\n # data = json.load(htmltext)\r\n except Exception as e:\r\n print('failed in parse_goog module:', str(e))\r\n\r\n#main():\r\n# input_page(filename)\r\nparse_goog(uni)\r\n","sub_path":"address_search_goog.py","file_name":"address_search_goog.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"511330524","text":"# Copyright (C) 2021 The Android Open Source Project\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\"\"\"Provide functionality to get all projects and their SHAs from Superproject.\n\nFor more information on superproject, check out:\nhttps://en.wikibooks.org/wiki/Git/Submodules_and_Superprojects\n\nExamples:\n superproject = Superproject()\n project_shas = superproject.GetAllProjectsSHAs()\n\"\"\"\n\nimport os\nimport sys\n\nfrom error import GitError\nfrom git_command import GitCommand\n\n\nclass Superproject(object):\n \"\"\"Get SHAs from superproject.\n\n It does a 'git clone' of superproject and 'git ls-tree' to get list of SHAs for all projects.\n It contains project_shas which is a dictionary with project/sha entries.\n \"\"\"\n def __init__(self, repodir, superproject_dir='exp-superproject'):\n \"\"\"Initializes superproject.\n\n Args:\n repodir: Path to the .repo/ dir for holding all internal checkout state.\n superproject_dir: Relative path under |repodir| to checkout superproject.\n \"\"\"\n self._project_shas = None\n self._repodir = os.path.abspath(repodir)\n self._superproject_dir = superproject_dir\n self._superproject_path = os.path.join(self._repodir, superproject_dir)\n\n @property\n def project_shas(self):\n \"\"\"Returns a dictionary of projects and their SHAs.\"\"\"\n return self._project_shas\n\n def _Clone(self, url, branch=None):\n \"\"\"Do a 'git clone' for the given url and branch.\n\n Args:\n url: superproject's url to be passed to git clone.\n branch: the branchname to be passed as argument to git clone.\n\n Returns:\n True if 'git clone ' is successful, or False.\n \"\"\"\n os.mkdir(self._superproject_path)\n cmd = ['clone', url, '--filter', 'blob:none']\n if branch:\n cmd += ['--branch', branch]\n p = GitCommand(None,\n cmd,\n cwd=self._superproject_path,\n capture_stdout=True,\n capture_stderr=True)\n retval = p.Wait()\n if retval:\n # `git clone` is documented to produce an exit status of `128` if\n # the requested url or branch are not present in the configuration.\n print('repo: error: git clone call failed with return code: %r, stderr: %r' %\n (retval, p.stderr), file=sys.stderr)\n return False\n return True\n\n def _Pull(self):\n \"\"\"Do a 'git pull' to to fetch the latest content.\n\n Returns:\n True if 'git pull ' is successful, or False.\n \"\"\"\n git_dir = os.path.join(self._superproject_path, 'superproject')\n if not os.path.exists(git_dir):\n raise GitError('git pull. Missing drectory: %s' % git_dir)\n cmd = ['pull']\n p = GitCommand(None,\n cmd,\n cwd=git_dir,\n capture_stdout=True,\n capture_stderr=True)\n retval = p.Wait()\n if retval:\n print('repo: error: git pull call failed with return code: %r, stderr: %r' %\n (retval, p.stderr), file=sys.stderr)\n return False\n return True\n\n def _LsTree(self):\n \"\"\"Returns the data from 'git ls-tree -r HEAD'.\n\n Works only in git repositories.\n\n Returns:\n data: data returned from 'git ls-tree -r HEAD' instead of None.\n \"\"\"\n git_dir = os.path.join(self._superproject_path, 'superproject')\n if not os.path.exists(git_dir):\n raise GitError('git ls-tree. Missing drectory: %s' % git_dir)\n data = None\n cmd = ['ls-tree', '-z', '-r', 'HEAD']\n p = GitCommand(None,\n cmd,\n cwd=git_dir,\n capture_stdout=True,\n capture_stderr=True)\n retval = p.Wait()\n if retval == 0:\n data = p.stdout\n else:\n # `git clone` is documented to produce an exit status of `128` if\n # the requested url or branch are not present in the configuration.\n print('repo: error: git ls-tree call failed with return code: %r, stderr: %r' % (\n retval, p.stderr), file=sys.stderr)\n return data\n\n def GetAllProjectsSHAs(self, url, branch=None):\n \"\"\"Get SHAs for all projects from superproject and save them in _project_shas.\n\n Args:\n url: superproject's url to be passed to git clone.\n branch: the branchname to be passed as argument to git clone.\n\n Returns:\n A dictionary with the projects/SHAs instead of None.\n \"\"\"\n if not url:\n raise ValueError('url argument is not supplied.')\n if os.path.exists(self._superproject_path):\n if not self._Pull():\n raise GitError('git pull failed for url: %s' % url)\n else:\n if not self._Clone(url, branch):\n raise GitError('git clone failed for url: %s' % url)\n\n data = self._LsTree()\n if not data:\n raise GitError('git ls-tree failed for url: %s' % url)\n\n # Parse lines like the following to select lines starting with '160000' and\n # build a dictionary with project path (last element) and its SHA (3rd element).\n #\n # 160000 commit 2c2724cb36cd5a9cec6c852c681efc3b7c6b86ea\\tart\\x00\n # 120000 blob acc2cbdf438f9d2141f0ae424cec1d8fc4b5d97f\\tbootstrap.bash\\x00\n shas = {}\n for line in data.split('\\x00'):\n ls_data = line.split(None, 3)\n if not ls_data:\n break\n if ls_data[0] == '160000':\n shas[ls_data[3]] = ls_data[2]\n\n self._project_shas = shas\n return shas\n","sub_path":"git_superproject.py","file_name":"git_superproject.py","file_ext":"py","file_size_in_byte":5810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"560765030","text":"#!/usr/bin/python3\n#SIMULATE\n#Desc : Script that executes internal wave simulation \n#Auth : J. DeFilippis\n#Date : 7-16-2019\n\nimport sys\nimport numpy as np\nimport pandas as pd\nimport feather\nimport json\nimport os \nimport functools\nimport scipy.interpolate as interp\nimport seawater as sw\n\n#Source local libraries\nsys.path.append('../src/iw_model')\nsys.path.append('../src/misc')\n\nfrom iw_field import InternalWaveField\nfrom iw_sim import InternalWaveSimulation\nfrom map_scalars import map_scalars\nfrom map_scalars import map_svel\nfrom map_scalars import map_svel_anom\nfrom map_scalars import map_anom\n\ncph = 3600\n\n#Get config file from user\nif len(sys.argv) > 1:\n config_fname = sys.argv[1]\nelse:\n print(\"Usage : need configuration filename \")\n sys.exit(1)\n\n\n#Read Sim Params\nwith open(config_fname) as param_file:\n p = json.load(param_file)\n\n#Spacial Params\niwrange = np.linspace(0,p['range_end'],p['range_res'])\niwdepth = np.linspace(0,p['depth_end'],p['depth_res'])\n\n#Mean Profile\nstrat=np.array([])\ntry :\n mprof = feather.read_dataframe(p['envfile'])\n strat = mprof['strat']\nexcept KeyError:\n \"Mean profile\"\n pass\n \n#Frequency Distrubution (non radial)\nfreqs = np.array(p['freqs'])/cph\nmodes = np.array(p['modes'])\namps_real = p['amps_real'] \namps_imag = p['amps_imag']\nheadings = p['headings']\n\nif len(amps_real) != len(modes)*len(freqs) != len(headings):\n print(len(amps_real), len(modes),len(freqs), len(headings))\n print(\"Config file error: length amps != length modes*freqs\")\n\namps = []\nfor i,a in enumerate(amps_real):\n zz = list(zip(a,amps_imag[i],headings[i]))\n amps.append( { 'amps' : [ complex(z[0],z[1]) for z in zz],\n 'headings': [2*np.pi*z[2]/360 for z in zz]} )\n\n\n#Make wave field\niwf = InternalWaveField(iwrange,iwdepth,\n freqs=freqs,\n modes=modes,\n amplitudes=amps,\n bfrq=strat)\n\n\n#Print parameters to users\nprint(\"INPUT PARAMETERS:\")\nprint(\"\\tFrequencies : \" , freqs)\n#print(\"\\tHeading & Amplitude : \",amps)\nprint(\"\\tHorizontal Wavenumber :\", [iwf.iwmodes[0].get_hwavenumber(m) for m in iwf.modes])\n\n\n#Make sampling coordinates\ncoords = []\nfor xi in p['x_samples']:\n for yi in p['y_samples']:\n for zi in p['z_samples']:\n coords.append( (xi,yi,zi) )\n\n\n#Run simulation\ntime = np.arange(0,p['time_stop']+p['time_step'],p['time_step'])\niws = InternalWaveSimulation(time,iwf=iwf,dpath=p['path'],fname='run',ftype=p['ftype'])\niws.make_metadata_file()\niws.run(coords=coords) \n \n \n#Mapping Sound Profile onto IW Field\ntry :\n T = mprof['T']\n S = mprof['S']\n\nexcept KeyError:\n print(\"No scalars to map\")\n exit(0)\n\n\n#Compute interpolation and potential derivative of T&S\ntprof = interp.UnivariateSpline(mprof['depth'], mprof['T'])\nadtg = interp.UnivariateSpline(mprof['depth'],\n sw.adtg(mprof['S'],mprof['T'],mprof['depth']))\nsprof = interp.UnivariateSpline(mprof['depth'], mprof['S'])\nsg = sprof.derivative()\n\ncprof = interp.UnivariateSpline(mprof['depth'],\n sw.svel(mprof['S'],mprof['T'],mprof['depth']))\n\n\n\n#Maps displacment to anomaly\nmat = functools.partial(map_anom, mean=tprof, grad=adtg)\nmas = functools.partial(map_anom, mean=sprof, grad=sg)\nmac = functools.partial(map_svel, func=sw.svel)\nmaca = functools.partial(map_svel_anom, func=cprof)\n\nmap_scalars(p['path'],'T',mat)\nmap_scalars(p['path'],'S',mas)\nmap_scalars(p['path'],'c',mac)\nmap_scalars(p['path'],'ca',maca)\n\n","sub_path":"IW/scripts/simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"7839253","text":"from otree.api import Currency as c, currency_range\nfrom . import models\nfrom ._builtin import Page, WaitPage\nfrom .models import Constants\n\n\nclass Mydecisions(Page):\n form_model = 'player'\n form_fields = [\n 'name',\n 'Experiment1',\n 'Experiment2',\n 'Experiment3'\n ]\n\n\n# class City(Page):\n# form_model = 'player'\n# form_fields = ['city',\n# 'yearsinmsc', 'mscyourcity', 'achieve', 'deput']\n\n\nclass Yourself(Page):\n form_model = 'player'\n form_fields = ['age',\n 'height',\n 'weight',\n 'yearcity16',\n 'riskat',\n 'satis',\n 'freedom',\n 'rating']\n\n# class polit(Page):\n# form_model = 'player'\n# form_fields = ['freedom',\n# 'politics',\n# 'leftright',\n# 'owner',\n# 'responsibility',\n# 'democracy',\n# 'democracy_today',\n# 'renovation',\n# 'attitudes']\n\n def before_next_page(self):\n self.player.set_payoff()\n\n\npage_sequence = [\n Mydecisions, Yourself #, polit, City,\n]\n","sub_path":"my_survey_eng/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"369900454","text":"import sys\nfrom PyQt5.QtWidgets import QMainWindow,QApplication\nfrom PyQt5.QtGui import QIcon\n\nclass FirstMainWin(QMainWindow):\n def __init__(self,parent=None):\n super(FirstMainWin,self).__init__(parent)\n self.setWindowTitle(\"第一个应用窗口\")\n self.resize(400,300)\n self.status=self.statusBar()\n self.status.showMessage('只存在5秒的消息',5000)\n\n\n\nif __name__ == '__main__':\n app=QApplication(sys.argv)\n app.setWindowIcon(QIcon('./image/1203057.png'))\n main=FirstMainWin()\n main.show()\n\n sys.exit(app.exec_())\n\n\n","sub_path":"src/control/mainwindow_test.py","file_name":"mainwindow_test.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"36349022","text":"motorcycles = ['honda', 'yamaha', 'suzuki']\nprint(motorcycles)\n\n#Изменили значение 1 элемента с списке\n\nmotorcycles[0] = 'ducati'\nprint(motorcycles)\n\n#Добавили в конец списка навый элемент\n\nmotorcycles.append('honda')\nprint(motorcycles)\n\n#Добавили 3 элемента в список\n\nmotorcycles = []\nmotorcycles.append('honda')\nmotorcycles.append('yamaha')\nmotorcycles.append('suzuki')\nprint(motorcycles)\n\n#Добавили элемент 'ducation' на первую позицую в список\n\nmotorcycles.insert(0, 'ducati')\nprint(motorcycles)\n\n#Удалили 1 элемент из списка, без возврата\n\ndel motorcycles[0]\nprint(motorcycles)\nmotorcycles.insert(0, 'ducati')\n\n#Удаление последнего элемента с возможностью врнуть\n\npopped_motorcycle = motorcycles.pop()\nprint(motorcycles)\nprint(popped_motorcycle)\n\n#Удаление последнего и первого элемента в возможностью вернуть\n\nmotorcycles.append(popped_motorcycle)\nlast_owned = motorcycles.pop()\nprint('The last motorcycle I owned was a %s' % last_owned)\nfirst_owned = motorcycles.pop(0)\nprint('The first motorcycle I owned was a %s' % first_owned)\n\n#Удаление из списка элемента по значению\n\nmotorcycles.insert(0, first_owned)\nmotorcycles.append(last_owned)\nmotorcycles.remove('ducati')\nprint(motorcycles)\nmotorcycles.insert(2, 'ducati')\n\n#Удаление из списка элемента по значению с возможностью вернуть\n\ntoo_expensive = 'ducati'\nmotorcycles.remove(too_expensive)\nprint(motorcycles)\nprint('\\nA' + too_expensive.title() + ' is too expensive for me.')\n\n","sub_path":"Изучаем python программирование игр, визализация данных, веб-приложений/Списки/motorcycles.py","file_name":"motorcycles.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"189168953","text":"from __future__ import print_function, division\nimport unittest, numpy as np\nfrom pyscf import gto, tddft, scf\nfrom pyscf.nao import bse_iter\nfrom pyscf.nao import polariz_freq_osc_strength\nfrom pyscf.data.nist import HARTREE2EV\n\nclass KnowValues(unittest.TestCase):\n\n def test_0147_bse_h2o_rks_pz(self):\n \"\"\" Interacting case \"\"\"\n mol=gto.M(verbose=0,atom='O 0 0 0;H 0 0.489 1.074;H 0 0.489 -1.074',basis='cc-pvdz',)\n gto_hf = scf.RKS(mol)\n gto_hf.kernel()\n gto_td = tddft.TDDFT(gto_hf)\n gto_td.nstates = 95\n gto_td.kernel()\n\n omegas = np.arange(0.0, 2.0, 0.01) + 1j*0.03\n p_ave = -polariz_freq_osc_strength(gto_td.e, gto_td.oscillator_strength(), omegas).imag\n data = np.array([omegas.real*HARTREE2EV, p_ave])\n np.savetxt('test_0147_bse_h2o_rks_pz_pyscf.txt', data.T, fmt=['%f','%f'])\n data_ref = np.loadtxt('test_0147_bse_h2o_rks_pz_pyscf.txt-ref').T\n self.assertTrue(np.allclose(data_ref, data, atol=1e-6, rtol=1e-3))\n \n nao_td = bse_iter(mf=gto_hf, gto=mol, verbosity=0, xc_code='LDA',)\n\n p_iter = -nao_td.comp_polariz_inter_ave(omegas).imag\n data = np.array([omegas.real*HARTREE2EV, p_iter])\n np.savetxt('test_0147_bse_h2o_rks_pz_nao.txt', data.T, fmt=['%f','%f'])\n data_ref = np.loadtxt('test_0147_bse_h2o_rks_pz_nao.txt-ref').T\n self.assertTrue(np.allclose(data_ref, data, atol=1e-6, rtol=1e-3))\n \nif __name__ == \"__main__\": unittest.main()\n","sub_path":"pyscf/nao/test/test_0147_bse_h2o_rks_pz.py","file_name":"test_0147_bse_h2o_rks_pz.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"472155623","text":"import mysql.connector\n\n\n#passwordは下記サイトで記号まで含めて8文字以上\n#http://www.luft.co.jp/cgi/randam.php\n#\n\n\n#GRANT ALL PRIVILEGES ON person_db.* TO person_user@localhost IDENTIFIED BY 'JYVVHr9)/B5c' WITH GRANT OPTION;\n#insert into person(name,age,language) values\n#('yamada',19,'PHP'),\n#('suzuki',22,'Java'),\n#('tanaka',18,'Ruby'),\n#('watanabe',25,'C'),\n#('satou',33,'Perl');\n\n\n#チュートリアル\n#https://algorithm.joho.info/programming/python/mysql-connector-python-install/\n#コマンドラインで下記を実行\n#pip install mysql-connector-python\n\n#実際のソース\n#https://algorithm.joho.info/programming/python/mysql-connector-get-data/\n#\n\n\ncnt = mysql.connector.connect(\n host='localhost',\n port='3306',\n db='person_db',\n user='person_user',\n password='JYVVHr9)/B5c',\n charset='utf8'\n)\n\n# カーソル取得\ndb = cnt.cursor(dictionary=True, buffered=True)\n\nsql = 'SELECT id,name,age,language FROM person';\ndb.execute(sql)\n\n#問1\n# 表示\nresults = db.fetchall()\ndata = []\nfor row in results:\n print(str(row['id']) + \":\" + row['name'] + \":\" + str(row['age']) + \":\" + row['language'])\n\n#問2\nsql2 = \" insert into person (name, age, language) values ('katou', 27, 'Python')\";\ndb.execute(sql2)\ncnt.commit()\n\n#問3\nsql3 = \" update person set age = 25 where id = 2\";\ndb.execute(sql3)\ncnt.commit()\n\n#問4\n#回答1\nsql4_1 = 'SELECT id,name,age,language FROM person';\ndb.execute(sql4_1)\nresults4 = db.fetchall()\n\nloop_cnt = 0\nage_sum = 0\nfor row4 in results4:\n loop_cnt += 1\n age_sum += row4['age']\n\nprint(round(age_sum/loop_cnt, 1))\n\n#回答2\nsql4_2 = \" select AVG(age) AS age_average from person\";\ndb.execute(sql4_2)\nperson = db.fetchone()\nprint(person['age_average'])\n\n#問5\nsql5 = \" delete from person where age >= 20\";\ndb.execute(sql5)\ncnt.commit()\n\n\n# カーソル終了\ndb.close()\n# MySQL切断\ncnt.close()\n","sub_path":"20181013/kadai_04.py","file_name":"kadai_04.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"279427140","text":"import requests\nfrom pymessenger.bot import Bot\n\nclass Responses():\n\tbot=\"\"\n\tURL = \"\"\n\tdef __init__(self,access_token):\n\t\tbot = Bot(access_token)\n\t\tself.bot = bot\n\n\tdef saluda(self, sender_id):\n\t\t#crear usuario con el sender_id y guardarlo en el backend \n\t\ttext = \"¡Hola! ¿Listo para empezar a leer?\"\n\t\tself.bot.send_text_message(sender_id,text)\n\t\n\tdef book(self, sender_id):\n\t\ttext = \"¿Genial! :D ¿Qué libro quieres leer hoy? \"\n\t\tself.bot.send_text_message(sender_id,text)\n\n\tdef paginas(self, sender_id):\n\t\t#guardar el libro\n\t\ttext = \"¡Perfecto! :) ¿Cuántas páginas tiene tu libro?\"\n\t\tself.bot.send_text_message(sender_id,text)\n\n\tdef dias(self, sender_id):\n\t\ttext = \"Ok, ¿en cuántos días lo planeas leer?\"\n\t\tself.bot.send_text_message(sender_id,text)\n\n\tdef num_paginas(self, sender_id):\n\t\t#calculo = ir al backend y preguntar\n\t\tcalculo = str(35)\n\t\ttext = \"Muy bien! Debes leer \" + calculo + \" páginas diarias para cumplir tu objetivo\"\n\t\tself.bot.send_text_message(sender_id,text)\n\t\tself.bot.send_text_message(sender_id,\"¿A qué hora quieres que te recuerde leer?\")\n\n\tdef reading_time(self,sender_id):\n\t\tJSON = {\n\t\t\t\"recipient\":{\n\t\t\t\t\"id\":sender_id\n\t\t\t\t\t\t},\n\t\t\t\"message\":{\n\t\t\t\t\"text\" : \"¿Cuánto tiempo planeas leer hoy?\",\n\t\t\t\t\"quick_replies\" : [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"content_type\":\"text\",\n\t\t\t\t\t\t\"title\":\"15 minutos\",\n\t\t\t\t\t\t\"payload\":\"15\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"content_type\":\"text\",\n\t\t\t\t\t\t\"title\":\"30 minutos\",\n\t\t\t\t\t\t\"payload\":\"30\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"content_type\":\"text\",\n\t\t\t\t\t\t\"title\":\"1 hora\",\n\t\t\t\t\t\t\"payload\":\"60\",\n\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\tURL=\"https://graph.facebook.com/v2.6/me/messages?access_token=EAAKHni1byYIBAIailUcuuVrwNLqmsG7VGEK29I5erzE3gC4ZCaITZCwxZAHTqMcePZCg3Y0K8yJe2VXC80ZBNXVZBZASpZCpJrTS3dX78hbWxCbcpwAv3KxBgayN2o0fVmvCfdY6G9g4yiRh4f1jLbSJNbD7EVupxjsllHyh77wit0nQwYLgKiha\"\n\t\tsend=requests.post(URL,json = JSON)\n\t\treturn True\n\n\tdef hora(self,sender_id):\n\t\tJSON = {\n\t\t\t\"recipient\":{\n\t\t\t\t\"id\":sender_id\n\t\t\t\t\t\t},\n\t\t\t\"message\":{\n\t\t\t\t\"text\" : \"¿Listo para leer?\",\n\t\t\t\t\"quick_replies\" : [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"content_type\":\"text\",\n\t\t\t\t\t\t\"title\":\"Sí :)\",\n\t\t\t\t\t\t\"payload\":\"Si\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"content_type\":\"text\",\n\t\t\t\t\t\t\"title\":\"No\",\n\t\t\t\t\t\t\"payload\":\"No :(\",\n\t\t\t\t\t},\t\t\t\t]\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\tURL=\"https://graph.facebook.com/v2.6/me/messages?access_token=EAAKHni1byYIBAIailUcuuVrwNLqmsG7VGEK29I5erzE3gC4ZCaITZCwxZAHTqMcePZCg3Y0K8yJe2VXC80ZBNXVZBZASpZCpJrTS3dX78hbWxCbcpwAv3KxBgayN2o0fVmvCfdY6G9g4yiRh4f1jLbSJNbD7EVupxjsllHyh77wit0nQwYLgKiha\"\n\t\tsend=requests.post(URL,json = JSON)\n\t\treturn True\n\n\n\n\n\tdef snooze_time(self,sender_id):\n\t\tJSON = {\n\t\t\t\"recipient\":{\n\t\t\t\t\"id\":sender_id\n\t\t\t\t\t\t},\n\t\t\t\"message\":{\n\t\t\t\t\"text\": \"¿En cuánto tiempo quieres que te vuelva a preguntar?\",\n\t\t\t\t\"quick_replies\" :[\n\t\t\t\t\t{\n\t\t\t\t\t\t\"content_type\":\"text\",\n\t\t\t\t\t\t\"title\":\"15 minutos\",\n\t\t\t\t\t\t\"payload\":\"POSTBACK_TEXT\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"content_type\":\"text\",\n\t\t\t\t\t\t\"title\":\"30 minutos\",\n\t\t\t\t\t\t\"payload\":\"POSTBACK_TEXT\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"content_type\":\"text\",\n\t\t\t\t\t\t\"title\":\"1 hora\",\n\t\t\t\t\t\t\"payload\":\"POSTBACK_TEXT\",\n\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\tURL=\"https://graph.facebook.com/v2.6/me/messages?access_token=EAAKHni1byYIBAIailUcuuVrwNLqmsG7VGEK29I5erzE3gC4ZCaITZCwxZAHTqMcePZCg3Y0K8yJe2VXC80ZBNXVZBZASpZCpJrTS3dX78hbWxCbcpwAv3KxBgayN2o0fVmvCfdY6G9g4yiRh4f1jLbSJNbD7EVupxjsllHyh77wit0nQwYLgKiha\"\n\t\tsend=requests.post(URL,json = JSON)\n\t\treturn True\n\tdef tiempo_lectura(self, sender_id):\n\t\t\ttext = \"Bien! :D ¿Cuántas páginas leíste hoy? \"\n\t\t\tself.bot.send_text_message(sender_id,text)\n\tdef resumen_diario(self, sender_id):\n\t\t\ttext = \"Excelente! :D Leíste 15 páginas más que tu objetivo diario\"\n\t\t\tself.bot.send_text_message(sender_id,text)\n\t\t\tself.bot.send_text_message(sender_id,\"Nos vemos mañana! :P\")\n\n","sub_path":"indexes pasados/responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"290185018","text":"'''\nFitting Data via DMCfun package adaptation.\n\nAuthor: Kenan Suljic\nDate: 08.08.2023\n\n'''\n\n#%%\nimport os\n\nfrom dataclasses import asdict\nfrom copy import deepcopy\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport pydmc\nfrom pydmc import *\n\nimport importlib\nimportlib.reload(pydmc)\n# --------------------\n\n\n\n# %%\nData = pydmc.flanker_data()\nData.head()\n\n# %%\nres_ob = Ob(Data, n_caf=9)\n\n# %%\nprmsfit = PrmsFit()\n#prmsfit.dmc_prms()\nprmsfit.set_random_start_values(seed_value=18)\n#prmsfit.set_start_values()\nprmsfit\n\n\n# %%\nfit_diff = Fit(res_ob, start_vals=prmsfit, n_caf=9)\n\n\n# %%\nfit_diff.fit_data('differential_evolution', maxiter=30)\n\n# %%\nfit_diff.print_summary()\n\n\n# %%\nPlotFit(fit_diff).summary()\n\n\n# %%\n#prms_res = fit_diff.return_result_prms()\n#prms_res\n\n\n# %%\nfit_diff.res_th.prms\n\n# %%\nfit_diff.res_th.plot.summary()\n\n# %%\nbest_prms = fit_diff.res_th.prms\n\n\n# %%\nsim = Sim(prms=best_prms, n_caf=9, full_data=False)\n\n# %%\nprint(sim.prms)\nPlot(sim).summary()\n\n# %% \nFit.calculate_cost_value_rmse(sim, res_ob)\n\n\n# %%\nprmsfit_adv = PrmsFit()\nbest_prms_dict = asdict(best_prms)\nprmsfit_adv.set_start_values(**best_prms_dict)\nprmsfit_adv\n\n\n# %%\nfit_diff_adv = Fit(res_ob, start_vals=prmsfit_adv, search_grid=False, n_caf=9)\n\n# %%\n#fit_diff.fit_data('differential_evolution', maxiter=10)\nfit_diff_adv.fit_data(maxiter=200)\n\n\n\n# %%\nfit_diff_adv.table_summary()\n\n# %%\n'''\nPaper Values (flanker)\n\nprms_instance = Prms(\n amp=19.42,\n tau=84.22,\n drc=0.6,\n bnds=56.47,\n res_mean=325.14,\n res_sd=28.28,\n aa_shape=2.24,\n sp_shape=2.8,\n sigma=4\n)\n\n'''\n\n\n# %%\n#result_para = fit_diff_adv.res_th.prms\n#print(result_para)\n\n\n# %%\nPlotFit(fit_diff_adv).summary()\n\n\n# %%\nbest_prms_adv = fit_diff_adv.res_th.prms\n\n\n\n# %%\nsim = Sim(best_prms_adv, n_caf=9, full_data=False)\n# sim = Sim(prms_instance, n_caf=9, full_data=True, n_trls_data=20)\n\n# %%\nsim.plot.summary()\n\n# %%\nprint(f'RMSE: {Fit.calculate_cost_value_rmse(sim, res_ob)}')\nprint(f'SPE (%): {Fit.calculate_cost_value_spe(sim, res_ob)*100:4.2f}')\n\n\n# %%\ndf1 = pd.DataFrame(data=sim.data[0].T, columns=['RT', 'Response'])\ndf2 = pd.DataFrame(data=sim.data[1].T, columns=['RT', 'Response'])\n# %%\nsns.histplot(data=df1,\n x='RT',\n hue='Response')\n# %%\nsns.histplot(data=df2,\n x='RT',\n hue='Response')\n# %%\nsns.histplot(data=Data,\n x='RT',\n hue='Error')\n# %%\n","sub_path":"tests/old/dmc_tests_evolution.py","file_name":"dmc_tests_evolution.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"651053185","text":"class ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n\nclass Solution:\n def reverseKGroup(self, head, k):\n if k <=1:\n return head\n\n if not head:\n return None\n\n temp = head\n new_head = None\n my_prev = None\n\n while temp != None:\n count = 1\n new_tail = temp\n temp2 = temp\n while temp2 is not None and temp2.next is not None and count < k:\n temp2 = temp2.next\n count = count + 1\n temp2_next = temp2.next\n\n # found k nodes to reverse\n if count == k:\n # reverse k nodes\n this_head, this_tail = self.reverse(new_tail, temp2)\n # get a new head for the linked list\n if not new_head:\n new_head = this_head\n # connecting the link list\n this_tail.next = temp2_next\n self.traverse(this_head)\n # else do noting\n if my_prev:\n my_prev.next = this_head\n my_prev = this_tail\n\n # for nxt batch of k nodes\n next_node = None\n if temp2:\n next_node = temp2_next\n temp = next_node\n\n if not new_head:\n return head\n\n return new_head\n\n def reverse(self, head, tail):\n print (\"in reverse\")\n print (\"head\" , head.val)\n print (\"tail\", tail.val)\n temp = head\n new_head = None\n prev = None\n new_tail = None\n while temp!=None and temp != tail:\n new_head = temp\n temp = temp.next\n new_head.next = prev\n prev = new_head\n if not new_tail:\n new_tail = prev\n\n tail.next = new_head\n new_head = tail\n\n return new_head, new_tail\n\n def traverse(self, head):\n temp = head\n while temp !=None:\n print (temp.val)\n temp = temp.next\n\nsolution = Solution()\n\nl = ListNode(1)\nl.next = ListNode(2)\nl.next.next = ListNode(3)\nl.next.next.next = ListNode(4)\nl.next.next.next.next = ListNode(5)\nhead = solution.reverseKGroup(l, 3)\n\nprint (\"---------end-----------\")\nsolution.traverse(head)\n\n\n\n\n\n\n","sub_path":"coding/reverse_nodes_in_k_group.py","file_name":"reverse_nodes_in_k_group.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"647359111","text":"from Jumpscale import j\n\n\nclass Test(j.baseclasses.object):\n def _init(self, **kwargs):\n self.r = j.clients.redis.core\n self._ns = \"tutorial\"\n self.scripts = {}\n\n def register_script(self, name, nrkeys=0):\n\n lua_path = \"%s/%s.lua\" % (self._dirpath, name)\n\n if not j.sal.fs.exists(lua_path):\n raise j.exceptions.Base(\"cannot find:%s\" % lua_path)\n\n name2 = \"%s_%s\" % (self._ns, name)\n\n self.scripts[name] = self.r.storedprocedure_register(name2, nrkeys, lua_path)\n\n return self.scripts[name]\n\n def execute(self, name, *args):\n name2 = \"%s_%s\" % (self._ns, name)\n self.r.storedprocedure_execute(name2, *args)\n\n def debug(self, name, *args):\n \"\"\"\n to see how to use the debugger see https://redis.io/topics/ldb\n\n to break put: redis.breakpoint() inside your lua code\n to continue: do 'c'\n\n\n :param name: name of the sp to execute\n :param args: args to it\n :return:\n \"\"\"\n name2 = \"%s_%s\" % (self._ns, name)\n self.r.storedprocedure_debug(name2, *args)\n\n def do(self):\n self.register_script(\"set\", 3)\n key = 0 # means not used\n data = b\"1234\"\n self.debug(\"set\", \"nstest\", key, data)\n\n\nt = Test()\nt.do()\n","sub_path":"tutorials/servers/redischecks/storeproceduretest.py","file_name":"storeproceduretest.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"549082265","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 19 14:32:59 2018\r\n\r\n@author: tlgreiner\r\n\"\"\"\r\n\r\nfrom keras.datasets import mnist\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.misc import imresize\r\nimport tensorflow as tf\r\nimport numpy as np\r\n\r\n\r\n\r\n(x_train, _), (x_test, _) = mnist.load_data()\r\n\r\nx_train = x_train.astype('float32') / 255.\r\nx_test = x_test.astype('float32') / 255.\r\n\r\nX_train = x_train[0:500,:,:]\r\nX_test = x_test[0:500,:,:]\r\n\r\n\r\n# Define target values\r\nlabel_ = X_train\r\nlabel_ = np.expand_dims(label_,axis=3)\r\nlabel_t = X_test\r\nlabel_t = np.expand_dims(label_t,axis=3)\r\nratio = 4\r\nshape = label_.shape\r\n# Define input values\r\ninput_ = label_[:,:,::ratio,:]\r\ninput_test = X_test[:,:,::ratio]\r\ninput_test = np.expand_dims(input_test,axis=3)\r\n#============Plot target and inputs======= \r\nplt.imshow(label_[5,:,:,0])\r\nplt.imshow(input_[5,:,:,0])\r\n\r\n# Define the high resolution (hr) and low resolution samples (lr) samples\r\nsamp_hr = np.int(shape[1])\r\nsamp_lr = np.int(shape[1]/ratio)\r\n\r\n#=================================================================================\r\n# Define placeholders for inputs and labels\r\nx = tf.placeholder(tf.float32, [shape[0], samp_hr, samp_lr, 1], name='inputs')\r\ny = tf.placeholder(tf.float32, [shape[0], samp_hr, samp_hr, 1], name='labels')\r\nyt= tf.placeholder(tf.float32, [shape[0], samp_hr, samp_hr, 1], name='labels')\r\nxt= tf.placeholder(tf.float32, [shape[0], samp_hr, samp_lr, 1], name='inputs_test')\r\n\r\nY = label_\r\nYt = label_t\r\nX = input_\r\nXt = input_test\r\n\r\nwith tf.Session() as sess:\r\n \r\n\r\n weight1 = tf.Variable(tf.truncated_normal([5, 5, 1, 64], stddev=0.1), name='w1') #(9x9x1 filter size, 64 filters)\r\n weight2 = tf.Variable(tf.truncated_normal([3, 3, 64, 32], stddev=0.1), name='w2') #(3x3x1 filter size, ratio filters) \r\n weight3 = tf.Variable(tf.truncated_normal([3, 3, 32, 16], stddev=0.1), name='w2') #(3x3x1 filter size, ratio filters) \r\n weight4 = tf.Variable(tf.truncated_normal([3, 3, 16, np.int(ratio/2)], stddev=0.1), name='w2') #(3x3x1 filter size, ratio filters)\r\n weight5 = tf.Variable(tf.truncated_normal([3, 3, 1, np.int(ratio/2)], stddev=0.1), name='w3') #(9x9x1 filter size, ratio filters)\r\n weight6 = tf.Variable(tf.truncated_normal([5, 5, 1, 64], stddev=0.1), name='w4')\r\n weight7 = tf.Variable(tf.truncated_normal([3, 3, 64, 32], stddev=0.1), name='w4')\r\n weight8 = tf.Variable(tf.truncated_normal([3, 3, 32, np.int(ratio/2)], stddev=0.1), name='w5') #(9x9x1 filter size, ratio filters)\r\n weight9 = tf.Variable(tf.truncated_normal([3, 3, 1, np.int(ratio/2)], stddev=0.1), name='w3') #(9x9x1 filter size, ratio filters)\r\n weight10 = tf.Variable(tf.truncated_normal([3, 3, 1, 32], stddev=0.1), name='w5') #(9x9x1 filter size, ratio filters)\r\n weight11 = tf.Variable(tf.truncated_normal([3, 3, 32, 1], stddev=0.1), name='w5') #(9x9x1 filter size, ratio filters)\r\n weight12 = tf.Variable(tf.truncated_normal([5, 5, 1, 1], stddev=0.1), name='w5') #(9x9x1 filter size, ratio filters)\r\n\r\n \r\n bias1 = tf.Variable(tf.zeros([64], name='b1'))\r\n bias2 = tf.Variable(tf.zeros([32], name='b2'))\r\n bias3 = tf.Variable(tf.zeros([16], name='b3'))\r\n bias4 = tf.Variable(tf.zeros([np.int(ratio/2)], name='b4'))\r\n bias5 = tf.Variable(tf.zeros([1], name='b5')) \r\n bias6 = tf.Variable(tf.zeros([64], name='b6'))\r\n bias7 = tf.Variable(tf.zeros([32], name='b7'))\r\n bias8 = tf.Variable(tf.zeros([np.int(ratio/2)], name='b7'))\r\n bias9 = tf.Variable(tf.zeros([1], name='b7'))\r\n bias10 = tf.Variable(tf.zeros([32], name='b7'))\r\n bias11 = tf.Variable(tf.zeros([1], name='b7'))\r\n bias12 = tf.Variable(tf.zeros([1], name='b7'))\r\n\r\n\r\n\r\n # Training\r\n conv1 = tf.nn.relu(tf.nn.conv2d(x, weight1, strides=[1,1,1,1], padding='SAME') + bias1)\r\n conv2 = tf.nn.relu(tf.nn.conv2d(conv1, weight2, strides=[1,1,1,1], padding='SAME') + bias2)\r\n conv3 = tf.nn.relu(tf.nn.conv2d_transpose(conv2, weight3, output_shape=(shape[0],samp_hr,np.int(samp_hr/2),1), strides=[1,1,2,1], padding='SAME') + bias3)\r\n conv4 = tf.nn.relu(tf.nn.conv2d(conv3, weight4, strides=[1,1,1,1], padding='SAME') + bias4)\r\n conv5 = tf.nn.relu(tf.nn.conv2d(conv4, weight5, strides=[1,1,1,1], padding='SAME') + bias5)\r\n conv6 = tf.nn.relu(tf.nn.conv2d_transpose(conv5, weight6, output_shape=(shape[0],samp_hr,samp_hr,1), strides=[1,1,2,1], padding='SAME') + bias6)\r\n pred = tf.nn.relu(tf.nn.conv2d(conv6, weight7, strides=[1,1,1,1], padding='SAME') + bias7) \r\n \r\n Sq = tf.square(y - pred)\r\n loss = tf.reduce_mean(Sq)\r\n train_op = tf.train.AdamOptimizer()\r\n training = train_op.minimize(loss)\r\n tf.global_variables_initializer().run()\r\n \r\n \r\n #test = sess.run(Sq, feed_dict={x: X, y: Y})\r\n #y11 = sess.run(conv1, feed_dict={x: X})\r\n #y22 = sess.run(conv2, feed_dict={x: X})\r\n #y33 = sess.run(conv3, feed_dict={x: X})\r\n #y44 = sess.run(conv4, feed_dict={x: X})\r\n #y55 = sess.run(conv5, feed_dict={x: X})\r\n #y66 = sess.run(conv6, feed_dict={x: X})\r\n #y77 = sess.run(pred, feed_dict={x: X}) \r\n #y88 = sess.run(conv7, feed_dict={x: X})\r\n #y5, y6 = sess.run([training, loss], feed_dict={x: X, y: Y})\r\n \r\n \r\n hm_epochs = 250\r\n epoch_loss = 0\r\n \r\n \r\n for epoch in range(hm_epochs):\r\n \r\n test, c = sess.run([training, loss], feed_dict = {x: X, y: Y})\r\n #ct = sess.run(losst, feed_dict = {xt: Xt, yt: Yt})\r\n epoch_loss = c\r\n print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:', epoch_loss)#,'test loss:',ct)\r\n \r\n \r\n test = np.squeeze(sess.run(pred, feed_dict = {x: X}))\r\n #test_test = np.squeeze(sess.run(predt, feed_dict = {xt: Xt}))\r\n \r\n\r\n# Display interpolated training data\r\nn = 10 # how many digits we will display\r\nplt.figure(figsize=(10, 4))\r\nfor i in range(n):\r\n \r\n # display original\r\n ax = plt.subplot(4, n, i + 1)\r\n plt.imshow(label_[i].reshape(28, 28),aspect=\"auto\")\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n\r\n # display input\r\n ax = plt.subplot(4, n, i + 1 + n)\r\n plt.imshow(input_[i].reshape(28, 7),aspect=\"auto\")\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n\r\n # display reconstruction\r\n ax = plt.subplot(4, n, i + 1 + 2*n)\r\n input_int = imresize(input_[i,:,:,0], (samp_hr,samp_hr,1), interp='bicubic', mode=None)\r\n plt.imshow(input_int,aspect=\"auto\")\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n \r\n # display reconstruction\r\n ax = plt.subplot(4, n, i + 1 + 3*n)\r\n plt.imshow(test[i].reshape(28, 28)/np.max(test),aspect=\"auto\")\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False) \r\n \r\n#plt.savefig('Interpolation_test.png', dpi=600) \r\nplt.show()\r\n\r\n\r\nn = 20 # how many digits we will display\r\nplt.figure(figsize=(10, 4))\r\nfor i in range(n):\r\n \r\n # display original\r\n ax = plt.subplot(4, n, i + 1)\r\n plt.imshow(X_test[i].reshape(28, 28),aspect=\"auto\")\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n\r\n # display input\r\n ax = plt.subplot(4, n, i + 1 + n)\r\n plt.imshow(input_test[i].reshape(28, 7),aspect=\"auto\")\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n\r\n # display reconstruction\r\n ax = plt.subplot(4, n, i + 1 + 2*n)\r\n input_int = imresize(input_test[i,:,:,0], (samp_hr,samp_hr,1), interp='bicubic', mode=None)\r\n plt.imshow(input_int,aspect=\"auto\")\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n \r\n \r\n # display reconstruction\r\n ax = plt.subplot(4, n, i + 1 + 3*n)\r\n plt.imshow(np.abs(test_test[i].reshape(28, 28)/np.max(test)),aspect=\"auto\")\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False) \r\nplt.savefig('Interpolation_test.png', dpi=600) \r\nplt.show()\r\n","sub_path":"FYS-STK4155/Project3/CNN_interpolate_Testing_double_decon.py","file_name":"CNN_interpolate_Testing_double_decon.py","file_ext":"py","file_size_in_byte":8500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"419866115","text":"import pandas as pd\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport csv\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom collections import defaultdict\nfrom helpers import nn_arch,nn_reg, myGMM\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import FastICA\nfrom sklearn.random_projection import SparseRandomProjection\nfrom helpers import ImportanceSelect\nfrom sklearn.ensemble import RandomForestClassifier\n\ndef plot_nn_dm_analysis():\n results = pd.read_csv('./NN_results.csv')\n\n original_accuracy = results['Benchmark']\n pca_accuracy = results['PCA']\n ica_accuracy= results['ICA']\n rp_accuracy = results['RP']\n rf_accuracy = results['RF']\n\n n_dimensions = range(1, 11)\n\n fig, ax = plt.subplots(figsize=(8, 5))\n plt.plot(n_dimensions, original_accuracy, color='royalblue', linewidth=2, linestyle='-', marker='p', label=\"Benchmark\")\n plt.plot(n_dimensions, pca_accuracy, color='firebrick', linestyle='-', marker='.', label=\"PCA\")\n plt.plot(n_dimensions, ica_accuracy, color='olivedrab', linestyle='-', marker='.', label=\"ICA\")\n plt.plot(n_dimensions, rp_accuracy, color='blueviolet', linestyle='-', marker='.', label=\"RP\")\n plt.plot(n_dimensions, rf_accuracy, color='darkorange', linestyle='-', marker='.', label=\"RF\")\n\n ax.set_xticks(range(1, 11))\n ax.set_yticks(range(50, 95, 5))\n plt.legend(loc='lower right')\n plt.xlabel(\"# of Dimensions\")\n plt.ylabel(\"Accuracy(%)\")\n plt.title(\"Neural Networks Dimension Reduction - Accuracy\")\n plt.grid()\n plt.savefig('./neuralnetwork_dr_acc.png')\n\nnp.random.seed(42)\ndims = range(1,11)\n\nwine = pd.read_csv('./BASE/Wine.csv')\nwineX = wine.drop('quality', 1).copy().values\nwineY = wine['quality'].copy().values\nwineX= StandardScaler().fit_transform(wineX)\n\n# Benchmark \ngrid ={'NN__alpha':nn_reg,'NN__hidden_layer_sizes':nn_arch}\nmlp = MLPClassifier(activation='relu',max_iter=1000,early_stopping=True,random_state=5)\npipe = Pipeline([('NN',mlp)])\ngs = GridSearchCV(pipe,grid,verbose=10,cv=5)\n\ngs.fit(wineX,wineY)\ntmp = pd.DataFrame(gs.cv_results_)\ntmp.to_csv('./BASE/NN_bmk.csv')\nbenchmark = gs.best_score_\nresults = defaultdict(dict)\n\nfor i in dims:\n\tresults[i]['Benchmark'] = 100.*benchmark\n\t# PCA\n\tgrid ={'pca__n_components':[i] ,'NN__alpha':nn_reg,'NN__hidden_layer_sizes':nn_arch}\n\tpca = PCA(random_state=5) \n\tmlp = MLPClassifier(activation='relu',max_iter=1000,early_stopping=True,random_state=5)\n\tpipe = Pipeline([('pca',pca),('NN',mlp)])\n\tgs = GridSearchCV(pipe,grid,verbose=10,cv=5)\n\n\tgs.fit(wineX, wineY)\n\tresults[i]['PCA'] = 100.*gs.best_score_\n\ttmp = pd.DataFrame(gs.cv_results_)\n\ttmp.to_csv('./PCA/nn.csv')\n\n\t# ICA\n\tgrid ={'ica__n_components':[i],'NN__alpha':nn_reg,'NN__hidden_layer_sizes':nn_arch}\n\tica = FastICA(random_state=5) \n\tmlp = MLPClassifier(activation='relu',max_iter=1000,early_stopping=True,random_state=5)\n\tpipe = Pipeline([('ica',ica),('NN',mlp)])\n\tgs = GridSearchCV(pipe,grid,verbose=10,cv=5)\n\n\tgs.fit(wineX, wineY)\n\tresults[i]['ICA'] = 100.*gs.best_score_\n\ttmp = pd.DataFrame(gs.cv_results_)\n\ttmp.to_csv('./ICA/nn.csv')\n\n\t# RP\n\tgrid ={'rp__n_components':[i],'NN__alpha':nn_reg,'NN__hidden_layer_sizes':nn_arch}\n\trp = SparseRandomProjection(random_state=5) \n\tmlp = MLPClassifier(activation='relu',max_iter=1000,early_stopping=True,random_state=5)\n\tpipe = Pipeline([('rp',rp),('NN',mlp)])\n\tgs = GridSearchCV(pipe,grid,verbose=10,cv=5)\n\n\tgs.fit(wineX,wineY)\n\tresults[i]['RP'] = 100.*gs.best_score_\n\ttmp = pd.DataFrame(gs.cv_results_)\n\ttmp.to_csv('./RP/nn.csv')\n\n\n\trfc = RandomForestClassifier(n_estimators=100,class_weight='balanced',random_state=5,n_jobs=-1)\n\tfiltr = ImportanceSelect(rfc)\n\tgrid ={'filter__n':[i],'NN__alpha':nn_reg,'NN__hidden_layer_sizes':nn_arch}\n\tmlp = MLPClassifier(activation='relu',max_iter=1000,early_stopping=True,random_state=5)\n\tpipe = Pipeline([('filter',filtr),('NN',mlp)])\n\tgs = GridSearchCV(pipe,grid,verbose=10,cv=5)\n\n\tgs.fit(wineX, wineY)\n\tresults[i]['RF'] = 100.*gs.best_score_\n\ttmp = pd.DataFrame(gs.cv_results_)\n\ttmp.to_csv('./RF/nn.csv')\n\nresults = pd.DataFrame(results).T\nresults.to_csv('./NN_results.csv')\n\nplot_nn_dm_analysis()\n\n'''\nclusters = [1,2,3,4,5,6,7,8,9,10]\n\ngrid ={'km__n_clusters':clusters,'NN__alpha':nn_reg,'NN__hidden_layer_sizes':nn_arch}\nmlp = MLPClassifier(activation='relu',max_iter=1000,early_stopping=True,random_state=5)\nkm = kmeans(random_state=5)\npipe = Pipeline([('km',km),('NN',mlp)])\ngs = GridSearchCV(pipe,grid,verbose=10,cv=5)\n\ngs.fit(wineX,wineY)\ntmp = pd.DataFrame(gs.cv_results_)\ntmp.to_csv('./wine_cluster_Kmeans.csv')\n\ngrid ={'gmm__n_components':clusters,'NN__alpha':nn_reg,'NN__hidden_layer_sizes':nn_arch}\nmlp = MLPClassifier(activation='relu',max_iter=1000,early_stopping=True,random_state=5)\ngmm = myGMM(random_state=5)\npipe = Pipeline([('gmm',gmm),('NN',mlp)])\ngs = GridSearchCV(pipe,grid,verbose=10,cv=5)\n\ngs.fit(wineX,wineY)\ntmp = pd.DataFrame(gs.cv_results_)\ntmp.to_csv('./wine_cluster_GMM.csv')\n'''","sub_path":"UnsupervisedLearningAndDimensionalityReduction/neuralnetwork.py","file_name":"neuralnetwork.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"62502036","text":"import scrapy\nfrom scrapy.http import HtmlResponse\nfrom leruamerlenparser.items import LeruamerlenparserItem\nfrom scrapy.loader import ItemLoader\n\n\nclass LeroymerlinSpider(scrapy.Spider):\n name = 'Leroymerlin'\n allowed_domains = ['https://leroymerlin.ru/']\n\n\n def __init__(self, query):\n \"\"\"Constructor.\"\"\"\n super(LeroymerlinSpider, self).__init__()\n self.start_urls = [f'https://leroymerlin.ru/search/?q={query}']\n self.query = query\n\n\n def parse(self, response):\n \"\"\"Goods parser.\"\"\"\n goods_links = response.xpath('//uc-plp-item-new/@href').extract()\n for link in goods_links:\n yield response.follow(link, callback=self.parse_item, dont_filter=True)\n\n next_page = response.xpath('//div[@class = \"next-paginator-button-wrapper\"]/a/@href').extract_first()\n if next_page:\n yield response.follow(next_page, callback=self.parse, dont_filter=True)\n\n\n def parse_item(self, response:HtmlResponse):\n \"\"\"Parse item.\"\"\"\n loader = ItemLoader(item=LeruamerlenparserItem(), response=response)\n loader.add_xpath('name', '//h1/text()')\n loader.add_xpath('photos', '//uc-pdp-media-carousel//picture[@slot=\"pictures\"]/img/@src')\n loader.add_xpath('characteristics', '//dt[@class=\"def-list__term\"]/text() | //dd[@class=\"def-list__definition\"]/text()')\n loader.add_value('url', response.url)\n loader.add_xpath('price', '//span[@slot=\"price\"]/text()')\n\n yield loader.load_item()\n","sub_path":"lesson_7/leruamerlenparser/spiders/Leroymerlin.py","file_name":"Leroymerlin.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"159560431","text":"from flask import Flask, render_template, request, redirect, url_for, flash, jsonify\napp = Flask(__name__)\n\n# imports for CRUD operations\nfrom database_setup import Restaurant, Base, MenuItem\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\n\n# Establish DB connection\n# the check_same_thread param allows CRUD ops to work between different pages. Possible better option is to use Flask-SQLAlchemy extension\nengine=create_engine('sqlite:///restaurantmenu.db?check_same_thread=False')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession=DBSession()\n\n# API endpoints\n@app.route('/restaurants/JSON')\ndef restaurantsJSON():\n restaurants=session.query(Restaurant).all()\n return jsonify(Restaurants=[r.serialize for r in restaurants])\n\n# Additional API endpoints\n@app.route('/restaurant//menu/JSON')\ndef restaurantMenuJSON(restaurant_id):\n restaurant = session.query(Restaurant).filter_by(id = restaurant_id).one()\n items = session.query(MenuItem).filter_by(restaurant_id = restaurant_id).all()\n return jsonify(MenuItems=[i.serialize for i in items])\n\n# Making another API Endpoint (GET request)\n@app.route('/restaurant//menu//JSON')\ndef restaurantMenuItemJSON(restaurant_id, menu_id):\n item = session.query(MenuItem).filter_by(id = menu_id).one()\n return jsonify(MenuItem=item.serialize)\n\n@app.route('/')\n@app.route('/restaurants')\ndef showRestaurants():\n restaurants=session.query(Restaurant).all()\n return render_template('restaurants.html', restaurants=restaurants)\n\n@app.route('/restaurant/new', methods=['GET', 'POST'])\ndef newRestaurant():\n if request.method == 'POST':\n newRestaurant = Restaurant(name = request.form['name'])\n session.add(newRestaurant)\n session.commit()\n flash(\"New Restaurant Created\")\n return redirect(url_for('showRestaurants'))\n else:\n return render_template('newRestaurant.html')\n\n@app.route('/restaurant//edit', methods=['GET', 'POST'])\ndef editRestaurant(restaurant_id):\n restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n if request.method == 'POST':\n newName = request.form['name']\n restaurant.name = newName\n session.add(restaurant)\n session.commit()\n flash(\"Restaurant Updated!\")\n return redirect(url_for('showRestaurants'))\n else:\n return render_template('editRestaurant.html', restaurant=restaurant)\n\n@app.route('/restaurant//delete', methods=['GET', 'POST'])\ndef deleteRestaurant(restaurant_id):\n restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n if request.method == 'POST':\n session.delete(restaurant)\n session.commit()\n flash(\"Restaurant Deleted!\")\n return redirect(url_for('showRestaurants'))\n return render_template('deleteRestaurant.html', restaurant=restaurant)\n\n@app.route('/restaurant/')\n@app.route('/restaurant//menu')\ndef restaurantMenu(restaurant_id):\n restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n items = session.query(MenuItem).filter_by(restaurant_id = restaurant.id)\n return render_template('menu.html', restaurant=restaurant, items=items)\n\n@app.route('/restaurant//menu/new', methods=['GET', 'POST'])\ndef newMenuItem(restaurant_id):\n if request.method == 'POST':\n newItem = MenuItem(name = request.form['name'], restaurant_id = restaurant_id)\n session.add(newItem)\n session.commit()\n flash(\"new menu item created\")\n return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))\n else:\n return render_template('newmenuitem.html', restaurant_id = restaurant_id)\n\n@app.route('/restaurant//menu//edit/', methods=['GET', 'POST'])\ndef editMenuItem(restaurant_id, menu_id):\n item = session.query(MenuItem).filter_by(id = menu_id).one()\n if request.method == 'POST':\n newName = request.form['name']\n item.name = newName\n session.add(item)\n session.commit()\n flash(\"Item updated!\")\n return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))\n else:\n return render_template('editmenuitem.html', restaurant_id=restaurant_id, menu_id=menu_id, item = item)\n\n\n@app.route('/restaurant//menu//delete/', methods=['GET', 'POST'])\ndef deleteMenuItem(restaurant_id, menu_id):\n item = session.query(MenuItem).filter_by(id = menu_id).one()\n if request.method == 'POST':\n session.delete(item)\n session.commit()\n flash(\"item deleted\")\n return redirect(url_for('restaurantMenu', restaurant_id = restaurant_id))\n else:\n return render_template('deletemenuitem.html', restaurant_id=restaurant_id, menu_id=menu_id)\n\nif __name__ == \"__main__\":\n app.secret_key = 'super_secret_key'\n app.debug = True\n app.run(host = '0.0.0.0', port = 5000)\n","sub_path":"vagrant/MenuProject/finalProject.py","file_name":"finalProject.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"402146270","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 20 17:06:00 2019\r\n\r\n@author: ignac\r\n\"\"\"\r\n\r\nimport pandapower as pp\r\nnet = pp.create_empty_network() \r\n\r\n#create buses\r\nb1 = pp.create_bus(net, vn_kv=20., name=\"Bus 1\")\r\nb2 = pp.create_bus(net, vn_kv=0.4, name=\"Bus 2\")\r\nb3 = pp.create_bus(net, vn_kv=0.4, name=\"Bus 3\")\r\n\r\n#create bus elements\r\npp.create_ext_grid(net, bus=b1, vm_pu=1.02, name=\"Grid Connection\")\r\npp.create_load(net, bus=b3, p_mw=0.1, q_mvar=0.05, name=\"Load\")\r\n\r\n#create branch elements\r\ntid = pp.create_transformer(net, hv_bus=b1, lv_bus=b2, std_type=\"0.4 MVA 20/0.4 kV\", name=\"Trafo\")\r\npp.create_line(net, from_bus=b2, to_bus=b3, length_km=0.1, name=\"Line\",std_type=\"NAYY 4x50 SE\") \r\n\r\npp.runpp(net,numba=False)\r\nprint(net.res_bus)\r\n\r\n# =============================================================================\r\n# EXAMPLE\r\n# =============================================================================\r\n# import SCOPF_EVALUACION_TECNICA as et\r\n# import numpy as np\r\n# PMIN = np.array([0,30,10]).tolist()\r\n# PMAX = np.array([100,150,150]).tolist()\r\n# FMAX = np.array([50,100,100]).tolist()\r\n# CV = np.array([5,30,120]).tolist()\r\n# CR = np.array([10,10,10]).tolist()\r\n# D = np.array([30,60,120]).tolist()\r\n# RAMPMAX = np.array([50,50,50]).tolist()\r\n# PROBSCEN = np.array([0,0.01,0.01,0.01,0.01,0.01, 0.01]).tolist()\r\n# CRUP = np.array([100,20,10]).tolist()\r\n# CRDOWN = np.array([80,50,10]).tolist()\r\n\r\n# filename = 'RES_CORRECTIVO.xlsx'\r\n# # wb = xw.Book(filename)\r\n# Qgen = np.array([0,0,0]).tolist()\r\n# Qcon= np.array([0,0,0]).tolist()\r\n# QMAX = np.array([100,100,100]).tolist()\r\n# QMIN = np.array([0,0,0]).tolist()\r\n\r\n# psol = np.array([90,60,90]).tolist()\r\n# et.evaluacionTec(psol,Qgen,D,Qcon,PMAX,QMAX,PMIN,QMIN,filename,2,print_results=True)","sub_path":"SIPS/prueba.py","file_name":"prueba.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"91995199","text":"from pytube import YouTube\nimport moviepy.editor as mp\nfrom PIL import Image\n# import imageio\n\nvideo_id = \"h6yJEHHT5eA\"\ntry:\n youtube = YouTube(\"https://www.youtube.com/watch?v=\"+video_id)\n youtube.set_filename('tmp')\nexcept:\n print(\"there is no video\")\n\ntry:\n video = youtube.get('mp4', '360p')\nexcept:\n print(\"there is no video for this setting\")\n\nvideo.download(\".\")\n\nclip = mp.VideoFileClip(\"tmp.mp4\")\nclip.audio.write_audiofile(\"tmp.wav\")\n\nfps = clip.fps\n\nnum_frames = int(fps * clip.duration)\n\n# to get frame\nclip.get_frame(0)\n# to get image instance from numpy array\nimg = Image.fromarray(clip.get_frame(0))\nimg.thumbnail([30,30], Image.ANTIALIAS)\n# reader = imageio.get_reader('tmp.mp4')","sub_path":"vgg/download_youtube.py","file_name":"download_youtube.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"336659684","text":"from __future__ import print_function, division\n\nimport os\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" \nos.environ['CUDA_VISIBLE_DEVICES'] = '1'\n\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.layers import Input, Dense, Reshape, Flatten, Dropout\nfrom tensorflow.keras.layers import BatchNormalization, Activation, ZeroPadding2D\nfrom tensorflow.keras.layers import LeakyReLU\n\n#from tensorflow.keras.layers import _Merge\nfrom tensorflow.keras.layers import Concatenate\nfrom tensorflow.keras.layers import UpSampling2D, Conv2D\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.optimizers import RMSprop\nfrom functools import partial\nfrom sklearn.utils import shuffle\nfrom tensorflow.keras.models import model_from_yaml\n\nimport keras.backend as K\nimport tensorflow.keras as keras\nimport matplotlib.pyplot as plt\n\nimport sys\nimport math\nimport numpy as np\n\nfrom data_handling import *\nfrom keras_models import *\nfrom processwGANs import *\n\nimport cv2 \nimport tensorflow as tf\nfrom keras.callbacks import TensorBoard\n\nfrom timeit import default_timer as timer\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\nfrom keras.backend.tensorflow_backend import set_session\nimport tensorflow as tf\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True # dynamically grow the memory used on the GPU\n#config.log_device_placement = True # to log device placement (on which device the operation ran)\nsess = tf.Session(config=config)\nset_session(sess)\n\n# batch size for the whole network.\nbatch_size = 256\n\n# it is used for the implemenaiton of gradient penalty for the Wasserstein loss.\nclass RandomWeightedAverage(Concatenate): #_Merge\n \"\"\"Provides a (random) weighted average between real and generated image samples\"\"\"\n def _merge_function(self, inputs):\n alpha = K.random_uniform((batch_size, 1, 1, 1))\n return (alpha * inputs[0]) + ((1 - alpha) * inputs[1])\n\nclass WGANGP():\n def __init__(self):\n \n self.mtds = MTDS()\n self.plimgs = PLIMGS()\n \n self.noise_weight = 0.3\n self.target_mod = \"face\"\n self.input_feats = \"3dCNN\"\n self.db = \"cremad\"\n self.learning_param = 0.0001\n self.input_type = \"with_source\"\n self._featsD = 64\n self._noizeD = 32\n\n self.face_sequence = False\n\n self.comment = \"third_version_with_noise_\"+ str(self._noizeD)\n self.db_path = \"../../GANs_models/tmp_dtst/dataAugm/\"\n # Following parameter and optimizer set as recommended in paper\n self.n_critic = 5\n optimizer = RMSprop(lr=self.learning_param)\n\n if self.input_type == \"with_source\":\n self.input_to_G = True\n else:\n self.input_to_G = False\n\n self.obj = data_handle()\n\n self.latent_dim = self._featsD + self._noizeD + 6\n \n if self.target_mod == \"audio\":\n self.img_rows = 28\n self.img_cols = 112\n self.channels = 3\n self.img_shape = (self.img_rows, self.img_cols, self.channels)\n\n # Build the generator and critic\n self.generator = build_generator(self.latent_dim, self.channels)\n #self.generator = self.build_generator_old()\n self.critic = build_critic(self.img_shape)\n\n elif self.target_mod == \"face\":\n \n if self.face_sequence == False:\n self.img_rows = 28\n self.img_cols = 28\n self.channels = 3\n else:\n self.img_rows = 28\n self.img_cols = 280\n self.channels = 3\n\n self.img_shape = (self.img_rows, self.img_cols, self.channels)\n\n # Build the generator and critic\n self.generator = build_generator_face(self.latent_dim, self.channels, self.face_sequence)\n #self.generator = self.build_generator_old()\n self.critic = build_critic_v(self.img_shape, self.face_sequence)\n\n #-------------------------------\n # Construct Computational Graph\n # for the Critic\n #-------------------------------\n\n # Freeze generator's layers while training critic\n self.generator.trainable = False\n\n # Image input (real sample)\n real_img = Input(shape=self.img_shape)\n\n # Noise input\n z_disc = Input(shape=(self.latent_dim,))\n # Generate image based of noise (fake sample)\n fake_img = self.generator(z_disc)\n\n # Discriminator determines validity of the real and fake images\n fake, aux1 = self.critic(fake_img)\n valid, aux2 = self.critic(real_img)\n\n # Construct weighted average between real and fake images\n interpolated_img = RandomWeightedAverage()([real_img, fake_img])\n # Determine validity of weighted sample\n validity_interpolated, aux3 = self.critic(interpolated_img)\n\n # Use Python partial to provide loss function with additional\n # 'averaged_samples' argument\n partial_gp_loss = partial(self.gradient_penalty_loss,\n averaged_samples=interpolated_img)\n partial_gp_loss.__name__ = 'gradient_penalty' # Keras requires function names\n\n self.critic_model = Model(inputs=[real_img, z_disc],\n outputs=[valid, fake, validity_interpolated, aux1])\n \n self.critic_model.compile(loss=[self.wasserstein_loss,\n self.wasserstein_loss,\n partial_gp_loss,\n 'categorical_crossentropy'],\n optimizer=optimizer,\n metrics=['accuracy'],\n loss_weights=[1, 1, 5, 1])\n\n #-------------------------------\n # Construct Computational Graph\n # for Generator\n #-------------------------------\n\n # For the generator we freeze the critic's layers\n self.critic.trainable = False\n self.generator.trainable = True\n\n # Sampled noise for input to generator\n z_gen = Input(shape=(self.latent_dim,))\n # Generate images based of noise\n img = self.generator(z_gen)\n # Discriminator determines validity\n valid = self.critic(img)\n # Defines generator model\n self.generator_model = Model(z_gen, valid)\n self.generator_model.compile(loss=self.wasserstein_loss, optimizer=optimizer)\n\n\n def gradient_penalty_loss(self, y_true, y_pred, averaged_samples):\n \"\"\"\n Computes gradient penalty based on prediction and weighted real / fake samples\n \"\"\"\n gradients = K.gradients(y_pred, averaged_samples)[0]\n # compute the euclidean norm by squaring ...\n gradients_sqr = K.square(gradients)\n # ... summing over the rows ...\n gradients_sqr_sum = K.sum(gradients_sqr,\n axis=np.arange(1, len(gradients_sqr.shape)))\n # ... and sqrt\n gradient_l2_norm = K.sqrt(gradients_sqr_sum)\n # compute lambda * (1 - ||grad||)^2 still for each single sample\n gradient_penalty = K.square(1 - gradient_l2_norm)\n # return the mean as loss over all the batch samples\n return K.mean(gradient_penalty)\n\n\n def wasserstein_loss(self, y_true, y_pred):\n return K.mean(y_true * y_pred)\n\n \n def named_logs(self, model, logs):\n \n result = {}\n for l in zip(model.metrics_names, logs):\n result[l[0]] = l[1]\n return result\n \n def load_model_from_yaml(self, file_name):\n\n yaml_model = open(file_name, 'r')\n loaded_model_yaml = yaml_model.read()\n yaml_model.close()\n loaded_model = model_from_yaml(loaded_model_yaml)\n\n return loaded_model\n\n\n def prediction_classificer(self, images):\n \n input_shape = (28, 112, 3)\n model = cnnModel(input_shape, 6)\n model.compile(optimizer= RMSprop(lr=0.0001, \n decay=1e-6), \n loss='categorical_crossentropy', \n metrics=['accuracy'])\n\n model.load_weights(\"../models/spec_classifier\")\n model.pop()\n preds = model.predict(images)\n return preds\n\n\n # whole training process\n def train(self, epochs, batch_size, sample_interval=50):\n\n start = timer()\n if self.input_feats == \"3dCNN\":\n if self.db == \"ravdess\":\n _dct_ = self.obj.load_3d_dataset_rav(self.target_mod) #ravdess\n else:\n if self.input_to_G == True and self.target_mod == 'face':\n _dct_ = self.obj.load_3d_dataset_v2(self.target_mod, self.img_rows) #crema\n elif self.input_to_G == False and self.target_mod == 'face':\n _dct_ = self.obj.load_3d_dataset(self.target_mod, self.img_rows)\n elif self.target_mod == 'audio':\n _dct_ = self.obj.load_3d_dataset_v2(self.target_mod, self.img_rows)\n else:\n _dct_ = self.obj.temporal_feats(self.target_mod, 1, \n self._featsD, \n self.input_feats, \n self.db_path)\n\n zero = timer()\n print(\"zero interval: \" + str(zero - start))\n\n file_name = self.target_mod\n\n # Adversarial ground truths\n valid = -np.ones((batch_size, 1))\n fake = np.ones((batch_size, 1))\n dummy = np.zeros((batch_size, 1)) # Dummy gt for gradient penalty\n\n # Create the TensorBoard callback,\n # which we will drive manually\n tensorboard = keras.callbacks.TensorBoard(\n log_dir='my_tf_logs',\n histogram_freq=0,\n batch_size=batch_size,\n write_graph=True,\n write_grads=True\n )\n\n tensorboard.set_model(self.generator_model)\n model_yaml_gn = self.generator_model.to_yaml()\n model_yaml_cr = self.critic_model.to_yaml()\n\n model_name = \"../../GANs_models/yaml/\" \\\n +self.input_feats \\\n +\"_\" + self.db \\\n +\"_\" + str(self.latent_dim) \\\n +\"_\"+ str(self.face_sequence) \\\n +\"_\" + str(self.learning_param) \\\n +\"_\"+str(self.input_feats) \\\n +\"_\" + self.input_type \\\n +\"_\" + self.comment \\\n +\"_\"+str(self.img_rows) \\\n +\"_gen_noise_feats_generator_model.yaml\"\n \n with open(model_name, \"w\") as yaml_file:\n yaml_file.write(model_yaml_gn)\n \n with open(model_name, \"w\") as yaml_file:\n yaml_file.write(model_yaml_cr)\n\n my_loss_trn = []\n my_loss_vld = []\n \n self.mtds.open_files(_dct_, file_name, self)\n for epoch in range(epochs):\n for _ in range(self.n_critic):\n first = timer()\n # ---------------------\n # Train Discriminator\n # ---------------------\n # Select a random batch of images\n idx = np.random.randint(0, _dct_[\"trn_trg\"].shape[0], batch_size)\n idx_tst = np.random.randint(0, _dct_[\"tst_trg\"].shape[0], batch_size)\n idx_vld = np.random.randint(0, _dct_[\"vld_trg\"].shape[0], batch_size)\n\n batch_lbls = _dct_[\"trn_lbls\"][idx]\n feats = _dct_[\"trn_fts\"][idx]\n\n batch_lbls_vld = _dct_[\"vld_lbls\"][idx_vld]\n feats_vld = _dct_[\"vld_fts\"][idx_vld]\n\n batch_lbls_tst = _dct_[\"tst_lbls\"][idx_tst]\n feats_tst = _dct_[\"tst_fts\"][idx_tst]\n\n half = timer()\n print(\"half interval: \" + str(half - first))\n\n if self.face_sequence == True:\n \n imgs = self.mtds._cmb_ten_fr_(_dct_[\"trn_trg\"][idx])\n imgs_tst = self.mtds._cmb_ten_fr_(_dct_[\"tst_trg\"][idx_tst])\n imgs_vld = self.mtds._cmb_ten_fr_(_dct_[\"vld_trg\"][idx_tst])\n #feats = self.prediction_classificer(feats)\n #feats_tst = self.prediction_classificer(feats_tst)\n else:\n imgs = _dct_[\"trn_trg\"][idx]\n imgs_tst = _dct_[\"tst_trg\"][idx_tst]\n imgs_vld = _dct_[\"vld_trg\"][idx_vld]\n\n second = timer()\n print(\"second interval: \" + str(second - half))\n\n pdb.set_trace()\n # Sample generator input\n #noise = np.random.rand(batch_size, self._noizeD).astype(np.float32)\n noise = self.noise_weight*np.random.random((batch_size, self._noizeD))\n if self.input_to_G ==True:\n conditional_vector = np.concatenate([feats, noise, batch_lbls], axis = 1)\n cndl_tst_vector = np.concatenate([feats_tst, noise, batch_lbls_tst], axis = 1)\n cndl_vld_vector = np.concatenate([feats_vld, noise, batch_lbls_vld], axis = 1)\n else:\n conditional_vector = np.concatenate([noise, batch_lbls], axis = 1)\n cndl_tst_vector = np.concatenate([noise, batch_lbls_tst], axis = 1)\n cndl_vld_vector = np.concatenate([noise, batch_lbls_vld], axis = 1)\n #conditional_vector = np.concatenate([noise], axis = 1)\n \n # Train the critic\n d_loss = self.critic_model.train_on_batch([imgs, conditional_vector],\n [valid, fake, dummy, batch_lbls])\n d_loss_vld = self.critic_model.evaluate([imgs_vld, cndl_vld_vector],\n [valid, fake, dummy, batch_lbls_tst], batch_size = batch_size)\n # ---------------------\n # Train Generator\n # ---------------------\n g_loss = self.generator_model.train_on_batch(conditional_vector, [valid, batch_lbls])\n g_loss_vld = self.generator_model.train_on_batch(cndl_vld_vector, [valid, batch_lbls_vld])\n tensorboard.on_epoch_end(epoch, self.named_logs(self.generator_model, g_loss)) \n\n print (\"============================\")\n print (\"training loss ...\")\n print (d_loss)\n # if d_loss_vld[8]>0.60:\n # pdb.set_trace()\n print (\"validation loss ... \" + str(d_loss_vld[8]))\n print (\"============================\")\n #print (\"%d [D loss: %f] [G loss: %f]\" % (epoch, d_loss[0], g_loss[0]))\n\n my_loss_trn.append(d_loss)\n my_loss_vld.append(d_loss_vld) \n # If at save interval => save generated image samples\n \n three = timer()\n print(\"third interval: \" + str(three - second))\n if epoch % 200 == 0:\n \n gen_trn = self.generator.predict([conditional_vector])\n gen_tst = self.generator.predict([cndl_tst_vector])\n\n ql_mtrcs = \"../../GANs_assets/metrics/quality/\"\\\n +\"batch_data_\"\\\n +self.input_feats \\\n +\"_\" + self.db \\\n +\"_\"+ str(self.face_sequence) \\\n +\"_\" + str(epoch) \\\n +\"_\"+str(self.latent_dim) \\\n +\"_\"+str(self.learning_param) \\\n +\"_\"+str(self.input_feats) \\\n +\"_\"+self.input_type \\\n +\"_\" + self.comment \\\n +\"_\"+str(self.img_rows) \\\n +\"_gen_noise_feats_\" \\\n + file_name+\".pkl\"\n \n batch_dict = {\"gen_trn\": gen_trn, \n \"gen_tst\": gen_tst,\n \"real\": imgs}\n\n self.obj.store_obj(ql_mtrcs, batch_dict)\n\n self.sample_images(epoch, \n batch_lbls, \n feats, \n batch_size, \n imgs, \n file_name)\n\n weight_name = \"../../GANs_models/weights/\"\\\n +\"generator_\" \\\n +self.input_feats \\\n +\"_\" + self.db \\\n +\"_\"+ str(self.face_sequence) \\\n +\"_\"+str(self.latent_dim) \\\n +\"_\"+str(self.learning_param) \\\n +\"_\"+str(self.input_feats) \\\n +\"_\"+self.input_type \\\n +\"_\" + self.comment \\\n +\"_\"+str(self.img_rows) \\\n +\"_gen_noise_feats_\" \\\n + file_name+\"_\"\n\n self.generator.save_weights(weight_name)\n \n _loss_obj_ = \"../../GANs_models/loss/\"\\\n +\"loss_\" \\\n +self.input_feats \\\n +\"_\" + self.db \\\n +\"_\"+ str(self.face_sequence) \\\n +\"_\"+str(self.latent_dim) \\\n +\"_\"+str(self.learning_param) \\\n +\"_\"+str(self.input_feats) \\\n +\"_\"+self.input_type \\\n +\"_\" + self.comment \\\n +\"_\"+str(self.img_rows) \\\n +\"_gen_noise_feats_\" \\\n + file_name+\"_loss.pkl\"\n\n #pdb.set_trace()\n loss_dict = {\"train_loss\": my_loss_trn, \"validation_loss\": my_loss_vld}\n self.obj.store_obj(_loss_obj_, loss_dict)\n\n\n # Store generated images.\n def sample_images(self, epoch, batch_lbls, feats, batch_size, imgs, file_name):\n r, c = 5, 5\n #noise = np.random.normal(0, 1, (r * c, self.latent_dim- 6))\n #noise = np.random.normal(0, 1, (batch_size, self._noizeD))\\\n noise = self.noise_weight*np.random.random((batch_size, self._noizeD))\n\n \n if self.input_to_G == True:\n conditional_vector = np.concatenate([feats, noise, batch_lbls], axis = 1)\n else:\n conditional_vector = np.concatenate([noise, batch_lbls], axis = 1)\n #conditional_vector = np.concatenate([noise], axis = 1)\n\n #conditional_vector = np.concatenate([noise, batch_lbls], axis = 1)\n gen_imgs = self.generator.predict(conditional_vector)\n # Finally store the images to the local path\n \n gen_imgs_name = \"../../GANs_assets/generated_imgs/wgans/\" \\\n +self.input_feats+\"_noise_lbls_\" \\\n +\"_\" + self.db \\\n +\"_\"+ str(self.face_sequence) \\\n +\"_\"+ file_name \\\n +\"_\"+self.input_type \\\n +\"_\" + self.comment \\\n +\"_\"+str(self.img_rows) \\\n +\"_new_img_%d.png\" % epoch \n \n real_imgs_name = \"../../GANs_assets/generated_imgs/wgans/\" \\\n +self.input_feats+\"_noise_lbls_\" \\\n +self.db \\\n +\"_\"+ str(self.face_sequence) \\\n +\"_\"+self.input_type \\\n +\"_\" + self.comment \\\n +\"_\"+str(self.img_rows) \\\n +\"_real_img_%d.png\" % epoch\n \n\n self.mtds._str_imgs_(gen_imgs, batch_lbls, gen_imgs_name)\n self.mtds._str_imgs_(imgs, batch_lbls, real_imgs_name)\n\n # self.plimgs._plotImgs_(gen_imgs, batch_lbls, gen_imgs_name, 16)\n # self.plimgs._plotImgs_(imgs, batch_lbls, real_imgs_name, 16)\n \n fl = \"../../GANs_assets/metrics/wgans/3dCNN/\" \\\n +self.input_feats+\"_noise_lbls_\" \\\n + str(self.input_feats) \\\n +\"_\" + self.db + \"_\" \\\n + file_name \\\n +\"_\"+self.input_type \\\n +\"_\" + self.comment \\\n +\"_\"+str(self.img_rows) \\\n +\"_quality_metrics_data_%d.pkl\" % epoch\n\n my_gen_dict = {\"real\": imgs, \"generated\": gen_imgs, \"labels\": batch_lbls}\n self.obj.store_obj(fl, my_gen_dict)\n\n\nif __name__ == '__main__':\n wgan = WGANGP()\n wgan.train(epochs=80000, \n batch_size=batch_size, \n sample_interval=100)","sub_path":"my_iwgans.py","file_name":"my_iwgans.py","file_ext":"py","file_size_in_byte":19609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"630151323","text":"import pickle\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nfrom datetime import datetime\n\ndef load_data():\n \"\"\"\n Load in the pickle file.\n \"\"\"\n try:\n with open('data/user2movie.json', 'rb') as f:\n user2movie = pickle.load(f)\n with open('data/movie2user.json', 'rb') as f:\n movie2user = pickle.load(f)\n with open('data/usermovie2rating.json', 'rb') as f:\n usermovie2rating = pickle.load(f)\n with open('data/user2movie_test.json', 'rb') as f:\n user2movie_test = pickle.load(f)\n with open('data/movie2user_test.json', 'rb') as f:\n movie2user_test = pickle.load(f)\n with open('data/usermovie2rating_test.json', 'rb') as f:\n usermovie2rating_test = pickle.load(f)\n except:\n raise Exception('File does not exist.')\n \n return user2movie, movie2user, usermovie2rating, user2movie_test, movie2user_test, usermovie2rating_test\n\ndef convert_dataset(user2movie, movie2user, usermovie2rating_test):\n \"\"\"\n Convert the dataset to make it vectorized.\n \"\"\"\n user2movierating = {}\n for i, movies in user2movie.items():\n r = np.array([usermovie2rating[(i,j)] for j in movies])\n user2movierating[i] = (movies, r)\n movie2userrating = {}\n for j, users in movie2user.items():\n r = np.array([usermovie2rating[(i,j)] for i in users])\n movie2userrating[j] = (users, r)\n \n movie2userrating_test = {}\n for (i, j), r in usermovie2rating_test.items():\n if j not in movie2userrating_test:\n movie2userrating_test[j] = [[i], [r]]\n else:\n movie2userrating_test[j][0].append(i)\n movie2userrating_test[j][1].append(r)\n for j, (users, r) in movie2userrating_test.items():\n movie2userrating_test[j][1] = np.array(r)\n return user2movierating, movie2userrating, movie2userrating_test\n\n\n\ndef initialize_variables(dim, user2movie, movie2user, movie2user_test, usermovie2rating):\n \"\"\"\n Initialize variables for training.\n \"\"\"\n N = np.max(list(user2movie.keys())) + 1\n m1 = np.max(list(movie2user.keys()))\n m2 = np.max(list(movie2user_test.keys()))\n M = max(m1, m2) + 1\n \n K = dim\n W = np.random.rand(N,K)\n b = np.zeros(N)\n U = np.random.rand(M,K)\n c = np.zeros(M)\n mu = np.mean(list(usermovie2rating.values()))\n return N, M, K, W, b, U, c, mu\n \ndef get_loss(m2u):\n \"\"\"\n Calculate loss for each user movie rating.\n \n Parameters\n --------\n m2u: movie_id -> (user_ids, ratings)\n \"\"\"\n N = 0.\n sse = 0\n for j, (u_ids, r) in m2u.items():\n p = W[u_ids].dot(U[j]) + b[u_ids] + c[j] + mu\n delta = p - r\n sse += delta.dot(delta)\n N += len(r)\n return sse / N\n\n\ndef train(epochs, reg, N, M ,K, W, b, U, c, mu, movie2userrating, movie2userrating_test):\n \"\"\"\n Train parameters.\n \n Parameters\n --------\n epochs: int, times to run\n reg: float, regularization penalty\n \"\"\"\n train_losses = []\n test_losses = []\n \n for epoch in range(epochs):\n print(\"Now: Epoch \", epoch)\n epoch_start = datetime.now()\n \n # update W and b\n t0 = datetime.now()\n for i in range(N):\n m_ids, r = user2movierating[i]\n matrix = U[m_ids].T.dot(U[m_ids]) * np.eye(K) * reg\n vector = (r - b[i] - c[m_ids] - mu).dot(U[m_ids])\n bi = (r - U[m_ids].dot(W[i]) - c[m_ids] - mu).sum()\n \n # set the updates\n W[i] = np.linalg.solve(matrix, vector)\n b[i] = bi / (len(user2movie[i]) + reg)\n \n if i % (N//10) == 0:\n print(\"Now i: \", i, \", N: \", N)\n print(\"Now: Update W and b: \", datetime.now() - t0)\n\n \n # update U and c\n t0 = datetime.now()\n for j in range(M):\n try:\n u_ids, r = movie2userrating[j]\n matrix = W[u_ids].T.dot(W[u_ids]) + np.eye(K) * reg\n vector = (r - b[u_ids] - c[j] - mu).dot(W[u_ids])\n cj = (r - W[u_ids].dot(U[j]) - b[u_ids] - mu).sum()\n \n # set the updates\n U[j] = np.linalg.solve(matrix, vector)\n c[j] = cj / (len(movie2user[j]) + reg)\n \n if j % (M//10) == 0:\n print(\"Now j: \", j, \", M: \", M)\n except KeyError:\n # pass for movies that don't have any rating\n pass\n print(\"Now: Update U and c: \", datetime.now() - t0)\n print(\"Epoch duration: \", datetime.now() - epoch_start)\n \n # store train loss\n t0 = datetime.now()\n train_losses.append(get_loss(movie2userrating))\n \n # store test loss\n test_losses.append(get_loss(movie2userrating_test))\n print(\"Calculate cost: \", datetime.now() - t0)\n print(\"Train loss: \", train_losses[-1])\n print(\"Test loss: \", test_losses[-1])\n \n print(\"Train losses: \", train_losses)\n print(\"Train losses: \", test_losses) \n \n # plot losses\n plt.plot(train_losses, label = \"train loss\")\n plt.plot(test_losses, label = \"test loss\")\n plt.legend()\n plt.show()\n\nif __name__ == '__main__':\n print(\"Now: Load data.\")\n user2movie, movie2user, usermovie2rating, user2movie_test, movie2user_test, usermovie2rating_test = load_data()\n user2movierating, movie2userrating, movie2userrating_test = convert_dataset(user2movie, movie2user, usermovie2rating_test)\n N, M, K, W, b, U, c, mu = initialize_variables(dim = 5, \n user2movie = user2movie, \n movie2user = movie2user, \n movie2user_test = movie2user_test, \n usermovie2rating = usermovie2rating)\n train(epochs = 15, reg = 20, N = N, M = M, K = K, W = W, \n b = b, U = U, c = c, mu = mu, \n movie2userrating = movie2userrating, \n movie2userrating_test = movie2userrating_test)","sub_path":"learning/Vectorized Matrix Factorization.py","file_name":"Vectorized Matrix Factorization.py","file_ext":"py","file_size_in_byte":6178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"166897634","text":"import re\nfrom abc import abstractmethod\n\nfrom denite.source.base import Base # pylint: disable=locally-disabled, import-error\nfrom denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position\n\n\nclass TagsBase(GtagsBase):\n\n TAG_PATTERN = re.compile('([^\\t]+)\\t(\\\\d+)\\t(.*)')\n\n @abstractmethod\n def get_search_flags(self):\n return []\n\n def get_search_word(self, context):\n args_count = len(context['args'])\n if args_count > 0:\n return context['args'][0]\n return context['input']\n\n def gather_candidates(self, context):\n word = self.get_search_word(context)\n tags = self.exec_global(self.get_search_flags() + ['--', word], context)\n candidates = self._convert_to_candidates(tags)\n return candidates\n\n @classmethod\n def _convert_to_candidates(cls, tags):\n candidates = []\n for tag in tags:\n path, line, text = cls._parse_tag(tag)\n col = text.find(text) - 1\n candidates.append({\n 'word': tag,\n 'action__path': path,\n 'action__line': line,\n 'action__text': text,\n 'action__col': col\n })\n return candidates\n\n @classmethod\n def _parse_tag(cls, tag):\n match = cls.TAG_PATTERN.match(tag)\n return match.groups()\n\n\nclass Source(Base):\n pass\n","sub_path":"rplugin/python3/denite/source/denite_gtags/tags_base.py","file_name":"tags_base.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"23067985","text":"import matplotlibHelpers as pltHelper\nimport numpy as np\nargs={'points': np.random.rand(7000),\n 'weights': np.random.rand(7000),\n 'color': 'blue',\n 'alpha': 1.0,\n 'linewidth': 1,\n 'name': 'Output',\n }\ntrain=pltHelper.dataSet(**args)\n\nargs={'points': np.random.rand(3000),\n 'weights': np.random.rand(3000),\n 'color': 'blue',\n 'alpha': 0.5,\n 'linewidth': 2,\n }\nvalid=pltHelper.dataSet(**args)\n\n\n\nargs={'points': np.zeros(0),\n 'weights': np.zeros(0),\n 'color': 'black',\n 'alpha': 1.0,\n 'linewidth': 1,\n 'name': 'Training Set',\n }\ntrainLegend=pltHelper.dataSet(**args)\nargs={'points': np.zeros(0),\n 'weights': np.zeros(0),\n 'color': 'black',\n 'alpha': 0.5,\n 'linewidth': 2,\n 'name': 'Validation Set',\n }\nvalidLegend=pltHelper.dataSet(**args)\n\nargs={'dataSets':[trainLegend,validLegend,train,valid], \n 'bins':[b/20.0 for b in range(21)], \n 'xlabel':'Random Number', \n 'ylabel':'Events',\n }\nhist = pltHelper.histPlotter(**args)\nprint(hist.artists)\nhist.artists[0].remove()\nhist.artists[1].remove()\nhist.savefig(\"../../../test.pdf\")\n","sub_path":"nTupleAnalysis/scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"56454817","text":"\nimport urllib\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\n\n@view_config(route_name=\"from_internet\", request_method='POST')\ndef from_internet(request):\n\n data=request.json_body\n web_url=data[\"url\"]\n stock_price_url = web_url\n\n source_code = urllib.request.urlopen(stock_price_url).read().decode()\n\n stock_data = []\n split_source = source_code.split('\\n')\n\n for line in split_source[0:]:\n split_line = line.split(',')\n if len(split_line) == 7:\n if 'values' not in line:\n stock_data.append(line)\n return Response(\"Data from websites\")","sub_path":"from_internet.py","file_name":"from_internet.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"248702876","text":"import argparse\nimport collections\nimport logging\nimport pickle\n\nimport pandas\nimport torch\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\n\nfrom constants import *\nfrom model.definition import *\nfrom tokenization import BertTokenizer\nfrom utils.dataset_prepare_utils import *\n\nlogger = logging.getLogger(__name__)\n\n\nclass GlossBERTDataset(Dataset):\n def __init__(self, data, tokenizer, **kwargs):\n # dataset content\n self._tokenizer = tokenizer\n self._sentences = []\n\n word_to_senses = {}\n last_sent_id = ''\n last_target_id = ''\n for i, item in enumerate(tqdm(data, desc=\"CSV Line Iteration\"), start=0):\n target_id, label, text, gloss, target_index_start, target_index_end, sense_key = item\n doc_id, sent_id, inst_id = target_id.split('.')\n if doc_id + sent_id != last_sent_id:\n last_sent_id = doc_id + sent_id\n sentence = Sentence('.'.join((doc_id, sent_id)), text)\n self.add_sentence(sentence)\n\n orig_tokens = text.split(' ')\n if target_id != last_target_id:\n bert_tokens = []\n bert_tokens.append(\"[CLS]\")\n for length in range(len(orig_tokens)):\n if length == target_index_start:\n target_to_tok_map_start = len(bert_tokens)\n if length == target_index_end:\n target_to_tok_map_end = len(bert_tokens)\n break\n bert_tokens.extend(tokenizer.tokenize(orig_tokens[length]))\n target_word = ' '.join(orig_tokens[target_index_start:target_index_end])\n if target_word not in word_to_senses.keys():\n word_to_senses[target_word] = [sense_key]\n elif sense_key not in word_to_senses[target_word]:\n word_to_senses[target_word].append(sense_key)\n last_target_id = target_id\n instance = Instance(target_id, sentence, target_word,\n start_pos=target_to_tok_map_start, end_pos=target_to_tok_map_end)\n sentence.add_instance(instance)\n instance.add_candidate_sense(sense_key, gloss, label)\n else:\n if target_word not in word_to_senses.keys():\n word_to_senses[target_word] = [sense_key]\n elif sense_key not in word_to_senses[target_word]:\n word_to_senses[target_word].append(sense_key)\n instance.add_candidate_sense(sense_key, gloss, label)\n sense_freq_counter = collections.Counter([item[6] if item[1] == 1 else '' for item in data])\n self.set_word_to_senses(word_to_senses)\n self.set_sense_freq_counter(sense_freq_counter)\n\n def __len__(self):\n pass\n\n def __getitem__(self, item):\n pass\n\n def add_sentence(self, sentence):\n self._sentences.append(sentence)\n\n def filter_data(self, max_seq_length):\n pass\n\n def set_word_to_senses(self, word_to_senses):\n self.word_to_senses = word_to_senses\n\n def set_sense_freq_counter(self, sense_freq_counter):\n self.sense_freq_counter = sense_freq_counter\n\n @classmethod\n def from_data_csv(cls, data_csv_path, tokenizer, **kwargs):\n \"\"\"\n csv file format:\n target_id\tlabel\tsentence\tgloss\ttarget_index_start\ttarget_index_end\tsense_key\n ['d000.s000.t000', 0, 'How long has it been since you reviewed the objectives of your benefit and service program ?', 'desire strongly or persistently', 1, 2, 'long%2:37:02::']\n :param data_csv_path: the path of csv file containing data.\n :return: the GlossBERTDataset instance\n \"\"\"\n data = pandas.read_csv(data_csv_path, sep=\"\\t\", na_filter=False).values\n dataset = cls(data, tokenizer, **kwargs)\n\n return dataset\n\n\nclass GlossBERTDataset_for_CGPair_Feature(GlossBERTDataset):\n def __init__(self, data, tokenizer, **kwargs):\n super().__init__(data, tokenizer, **kwargs)\n try:\n self.max_seq_length = kwargs['max_seq_length']\n except:\n self.max_seq_length = 150\n #self.positive_examples = []\n #self.negative_examples = []\n\n self.pos_indexes = []\n self.neg_indexes = []\n self.all_examples = []\n self.invalid_indexes = []\n for sentence in tqdm(self._sentences, desc=\"Sentence Iteration\"):\n for instance in sentence:\n for idx, cand_sense in enumerate(instance, start=0):\n sense_key, gloss, label = cand_sense\n if instance.end_pos >= self.max_seq_length * 2 // 3:\n # Ignore target words whose end pos is larger than the max_seq_length.\n # Set the label to -1 to avoid loss calculation.\n label = -1\n # sample: ((self.sentence.text, gloss), is_next, start_pos, span_length)\n cur_example = InputExample(guid=instance.id, cand_sense_key=sense_key, text_a=sentence.text,\n start_id=instance.start_pos, end_id=instance.end_pos,\n text_b=gloss, label=label)\n if label == 1:\n self.pos_indexes.append(len(self.all_examples))\n #self.positive_examples.append(cur_example)\n elif label == 0:\n self.neg_indexes.append(len(self.all_examples))\n #self.negative_examples.append(cur_example)\n else: # label == -1\n self.invalid_indexes.append(len(self.all_examples))\n self.all_examples.append(cur_example)\n\n self.all_features = []\n for example in tqdm(self.all_examples, desc=\"Training Example Iteration\"):\n feature = convert_example_to_features2(example, self.max_seq_length, tokenizer)\n self.all_features.append(feature)\n\n def __getitem__(self, item):\n return self.all_features[item]\n\n def __len__(self):\n assert len(self.all_examples) == len(self.all_features)\n return len(self.all_features)\n\n\nclass GlossBERTDataset_for_Sentence(GlossBERTDataset):\n def __init__(self, data, tokenizer, **kwargs):\n super().__init__(data, tokenizer, **kwargs)\n\n def __len__(self):\n return len(self._sentences)\n\n def __getitem__(self, item):\n return self._sentences[item]\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser()\n ## Required parameters\n parser.add_argument(\"--target\",\n default='train',\n type=str,\n choices=['train', 'dev', 'semeval2013', 'semeval2015', 'semeval2', 'semeval3'])\n parser.add_argument(\"--max_seq_length\",\n default=128,\n type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n args = parser.parse_args()\n\n return args\n\n\nif __name__ == '__main__':\n args = _parse_args()\n\n\n tokenizer = BertTokenizer.from_pretrained('../bert-model', do_lower_case=True)\n\n #with open('../Training_Corpora/SemCor/train_glossbert_dataset.pkl', 'rb') as rbf:\n #glossbert_dataset = pickle.load(rbf)\n\n target = 'dev'\n if target == 'train':\n glossbert_dataset = GlossBERTDataset_for_CGPair_Feature.from_data_csv(\n csv_paths['train'], tokenizer, max_seq_length=args.max_seq_length)\n with open('.. /Training_Corpora/SemCor/train_glossbert_dataset.pkl', 'wb') as wbf:\n pickle.dump(glossbert_dataset, wbf)\n elif target == 'dev':\n glossbert_dataset = GlossBERTDataset_for_CGPair_Feature.from_data_csv(\n csv_paths['dev'], tokenizer, max_seq_length=args.max_seq_length)\n with open('../Evaluation_Datasets/semeval2007/semval2007_glossbert_dataset.pkl', 'wb') as wbf:\n pickle.dump(glossbert_dataset, wbf)\n elif target == '2013':\n glossbert_dataset = GlossBERTDataset_for_CGPair_Feature.from_data_csv(\n csv_paths['2013'], tokenizer, max_seq_length=args.max_seq_length)\n with open('../Evaluation_Datasets/semeval2013/senseval2013_glossbert_dataset.pkl', 'wb') as wbf:\n pickle.dump(glossbert_dataset, wbf)\n elif target == '2015':\n glossbert_dataset = GlossBERTDataset_for_CGPair_Feature.from_data_csv(\n csv_paths['2015'], tokenizer, max_seq_length=args.max_seq_length)\n with open('../Evaluation_Datasets/semeval2015/senseval2015_glossbert_dataset.pkl', 'wb') as wbf:\n pickle.dump(glossbert_dataset, wbf)\n elif target == '2':\n glossbert_dataset = GlossBERTDataset_for_CGPair_Feature.from_data_csv(\n csv_paths['2'], tokenizer, max_seq_length=args.max_seq_length)\n with open('../Evaluation_Datasets/senseval2/senseval2_glossbert_dataset.pkl', 'wb') as wbf:\n pickle.dump(glossbert_dataset, wbf)\n elif target == '3':\n glossbert_dataset = GlossBERTDataset_for_CGPair_Feature.from_data_csv(\n csv_paths['3'], tokenizer, max_seq_length=args.max_seq_length)\n with open('../Evaluation_Datasets/senseval3/senseval3_glossbert_dataset.pkl', 'wb') as wbf:\n pickle.dump(glossbert_dataset, wbf)\n elif target == 'ALL':\n glossbert_dataset = GlossBERTDataset_for_CGPair_Feature.from_data_csv(\n csv_paths['ALL'], tokenizer, max_seq_length=args.max_seq_length)\n with open('../Evaluation_Datasets/ALL/ALL_glossbert_dataset.pkl', 'wb') as wbf:\n pickle.dump(glossbert_dataset, wbf)\n","sub_path":"dataset/glossbert_dataset.py","file_name":"glossbert_dataset.py","file_ext":"py","file_size_in_byte":10356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"554051951","text":"import numpy as np\nimport sympy\n\nsqrt = sympy.sqrt\n\ntp, tn, fp, fn, B = sympy.symbols(['tp', 'tn', 'fp', 'fn', 'B'], integer=True, negative=False)\nnumer = (tp * tn - fp * fn)\ndenom = ((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) ** 0.5\nmcc = numer / denom\n\nppv = tp / (tp + fp)\ntpr = tp / (tp + fn)\n\nFM = ((tp / (tp + fn)) * (tp / (tp + fp))) ** 0.5\n\nB2 = (B ** 2)\nB2_1 = (1 + B2)\n\nF_beta_v1 = (B2_1 * (ppv * tpr)) / ((B2 * ppv) + tpr)\nF_beta_v2 = (B2_1 * tp) / (B2_1 * tp + B2 * fn + fp)\n\n# Demo how Beta interacts with harmonic mean weights for F-Beta\nw1 = 1\nw2 = 1\nx1 = tpr\nx2 = ppv\nharmonic_mean = (w1 + w2) / ((w1 / x1) + (w2 / x2))\nharmonic_mean = sympy.simplify(harmonic_mean)\nexpr = sympy.simplify(harmonic_mean - F_beta_v1)\nsympy.solve(expr, B2)\n\ngeometric_mean = ((x1 ** w1) * (x2 ** w2)) ** (1 / (w1 + w2))\ngeometric_mean = sympy.simplify(geometric_mean)\nassert sympy.simplify(sympy.simplify(geometric_mean) - sympy.simplify(FM)) == 0\n\nprint('geometric_mean = {!r}'.format(geometric_mean))\n\n# How do we apply weights to precision and recall when tn is included\n# in mcc?\n\nprint(sympy.simplify(F_beta_v1))\nprint(sympy.simplify(F_beta_v2))\nassert sympy.simplify(sympy.simplify(F_beta_v1) - sympy.simplify(F_beta_v2)) == 0\n\n\ntnr_denom = (tn + fp)\ntnr = tn / tnr_denom\n\npnv_denom = (tn + fn)\nnpv = tn / pnv_denom\n\nmk = ppv + npv - 1 # markedness (precision analog)\nbm = tpr + tnr - 1 # informedness (recall analog)\n\n# Demo how Beta interacts with harmonic mean weights for F-Beta\nw1 = 2\nw2 = 1\nx1 = mk # precision analog\nx2 = bm # recall analog\ngeometric_mean = ((x1 ** w1) * (x2 ** w2)) ** (1 / (w1 + w2))\ngeometric_mean = sympy.simplify(geometric_mean)\nprint('geometric_mean w1=2 = {!r}'.format(geometric_mean))\n\nw1 = 0.5\nw2 = 1\ngeometric_mean = ((x1 ** w1) * (x2 ** w2)) ** (1 / (w1 + w2))\ngeometric_mean = sympy.simplify(geometric_mean)\nprint('geometric_mean w1=.5 = {!r}'.format(geometric_mean))\n\n# By taking the weighted geometric mean of bm and mk we can effectively\n# create a mcc-beta measure\n\nvalues = {fn: 3, fp: 10, tp: 100, tn: 200}\n\n# Cant seem to verify that gmean(bm, mk) == mcc, with sympy, but it is true\nvalues = {fn: np.random.rand() * 10, fp: np.random.rand() * 10, tp: np.random.rand() * 10, tn: np.random.rand() * 10}\nprint(geometric_mean.subs(values))\nprint(abs(mcc).subs(values))\n\ndelta = sympy.simplify(sympy.simplify(geometric_mean) - sympy.simplify(sympy.functions.Abs(mcc)))\n# assert sympy.simplify(sympy.simplify(geometric_mean) - sympy.simplify(sympy.functions.Abs(mcc))) == 0\n","sub_path":"dev/devcheck/sympy_metrics.py","file_name":"sympy_metrics.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"544319136","text":"\nfrom iemlav.lib.antivirus.antivirus_logger import AntiVirusLogger\n\nimport os\n\n\nclass GatherFile(object):\n \"\"\"GatherFile class.\"\"\"\n\n def __init__(self, debug=False, path=None):\n\n # Initialize logger\n self.logger = AntiVirusLogger(\n __name__,\n debug=debug\n )\n\n # Initialize path of directory to look for\n self._PATH = path\n\n def scan_dir(self):\n\n found_files = [] # Initialize empty list of found files\n\n try:\n # Iterate through the directory\n for root, _, files in os.walk(self._PATH):\n for file in files:\n found_files.append(os.path.join(root, file))\n except Exception as e:\n self.logger.log(\n \"Error occurred: \" + str(e),\n logtype=\"error\"\n )\n\n # Return the list of found files\n return found_files\n","sub_path":"build/lib/iemlav/lib/antivirus/tools/file_gather.py","file_name":"file_gather.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"221991894","text":"from typing import List\r\nfrom collections import Counter\r\nfrom itertools import accumulate\r\n\r\n\r\n# 2 <= n <= 105\r\n# 给你一个整数 k 。你可以将 nums 中 一个 元素变为 k 或 不改变 数组。\r\n# 1 <= pivot < n\r\n# nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]\r\n# 其中左半部分和右半部分都至少拥有一个元素。\r\n# 请你返回在 至多 改变一个元素的前提下,最多 有多少种方法 分割 nums 使得上述两个条件都满足。\r\n\r\n# 思路:\r\n# 如果改变一个元素nums[i]为k,那么原数组总和为total变为total - nums[i] + k\r\n# 对于前缀和数组presum来说,presum[0,..,i-1]的值是没有发生改变的,而presum[i,..,n-1]的值都增加了k - nums[i]\r\n# 假设原先元素值为x,那么希望有x + k - nums[i] == (total + k - nums[i]) / 2,\r\n# 即x = total / 2 - (k - nums[i]) / 2,即统计presum[i,..,n-2]有多少元素值为total / 2 - (k - nums[i]) / 2\r\n\r\n\r\nclass Solution:\r\n def waysToPartition(self, nums: List[int], k: int) -> int:\r\n \"\"\"前缀和+双哈希表+枚举修改元素 O(n)\r\n \r\n https://leetcode-cn.com/problems/maximum-number-of-ways-to-partition-an-array/solution/qian-zhui-he-ha-xi-biao-mei-ju-xiu-gai-y-l546/\r\n \"\"\"\r\n n, preSum = len(nums), list(accumulate(nums))\r\n left, right, sum_ = Counter(), Counter(preSum[:-1]), preSum[-1]\r\n\r\n # 不改变\r\n res = right[sum_ / 2]\r\n\r\n # 改变\r\n for i in range(n):\r\n if i > 0:\r\n left[preSum[i - 1]] += 1\r\n right[preSum[i - 1]] -= 1\r\n diff = k - nums[i]\r\n leftTarget = (sum_ + diff) / 2\r\n rightTarget = (sum_ - diff) / 2\r\n res = max(res, left[leftTarget] + right[rightTarget])\r\n\r\n return res\r\n\r\n\r\nprint(Solution().waysToPartition([22, 4, -25, -20, -15, 15, -16, 7, 19, -10, 0, -13, -14], k=-33))\r\n# 输出:4\r\n# 解释:一个最优的方案是将 nums[2] 改为 k 。数组变为 [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14] 。\r\n# 有四种方法分割数组。\r\n\r\n","sub_path":"22_专题/枚举/枚举分割点-前后缀分解/枚举分割点/2025. 分割数组的最多方案数-枚举分割点.py","file_name":"2025. 分割数组的最多方案数-枚举分割点.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"77394104","text":"import os, re\nfrom shutil import copyfile\n\nmin_incorrect_fs = 10\nfiles = os.listdir('output')\nfiles.sort()\ncorrect_files = []\n\nfor file in files:\n filepath = os.path.join('output', file)\n if os.stat(filepath).st_size > min_incorrect_fs:\n correct_files.append(filepath)\n\nvalues = list()\ncount = list()\ndata = list()\nlineregex = re.compile(r'^[-#]')\nregex = re.compile(r'^[0-9]+\\.?([0-9]+)?$')\ncategory = ['Автохимия', 'Аккумуляторы', 'Аксессуары', 'Амортизация автомобиля', 'Выхлопные системы', 'Газели', 'Детали двигателя', 'Жидкости рабочие', \n 'Запчасти на авто', 'Инструмент (Интертул)', 'Инструменты', 'Кузов', 'Масла и смазки', 'Метлы', 'Очистка окон', 'Пакеты', 'Подвеска и рулевое управление',\n 'Разное', 'Резина тех изделия', 'Тормозная система', 'Трансмиссия', 'Фильтры']\nsubcategory = []\n\nfor xPath in correct_files:\n tmp_val, tmp_co = [], []\n with open(xPath, encoding='utf-8') as file:\n text_lines = list(map(lambda line: line.strip(), file.read().split('\\n')))\n filtered_text_lines = list(filter(lambda line: (len(line) != 0 and not re.match(lineregex, line) and not line == 'Итого'), text_lines))\n for line in filtered_text_lines:\n if re.match(regex, line):\n tmp_co.append(line)\n else:\n tmp_val.append(line)\n print(xPath)\n print('values {}, count {}'.format(len(tmp_val), len(tmp_co)))\n if len(tmp_val) != len(tmp_co):\n print('{} includes incorrect values please fix manualy'.format(xPath))\n print('Saved in /err/{}'.format(os.path.basename(xPath)))\n if 'err' not in os.listdir('.'):\n os.mkdir('err')\n copyfile(xPath, os.path.join('err', os.path.basename(xPath)))\n if input('want to get listing? [y | n]') == 'y':\n for x in range(len(tmp_val)):\n try:\n print('value: {}'.format(tmp_val[x]).ljust(110, ' ') + 'count: {}'.format(tmp_co[x]).rjust(5, ' '))\n except IndexError:\n print('value: {}'.format(tmp_val[x]).ljust(100, ' ') + 'count: undefined')\n\n break\n \n\n # for x in values: print(x)\n values += tmp_val\n count += tmp_co\n\nfor x in range(len(values)):\n data.append('{} : {}'.format(values[x].ljust(110, ' '), count[x]))\n\nwith open('file.txt', 'w', encoding='utf-8') as f:\n f.write('\\n'.join(data))","sub_path":"Python/worksection/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"423896397","text":"import hashlib\n\nx = [str(i) for i in range(10)]\n\n\n#Checks all possible 6-digit pins, including ones that start with 0\nfor a in x:\n for b in x:\n for c in x:\n for d in x:\n for e in x:\n for f in x:\n\n X = a+b+c+d+e+f\n\n H = hashlib.sha256(X.encode(\"utf-8\")).hexdigest()\n\n #Paste the bytes from the checkpin column in clientDB here\n if H == \"7f72932585059397e5dfaca5cfa77515025e0c31e6e20f70ce814e0b3690f5ee\":\n print(X,H)\n exit()","sub_path":"Task 4/pin.py","file_name":"pin.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"279811374","text":"import os\nimport requests\nimport pandas as pd\n\ndef savepucs(img_urls,titles):\n for i in range(len(img_urls)):\n imgUrl=img_urls[i]\n title=titles[i]\n img_data=requests.get(url=imgUrl).content\n with open(str(title)+'.jpg','wb') as f:\n f.write(img_data)\n\nif __name__=='__main':\n if 'xlsxdata' not in os.listdir():\n os.mkdir('xlsxdata')\n os.chdir('xlsxdata')\n\n book_data=pd.read_csv('result.csv')\n img_urls=book_data['img_urls']\n titles=book_data['titles']\n savepucs(img_urls,titles)","sub_path":"爬虫/p122.py","file_name":"p122.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"287428513","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 20 14:10:59 2019\n\n@author: angelo\n\n\"\"\"\n\ndef crea_matrice_numeri(n, m):\n \"\"\" la funzione costruisce una matrice che ha tutti i numeri da 1 a n*m ordinati per riga\n es.:\n crea_matrice_numeri(2, 4) ritorna\n [[1,2,3,4],[5,6,7,8]] \"\"\"\n\n matrice = []\n riga = []\n for i in range (1,n*m+1):\n riga.append(i)\n if i % m == 0:\n matrice.append(riga)\n riga = []\n return matrice\n\ndef crea_matrice_numeri2(n, m):\n matrice = []\n for i in range(n):\n riga = []\n for j in range(m):\n riga.append(i*m+j+1)\n matrice.append(riga)\n return matrice\n\ndef crea_matrice_numeri3(n, m):\n matrice = []\n for i in range(n):\n riga = []\n for j in range(i*m+1, i*m+m+1):\n riga.append(j)\n matrice.append(riga)\n return matrice\n\ndef crea_matrice_numeri4(n,m):\n return [[j for j in range(i*m+1, i*m+m+1)] for i in range(n)]\n\n\n\n\n\n\n\n\n\n\n","sub_path":"programming_lab/lab201119/crea_matrici.py","file_name":"crea_matrici.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"62143975","text":"import datetime\nimport time\nimport pandas as pd\nimport numpy as np\nimport calendar\n\n## I like pie\n\nCITY_DATA = {'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv'}\n# I like pie\n# hehehe\ndef get_city():\n \"\"\"\n Asks user to specify a city to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n \"\"\"\n print('\\nHello! Let\\'s explore some US bikeshare data!\\n')\n city = input('Which city would you like to see the data for - Chicago, New York City, or Washington?:\\n')\n while True:\n if city.lower() == 'chicago' or city == 'Chicago' or city == 'c' or city == 'C':\n print(\"\\nThe Windy City it is!\\n\")\n return 'chicago.csv'\n elif city.lower() == 'new york city' or city == 'New York City' or city == 'n' or city == 'N':\n print(\"\\nThe Big Apple!\\n\")\n return 'new_york_city.csv'\n elif city.lower() == 'washington' or city == 'washington' or city == 'w' or city == 'W':\n print(\"\\nEl Capital!\\n\")\n return 'washington.csv'\n else:\n print(\"\\nSorry, that's not a valid city - please try again.\")\n return get_city()\n\n\n#I like pizza\ndef get_month():\n \"\"\"\n Asks user to specify a month between January and July\n\n Args:\n none\n\n Returns:\n (str) month - Which month to analyze the data for. Each month is converted\n into their respective number\n \"\"\"\n month = input('Which month? January, February, March, April, May, or June?\\n').title()\n if month == 'January':\n return '01'\n elif month == 'February':\n return '02'\n elif month == 'March':\n return '03'\n elif month == 'April':\n return '04'\n elif month == 'May':\n return '05'\n elif month == 'June':\n return '06'\n else:\n print(\"\\nThat's an invalid month - Please try again.\")\n return get_month()\n\n\ndef get_day():\n \"\"\" Asks the user which day to pick from.\n Args:\n none\n Returns:\n (str) Gets the day from the data. Each day represents a specific number.\n \"\"\"\n day = input('\\nGreat! Now which day - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday?\\n').title()\n if day == 'Monday':\n print(\"\\nGross - Mondays :(\\n\")\n return 0\n elif day == 'Tuesday':\n print(\"\\nTuesday it is!\\n\")\n return 1\n elif day == 'Wednesday':\n print(\"\\nHump day!\\n\")\n return 2\n elif day== 'Thursday':\n print(\"\\nThirsty Thursdays! *chugs*\\n\")\n return 3\n elif day == 'Friday':\n print(\"\\nIt's finally Friday!\\n\")\n return 4\n elif day == 'Saturday':\n print(\"\\nSaturdays are the best day of the week!\\n\")\n return 5\n elif day == 'Sunday':\n print(\"\\nSunday Funday!\\n\")\n return 6\n else:\n print(\"\\nThat's an invalid day. Please try again.\\n\")\n return get_day()\n\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by\n (str) day - name of the day of week to filter by\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n\n # Filter by city - month - day\n df = pd.read_csv('{}'.format(city))\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['month'] = df['Start Time'].dt.month\n df['day'] = df['Start Time'].dt.weekday\n return df\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['month'] = df['Start Time'].dt.month\n pop_month = df.groupby('month')['Start Time'].count()\n print(\"The most common month is: \" + calendar.month_name[int(pop_month.sort_values(ascending=False).index[0])])\n\n\n # display the most common day of week\n df['day'] = df['Start Time'].dt.weekday\n pop_day = df.groupby('day')['Start Time'].count()\n print(\"The most common day of the week is: \" + calendar.day_name[int(pop_day.sort_values(ascending=False).index[0])])\n\n # display the most common start hour\n pop_hour = int(df['Start Time'].dt.hour.mode())\n if pop_hour == 0:\n am_or_pm = 'AM'\n most_pop_hour = 12\n elif 1 <= pop_hour < 13:\n am_or_pm = 'PM'\n most_pop_hour = pop_hour\n elif 13 <= pop_hour < 24:\n am_or_pm = 'PM'\n most_pop_hour = pop_hour - 12\n print(\"The most common start hour is: {} {}\".format(most_pop_hour, am_or_pm))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n popular_start_station = df['Start Station'].mode().to_string(index = False)\n print(\"The most commonly used start station is: {}\".format(popular_start_station))\n\n # display most commonly used end station\n popular_end_station = df['End Station'].mode().to_string(index = False)\n print(\"The most commonly used end station is: {}\".format(popular_end_station))\n\n # display most frequent combination of start station and end station trip\n pd.set_option('max_colwidth',100)\n df['Trip'] = df['Start Station'].str.cat(df['End Station'], sep = ' to ')\n popular_combo = df['Trip'].mode().to_string(index = False)\n print(\"The mose frequent combination of stations is: {}\".format(popular_combo))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # display total travel time\n total_time = round(df['Trip Duration'].sum())\n minute, second = divmod(total_time, 60)\n hour, minute = divmod(minute, 60)\n day, hour = divmod(hour, 24)\n year, day = divmod(day, 365)\n print(\"The total travel time is {} years, {} days, {} hours, {} minutes, and {} seconds.\".format(year, day, hour, minute, second))\n\n # display mean travel time\n avg_time = round(df['Trip Duration'].mean())\n minute, second = divmod(avg_time, 60)\n hour, minute = divmod(minute, 60)\n print(\"The average travel time on a bike is {} hours, {} minutes, and {} seconds.\".format(hour, minute, second))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n user_types = df.groupby('User Type')['User Type'].count()\n print(user_types)\n\n # Display counts of gender\n if 'Gender' in df.columns:\n male = df.query('Gender == \"Male\"').Gender.count()\n female = df.query('Gender == \"Female\"').Gender.count()\n print(\"\\n{} total Male users.\".format(male))\n print(\"{} total Female users.\\n\".format(female))\n\n # Display earliest, most recent, and most common year of birth\n if 'Birth Year' in df.columns:\n early = int(df['Birth Year'].min())\n recent = int(df['Birth Year'].max())\n common = int(df['Birth Year'].mode())\n print(\"Earliest birth year: {}\".format(early))\n print(\"Most recent birth year: {}\".format(recent))\n print(\"Most common birth year: {}\".format(common))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef display_data(df):\n \"\"\" Displays 5 files of data if the user selects yes\n If user says no - it goes to def main(). This program continues\n until the user says no.\n\n Args:\n df: dataframe of the bikeshare data\n Returns:\n User selects yes - returns 5 lines of data then asks again\n User selects no - moves on \"\"\"\n\n def is_valid(display):\n if display.lower() in ['yes', 'no']:\n return True\n else:\n return False\n x = 0\n y = 5\n valid_input = False\n while valid_input == False:\n display = input('\\nWould you like to view individual trip data? '\n 'Type \\'yes\\' or \\'no\\'.\\n')\n valid_input = is_valid(display)\n if valid_input == True:\n break\n else:\n print(\"Sorry, I do not understand your input. Please type 'yes' or\"\n \" 'no'.\")\n if display.lower() == 'yes' or display.lower() == 'y':\n print(df[df.columns[0:-1]].iloc[x:y])\n display_lines = ''\n while display_lines.lower() != 'no':\n valid_input_2 = False\n while valid_input_2 == False:\n display_lines = input('\\nWould you like to view more individual'\n ' trip data? Type \\'yes\\' or \\'no\\'.\\n')\n valid_input_2 = is_valid(display_lines)\n if valid_input_2 == True:\n break\n else:\n print(\"Sorry, I do not understand your input. Please type \"\n \"'yes' or 'no'.\")\n if display_lines.lower() == 'yes' or display_lines.lower() == 'y':\n x += 5\n y += 5\n print(df[df.columns[0:-1]].iloc[x:y])\n elif display_lines.lower() == 'no' or display_lines.lower() == 'n':\n break\n\ndef main():\n while True:\n city = get_city()\n month = get_month()\n day = get_day()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n display_data(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":10229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"355087506","text":"import os\nimport dateutil.parser\nfrom optparse import OptionParser\n\nimport leo_api.leo_api as leo_api\nfrom leo_api.LoggerInit.LoggerInit import *\n\nvalid_programs = (\n \"measurements/raw\",\n \"target_interests\",\n )\n\nif __name__ == \"__main__\":\n\n usage = \"\\n\".join([\n \"usage: main.py program_name [options]\",\n \"\\tprogram_names: %s\" % \",\".join(valid_programs)\n ])\n if len(sys.argv)<2:\n print(\"%s\" % usage)\n sys.exit(0)\n\n program_name = sys.argv[1]\n if program_name not in valid_programs:\n print(\"%s\" % usage)\n sys.exit(0)\n\n # parse inputs\n usage = \"usage: %%prog %s [options]\" % program_name\n parser = OptionParser(usage=usage)\n parser.add_option(\"-c\", \"--config_path\", dest=\"config_path\", help=\"path to configuration files\", default='config')\n\n if program_name == \"measurements/raw\":\n parser.add_option(\"--exp_id\", dest=\"exp_id\", type=\"int\", help=\"this will only query for experiment ids greater than the supplied exp_id\")\n parser.add_option(\"--norad_id\", dest=\"norad_id\", type=\"int\", help=\"this will filter the measurements based on the associated target's NORAD id\")\n parser.add_option(\"--start\", dest=\"start_time\", help=\"this will filter the measurements for experiment start times greater than the value (e.g. 2017-01-30T23:00:00)\")\n parser.add_option(\"--run_forever\", action=\"store_true\", dest=\"run_forever\", help=\"run forever\", default=False)\n parser.add_option(\"--target_interest_id\", dest=\"target_interest_id\", type=\"int\", help=\"if supplied, will get measurements for the id corresponding to the target_interest\")\n\n elif program_name == \"target_interests\":\n parser.add_option(\"--norad_id\", dest=\"norad_id\", type=\"int\", help=\"the target's NORAD id\")\n parser.add_option(\"--start\", dest=\"start_time\", help=\"the start time of interest (e.g. 2017-01-30T22:00:00)\")\n parser.add_option(\"--end\", dest=\"end_time\", help=\"the end time of interest (e.g. 2017-01-30T23:00:00)\")\n\n (options, args) = parser.parse_args()\n\n # check inputs\n if options.config_path is None or not os.path.exists(options.config_path):\n parser.error('config_path error')\n sys.exit(0)\n\n # create logger\n LoggerInit(os.path.join(options.config_path,\"log.ini\"))\n\n # run\n keyword_args = {}\n a = leo_api.leo_api(options.config_path)\n\n if program_name == \"measurements/raw\":\n keyword_args['run_forever'] = options.run_forever\n if options.norad_id is not None:\n keyword_args['norad_id'] = options.norad_id\n if options.exp_id is not None:\n keyword_args['exp_id'] = options.exp_id\n if options.start_time is not None:\n keyword_args['start_time'] = dateutil.parser.parse(options.start_time)\n if options.target_interest_id is not None:\n keyword_args['target_interest_id'] = options.target_interest_id\n a.measurements_raw(**keyword_args)\n\n if program_name == \"target_interests\":\n if options.norad_id is None:\n parser.error('norad_id not given')\n if options.start_time is None:\n parser.error('start_time not given')\n if options.end_time is None:\n parser.error('end_time not given')\n keyword_args['norad_id'] = options.norad_id\n keyword_args['start_time'] = dateutil.parser.parse(options.start_time)\n keyword_args['end_time'] = dateutil.parser.parse(options.end_time)\n a.target_interests(**keyword_args)\n","sub_path":"leo_api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"548853938","text":"#!/usr/bin/env python\nimport os\nimport multiprocessing as mp\n\n\nfrom lib_helpers import run_solver\n\n\nQ = 50.0\nE_ACT = 26.00\nT_FINAL = 30.0\n\n\nif __name__ == '__main__':\n n12_list = [20, 40, 80, 160, 320, 640, 1280]\n top_outdir = 'q={:06.2f}-e_act={:06.2f}'.format(Q, E_ACT)\n top_outdir = os.path.join('_output', top_outdir)\n\n if not os.path.isdir(top_outdir):\n os.mkdir(top_outdir)\n\n tasks = [(Q, E_ACT, T_FINAL, top_outdir, n12) for n12 in n12_list]\n\n with mp.Pool(processes=2) as pool:\n pool.map(run_solver, tasks)\n","sub_path":"comparison-with-normal-modes/run-q=50-e_act=26.00.py","file_name":"run-q=50-e_act=26.00.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"220477302","text":"from numpy import *\nfrom matplotlib.pyplot import *\nfrom scipy.signal import find_peaks\n\nfrom ..Packets.check_grouped import check_grouped\nfrom ..Packets.mean_min_max_distance import mean_min_max_distance\nfrom ..Background.prominence_factor import prominence_factor\nfrom ..time_error import time_error\nfrom ..Motions.projected_angular_velocity import projected_angular_velocity\n\n\ndef velocity_to_baseline(datas, time, frequencies, velocity_function, neighbors = 2):\n \"\"\"This function takes the following input:\n\n datas, time, frequencies: The corresponding quantities of a given\n batch of measurements.\n\n velocity: This has to be a function handle to a function that computes\n the angular velocity of the object at any given time, and projected\n onto the equatorial direction.\n\n\n The function then outputs a list of frequencies and baselines that were computed\n for the object, based on the data above.\"\"\"\n\n resulting_frequencies = []\n resulting_baselines = []\n resulting_s_baselines = []\n\n for i, data in enumerate(datas):\n if frequencies[i] < 0.0:\n continue\n \n h = max(data)\n \n peaks_max, _ = find_peaks(data, prominence = prominence_factor * h)\n peaks_min, _ = find_peaks(-data, prominence = prominence_factor * h)\n if peaks_max.shape[0] == 0 or peaks_min.shape[0] == 0:\n continue\n peak_max = peaks_max[argmax(data[peaks_max])]\n\n if check_grouped(peak_max, peaks_max, peaks_min, neighbors) != True:\n continue\n\n max_to_min_time = mean_min_max_distance(peak_max, peaks_max, peaks_min, time, neighbors)\n s_max_to_min_time = sqrt(2.0) * time_error/3600.0\n\n w = projected_angular_velocity(velocity_function, time[peak_max])\n w = w * 2.0 * pi / 360.0 # Get it in radians\n theta = w * max_to_min_time\n s_theta = w * s_max_to_min_time\n\n \n\n B_lambda = 1.0 / (2.0 * theta)\n s_B_lambda = s_theta / (2.0 * theta**2)\n\n baseline = (B_lambda * 299792458.0) / (frequencies[i] * 1000000.0)\n s_baseline = (s_B_lambda * 299792458.0) / (frequencies[i] * 1000000.0)\n \n resulting_baselines.append(baseline)\n resulting_s_baselines.append(s_baseline)\n resulting_frequencies.append(frequencies[i])\n\n return array(resulting_frequencies), array(resulting_baselines), array(resulting_s_baselines)\n \n","sub_path":"AstroWeek/Radii_Velocities/velocity_to_baseline.py","file_name":"velocity_to_baseline.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"612613349","text":"import uuid\nimport time\nimport os\nimport glob\nimport hashlib\n\nfrom OpenSSL import crypto\nfrom twisted.internet import ssl\nfrom twisted.application import service\n\nfrom tint.log import Logger\n\n\ndef sha256(s):\n return hashlib.sha256(s).hexdigest()\n\n\nclass DuplicateIssuer(Exception):\n \"\"\"\n Each issuer (aka, CA) is unique to each user. There shouldn't\n be two authorized keys with the same issuer.\n \"\"\"\n\n\nclass DuplicateKeyFilename(Exception):\n \"\"\"\n Each key filename is unique to you. There shouldn't\n be two authorized keys with the same filename.\n \"\"\"\n\n\nclass InvalidIssuer(Exception):\n \"\"\"\n If an cert issuer can't be found in the local authorized keys,\n this should be raised.\n \"\"\"\n\n\nclass InvalidAuthorizedKeyFilename(Exception):\n \"\"\"\n If the key filename is not comprised of one or more alpha numeric\n characters, this should be raised.\n \"\"\"\n\n\nclass PublicKey(object):\n def __init__(self, pemContents, name=None):\n self.pemContents = pemContents\n self.cert = ssl.Certificate.loadPEM(pemContents)\n self.name = name\n\n def getIssuer(self):\n return self.cert.getIssuer().commonName\n\n @classmethod\n def load(Class, path):\n with open(path, 'r') as f:\n contents = f.read()\n name = os.path.basename(os.path.splitext(path)[0])\n return Class(contents, name)\n\n def store(self, path):\n with open(path, 'w') as f:\n f.write(self.pemContents)\n\n def getKeyId(self):\n return sha256(self.pemContents)\n\n def __str__(self):\n return self.pemContents\n\n\nclass KeyPair(object):\n def __init__(self, pemContents):\n self.pemContents = pemContents\n self.kp = ssl.PrivateCertificate.loadPEM(pemContents)\n\n def getKeyId(self):\n return self.getPublicKey().getKeyId()\n\n def getPublicKey(self):\n return PublicKey(self.kp.dump(crypto.FILETYPE_PEM))\n\n def generateSignedTmpKeyPair(self, expiresIn):\n # make a copy of subject, with different common name\n dn = self.kp.getSubject()\n dn.commonName = \"%s-tmp\" % self.kp.getIssuer().commonName\n\n privkey = ssl.KeyPair.generate(crypto.TYPE_RSA, size=1024)\n cert = self.kp.privateKey.signRequestObject(\n self.kp.getIssuer(),\n privkey.requestObject(dn, 'sha1'),\n int(time.time()),\n expiresIn,\n digestAlgorithm='sha1')\n return (privkey, cert)\n\n @classmethod\n def generate(Class):\n kp = ssl.KeyPair.generate(crypto.TYPE_RSA, size=2048)\n # a unique id for this key's common name - used as issuer\n # for all subsequent signed keys\n commonName = str(uuid.uuid4())\n signed = kp.selfSignedCert(int(time.time()), commonName=commonName)\n return Class(signed.dumpPEM())\n\n @classmethod\n def load(Class, path):\n with open(path, 'r') as f:\n contents = f.read()\n return Class(contents)\n\n def store(self, path):\n with open(path, 'w') as f:\n f.write(self.kp.dumpPEM())\n\n def __str__(self):\n return self.pemContents\n\n\nclass KeyStore(service.Service):\n def __init__(self, keyPath, authorizedKeysDir):\n \"\"\"\n Handle all key interactions.\n\n @param keyPath: Path to the key to use as this server's id. If\n it doesn't exist, it will be created.\n\n @param authorizedKeysDir: Path to a directory to read/write\n authorized keys to. They are stored in memory in the keystore\n upon this object's construction.\n \"\"\"\n self.log = Logger(system=self)\n\n # first, check our key\n if not os.path.isfile(keyPath):\n self.log.debug(\"%s doesn't exist; creating new keypair\" % keyPath)\n self.kpair = KeyPair.generate()\n self.kpair.store(keyPath)\n else:\n self.log.debug(\"using %s as this node's keypair\" % keyPath)\n self.kpair = KeyPair.load(keyPath)\n\n # load other keys\n self.authorizedKeysDir = authorizedKeysDir\n self.refreshAuthorizedKeys()\n\n def startService(self):\n self.log.debug(\"Using keypair id: %s\" % self.getKeyId())\n service.Service.startService(self)\n\n def getKeyId(self):\n return self.kpair.getKeyId()\n\n def getPublicKey(self):\n return self.kpair.getPublicKey()\n\n def generateSignedTmpKeyPair(self, expiresIn):\n self.log.debug(\"Creating a new tmp keypair that expires in %i seconds\" % expiresIn)\n return self.kpair.generateSignedTmpKeyPair(expiresIn)\n\n def refreshAuthorizedKeys(self):\n self.authorizedKeys = {}\n pemFilter = os.path.join(self.authorizedKeysDir, \"*.pem\")\n for fname in glob.glob(pemFilter):\n self.log.debug(\"Loading %s into authorized keys\" % fname)\n keyId = PublicKey.load(fname).getIssuer()\n if keyId in self.authorizedKeys:\n msg = \"There are two keys with the same issuer - %s and %s.\"\n msg += \" Only one can be used - please delete the duplicate.\"\n raise DuplicateIssuer(msg % (fname, self.authorizedKeys[keyId]))\n self.authorizedKeys[keyId] = fname\n\n def getIssuerPublicKey(self, issuerCommonName):\n # this shouldn't happen - if a connection is successfully made,\n # then that means the key *must* be in the local authorized keys.\n # However, this is a double check, cause safety first and all that.\n if issuerCommonName not in self.authorizedKeys:\n msg = \"Issuer %s could not be found in local authorized keys\"\n raise InvalidIssuer(msg % issuerCommonName)\n return PublicKey.load(self.authorizedKeys[issuerCommonName])\n\n def getAuthorizedKeysList(self):\n return [PublicKey.load(fname) for fname in self]\n\n def removeAuthorizedKey(self, fname):\n path = os.path.join(self.authorizedKeysDir, fname + \".pem\")\n if not os.path.isfile(path):\n return False\n try:\n os.remove(path)\n self.refreshAuthorizedKeys()\n return True\n except:\n return False\n\n def setAuthorizedKey(self, publicKey, fname):\n path = os.path.join(self.authorizedKeysDir, fname + \".pem\")\n\n if not fname.isalnum():\n msg = \"Filename %s is not alpha numeric\"\n raise InvalidAuthorizedKeyFilename(msg % fname)\n\n if path in self:\n msg = \"There is already a key with the same filename - %s.\"\n msg += \" If you want to update - please delete first.\"\n raise DuplicateKeyFilename(msg % fname)\n\n if publicKey.getIssuer() in self.authorizedKeys:\n msg = \"There are two keys with the same issuer - %s and %s.\"\n msg += \" Only one can be used - please delete the duplicate.\"\n raise DuplicateIssuer(msg % (fname, self.authorizedKeys[publicKey.getIssuer()]))\n\n publicKey.store(path)\n self.refreshAuthorizedKeys()\n\n def __len__(self):\n return len(self.authorizedKeys)\n\n def __iter__(self):\n return self.authorizedKeys.itervalues()\n","sub_path":"tint/ssl/keymagic.py","file_name":"keymagic.py","file_ext":"py","file_size_in_byte":7131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"225421175","text":"from requests import get\nfrom json import loads\nfrom flask import Flask, render_template, request, redirect\nfrom datetime import datetime\napp = Flask(__name__)\n\n\ndef get_db():\n db = loads(get('http://127.0.0.1:10002/db').text)\n for k in db.keys():\n for u in db[k]['uid'].keys():\n db[k]['uid'][u] = str(datetime.fromtimestamp(db[k]['uid'][u]))\n return db\n\n\ndef delete(ku):\n get('http://127.0.0.1:10002/del/'+ku)\n\n\ndef gen_key(max):\n return get('http://127.0.0.1:10002/gen/'+max).txt\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n key = ''\n if request.method == 'POST':\n if 'gen' in list(request.form.keys()):\n key = gen_key(request.form.get('max'))\n else:\n delete(list(request.form.keys())[0])\n return render_template('index.html', db=get_db(), key=key)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"169353951","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTencent is pleased to support the open source community by making BK-ITSM 蓝鲸流程服务 available.\n\nCopyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.\n\nBK-ITSM 蓝鲸流程服务 is licensed under the MIT License.\n\nLicense for BK-ITSM 蓝鲸流程服务:\n--------------------------------------------------------------------\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\nand to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial\nportions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n__author__ = \"蓝鲸智云\"\n__copyright__ = \"Copyright © 2012-2020 Tencent BlueKing. All Rights Reserved.\"\n\nfrom rest_framework.routers import DefaultRouter, DynamicDetailRoute, DynamicListRoute, Route\n\n\nclass CustomDefaultRouter(DefaultRouter):\n routes = [\n # List route.\n Route(\n url=r'^{prefix}{trailing_slash}$',\n mapping={'get': 'list', 'post': 'create'},\n name='{basename}-list',\n initkwargs={'suffix': 'List'},\n ),\n # Dynamically generated list routes.\n # Generated using @list_route decorator\n # on methods of the viewset.\n DynamicListRoute(\n url=r'^{prefix}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={}\n ),\n # Detail route.\n Route(\n url=r'^{prefix}/{lookup}{trailing_slash}$',\n mapping={'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'},\n name='{basename}-detail',\n initkwargs={'suffix': 'Instance'},\n ),\n # Dynamically generated detail routes.\n # Generated using @detail_route decorator on methods of the viewset.\n DynamicDetailRoute(\n url=r'^{prefix}/{lookup}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={}\n ),\n Route(\n url=r'^remote/{prefix}{trailing_slash}$',\n mapping={\n 'get': 'get_requests',\n 'post': 'post_requests',\n 'put': 'put_requests',\n 'delete': 'delete_requests',\n },\n name='{basename}-request',\n initkwargs={'suffix': 'Request'},\n ),\n ]\n","sub_path":"itsm/component/drf/routers.py","file_name":"routers.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"620859013","text":"import socket\nimport json\nfrom shoto import execs\nfrom shoto.app import interfaceService,firewallService,proxyService\n\n\nclass Service:\n def __init__(self):\n pass\n \n def get_functions(self,func):\n try:\n arrayf=[]\n funcfin=json.loads(func[1])\n for line in funcfin:\n arrayf.append(line) \n ret=''\n \n if func[0] == 'status':\n ret=self.get_boss_status() \n if func[0] == 'cmd':\n ret=self.get_command(arrayf)\n if func[0] == 'staticroutes':\n ret=self.execute_static_routes()\n if func[0] == 'fw':\n ret=self.execute_fw(arrayf)\n if func[0] == 'proxyreload':\n ret=self.proxyreload()\n if func[0] == 'proxyrestart':\n ret=self.proxyrestart() \n return 200,ret\n except Exception as e: \n print(e)\n return 403,'erro'\n \n def get_boss_status(self):\n s = socket.socket()\n address = '127.0.0.1'\n port = 8888 \n try:\n s.connect((address, port)) \n return 'True'\n except Exception as e: \n return 'False'\n\n def get_command(self,func):\n strr=''\n for lin in func:\n strr=strr+' '+ lin\n return str(execs.cmd(strr)[2])\n\n def proxyreload(self):\n try:\n if proxyService.proxy().setConfig() == True:\n if proxyService.proxy().proxyReconfigure() == True:\n return 'True'\n else:\n return 'False'\n else:\n return 'False'\n except Exception as e: \n return 'False'\n\n \n def proxyrestart(self):\n try:\n if proxyService.proxy().setConfig() == True:\n if proxyService.proxy().proxyRestart() == True:\n return 'True'\n else:\n return 'False'\n else:\n return 'False'\n except Exception as e: \n return 'False'\n \n \n def execute_static_routes(self):\n try:\n interfaceService.iface().static_routes_exec()\n return 'True'\n except Exception as e: \n return 'False'\n \n def execute_fw(self,table):\n try:\n firewallService.service().execFirewall(table[0])\n return 'True'\n except Exception as e: \n return 'False' \n ","sub_path":"shotofw/lib/shoto/boss.py","file_name":"boss.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"354748941","text":"t=int(input());\r\nprice=[2048,1024,512,256,128,64,32,16,8,4,2,1];\r\nfor i in range(t):\r\n num=int(input());\r\n count=0;\r\n for j in range(len(price)):\r\n if(num==0):\r\n break;\r\n if(price[j]>num):\r\n continue;\r\n while(num>=price[j]):\r\n num-=price[j];\r\n count+=1;\r\n print(count);\r\n","sub_path":"Beginner/CIELRCPT.py","file_name":"CIELRCPT.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"125299225","text":"from PyQt4 import QtGui, QtCore\n\nclass Tray(QtGui.QSystemTrayIcon):\n \n def __init__(self, parent):\n # Create main widget\n self.widget = QtGui.QWidget()\n self.icon = QtGui.QIcon(\":/webiny/webiny.png\")\n super(Tray, self).__init__(self.icon, self.widget)\n self.setParent(parent)\n \n # Add signal handlers\n self.messageClicked.connect(self.parent().balloonClicked)\n self.activated.connect(self.parent().iconClicked)\n \n # Add context menu\n menu = QtGui.QMenu(self.widget) \n settingsAction = menu.addAction(\"Settings\")\n QtCore.QObject.connect(settingsAction, QtCore.SIGNAL(\"triggered()\"), self.parent().openSettings)\n menu.addSeparator()\n exitAction = menu.addAction(\"Exit\")\n QtCore.QObject.connect(exitAction, QtCore.SIGNAL(\"triggered()\"), self.parent().exitApp)\n \n self.setContextMenu(menu) \n self.show()","sub_path":"WebinyNotifier/lib/tray.py","file_name":"tray.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"425438797","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n#\n# Author: Payne Zheng \n# Date: 2019/7/18\n# Location: DongGuang\n# Desc: 进度条生成器\n\nimport time\nfrom modules.size_format import SizeUnitFormat\nfrom modules.colored import Colored\n\ncolors = Colored()\nSizeFormat = SizeUnitFormat()\n\ndef progress_bar(length):\n \"\"\"打印进度条\n \\r: 将光标移动到当前行的首位而不换行\n \\n: 将光标移动到下一行,并不移动到首位\n \\r\\n: 将光标移动到下一行首位\n :param length: 总长度\n \"\"\"\n bar_style = \">\" # 进度条样式\n bar_total_length = 50 # 总共显示多少个进度条样式\n rotate_list = \"|/-\\\\\" # 进度旋转图示\n start_time = time.time()\n size = 0\n while size <= length:\n if size == length:print() # 大小接收完后打印个空来结束end='\\r',不然进度条内容会被清空\n size = yield # 当前进度需要调用者通过 send()方法传入\n bar_num = bar_style * int(size*(bar_total_length/length)) # 当前进度条长度\n rate = size/length*100 # 当前百分比\n print(colors.yellow('[{}][size:{}][time:{:.2f}s][{}][{:.2f}%]'.format(\n rotate_list[int(rate) % 4],\n SizeFormat.size2human(size),\n time.time() - start_time,\n bar_num,\n rate)), end='\\r')\n # print() # 生成器写在这里不会被执行,所以写在上面\n\n\n# # 调用示例:\n# total_size = 138763400\n# p = progress_bar(total_size)\n# next(p)\n# for i in range(0, total_size+1, 100):\n# p.send(i)\n# print('done')\n","sub_path":"luffycity-s8/第三模块_面向对象_网络编程基础/网络编程基础/作业_FTP文件服务器/FTPProject/client/modules/progress_bar.py","file_name":"progress_bar.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"21592962","text":"# Copyright 2016-present CERN – European Organization for Nuclear Research\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.\nimport random\nfrom collections import defaultdict\nfrom typing import List, Dict, Sequence, Optional\n\nimport numpy as np\n\nfrom qf_lib.backtesting.alpha_model.alpha_model import AlphaModel\nfrom qf_lib.backtesting.alpha_model.exposure_enum import Exposure\nfrom qf_lib.backtesting.alpha_model.signal import Signal\nfrom qf_lib.backtesting.contract.contract import Contract\nfrom qf_lib.backtesting.events.time_event.regular_time_event.before_market_open_event import BeforeMarketOpenEvent\nfrom qf_lib.backtesting.portfolio.position import Position\nfrom qf_lib.backtesting.trading_session.trading_session import TradingSession\nfrom qf_lib.common.exceptions.future_contracts_exceptions import NoValidTickerException\nfrom qf_lib.common.tickers.tickers import Ticker\nfrom qf_lib.common.utils.logging.qf_parent_logger import qf_logger\nfrom qf_lib.containers.dataframe.qf_dataframe import QFDataFrame\n\n\nclass AlphaModelStrategy(object):\n \"\"\"\n Puts together models and all settings around it and generates orders on before market open.\n\n Parameters\n ----------\n ts: TradingSession\n Trading session\n model_tickers_dict: Dict[AlphaModel, Sequence[Ticker]]\n Dict mapping models to list of tickers that the model trades. (The tickers for which the\n model gives recommendations)\n use_stop_losses: bool\n flag indicating if the stop losses should be used or not. If False, all stop orders are ignored\n max_open_positions: None, int\n maximal number of positions that may be open at the same time in the portfolio. If the value is set to None,\n the number of maximal open positions is not limited.\n \"\"\"\n\n def __init__(self, ts: TradingSession, model_tickers_dict: Dict[AlphaModel, Sequence[Ticker]], use_stop_losses=True,\n max_open_positions: Optional[int] = None):\n self._broker = ts.broker\n self._order_factory = ts.order_factory\n self._data_handler = ts.data_handler\n self._contract_ticker_mapper = ts.contract_ticker_mapper\n self._position_sizer = ts.position_sizer\n self._orders_filters = ts.orders_filters\n self._timer = ts.timer\n\n self._model_tickers_dict = model_tickers_dict\n self._use_stop_losses = use_stop_losses\n self._signals = defaultdict(list) # signals with date and \"Ticker@AlphaModel\" string\n self._signals_dates = []\n self._max_open_positions = max_open_positions\n\n ts.notifiers.scheduler.subscribe(BeforeMarketOpenEvent, listener=self)\n self.logger = qf_logger.getChild(self.__class__.__name__)\n self._log_configuration()\n\n def on_before_market_open(self, _: BeforeMarketOpenEvent = None):\n if self._timer.now().weekday() not in (5, 6): # Skip saturdays and sundays\n self.logger.info(\"on_before_market_open - Signals Generation Started\")\n signals = self._calculate_signals()\n self.logger.info(\"on_before_market_open - Signals Generation Finished\")\n\n if self._max_open_positions is not None:\n self._adjust_number_of_open_positions(signals)\n\n self.logger.info(\"on_before_market_open - Save All Original Signals\")\n self._save_signals(signals)\n\n self.logger.info(\"on_before_market_open - Remove Redundant Signals\")\n self._remove_redundant_signals(signals)\n\n self.logger.info(\"on_before_market_open - Placing Orders\")\n self._place_orders(signals)\n self.logger.info(\"on_before_market_open - Orders Placed\")\n\n def _remove_redundant_signals(self, signals: List[Signal]):\n \"\"\"\n Remove all these signals, which do not need to be passed into position sizer as they obviously do not change the\n state of the portfolio (current exposure equals Exposure.OUT and suggested exposure is also Exposure.OUT).\n \"\"\"\n open_positions = self._broker.get_positions()\n tickers_with_open_positions = set(\n self._contract_to_ticker(position.contract()) for position in open_positions\n )\n\n signals_with_suggested_exposure_out = [signal for signal in signals if\n signal.suggested_exposure == Exposure.OUT]\n redundant_signals = [signal for signal in signals_with_suggested_exposure_out\n if signal.ticker not in tickers_with_open_positions]\n\n for signal in redundant_signals:\n signals.remove(signal)\n\n def _adjust_number_of_open_positions(self, signals: List[Signal]):\n \"\"\"\n Adjust the number of positions that, after placing the orders, will be open in th portfolio, so that it\n will not exceed the maximum number.\n\n In case if we already reached the maximum number of positions in the portfolio and we get 2 new signals,\n one for opening and one for closing a position, we ignore the opening position signal in case if during\n position closing an error would occur and the position will remain in the portfolio.\n\n Regarding Futures Contracts:\n While checking the number of all possible open positions we consider family of contracts\n (for example Gold) and not specific contracts (Jul 2020 Gold). Therefore even if 2 or more contracts\n corresponding to one family existed in the portfolio, they would be counted as 1 open position.\n\n \"\"\"\n\n open_positions = self._broker.get_positions()\n open_positions_tickers = set(self._contract_to_ticker(position.contract()) for position in open_positions)\n\n # Signals, which correspond to either already open positions in the portfolio or indicate that a new position\n # should be open for the given contract (with Exposure = LONG or SHORT)\n position_opening_signals = [signal for signal in signals if signal.suggested_exposure != Exposure.OUT]\n\n # Check if the number of currently open positions in portfolio + new positions, that should be open according\n # to the signals, does not exceed the limit\n all_open_positions_tickers = open_positions_tickers.union(\n [signal.ticker for signal in position_opening_signals]\n )\n if len(all_open_positions_tickers) <= self._max_open_positions:\n return signals\n\n self.logger.info(\"The number of positions to be open exceeds the maximum limit of {}. Some of the signals need \"\n \"to be changed.\".format(self._max_open_positions))\n\n # Signals, which indicate openings of new positions in the portfolio\n new_positions_signals = [signal for signal in signals if signal.ticker not in open_positions_tickers and\n signal in position_opening_signals]\n\n # Compute how many signals need to be changed (their exposure has to be changed to OUT in order to fulfill the\n # requirements)\n number_of_signals_to_change = len(new_positions_signals) - (\n self._max_open_positions - len(open_positions_tickers))\n assert number_of_signals_to_change >= 0\n\n # Select a random subset of signals, for which the exposure will be set to OUT (in order not to exceed the\n # maximum), which would be deterministic across multiple backtests for the same period of time (certain seed)\n random.seed(self._timer.now().timestamp())\n new_positions_signals = sorted(new_positions_signals, key=lambda s: s.fraction_at_risk) # type: List[Signal]\n signals_to_change = random.sample(new_positions_signals, number_of_signals_to_change)\n\n for signal in signals_to_change:\n signal.suggested_exposure = Exposure.OUT\n\n return signals\n\n def _contract_to_ticker(self, contract: Contract):\n \"\"\" Map contract to corresponding ticker, where two contracts from one future family should be mapped into\n the same ticker\"\"\"\n return self._contract_ticker_mapper.contract_to_ticker(contract, strictly_to_specific_ticker=False)\n\n def _calculate_signals(self):\n current_positions = self._broker.get_positions()\n signals = []\n\n for model, tickers in self._model_tickers_dict.items():\n tickers = list(set(tickers)) # remove duplicates\n\n def map_valid_tickers(ticker):\n try:\n return self._contract_ticker_mapper.ticker_to_contract(ticker)\n except NoValidTickerException:\n return None\n\n contracts = [map_valid_tickers(ticker) for ticker in tickers]\n tickers_and_contracts = zip(tickers, contracts)\n valid_tickers_and_contracts = [(t, c) for t, c in tickers_and_contracts if c is not None]\n\n for ticker, contract in valid_tickers_and_contracts:\n current_exposure = self._get_current_exposure(contract, current_positions)\n signal = model.get_signal(ticker, current_exposure)\n signals.append(signal)\n\n return signals\n\n def _place_orders(self, signals):\n self.logger.info(\"Converting Signals to Orders using: {}\".format(self._position_sizer.__class__.__name__))\n orders = self._position_sizer.size_signals(signals, self._use_stop_losses)\n\n for orders_filter in self._orders_filters:\n self.logger.info(\"Filtering Orders based on selected requirements: {}\".format(orders_filter))\n orders = orders_filter.adjust_orders(orders)\n\n self.logger.info(\"Cancelling all open orders\")\n self._broker.cancel_all_open_orders()\n\n self.logger.info(\"Placing orders\")\n self._broker.place_orders(orders)\n\n def _save_signals(self, signals: List[Signal]):\n tickers_to_models = {\n ticker: model.__class__.__name__ for model, tickers_list in self._model_tickers_dict.items()\n for ticker in tickers_list\n }\n\n tickers_to_signals = {\n ticker: None for model_tickers in self._model_tickers_dict.values() for ticker in model_tickers\n }\n\n tickers_to_signals.update({\n signal.ticker: signal for signal in signals\n })\n\n for ticker in tickers_to_signals.keys():\n signal = tickers_to_signals[ticker]\n model_name = tickers_to_models[ticker]\n\n self.logger.info(signal)\n\n ticker_str = ticker.as_string() + \"@\" + model_name\n self._signals[ticker_str].append((self._timer.now().date(), signal))\n\n self._signals_dates.append(self._timer.now())\n\n def get_signals(self):\n \"\"\"\n Returns a QFDataFrame with all generated signals. The columns names are of the form TickerName@ModelName,\n and the rows are indexed by the time of signals generation.\n\n Returns\n --------\n QFDataFrame\n QFDataFrame with all generated signals\n \"\"\"\n return QFDataFrame(data=self._signals, index=self._signals_dates)\n\n def _get_current_exposure(self, contract: Contract, current_positions: List[Position]) -> Exposure:\n matching_position_quantities = [position.quantity()\n for position in current_positions if position.contract() == contract]\n\n assert len(matching_position_quantities) in [0, 1]\n quantity = next(iter(matching_position_quantities), 0)\n current_exposure = Exposure(np.sign(quantity))\n return current_exposure\n\n def _log_configuration(self):\n self.logger.info(\"AlphaModelStrategy configuration:\")\n for model, tickers in self._model_tickers_dict.items():\n self.logger.info('Model: {}'.format(str(model)))\n for ticker in tickers:\n try:\n self.logger.info('\\t Ticker: {}'.format(ticker.as_string()))\n except NoValidTickerException:\n raise ValueError(\"Futures Tickers are not supported by the AlphaModelStrategy. Use the \"\n \"FuturesAlphaModelStrategy instead.\")\n","sub_path":"qf_lib/backtesting/alpha_model/alpha_model_strategy.py","file_name":"alpha_model_strategy.py","file_ext":"py","file_size_in_byte":12665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"526683569","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 2.3.33.0\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass X509CertificateApiModel(Model):\n \"\"\"Certificate model.\n\n :param subject: Subject\n :type subject: str\n :param thumbprint: Thumbprint\n :type thumbprint: str\n :param serial_number: Serial number\n :type serial_number: str\n :param not_before_utc: Not before validity\n :type not_before_utc: datetime\n :param not_after_utc: Not after validity\n :type not_after_utc: datetime\n :param certificate: Raw data\n :type certificate: object\n \"\"\"\n\n _attribute_map = {\n 'subject': {'key': 'subject', 'type': 'str'},\n 'thumbprint': {'key': 'thumbprint', 'type': 'str'},\n 'serial_number': {'key': 'serialNumber', 'type': 'str'},\n 'not_before_utc': {'key': 'notBeforeUtc', 'type': 'iso-8601'},\n 'not_after_utc': {'key': 'notAfterUtc', 'type': 'iso-8601'},\n 'certificate': {'key': 'certificate', 'type': 'object'},\n }\n\n def __init__(self, subject=None, thumbprint=None, serial_number=None, not_before_utc=None, not_after_utc=None, certificate=None):\n super(X509CertificateApiModel, self).__init__()\n self.subject = subject\n self.thumbprint = thumbprint\n self.serial_number = serial_number\n self.not_before_utc = not_before_utc\n self.not_after_utc = not_after_utc\n self.certificate = certificate\n","sub_path":"api/generated/python/azure-iiot-opc-vault/models/x509_certificate_api_model.py","file_name":"x509_certificate_api_model.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"358294827","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.3 (62011)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: \\Ft\\Xml\\Xslt\\Exslt\\Functions.py\n# Compiled at: 2005-12-10 14:51:55\n\"\"\"\nEXSLT 2.0 - Functions (http://www.exslt.org/func/index.html)\nWWW: http://4suite.org/XSLT e-mail: support@4suite.org\n\nCopyright (c) 2001 Fourthought Inc, USA. All Rights Reserved.\nSee http://4suite.org/COPYRIGHT for license and copyright information\n\"\"\"\nfrom Ft.Xml import XPath\nfrom Ft.Xml.Xslt import XSL_NAMESPACE, XsltElement\nfrom Ft.Xml.Xslt import XsltRuntimeException\nfrom Ft.Xml.Xslt import ContentInfo, AttributeInfo\nfrom Ft.Xml.Xslt.Exslt.MessageSource import Error as ExsltError\nfrom Ft.Xml.Xslt.XPathExtensions import RtfExpr\nEXSL_FUNCTIONS_NS = 'http://exslt.org/functions'\n\nclass FunctionElement(XsltElement):\n __module__ = __name__\n content = ContentInfo.Seq(ContentInfo.Rep(ContentInfo.QName(XSL_NAMESPACE, 'xsl:param')), ContentInfo.Template)\n legalAttrs = {'name': AttributeInfo.QNameButNotNCName(required=1)}\n doesPrime = True\n\n def prime(self, processor, context):\n context.addFunction(self._name, self)\n return\n\n def __call__(self, context, *args):\n processor = context.processor\n ctx_state = context.copy()\n ctx_namespaces = context.processorNss\n ctx_instruction = context.currentInstruction\n context.processorNss = self.namespaces\n context.currentInstruction = self\n counter = 0\n self.result = ''\n for child in self.children:\n if child.expandedName == (XSL_NAMESPACE, 'param'):\n if counter < len(args):\n context.varBindings[child._name] = args[counter]\n else:\n child.instantiate(context, processor)\n counter = counter + 1\n else:\n child.instantiate(context, processor)\n\n context.currentInstruction = ctx_instruction\n context.processorNss = ctx_namespaces\n context.set(ctx_state)\n return self.result\n\n\nclass ResultElement(XsltElement):\n \"\"\"\n When an func:result element is instantiated, during the\n instantiation of a func:function element, the function returns\n with its value.\n \"\"\"\n __module__ = __name__\n content = ContentInfo.Template\n legalAttrs = {'select': AttributeInfo.Expression()}\n doesSetup = doesPrime = True\n\n def setup(self):\n if not self._select:\n self._select = RtfExpr(self.children)\n return\n\n def prime(self, processor, context):\n self._function = None\n current = self.parent\n while current:\n if current.expandedName == (EXSL_FUNCTIONS_NS, 'function'):\n self._function = current\n break\n current = current.parent\n\n if not self._function:\n raise XsltRuntimeException(ExsltError.RESULT_NOT_IN_FUNCTION, self)\n if not self.isLastChild():\n siblings = self.parent.children\n for node in siblings[siblings.index(self) + 1:]:\n if node.expandedName != (XSL_NAMESPACE, 'fallback'):\n raise XsltRuntimeException(ExsltError.ILLEGAL_RESULT_SIBLINGS, self)\n\n return\n return\n\n def instantiate(self, context, processor):\n context.processorNss = self.namespaces\n context.currentInstruction = self\n self._function.result = self._select.evaluate(context)\n return\n\n\nclass ScriptElement(XsltElement):\n \"\"\"\n NOT YET IMPLEMENTED\n\n The top-level func:script element provides an implementation of\n extension functions in a particular namespace.\n \"\"\"\n __module__ = __name__\n\n\nExtNamespaces = {EXSL_FUNCTIONS_NS: 'func'}\nExtFunctions = {}\nExtElements = {(EXSL_FUNCTIONS_NS, 'function'): FunctionElement, (EXSL_FUNCTIONS_NS, 'result'): ResultElement}","sub_path":"pycfiles/test1/Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":3918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"152451228","text":"from keras.models import Sequential\nfrom keras.layers import Convolution2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.layers import MaxPooling2D\nfrom keras.preprocessing import image\nimport numpy as np\nimport os\n\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\nclassifier = Sequential()\n\n#Step 1 - Convolution\n\nclassifier.add(Convolution2D(32, 3, 3, input_shape=(64,64,3), activation='relu'))\n\n\n#Step 2 - Max pooling\n\nclassifier.add(MaxPooling2D(pool_size=(2,2)))\n\n#steps 1 and 2 repeated to add a second convolutional layer\nclassifier.add(Convolution2D(32, 3, 3, activation='relu'))\nclassifier.add(MaxPooling2D(pool_size=(2,2)))\n\n#Step 3 - Flattening\n\nclassifier.add(Flatten())\n\n#Step 4 - Full connection\n\nclassifier.add(Dense(units = 128, activation='relu'))\n\nclassifier.add(Dense(units = 1, activation='sigmoid'))\n\nclassifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n#binary crossentropy uses the logarithmic loss function, which is usually used for classification problems. Since\n#the problem is binary, we use binary_crossentropy\n\n\n#image augmentation to prevent overfitting, allows us to enrich our dataset without adding more images\n\nfrom keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntraining_set = train_datagen.flow_from_directory(\n '/Users/stevengong/Desktop/Deep-Learning-course/Volume 1 - Supervised Deep Learning/Part 2 - Convolutional Neural Networks (CNN)/Section 8 - Building a CNN/dataset/training_set',\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\ntest_set = test_datagen.flow_from_directory(\n '/Users/stevengong/Desktop/Deep-Learning-course/Volume 1 - Supervised Deep Learning/Part 2 - Convolutional Neural Networks (CNN)/Section 8 - Building a CNN/dataset/test_set',\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\nclassifier.fit_generator(\n training_set,\n steps_per_epoch=8000,\n epochs=25,\n validation_data=test_set,\n validation_steps=2000)\n\nimg = image.open('/Users/stevengong/Desktop/Deep-Learning-course/Volume 1 - Supervised Deep Learning/Part 2 - Convolutional Neural Networks (CNN)/Section 8 - Building a CNN/dataset/single_prediction/cat_or_dog_1.jpg')\nimg = np.array(img).astype('float32')/255\nimg = transform.resize(np_image, (64,64,3))\nimg = np.expand_dims(img, axis=0)\n\nclassifier.predict(img)","sub_path":"Volume 1 - Supervised Deep Learning/Part 2 - Convolutional Neural Networks (CNN)/Section 8 - Building a CNN/stevencnn.py","file_name":"stevencnn.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"448584730","text":"\n # *************************\n # Catherine Ann Celeste Quinlan.\n# Programming 2019 Data Analytics\n# This program asks the user whether or not today is a day that begins with the letter T.\n# Question 2\n# *************************\n\nimport datetime # Importing datatime Pythonhttps://stackoverflow.com/questions/34296860/how-do-you-get-the-time-and-date-in-python\nnow = datetime.datetime.now\nweekday = datetime.datetime.today().strftime(\"%A\") # Taken from # Ian McLoughlin, 2018-02-01\n# Is it Tuesday?\nif datetime.datetime.today().weekday() == 1:\n print (\"Yes! It is Tuesday\") \nelif datetime.datetime.today() .weekday() == 3:\n print (\"Yes! It is Thursday\") # Printing if it is Tuesday \n\nelse:\n print (\"Unfortunately today does not start with T.\"\"\\n\" \"Today is :\", weekday) # prints out day that doesnt start with T","sub_path":"Problem2.py","file_name":"Problem2.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"285149454","text":"from datetime import datetime, timedelta\nfrom json import loads, dump\nfrom business.helpers.config import config_map\nfrom business.helpers.constantes import Constantes\n\nHOUR_FORMAT = '%H:%M'\nconstantes = Constantes()\n\n\ndef get_match(list, filter):\n \"\"\"\n Return the first element that matches to the filter criteria\n :param list: list of elements\n :param filter: Example: lambda x: x.n == 3\n :return: None or the element found\n \"\"\"\n for x in list:\n if filter(x):\n return x\n return None\n\n\ndef get_matches(list, filter):\n \"\"\"\n Return all elements that matches to the filter criteria\n :param list: list of elements\n :param filter: Example: lambda x: x.n == 3\n :return: None or the element found\n \"\"\"\n response = []\n for x in list:\n if filter(x):\n response.append(x)\n return response\n\n\ndef extract_next_time(json):\n try:\n # Also convert to int since update_time will be string. When comparing\n # strings, \"10\" is smaller than \"2\".\n return int(json['arrivals'][0])\n except KeyError:\n return 0\n except ValueError:\n return 9999999\n except IndexError:\n return 9999999\n\n\ndef convert_eta_to_minutes(eta):\n \"\"\"\n Convert hour format to minutes\n :param eta: estimate time arrivals to be converted\n :return:\n \"\"\"\n now = datetime.now().strftime(HOUR_FORMAT)\n for idx, est_hour in enumerate(eta['arrivals']):\n tdelta = datetime.strptime(est_hour, HOUR_FORMAT) - datetime.strptime(now, HOUR_FORMAT)\n if tdelta.days < 0:\n tdelta = timedelta(days=0,\n seconds=tdelta.seconds, microseconds=tdelta.microseconds)\n est_min = int(tdelta.total_seconds() / 60)\n eta['arrivals'][idx] = str(est_min)\n return eta\n\n\ndef isint(value):\n \"\"\"\n Try to convert value to int\n :param value: value to try to convert to int\n :return: value converted or None\n \"\"\"\n try:\n return int(value)\n except:\n return None\n\n\ndef get_json_from_file(file_path):\n \"\"\"\n Retrieves json from a file\n :param file_path:\n :return:\n \"\"\"\n with open(file_path, \"r\") as file:\n return loads(file.read())\n\n\ndef update_json_file(file_path, json_obj):\n \"\"\"\n Update json file\n :param file_path:\n :return:\n \"\"\"\n with open(file_path, \"w+\") as file:\n dump(json_obj, file)\n\n\ndef remove_empty_from_dict(d):\n \"\"\"\n remove empty keys from dicts\n :param d: dictionary that will be iterated\n :return: cleaned dictionary\n \"\"\"\n if type(d) is dict:\n return dict((k, remove_empty_from_dict(v)) for k, v in d.items() if v and remove_empty_from_dict(v))\n elif type(d) is list:\n return [remove_empty_from_dict(v) for v in d if v and remove_empty_from_dict(v)]\n else:\n return d\n\n\ndef must_update_diff(ref_name, last_update):\n \"\"\"\n Verify difference between times and config file\n :param ref_name: reference name that will be checked\n :param last_update: last update time\n :return:\n \"\"\"\n # 1w 1d 1h 1m 1s\n update_str = config_map('update')[ref_name]\n end = datetime.now()\n start = datetime.strptime(last_update, constantes.DT_FORMAT)\n\n expected_int = [int(s) for s in update_str if s.isdigit()]\n expected_str = [s for s in update_str if not s.isdigit()]\n\n if len(expected_int) == 0:\n my_int = 1\n else:\n my_int = expected_int[0]\n\n if len(expected_str) == 0:\n my_str = \"d\"\n else:\n my_str = expected_str[0]\n\n if my_str == \"s\":\n return (end - start).seconds > my_int\n if my_str == \"m\":\n return (end - start).seconds / 60 > my_int\n if my_str == \"h\":\n return (end - start).seconds / 3600 > my_int\n if my_str == \"d\":\n return (end - start).days > my_int\n if my_str == \"w\":\n return (end - start).days / 7 > my_int\n\n return True\n\n\n","sub_path":"business/helpers/auxiliar.py","file_name":"auxiliar.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"51050989","text":"def make_graph(data1,data2):\n x = now_head[data1]\n y = now_head[data2]\n if x != y:\n x, y = [x,y] if x < y else [y,x]\n for i in range(len(now_head)):\n if now_head[i] == y:\n now_head[i] = x\n\n\nT = int(input())\nfor t in range(1,T+1):\n N, M = list(map(int,input().split()))\n question = list(map(int,input().split()))\n now_head = list(range(N+1))\n for i in range(0,len(question),2):\n make_graph([question[i],question[i+1]])\n print(\"#{} {}\".format(t,len(set(now_head))-1))","sub_path":"KYC/algorithm/Advanced/GraphBasic/Advanced2.py","file_name":"Advanced2.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"99793420","text":"import scipy.sparse as sparse\nimport numpy as np\nimport theano\nfrom theano import tensor as T\n\n\ndef deepwalk_filter(evals, window):\n for i in range(len(evals)):\n x = evals[i]\n evals[i] = 1. if x >= 1 else x*(1-x**window) / (1-x) / window\n evals = np.maximum(evals, 0)\n \"\"\"logger.info(\"After filtering, max eigenvalue=%f, min eigenvalue=%f\",\n np.max(evals), np.min(evals))\"\"\"\n return evals\n\n\ndef approximate_deepwalk_matrix(evals, D_rt_invU, window, vol, b):\n evals = deepwalk_filter(evals, window=window)\n X = sparse.diags(np.sqrt(evals)).dot(D_rt_invU.T).T\n m = T.matrix()\n mmT = T.dot(m, m.T) * (vol/b)\n f = theano.function([m], T.log(T.maximum(mmT, 1)))\n Y = f(X.astype(theano.config.floatX))\n \"\"\"logger.info(\"Computed DeepWalk matrix with %d non-zero elements\",\n np.count_nonzero(Y))\"\"\"\n return sparse.csr_matrix(Y)\n\n\ndef svd_deepwalk_matrix(X, dim, logger):\n logger.info(\"SVD on proximity matrix\")\n X = X.asfptype()\n u, s, v = sparse.linalg.svds(X.todense(), dim, return_singular_vectors=\"u\")\n # return U \\Sigma^{1/2}\n return sparse.diags(np.sqrt(s)).dot(u.T).T","sub_path":"src/embed_methods/SVD.py","file_name":"SVD.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"342815472","text":"# Name: Jason James\n# Course: CS 4308\n# Section: W01\n# Assignment: Project Deliverable 3\n# Date: 7/20/19\n\nfrom scl.parser.SCL_Parser import SCL_Parser\nfrom scl.parser.NodeType import NodeType\nfrom scl.scanner.Token import Token\nfrom scl.scanner.Lexeme import Lexeme\nimport re\n\n\nclass SCL_Interpreter(SCL_Parser):\n\n\t# Constructor\n\tdef __init__(self, sclFilePath):\n\t\tSCL_Parser.__init__(self, sclFilePath)\n\t\tself.globalVariables = {}\n\t\tself.globalConstants = {}\n\t\tself.implementVariables = {}\n\t\tself.implementConstants = {}\n\n\t# Performs Python-SCL Interpretation\n\tdef interpret(self):\n\t\tprint(\"Parsing SCL File\", \"\\n\")\n\t\tparseTree = super().parse()\n\t\tprint(\"\\nFinished Parsing SCL File\")\n\t\tprint(\"=\"*50, \"\\n\")\n\n\t\t# Iterate through all of node's direct children\n\t\tfor node in parseTree.getRoot().getChildren():\n\n\t\t\tif node.getNodeType() is NodeType.IMPORT:\n\t\t\t\t# Nothing to interpret for imports in this subset of SCL\n\t\t\t\tpass\n\n\t\t\telif node.getNodeType() is NodeType.SYMBOL:\n\t\t\t\t# Nothing to interpret for symbols in this subset of SCL\n\t\t\t\tpass\n\n\t\t\telif node.getNodeType() is NodeType.GLOBALS:\n\t\t\t\tself.interpretGlobals(node)\n\n\t\t\telif node.getNodeType() is NodeType.IMPLEMENT:\n\t\t\t\tself.interpretImplement(node)\n\n\t# Interprets globals\n\tdef interpretGlobals(self, node):\n\t\tfor child in node.getChildren():\n\t\t\tif child.getNodeType() is NodeType.CONST_DEC:\n\t\t\t\tself.interpretConstDec(child)\n\t\t\telif child.getNodeType() is NodeType.VAR_DEC:\n\t\t\t\tself.interpretVarDec(child)\n\n\t# Interprets implement\n\tdef interpretImplement(self, node):\n\t\tfor child in node.getChildren():\n\t\t\tif child.getNodeType() is NodeType.FUNCT_LIST:\n\t\t\t\tself.interpretFunctList(child)\n\n\t# Interprets const_dec\n\tdef interpretConstDec(self, node):\n\t\t# There should only be one child of \n\t\tfor child in node.getChildren():\n\t\t\tif child.getNodeType() is NodeType.CONST_LIST:\n\t\t\t\tself.interpretConstList(child)\n\n\t# Interprets const_list\n\tdef interpretConstList(self, node):\n\t\tfor child in node.getChildren():\n\t\t\tif child.getNodeType() is NodeType.COMP_DECLARE:\n\t\t\t\tself.interpretCompDeclare(child)\n\n\t# Interprets var_dec\n\tdef interpretVarDec(self, node):\n\t\t# There should only be one child of \n\t\tfor child in node.getChildren():\n\t\t\tif child.getNodeType() is NodeType.VAR_LIST:\n\t\t\t\tself.interpretVarList(child)\n\n\t# Interprets var_list\n\tdef interpretVarList(self, node):\n\t\tfor child in node.getChildren():\n\t\t\tif child.getNodeType() is NodeType.COMP_DECLARE:\n\t\t\t\tself.interpretCompDeclare(child)\n\n\t# Interprets comp_declare\n\tdef interpretCompDeclare(self, node):\n\t\tparent = node.getParent()\n\t\tgreatGrandparent = parent.getParent().getParent()\n\n\t\tisConstant = True if parent.getNodeType() is NodeType.CONST_LIST else False\n\t\tisGlobal = True if greatGrandparent.getNodeType() is NodeType.GLOBALS else False\n\n\t\tlexemes = node.getScanLine().getLexemes()\n\t\treturnTypeToken = None\n\n\t\tfor child in node.getChildren():\n\t\t\tif child.getNodeType() is NodeType.RET_TYPE:\n\t\t\t\treturnTypeToken = self.interpretRetType(child)\n\n\t\tif isGlobal is True:\n\t\t\tif isConstant is True:\n\t\t\t\tself.globalConstants[lexemes[1].getLexemeString()] = [lexemes[3].getLexemeString(), returnTypeToken]\n\t\t\telse:\n\t\t\t\tself.globalVariables[lexemes[1].getLexemeString()] = [\"\", returnTypeToken]\n\t\telse:\n\t\t\tif isConstant is True:\n\t\t\t\tself.implementConstants[lexemes[1].getLexemeString()] = [lexemes[3].getLexemeString(), returnTypeToken]\n\t\t\telse:\n\t\t\t\tself.implementVariables[lexemes[1].getLexemeString()] = [\"\", returnTypeToken]\n\n\t# Returns return type token\n\tdef interpretRetType(self, node):\n\t\tlexemes = node.getScanLine().getLexemes()\n\n\t\treturnType = lexemes[len(lexemes)-1]\n\t\treturnTypeToken = returnType.getToken()\n\n\t\treturn returnTypeToken\n\n\t# Interprets funct_list\n\tdef interpretFunctList(self, node):\n\t\tfor child in node.getChildren():\n\t\t\tif child.getNodeType() is NodeType.FUNCT_BODY:\n\t\t\t\tself.interpretFunctBody(child)\n\n\t# Interprets funct_body\n\tdef interpretFunctBody(self, node):\n\t\tfor child in node.getChildren():\n\t\t\tif child.getNodeType() is NodeType.CONST_DEC:\n\t\t\t\tself.interpretConstDec(child)\n\t\t\telif child.getNodeType() is NodeType.VAR_DEC:\n\t\t\t\tself.interpretVarDec(child)\n\t\t\telif child.getNodeType() is NodeType.PACTIONS:\n\t\t\t\tself.interpretPActions(child)\n\n\t# Interprets pactions\n\tdef interpretPActions(self, node):\n\t\tfor child in node.getChildren():\n\t\t\tif child.getNodeType() is NodeType.ACTION_DEF:\n\t\t\t\tself.interpretActionDef(child)\n\n\t# Interprets action_def\n\tdef interpretActionDef(self, node):\n\t\tlexemes = node.getScanLine().getLexemes()\n\n\t\t# If action is to SET\n\t\tif lexemes[0].getToken() is Token.SET:\n\t\t\tif lexemes[1].getLexemeString() in self.globalVariables:\n\t\t\t\texpResult = None\n\t\t\t\tfor child in node.getChildren():\n\t\t\t\t\tif child.getNodeType() is NodeType.EXP:\n\t\t\t\t\t\texpResult = self.interpretExp(child)\n\t\t\t\t\t\tself.globalVariables[lexemes[1].getLexemeString()][0] = expResult\n\t\t\telif lexemes[1].getLexemeString() in self.implementVariables:\n\t\t\t\texpResult = None\n\t\t\t\tfor child in node.getChildren():\n\t\t\t\t\tif child.getNodeType() is NodeType.EXP:\n\t\t\t\t\t\texpResult = self.interpretExp(child)\n\t\t\t\t\t\tself.implementVariables[lexemes[1].getLexemeString()][0] = expResult\n\t\t\telif lexemes[1].getLexemeString() in (self.globalConstants, self.implementConstants):\n\t\t\t\tprint(\"ERROR: Constant variable cannot be changed!\")\n\t\t\telse:\n\t\t\t\tprint(\"ERROR: Variable not found!\")\n\n\t\t# If action is to INPUT\n\t\telif lexemes[0].getToken() is Token.INPUT:\n\t\t\tif lexemes[1].getToken() is Token.STRING_LITERAL:\n\t\t\t\tif self.getVarType(lexemes[2].getLexemeString()) is not None:\n\t\t\t\t\tif lexemes[2].getLexemeString() in self.globalVariables:\n\t\t\t\t\t\tself.globalVariables[lexemes[2].getLexemeString()][0] = input(self.getStringLiteralTxt(lexemes[1].getLexemeString()))\n\t\t\t\t\telif lexemes[2].getLexemeString() in self.implementVariables:\n\t\t\t\t\t\tself.implementVariables[lexemes[2].getLexemeString()][0] = input(self.getStringLiteralTxt(lexemes[1].getLexemeString()))\n\t\t\t\t\telif lexemes[2].getLexemeString() in (self.globalConstants, self.implementConstants):\n\t\t\t\t\t\tprint(\"ERROR: Constant Variable cannot be changed!\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"ERROR: Variable not found!\")\n\n\t\t# If action is to DISPLAY\n\t\telif lexemes[0].getToken() is Token.DISPLAY:\n\t\t\t# Should only be one child\n\t\t\tfor child in node.getChildren():\n\t\t\t\tvalueListTxt = self.interpretPVarValueList((child))\n\t\t\t\tprint(valueListTxt)\n\n\t# Interprets p_var_value_list and returns a list of values\n\tdef interpretPVarValueList(self, node):\n\t\tallLexemesOnLine = node.getScanLine().getLexemes()\n\n\t\tvalueListLexemes = allLexemesOnLine[1:len(allLexemesOnLine)]\n\t\tprintString = \"\"\n\n\t\tfor lexeme in valueListLexemes:\n\t\t\t# If Lexeme token is any type of identifier EXCEPT string type identifiers\n\t\t\tif lexeme.getToken().getNumCode() in (2, 3, 5, 6, 7, 9):\n\t\t\t\tprintString += str(self.getVarValue(lexeme.getLexemeString()))\n\t\t\t# If Lexeme token is string identifier or constant string identifier\n\t\t\telif lexeme.getToken().getNumCode() in (4, 8):\n\t\t\t\tprintString += str(self.getStringLiteralTxt(self.getVarValue(lexeme.getLexemeString())))\n\t\t\t# If lexeme token is any type of literal EXCEPT a string literal\n\t\t\telif lexeme.getToken().getNumCode() in (10, 11, 13):\n\t\t\t\tprintString += str(lexeme.getLexemeString())\n\t\t\t# If lexeme token is a string literal\n\t\t\telif lexeme.getToken() is Token.STRING_LITERAL:\n\t\t\t\tprintString += str(self.getStringLiteralTxt(lexeme.getLexemeString()))\n\n\t\treturn printString\n\n\t# Returns string value which excludes the quotes and comma\n\tdef getStringLiteralTxt(self, lexemeStr):\n\t\tresult = re.search(\"\\\"(.*)\\\"\", lexemeStr)\n\t\treturn result.group(1)\n\n\t# Interprets exp node and returns expression value\n\tdef interpretExp(self, node):\n\t\tallLexemesOnLine = node.getScanLine().getLexemes()\n\n\t\texpLexemes = allLexemesOnLine[3:len(allLexemesOnLine)]\n\n\t\t# Creates priority dictionary to rank which operators are solved first\n\t\tpriority = {\"*\": 1, \"/\": 1, \"+\": 2, \"-\": 2}\n\n\t\tlexemeList = []\n\t\toperList = []\n\n\t\tindex = 0\n\t\texprResult = 0\n\n\t\tfor lexeme in expLexemes:\n\t\t\tif lexeme.getToken().getNumCode() in (2, 3, 6, 7, 10, 11):\n\t\t\t\tlexemeList.append(lexeme)\n\t\t\telif lexeme.getToken().getNumCode() in (25, 26, 27, 28):\n\t\t\t\twhile len(operList) != 0 and priority[operList[len(operList)-1]] <= priority[lexeme.getLexemeString()]:\n\t\t\t\t\tlexemeList.append(Lexeme(operList[len(operList)-1], Token.findToken(operList.pop())))\n\t\t\t\toperList.append(lexeme.getLexemeString())\n\n\t\twhile len(operList) != 0:\n\t\t\tlexemeList.append(Lexeme(operList[len(operList) - 1], Token.findToken(operList.pop())))\n\n\t\tpostFixList = []\n\n\t\tfor lexeme in lexemeList:\n\t\t\tif lexeme.getToken() is Token.MUL_OPERATOR:\n\t\t\t\tself.mulOper(postFixList)\n\t\t\telif lexeme.getToken() is Token.DIV_OPERATOR:\n\t\t\t\tself.divOper(postFixList)\n\t\t\telif lexeme.getToken() is Token.ADD_OPERATOR:\n\t\t\t\tself.addOper(postFixList)\n\t\t\telif lexeme.getToken() is Token.SUB_OPERATOR:\n\t\t\t\tself.subOper(postFixList)\n\t\t\telse:\n\t\t\t\tpostFixList.append(lexeme.getLexemeString())\n\n\t\treturn postFixList.pop()\n\n\t# Multiplies the two top elements in postFixList\n\tdef mulOper(self, postFixList):\n\t\tvarTwo = postFixList.pop()\n\t\tvarOne = postFixList.pop()\n\n\t\tvalOne = None\n\t\tvalTwo = None\n\n\t\t# Find value of first variable\n\t\tif Token.findToken(varOne) is Token.INTEGER_LITERAL:\n\t\t\tvalOne = int(varOne)\n\t\telif Token.findToken(varOne) is Token.FLOAT_LITERAL:\n\t\t\tvalOne = float(varOne)\n\t\telse:\n\t\t\tvarOneType = self.getVarType(varOne)\n\t\t\tif varOneType is Token.INTEGER:\n\t\t\t\tvalOne = int(self.getVarValue(varOne))\n\t\t\telif varOneType is Token.FLOAT:\n\t\t\t\tvalOne = float(self.getVarValue(varOne))\n\n\t\t# Find value of second variable\n\t\tif Token.findToken(varTwo) is Token.INTEGER_LITERAL:\n\t\t\tvalTwo = int(varTwo)\n\t\telif Token.findToken(varTwo) is Token.FLOAT_LITERAL:\n\t\t\tvalTwo = float(varTwo)\n\t\telse:\n\t\t\tvarTwoType = self.getVarType(varTwo)\n\t\t\tif varTwoType is Token.INTEGER:\n\t\t\t\tvalTwo = int(self.getVarValue(varTwo))\n\t\t\telif varTwoType is Token.FLOAT:\n\t\t\t\tvalTwo = float(self.getVarValue(varTwo))\n\n\t\tresult = valOne * valTwo\n\t\tpostFixList.append(str(result))\n\n\t# Divides the two top elements in postFixList\n\tdef divOper(self, postFixList):\n\t\tvarTwo = postFixList.pop()\n\t\tvarOne = postFixList.pop()\n\n\t\tvalOne = None\n\t\tvalTwo = None\n\n\t\t# Find value of first variable\n\t\tif Token.findToken(varOne) is Token.INTEGER_LITERAL:\n\t\t\tvalOne = int(varOne)\n\t\telif Token.findToken(varOne) is Token.FLOAT_LITERAL:\n\t\t\tvalOne = float(varOne)\n\t\telse:\n\t\t\tvarOneType = self.getVarType(varOne)\n\t\t\tif varOneType is Token.INTEGER:\n\t\t\t\tvalOne = int(self.getVarValue(varOne))\n\t\t\telif varOneType is Token.FLOAT:\n\t\t\t\tvalOne = float(self.getVarValue(varOne))\n\n\t\t# Find value of second variable\n\t\tif Token.findToken(varTwo) is Token.INTEGER_LITERAL:\n\t\t\tvalTwo = int(varTwo)\n\t\telif Token.findToken(varTwo) is Token.FLOAT_LITERAL:\n\t\t\tvalTwo = float(varTwo)\n\t\telse:\n\t\t\tvarTwoType = self.getVarType(varTwo)\n\t\t\tif varTwoType is Token.INTEGER:\n\t\t\t\tvalTwo = int(self.getVarValue(varTwo))\n\t\t\telif varTwoType is Token.FLOAT:\n\t\t\t\tvalTwo = float(self.getVarValue(varTwo))\n\n\t\tresult = valOne / valTwo\n\t\tpostFixList.append(str(result))\n\n\t# Adds the two top elements in postFixList\n\tdef addOper(self, postFixList):\n\t\tvarTwo = postFixList.pop()\n\t\tvarOne = postFixList.pop()\n\n\t\tvalOne = None\n\t\tvalTwo = None\n\n\t\t# Find value of first variable\n\t\tif Token.findToken(varOne) is Token.INTEGER_LITERAL:\n\t\t\tvalOne = int(varOne)\n\t\telif Token.findToken(varOne) is Token.FLOAT_LITERAL:\n\t\t\tvalOne = float(varOne)\n\t\telse:\n\t\t\tvarOneType = self.getVarType(varOne)\n\t\t\tif varOneType is Token.INTEGER:\n\t\t\t\tvalOne = int(self.getVarValue(varOne))\n\t\t\telif varOneType is Token.FLOAT:\n\t\t\t\tvalOne = float(self.getVarValue(varOne))\n\n\t\t# Find value of second variable\n\t\tif Token.findToken(varTwo) is Token.INTEGER_LITERAL:\n\t\t\tvalTwo = int(varTwo)\n\t\telif Token.findToken(varTwo) is Token.FLOAT_LITERAL:\n\t\t\tvalTwo = float(varTwo)\n\t\telse:\n\t\t\tvarTwoType = self.getVarType(varTwo)\n\t\t\tif varTwoType is Token.INTEGER:\n\t\t\t\tvalTwo = int(self.getVarValue(varTwo))\n\t\t\telif varTwoType is Token.FLOAT:\n\t\t\t\tvalTwo = float(self.getVarValue(varTwo))\n\n\t\tresult = valOne + valTwo\n\t\tpostFixList.append(str(result))\n\n\t# Subtracts the two top elements in postFixList\n\tdef subOper(self, postFixList):\n\t\tvarTwo = postFixList.pop()\n\t\tvarOne = postFixList.pop()\n\n\t\tvalOne = None\n\t\tvalTwo = None\n\n\t\t# Find value of first variable\n\t\tif Token.findToken(varOne) is Token.INTEGER_LITERAL:\n\t\t\tvalOne = int(varOne)\n\t\telif Token.findToken(varOne) is Token.FLOAT_LITERAL:\n\t\t\tvalOne = float(varOne)\n\t\telse:\n\t\t\tvarOneType = self.getVarType(varOne)\n\t\t\tif varOneType is Token.INTEGER:\n\t\t\t\tvalOne = int(self.getVarValue(varOne))\n\t\t\telif varOneType is Token.FLOAT:\n\t\t\t\tvalOne = float(self.getVarValue(varOne))\n\n\t\t# Find value of second variable\n\t\tif Token.findToken(varTwo) is Token.INTEGER_LITERAL:\n\t\t\tvalTwo = int(varTwo)\n\t\telif Token.findToken(varTwo) is Token.FLOAT_LITERAL:\n\t\t\tvalTwo = float(varTwo)\n\t\telse:\n\t\t\tvarTwoType = self.getVarType(varTwo)\n\t\t\tif varTwoType is Token.INTEGER:\n\t\t\t\tvalTwo = int(self.getVarValue(varTwo))\n\t\t\telif varTwoType is Token.FLOAT:\n\t\t\t\tvalTwo = float(self.getVarValue(varTwo))\n\n\t\tresult = valOne * valTwo\n\t\tpostFixList.append(str(result))\n\n\t# Looks up the stored value of the variable identity lexeme\n\tdef getVarValue(self, varIdent):\n\t\tvarVal = None\n\n\t\tif str(varIdent) in self.globalVariables:\n\t\t\tvarVal = self.globalVariables[str(varIdent)][0]\n\t\telif str(varIdent) in self.globalConstants:\n\t\t\tvarVal = self.globalConstants[str(varIdent)][0]\n\t\telif str(varIdent) in self.implementVariables:\n\t\t\tvarVal = self.implementVariables[str(varIdent)][0]\n\t\telif str(varIdent) in self.implementConstants:\n\t\t\tvarVal = self.implementConstants[str(varIdent)][0]\n\n\t\treturn varVal\n\n\t# Looks up the stored type of the variable identity lexeme\n\tdef getVarType(self, varIdent):\n\t\tvarType = None\n\n\t\tif str(varIdent) in self.globalVariables:\n\t\t\tvarType = self.globalVariables[str(varIdent)][1]\n\t\telif str(varIdent) in self.globalConstants:\n\t\t\tvarType = self.globalConstants[str(varIdent)][1]\n\t\telif str(varIdent) in self.implementVariables:\n\t\t\tvarType = self.implementVariables[str(varIdent)][1]\n\t\telif str(varIdent) in self.implementConstants:\n\t\t\tvarType = self.implementConstants[str(varIdent)][1]\n\n\t\treturn varType\n\n\t# Returns true if variable identity lexeme is a number\n\tdef isNumber(self, varIdent):\n\t\tvarType = self.getVarType(varIdent)\n\n\t\tif varType is Token.INTEGER or varType is Token.FLOAT:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n","sub_path":"scl/interpreter/SCL_Interpreter.py","file_name":"SCL_Interpreter.py","file_ext":"py","file_size_in_byte":14351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"405536877","text":"# -*- coding: utf-8 -*-\n# @Author: Orange灬Fish\n# @Date: 2019-05-08 13:30:09\n# @Last Modified by: Orange灬Fish\n# @Last Modified time: 2019-05-08 13:38:00\n\n\n# need no extra sapce\nclass Solution:\n\tdef minimumTotal(self, triangle):\n\t\tif sum(triangle, []) == []:\n\t\t\treturn 0\n\t\tfor i in range(len(triangle)-2, -1, -1):\n\t\t\t# len(triangle[i]) == i + 1\n\t\t\tfor j in range(i+1):\n\t\t\t\ttriangle[-1][j] = min(triangle[-1][j] + triangle[i][j], triangle[-1][j+1] + triangle[i][j])\n\t\t\n\t\treturn triangle[-1][0]\n","sub_path":"Leetcode/leetcode120 三角形最小路径和.py","file_name":"leetcode120 三角形最小路径和.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"545006652","text":"# -*- coding: utf-8 -*-\n\nfrom time import sleep\nfrom api import settings\nimport sys\nimport logging\nimport redis\nimport mandrill\nimport json\n\nloop = False\n\nif len(sys.argv) > 1:\n loop = True\n\ndef sendmail(message_id):\n\n redis_client = redis.StrictRedis(\n host='localhost',\n port=6379,\n db=0,\n decode_responses=True)\n\n recipients_list_name = 'mail:' + str(message_id) + ':recipients'\n message_hash_name = 'mail:' + str(message_id)\n message = redis_client.hgetall(message_hash_name)\n\n if not message:\n logging.error('Cronjob Mail: Message hash not found')\n raise ValueError('Cronjob Mail: Message hash not found')\n\n message['to'] = []\n\n recipients = redis_client.lrange(recipients_list_name, 0, -1)\n for email in recipients:\n message['to'].append({'email': email})\n\n logging.error(message['to'])\n message['headers'] = {\"Reply-To\": message['from_email']}\n message['from_name'] = message['from_name'] + ' | ' + settings.CLIENT_NAME\n\n logging.info('Cronjob Mail: trying to send email')\n\n try:\n mandrill_client = mandrill.Mandrill('9cDB-QaLlEMKKeZtba3O7A')\n mandrill_client.messages.send(message=message)\n except mandrill.Error as e:\n errors = 'A mandrill error occurred: %s - %s' % (e.__class__, e)\n redis_client.lpush('mail:failed', message_id)\n logging.error(errors)\n redis_client.incr('mail:errors')\n mailjob()\n\n redis_client.delete('mail:' + str(message_id))\n\n logging.info('Cronjob Mail: email sent')\n\ndef mailjob():\n\n redis_client = redis.StrictRedis(\n host='localhost',\n port=6379,\n db=0,\n decode_responses=True)\n\n outbox_count = redis_client.llen('mail:outbox')\n failed_count = redis_client.llen('mail:failed')\n\n while failed_count > 0:\n\n if int(redis_client.get('mail:errors')) >= 10:\n break\n\n logging.debug('Cronjob Mail: failed')\n\n message_id = redis_client.rpop('mail:failed')\n sendmail(message_id)\n failed_count -= 1\n\n while outbox_count > 0:\n\n logging.debug('Cronjob Mail: processing outbox')\n\n message_id = redis_client.rpop('mail:outbox')\n sendmail(message_id)\n outbox_count -= 1\n\nwhile loop is True:\n logging.debug('starting cronjob')\n mailjob()\n logging.debug('waiting 10s to restart')\n sleep(10)\nelse:\n mailjob()\n","sub_path":"api/cronjobs.py","file_name":"cronjobs.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"74165211","text":"# 全国大学生化工设计竞赛\nimport tornado.httpclient\nfrom bs4 import BeautifulSoup\nhttp_header = {'User-Agent':'Chrome'}\nteamurl='http://iche.zju.edu.cn/redir.php?catalog_id=186&page='#本次参赛队伍 0-148 NUM:2\nreason=[]\nteam={'school':'','team':''}\nfor i in range(149):\n http_request=tornado.httpclient.HTTPRequest(url=teamurl+str(i),method='GET',headers=http_header,connect_timeout=20,request_timeout=600)\n http_client = tornado.httpclient.HTTPClient()\n http_response = http_client.fetch(http_request)\n # print(http_response.code)\n text=BeautifulSoup(http_response.body,'lxml')\n\n #following is for team of this time NUM:2\n sch = text.find_all('table', attrs={'class': \"bmingfo\"})[0]\n detail = sch.find_all('td',attrs={'align':'left'})\n detail.insert(0,'')\n detail_new=[detail[i] for i in range(len(detail)) if i%3!=0]\n j = 0\n for item, i in zip(detail_new, range(len(detail_new))):\n if i % 2 == 0:\n j = 1\n team['school'] = str(item.string)\n if i % 2 != 0:\n j = 2\n team['team'] = str(item.string)\n if j == 2:\n reason.append(team)\n team = {'school': '', 'team': ''}\n j = 0\n\n\n # print(detail_new)\n\nprint(reason)\n #THE END","sub_path":"tornado_cawlr/huagong.py","file_name":"huagong.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"362985717","text":"from iTunesManipulator import iTunesSearch\nimport os\nimport shutil\nimport glob\n # this functionality is alpha.. doesnt quite work. Needs to be pasted into musicPlatyer.py above have a fine day\n # while editorOrSongDownload == '0' and continueEditing != 'no':\n # searchFor = input(\"(EDITOR MODE) - Enter song(s).. separated by a ';' : \")\n # searchList = searchFor.split('; ')\n #\n # for searchForSong in searchList:\n # print(\" - Running program for: \", searchForSong)\n # iTunesPaths = setItunesPaths(operatingSystem, searchFor=searchForSong)\n #\n # if iTunesPaths != None:\n # Editor.songPropertyEdit(iTunesPaths, searchForSong=searchForSong)\n # print('=----------Done Cycle--------=')\n # else:\n # print('Im sorry this is for machines with iTunes only')\n #\n # continueEditing = input('Want to go again? (yes/no): ')\ndef syncWithGDrive(gDriveFolderPath, iTunesAutoAddFolderPath):\n print(\"--GDRIVE SECRET COMMAND--\")\n if os.path.isdir(gDriveFolderPath):\n music_files = [file for file in os.listdir(gDriveFolderPath) if \".DS\" not in file]\n if len(music_files) == 0:\n return print(\"No Files in folder.\")\n print(\"Files to move are: %s\" % (music_files))\n for file in music_files:\n fileAbsPath = os.path.join(gDriveFolderPath, file)\n fileDest = os.path.join(iTunesAutoAddFolderPath, file)\n shutil.move(fileAbsPath, fileDest)\n print(\"Moved to iTunes: %s\" % (file))\n return\n else:\n return print(\"No google drive installed! Check your settings.json file for correct path to gDrive folder.\")\n\ndef songPropertyEdit(iTunesPaths, searchForSong='', autoDownload=False):\n artists = [] # will hold list of artists\n songNames = [] # will hold list of songNames\n\n\n if len(iTunesPaths['searchedSongResult']) == 0:\n print(\"File not found in iTunes Library\")\n\n else:\n\n # get the first item of the songs returned from the list of song paths matching\n # plays song immediatly, so return after this executes\n print(\"Here are song(s) in your library matching your search: \")\n i = 0\n for songPath in iTunesPaths['searchedSongResult']:\n songName = songPath.split(os.sep)\n artists.append(songName[len(songName)-3])\n songNames.append(songName[len(songName)-1])\n print(' %d \\t- %s: %s' % (i, artists[i], songNames[i]))\n i += 1\n\n songSelection = int(input('Please enter the song you wish to reformat: '))\n while songSelection not in range(0, len(iTunesPaths['searchedSongResult'])):\n songSelection = int(input('Invalid Input. Try Again'))\n\n print('You chose: ', songSelection)\n\n trackProperties = iTunesSearch.parseItunesSearchApi(searchVariable=searchForSong,\n limit=10, entity='song',\n autoDownload=autoDownload)\n\n # parseItunesSearchApi() throws None return type if the user selects no properties\n if trackProperties != None:\n properSongName = iTunesSearch.mp3ID3Tagger(mp3Path=iTunesPaths['searchedSongResult'][songSelection],\n dictionaryOfTags=trackProperties)\n\n shutil.move(iTunesPaths['searchedSongResult'][songSelection], iTunesPaths['autoAdd'])\n\n\n\n print('Placed your file into its new spot.')\n else:\n print('Skipping tagging process (No itunes properties selected)')\n\n return\n","sub_path":"JukeBox/iTunesManipulator/Editor.py","file_name":"Editor.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"351138278","text":"\r\nfrom tkinter import *\r\n\r\nroot = Tk()\r\n\r\n\r\ndef send():\r\n send = \"you:\"+a.get()\r\n text.insert(END, \"\\n\"+send)\r\n if a.get() == 'hi':\r\n text.insert(END, \"\\n\" + \"Bot: Hello\")\r\n elif a.get() == 'hello':\r\n text.insert(END, \"\\n\" + \"Bot: Hi\")\r\n elif a.get() == 'how are you?':\r\n text.insert(END, \"\\n\" + \"Bot: I am fine. How are you?\")\r\n elif a.get() == 'I am fine':\r\n text.insert(END, \"\\n\" + \"Nice to hear that\")\r\n else:\r\n text.insert(END, \"Bot: I'm sorry you must use the right statement.\")\r\n\r\n\r\ntext = Text(root, bg='white')\r\ntext.grid(row=0, column=0, columnspan=2)\r\na = Entry(root, width=80)\r\nsend = Button(root, text='Send', bg='white', width=20, command=send).grid(row=1, column=1)\r\na.grid(row=1, column=0)\r\nroot.title('Simple Chat bot')\r\nroot.mainloop()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"167291524","text":"# Copyright (c) 2019 ETH Zurich, Lukas Cavigelli\n\nimport numpy as np\nimport re\nimport os\nimport pickle\n\ndef readSingleFile(fname):\n with open(fname) as f:\n fileCont = f.read()\n arrs = re.findall('array\\(\\[(.*)\\]\\)', fileCont)\n arrs = [np.fromstring(a, sep=',', dtype=np.int16) for a in arrs]\n# print('fname: %s' % fname)\n# print([t.shape for t in arrs])\n arrs = [t.reshape(64,-1) for t in arrs] #shape: n_t x 64\n \n #sum of lengths: 8*60+48+52 = 580\n #'normal' size: 400 --> overlap of 10 on both sides (or 20 on one)\n arrsConcat = [arrs[0]] + [t[:,20:] for t in arrs[1:]]\n spectrogram = np.concatenate(arrsConcat, axis=1)\n return spectrogram #64 x 25600\n\ndef getClasses(rootDir):\n filelist = os.listdir(rootDir) \n # regex for format {className}_{someNum}_{randomString}.csv to parse class\n classes = (re.findall('^(.*)\\_\\d*_.*.csv$', fname) for fname in filelist)\n classes = filter(lambda s: len(s) >= 1, classes)\n classes = (s[0] for s in classes)\n classes = list(set(classes)) # uniquify\n return classes\n\ndef readClassSpectrograms(cl, rootDir):\n filelist = os.listdir(rootDir)\n clFiles = (re.findall('^(%s_.*.csv)$' % cl, fname) for fname in filelist)\n clFiles = filter(lambda s: len(s) >= 1, clFiles)\n clFiles = (rootDir + s[0] for s in clFiles)\n clSpectrograms = [readSingleFile(fname) for fname in clFiles]\n return clSpectrograms\n\n\n#readSingleFile('./test/car_172_offset25.csv')\n#readSingleFile('./test/car_172_offset50.csv')\n\n\n\nclasses = getClasses('./train/')\nprint('classes: %s' % str(classes))\ndatasetTrain = {cl: readClassSpectrograms(cl, './train/') for cl in classes}\ndatasetTest = {cl: readClassSpectrograms(cl, './test/') for cl in classes}\n\nfname = './train.pickle'\nwith open(fname, 'wb') as f:\n pickle.dump(datasetTrain, f)\nfname = './test.pickle'\nwith open(fname, 'wb') as f:\n pickle.dump(datasetTest, f)\n\n\n#import matplotlib.pyplot as plt\n#spectrogram = datasetTrain['acoustic_guitar'][3]\n#plt.imshow(spectrogram)\n","sub_path":"quantlab/ETHZ-CVL-AED/MeyerNet/acousticEventDetDatasetConvert.py","file_name":"acousticEventDetDatasetConvert.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"333913847","text":"#!/usr/bin/env python\nfrom nbconvert.exporters import ScriptExporter\nfrom argparse import ArgumentParser\nfrom typing import Optional\nfrom os.path import splitext\n\n\ndef nbcode(input_name: str,\n input_path: str = './',\n output_name: Optional[str] = None,\n output_path: str = './') -> None:\n\n if not input_path.endswith('/'):\n input_path += '/'\n\n se = ScriptExporter()\n base, ext = splitext(input_path+input_name)\n script, resources = se.from_filename(input_path+input_name)\n\n if output_name is None:\n script_fname = base + resources.get('output_extension', '.txt')\n with open(output_path+script_fname, 'wt') as f:\n f.write(script)\n\n else:\n if not output_path.endswith('/'):\n output_path += '/'\n with open(output_path+output_name, 'wt') as f:\n f.write(script)\n\n\ndef command_line_runner():\n\n parser = ArgumentParser(\n description='Convert a notebook into code from the command line.')\n\n parser.add_argument('input_name', help='The filename of the input notebook.')\n\n parser.add_argument('--input_path', '-i', default='./',\n help='The filepath to the input notebook.')\n\n parser.add_argument('--output_name', '-n', default=None,\n help='The filename of the output code file.')\n\n parser.add_argument('--output_path', '-o', default='./',\n help='The filepath where the output file is saved.')\n\n\n args = parser.parse_args()\n in_name = args.input_name\n in_path = args.input_path\n out_name = args.output_name\n out_path = args.output_path\n\n nbcode(input_name=in_name,\n input_path=in_path,\n output_name=out_name,\n output_path=out_path)\n\n\nif __name__ == \"__main__\":\n command_line_runner()\n","sub_path":"build/lib/nbless/nbcode.py","file_name":"nbcode.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"268429695","text":"#encoding:utf8\n# __author__ = 'donghao'\n# __time__ = 2019/1/14 22:26\n\nfrom django.urls import path,re_path\nfrom . import views\napp_name = 'blog'\nurlpatterns = [\n path('',views.IndexView.as_view(),name='index'),\n path('list/',views.AboutView.as_view(),name='about'),\n path('login/',views.LoginView.as_view(),name='login'),\n path('logout/',views.LogoutView.as_view(),name='logout'),\n path('add_article/',views.AddArticleView.as_view(),name='add_article'),\n path('add_tag/',views.AddTagView.as_view(),name='add_tag'),\n path('upload/',views.Fileupload.as_view(),name='upload'),\n path('edit/',views.EditProfileView.as_view(),name='edit'),\n path('change_avater/',views.ChangAvaterView.as_view(),name='change_avater'),\n re_path('article_detail/(?P\\w+)/',views.ArticleDetailView.as_view(),name='article_detail'),\n]","sub_path":"apps/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"599307651","text":"#!/home/kjeong23/softwares/bin/python3.4\n# prototype program for urea dimer autoselection from MD traj.\n# algorithm : read dcd file to get coord -> from given criterion, randomly pick dimers\n# -> write xyz files\n\nimport math\nimport sys\nimport numpy\nimport timeit\nimport mdtraj as md\nfrom scipy.stats import itemfreq\n\ndef main():\n #declare topology (.pdb) file and trajectory (.dcd) file\n topfile = sys.argv[1]\n trjfile = sys.argv[2]\n drudes=['DO','DN1','DN2','DC']\n #settings for dimer choice.\n #ndim=int(input(\"how many dimer output files?\\n\"))\n\n start_time=timeit.default_timer()\n\n #load files and process\n oritopol=md.load(topfile).topology\n table,bonds=oritopol.to_dataframe()\n table.loc[table['name'] == 'O2a','name'] = 'O'\n topology=md.Topology.from_dataframe(table,bonds)\n traj=md.load_dcd(trjfile,top=topology)\n \n #print(traj)\n traj=traj.atom_slice(topology.select('name != DO and name != DN1 and name != DN2 and name != DC'))\n oneframe=traj[100]\n topology=oneframe.topology\n atoms=topology.atoms\n #print(table.head())\n #print(oneframe)\n #print(topology)\n sel_dimer=oneframe.atom_slice(topology.select('resid 0 or resid 2'))\n #print(topology.select('resid 0 or resid 2'))\n #print(sel_dimer)\n #print(sel_dimer)\n #sel_dimer.image_molecules()\n sel_dimer.save_xyz('test.xyz')\n #apair=[[0,1]]\n #cont_result=md.compute_contacts(oneframe,contacts=apair,scheme='closest')\n #print(cont_result)\n \n natoms=oneframe.n_atoms\n atomids=topology.select('resid 0')\n print(atomids)\n search=[x for x in range(natoms) if x not in atomids]\n neigh=md.compute_neighbors(oneframe,0.3,atomids,haystack_indices=search,periodic=True)\n print(neigh,len(neigh[0]))\n\n resilist=[]\n for x in neigh[0]:\n resilist.append(topology.atom(x).residue.index)\n print(resilist)\n freq=itemfreq(resilist)\n #print(freq)\n for f in freq:\n if f[1]>=3:\n m2=f[0]\n break\n print(m2)\n #print(resilist)\n #loop\n #for dindex in range(ndim):\n\n # if dindex%50==0:\n # elapsed=timeit.default_timer() - start_time\n # print(''.format(dindex,elapsed))\n elapsed=timeit.default_timer() - start_time\n print('elapsed time {}'.format(elapsed))\n\nif __name__ == \"__main__\": main()\n","sub_path":"py_development/data_process/sapt_dimer/test_read_dcd.py","file_name":"test_read_dcd.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"103024922","text":"import sqlite3\nimport random\n\nconn = sqlite3.connect(\"./db/test.db\")\n\nfam_names = list(\"김이박최강고윤엄한배성백전황서천방지마피\")\nfirst_names = list(\"건성현욱정민현주희진영래주동혜도모영진선재현호시우인성마무병별솔하라\")\n\n\nname = list()\n\n\nfor i in range(100):\n sung = random.choice(fam_names)\n name_1 = random.choice(first_names)\n name_2 = random.choice(first_names)\n tuple_a = sung + name_1 + name_2\n tuple_b = (tuple_a ,)\n name.append(tuple_b)\n\n\n# print(name)\ndata = tuple(name)\nprint(data)\n\nwith conn:\n cur = conn.cursor()\n sql = \"insert into Student(name) values(?)\"\n cur.executemany(sql, data)\n\n conn.commit()","sub_path":"sqlite_many2.py","file_name":"sqlite_many2.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"538266619","text":"#========================================================================================\n# TOPIC: PYTHON - MultiThreading Parallel programming Concurrent programming\n#========================================================================================\n# NOTES: * PYTHON supports Multithreading\n# * Normal execution of python, where each step in the code is executed one after \n# another is run as a single THREAD. but in a multi-threaded application, code \n# (or steps) can be run together with another in parallel (two or more steps at \n# the same time) even though the code is written one after another.\n# * Such a requirement is very much needed in a variety of applications, such as \n# games GUI applications, large volume data processing..\n# * To invoke multithreading features we need to use the threading module\n# * We simulate multithreading by running a function that takes 5 seconds \n# to run (there is a SLEEP command) twice and make the TWO 5 seconds run in \n# FIVE seconds instead of 10 Seconds\n# * Create Threads using \"_thread\" module\n# * Create Threads using \"threading\" module Thread class\n# * Dynamically Create Threads, With Named Thread-IDs\n#\n#\n#========================================================================================\n#\n# FILE-NAME : 028_mutlithreading_basics.py\n# DEPENDANT-FILES : These are the files and libraries needed to run this program ;\n# N/A\n#\n# AUTHOR : tinitiate.com / Venkata Bhattaram\n# (c) 2016\n#\n# DESC : Python Regular Expressions Patterns\n#\n#========================================================================================\n\n# IMPORT the required modules\nimport _thread\nimport time\n\n# Create a FUNCTION that takes FIVE seconds to execute (This is a wait (sleep) command\n# that pauses the program for FIVE seconds\ndef five_seconds_process(thread_id):\n \"This function when called takes 5 Seconds to execute\"\n # Thread Start message\n print(\"ThreadID: \",thread_id,\" Started at: \", time.time())\n for c in range(5):\n print(\"thread_id: \", thread_id,\" Iteration Number \", c+1)\n time.sleep(1) # This causes the program to PAUSE for 1 Sec\n # Thread END message\n print(\"ThreadID: \",thread_id,\" Ended at: \", time.time())\n\n\n#############################################\n# 1) Create THREADS using the _thread module\n#############################################\n\n# USING the _thread.start_new_thread\n# This function accepts a FUNCTION-name and FUNCTION-Parameters\n# as its parameters\n# In this case we want to run the function: five_seconds_process\n# and its SINGLE parameter.\n# Also make sure to include a \"COMMA\" after the LAST PARAMETER that\n# is being passed to the _thread.start_new_thread\n\nprint(\"Demonstration of THREADS using the _thread module's start_new_thread function\")\n\n# Run five_seconds_process function as a THREAD with a THREAD-ID 1\n_thread.start_new_thread(five_seconds_process,(1,))\n\n\n# Run five_seconds_process function as a THREAD with a THREAD-ID 2\n_thread.start_new_thread(five_seconds_process,(2,))\n\n\n# This is needed, because all the threads will exit, if the main program finishes\n# in order to keep the program alive we make the program execute for 5 seconds\n# This infact is running 3 Threads ! (Including the time.sleep(5) below.\ntime.sleep(5)\n\nprint(\"\");\n\n\n################################################\n# 2) Create THREADS using the threading module\n################################################\nprint(\"Demonstration of THREADS using the threading module's Thread CLASS\")\n\n#Import the threading module\nfrom threading import Thread \n\n# * The Thread CLASS constructor accepts a function and \n# its argument list as a tuple.\n# * When the OBJECT.start() function is called, it runs\n# as a thread. \n\n\n# Create a Thread Object using the Thread class of the threading module\nt1 = Thread(target=five_seconds_process, args=(1,))\nt1.start()\n\n\n# Create one more Thread Object using the Thread class of the threading module\nt2 = Thread(target=five_seconds_process, args=(2,))\nt2.start()\n\n\n################################################\n# 3) Create Dynamic THREADS\n################################################\n# Create a Threads List\nthreads = []\n\n# Create 3 Threads\nfor threadID in range(2):\n t = Thread(target=five_seconds_process, args=(threadID+1, ))\n t.start()\n # threads.append(t)\n\n# join all threads\nfor t in threads:\n t.join()\n\n\n\n#========================================================================================\n# END OF CODE\n#========================================================================================\n#TAGS: PYTHON - MultiThreading Parallel programming Concurrent programming\n# using python _thread module, start_new_thread example tutorial\n# using python threading module Thread Class\n#========================================================================================\n","sub_path":"python-modules/028_mutlithreading_basics.py","file_name":"028_mutlithreading_basics.py","file_ext":"py","file_size_in_byte":5016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"184303868","text":"import pytest\nfrom rest_framework import exceptions\n\nfrom rules_server.models import Ruleset, SyntaxSchema\n\n\n@pytest.fixture(autouse=True)\ndef rule_models():\n\n rs0 = Ruleset(\n program='syntactic',\n entity='syntactic',\n sample_input=[{\n \"id\": 1,\n \"foo\": 0\n }])\n rs0.save()\n\n ss0 = SyntaxSchema(\n ruleset=rs0,\n code={\n 'items': {\n 'properties': {\n 'id': {\n 'type': 'integer'\n },\n 'foo': {\n 'type': 'integer'\n }\n },\n 'type': 'object'\n },\n 'type': 'array'\n })\n ss0.save()\n\n\npayload0 = [{'id': 1, 'foo': 100}]\n\n\n@pytest.mark.django_db\ndef test_valid_syntax_passes():\n\n rs = Ruleset.objects.get(program='syntactic', entity='syntactic')\n rs.validate(payload0)\n\n\n@pytest.mark.django_db\ndef test_invalid_syntax_fails():\n\n payload1 = [{'id': 1, 'foo': 'bar'}]\n\n rs = Ruleset.objects.get(program='syntactic', entity='syntactic')\n with pytest.raises(exceptions.ParseError):\n rs.validate(payload1)\n","sub_path":"rules_server/tests/test_syntactic.py","file_name":"test_syntactic.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"293622197","text":"\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\nclass Solution(object):\n def sumOfLeftLeaves(self, root):\n # edge case\n if not root: return 0\n \n self.res = 0\n self.dfs(root)\n return self.res\n \n def dfs(self, root):\n if not root: return 0\n\n if root.left:\n self.dfs(root.left)\n if not root.left.left and not root.right.right:\n self.res += root.left.val\n \n if root.right:\n self.dfs(root.right)\n","sub_path":"daily/tree_model.py","file_name":"tree_model.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"93400164","text":"from django.shortcuts import render\nfrom content.models import Content\n\n\ndef tag_view(request, *args, **kwargs):\n tag = request.GET.get('tag', None)\n if tag is not None:\n print(tag)\n content = Content.objects.filter(tag__slug=tag)\n context={\"content\" : content}\n return render(request, 'tag/tag.html', context)\n","sub_path":"rahatapply_v0.0.3/src/tags/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"452173563","text":"import numpy as np\nimport kernels\nimport pytest\nfrom scipy.spatial import distance\n\n\n@pytest.mark.parametrize('n', (10, 17, 99))\ndef test_index_conversion(n):\n # Evaluate condensed an square distance matrix\n x = np.random.normal(0, 1, (n, 2))\n y = distance.pdist(x)\n d = distance.squareform(y)\n\n # Sample indices and filter them\n i, j = np.random.randint(n, size=(2, 100))\n f = i != j\n i, j = i[f], j[f]\n\n # Evaluate condensed index\n c = kernels.square_to_condensed(i, j, n)\n np.testing.assert_array_equal(y[c], d[i, j])\n\n # Make sure we can recover the original indices\n i2, j2 = kernels.condensed_to_square(c, n)\n np.testing.assert_array_equal(np.minimum(i, j), i2)\n np.testing.assert_array_equal(np.maximum(i, j), j2)\n\n\ndef test_negate():\n assert kernels.negate(lambda: 4)() == -4\n\n\ndef test_l1_feature_map():\n n = 10000\n x, y = np.random.uniform(0, 1, (2, n, 1))\n features = kernels.l1_feature_map(x, y)\n assert features.shape == (n, 2)\n np.testing.assert_allclose(features[..., 0], 1)\n mean = np.mean(features[..., 1])\n std = np.std(features[:, 1])\n z = mean / (std / np.sqrt(n))\n # Assert that the mean is close to zero (this test may fail on occasion if the rng is not\n # seeded)\n assert abs(z) < 3\n # Assert that the standard deviation is close to .5 (after standardisation following Gelman)\n assert abs(std - 0.5) < 0.01\n\n\ndef test_l1_feature_map_invalid_arguments():\n with pytest.raises(ValueError):\n kernels.l1_feature_map(None, None, offset='invalid')\n with pytest.raises(ValueError):\n kernels.l1_feature_map(None, None, scale='invalid')\n\n\ndef test_case_control_invalid_arguments():\n n, p = 100, 3\n x = np.random.normal(0, 1, (n, p))\n theta = np.random.normal(0, 1, p)\n y = np.random.normal(0, 1, n) > 0\n\n with pytest.raises(ValueError):\n kernels.evaluate_case_control_log_likelihood(theta, x, 0)\n with pytest.raises(ValueError):\n kernels.evaluate_case_control_log_likelihood(0, x, y)\n with pytest.raises(ValueError):\n kernels.evaluate_case_control_log_likelihood(theta, 0, y)\n with pytest.raises(ValueError):\n kernels.evaluate_case_control_log_likelihood(theta, x, y)\n with pytest.raises(ValueError):\n kernels.evaluate_case_control_log_likelihood(theta, x, y, prevalence=np.empty(3))\n\n\ndef test_sample():\n xs, values = kernels.sample(lambda x: - x ** 2 / 2, 0, 1, 10000)\n assert abs(np.mean(xs)) < 0.1\n assert abs(np.std(xs) - 1) < 0.1\n\n\ndef test_sample_invalid_arguments():\n def _log_dist(_):\n return 0\n x = 0\n cov = 1\n num = 10\n\n with pytest.raises(ValueError):\n kernels.sample(_log_dist, np.empty((1, 1)), cov, num)\n with pytest.raises(ValueError):\n kernels.sample(_log_dist, x, np.empty((1, 1, 1)), num)\n with pytest.raises(ValueError):\n kernels.sample(_log_dist, x, np.empty((1, 2)), num)\n\n\ndef test_get_args():\n def _func(a, *args, b, **kwargs):\n return kernels.get_args()\n\n args = _func(3, 4, 5, b=np.pi, foo='bar')\n assert args == {\n 'a': 3,\n '*varargs': (4, 5),\n 'b': np.pi,\n 'foo': 'bar',\n }\n","sub_path":"tests/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"404800928","text":"\"\"\"dashboard URL Configuration.\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.http import HttpResponse\nfrom django.shortcuts import redirect\nfrom django.urls import include, path, re_path, reverse\nfrom django.views import defaults as default_views\nfrom drf_yasg import openapi\nfrom drf_yasg.views import get_schema_view\nfrom rest_framework import permissions\n\nhandler500 = \"book.views.views_function.server_error_page\"\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"Yozit API\",\n default_version=\"v1\",\n description=\"Yozit API\",\n terms_of_service=\"https://www.google.com/policies/terms/\",\n license=openapi.License(name=\"BSD License\"),\n ),\n public=True,\n permission_classes=(permissions.AllowAny,),\n)\n\n\ndef simple_redirect(_):\n \"\"\"\n Index 페이지로 Redirect.\n\n :param _:\n :return:\n \"\"\"\n return redirect(reverse(\"book:index\"))\n\n\ndef get_ip(request):\n \"\"\"Debug 용.\"\"\"\n ip = request.META[\"REMOTE_ADDR\"]\n return HttpResponse(\"{}\".format(ip))\n\n\nurlpatterns = [\n path(\"\", simple_redirect),\n path(\"book/\", include(\"book.urls\")),\n path(\"admin/\", admin.site.urls),\n path(\"accounts/\", include(\"django.contrib.auth.urls\")),\n path(\"chatbot/\", include(\"chatbot.urls\")),\n # path(\"people/\", include(\"people.urls\")),\n path(\"api/\", include(\"dashboard.api_router\")),\n path(\"api-auth/\", include(\"rest_framework.urls\")),\n]\n\nif settings.DEBUG:\n urlpatterns += [\n path(\n \"400/\",\n default_views.bad_request,\n kwargs={\"exception\": Exception(\"Bad Request!\")},\n ),\n path(\n \"403/\",\n default_views.permission_denied,\n kwargs={\"exception\": Exception(\"Permission Denied\")},\n ),\n path(\n \"404/\",\n default_views.page_not_found,\n kwargs={\"exception\": Exception(\"Page not Found\")},\n ),\n path(\"500/\", default_views.server_error),\n path(\"debug/\", get_ip),\n ]\n\n if \"debug_toolbar\" in settings.INSTALLED_APPS:\n # noinspection PyPackageRequirements\n import debug_toolbar\n\n urlpatterns = [path(\"__debug__/\", include(debug_toolbar.urls))] + urlpatterns\n\n urlpatterns += [\n re_path(\n r\"^swagger(?P\\.json|\\.yaml)$\",\n schema_view.without_ui(cache_timeout=0),\n name=\"schema-json\",\n ),\n re_path(\n r\"^swagger/$\",\n schema_view.with_ui(\"swagger\", cache_timeout=0),\n name=\"schema-swagger-ui\",\n ),\n re_path(\n r\"^redoc/$\",\n schema_view.with_ui(\"redoc\", cache_timeout=0),\n name=\"schema-redoc\",\n ),\n ]\n","sub_path":"dashboard/dashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"7776880","text":"import turtle\n# for x in range(4):\n# turtle.forward(100)\n# turtle.right(90)\n\nnumCircles = 20\nstartingRadius = 20\noffset = 20\nanimationSpeed = 0\nturtle.speed(animationSpeed)\nturtle.hideturtle()\nradius = startingRadius\n# draw the circles\nfor count in range(numCircles):\n #draw the circle\n turtle.circle(radius)\n # get the coords for the next coordinates\n x = turtle.xcor()\n y = turtle.ycor() - offset\n # calc Radius of the next circle\n radius+=offset\n #position the turtle for the next circle\n turtle.penup()\n turtle.goto(x,y)\n turtle.pendown()","sub_path":"python scraps/Tortle.py","file_name":"Tortle.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"52226953","text":"def add(dict_m,movie,time):\n if time == '12':\n dict_m[movie][0]+=1\n elif time == '3':\n dict_m[movie][1]+=1\n elif time == '6':\n dict_m[movie][2]+=1\n else:\n dict_m[movie][3]+=1\n return dict_m\n\ndef max_index(my_list):\n return my_list.index(max(my_list))\n\ndef find_profit(orginal):\n my_list = orginal.copy()\n s = 0\n for i in range(4):\n if max(my_list) != 0:\n s+=(100-25*i)*max(my_list)\n my_list[max_index(my_list)] = -1\n else:\n s-=100\n return s\n\n\nT = int(input())\nfinal_list = []\nwhile T>0:\n n = int(input())\n movie = {'A':[0,0,0,0], 'B':[0,0,0,0], 'C':[0,0,0,0], 'D':[0,0,0,0]}\n sell = {100:0,75:0,50:0,25:0,-100:0}\n for _ in range(n):\n m, t = map(str,input().split())\n if m == 'A':\n movie = add(movie,m,t)\n elif m == 'B':\n movie = add(movie,m,t)\n elif m == 'C':\n movie = add(movie,m,t)\n else:\n movie = add(movie,m,t)\n\n s = []\n for a in range(4):\n my_list = [0,0,0,0]\n my_list[0] = movie['A'][a]\n for b in range(4):\n if a==b:\n pass\n else:\n my_list[1] = movie['B'][b]\n for c in range(4):\n if c==a or b==c:\n pass\n else:\n my_list[2] = movie['C'][c]\n for d in range(4):\n if d==a or d==b or d==c:\n pass\n else:\n my_list[3] = movie['D'][d]\n s.append(find_profit(my_list))\n s_max = max(s)\n print(s_max)\n final_list.append(s_max)\n T-=1\nprint(sum(final_list))\n","sub_path":"FEB20B/THEATRE/theater2.py","file_name":"theater2.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"516783424","text":"import sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nsys.path.append('../../control_engineering_lib')\nimport control_engineering as lib\n\nshow_cor=1\n#Cnum=12.66\n\nnum=3/2.0;\nden=[3,1]\nt=np.linspace(0,18,401)\n\nt,s=lib.step_response(num,den,2,t)\nplt.plot(t,s,label=\"Système orginal\")\nplt.xlabel('Temps (s)')\nplt.ylabel('Sortie')\n\nif show_cor==1:\n #correcteur P\n Cnum = float(input('Valeur du gain: '))\n Cden=1\n t,s=lib.step_response_BF_cor(Cnum,Cden,num,den,1,t)\n plt.plot(t,2*s,label=\"Système corrigé\")\n\n\nplt.axhline(y=2,color='k',ls='dashed',label=\"Entrée\")\nplt.legend()\nplt.show()","sub_path":"AU3_exercices/src/show_RI_BF.py","file_name":"show_RI_BF.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"253090440","text":"import pymysql\nimport sqlalchemy.pool as pool\nimport multiprocessing as processing\nimport multiprocessing.dummy as threading\nfrom queue import LifoQueue\nimport concurrent.futures\nimport socket\nimport signal\n\nfrom .core import Core\nfrom .pkg import *\nfrom . import outputor\nfrom . import inputor\n\n\nclass Cache(processing.Process):\n \"\"\"\n 进程封装,处理输入和输出的类\n \"\"\"\n\n def __init__(self, server=False, local=False, sock=False, **kwargs):\n super().__init__()\n\n self.queue = LifoQueue()\n\n self.inputor = None\n self.outputors = list()\n self.watcher = None\n self.kwargs = kwargs\n\n self.connpool = pool.QueuePool(\n lambda: pymysql.connect(**cacheconf.DBCONF),\n pool_size=10,\n max_overflow=10\n )\n\n self.backupdb = Backupdb(self.connpool)\n self.core = Core(self.connpool)\n\n if server and local and sock:\n raise Exception('wrong params')\n\n if server:\n self.outputors.extend([outputor.Database(self.connpool)])\n self.inputor = inputor.Database(self.kwargs['sdate'], self.kwargs['edate'])\n\n self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n if os.path.exists(cacheconf.SOCK_PATH):\n os.unlink(cacheconf.SOCK_PATH)\n self.sock.bind(cacheconf.SOCK_PATH)\n self.sock.listen(0)\n\n self.watcher = Watcher()\n\n elif local:\n self.outputors.extend([outputor.Database(self.connpool), outputor.Logger()])\n self.inputor = inputor.Database(self.kwargs['sdate'], self.kwargs['edate'])\n\n elif sock:\n self.outputors.extend([outputor.Database(self.connpool), outputor.Logger(), outputor.FileLogger()])\n self.inputor = inputor.Socket()\n\n else:\n raise Exception('wrong params')\n\n def run(self):\n if self.watcher:\n self.watcher.start()\n\n with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:\n \"\"\"\n 进程池\n 使用mapreduce方法对数据进行处理\n \"\"\"\n rawpak_generator = self.input()\n for rawpak, result in zip(rawpak_generator, executor.map(self.predict, rawpak_generator)):\n print(rawpak)\n if result:\n self.output(rawpak)\n else:\n pass\n return\n\n def predict(self, rawpak):\n self.backupdb.backup(rawpak)\n\n if self.core.predict(rawpak):\n return True\n else:\n return False\n\n def output(self, rawpak):\n catchedpak = Catchedpak(\n ip=rawpak.ip,\n time=rawpak.querytime,\n type='cache'\n )\n [outputor.output(catchedpak) for outputor in self.outputors]\n return\n\n def input(self):\n return self.inputor.input()\n\n\nclass Watcher(threading.Process):\n \"\"\"\n 服务器用的\n 当cache在后台运行时\n 这个线程会监听一个文件\n 当服务器接受请求时,会找到这个监听的文件关闭后台的cache\n \"\"\"\n def __init__(self):\n super().__init__()\n self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n\n def run(self):\n while True:\n connection, address = self.sock.accept()\n data = connection.recv(1024)\n if data == 'close'.encode('utf-8'):\n os.kill(os.getpid(), signal.SIGTERM)\n else:\n pass\n\n\"\"\"\n用于关闭cache的代码\n\nclient = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\ntry:\n client.connect(cacheconf.SOCK_PATH)\nexcept ConnectionRefusedError :\n pass\nelse:\n client.send('close'.encode('utf-8'))\nfinally:\n client.close()\n\"\"\"\n\n\nclass Backupdb(object):\n \"\"\"\n 对所有进入cache的数据进行备份供svm进行使用\n \"\"\"\n\n def __init__(self, connpool):\n self.connpool = connpool\n\n conn = self.connpool.connect()\n cursor = conn.cursor()\n cursor.execute(\n 'create table if not exists cachedata.backup(\\n'\n '`ip` varchar(30) DEFAULT NULL,\\n'\n '`querytime` datetime NOT NULL,\\n'\n '`command` varchar(20) DEFAULT NULL,\\n'\n '`depature` varchar(5) NOT NULL,\\n'\n '`arrival` varchar(5) NOT NULL,\\n'\n '`result` varchar(500) NOT NULL,\\n'\n 'KEY `querytime` (`querytime`),\\n'\n 'KEY `ip` (`ip`)\\n'\n ') ENGINE=MyISAM DEFAULT CHARSET=gbk\\n'\n )\n conn.close()\n\n return\n\n def backup(self, rawpak):\n basesql = (\n 'insert into cachedata.backup\\n'\n '(`ip`, `querytime`, `command`, `depature`, `arrival`, `result`)\\n'\n 'VALUES (\\'{ip}\\', \\'{querytime}\\', \\'{command}\\', \\'{depature}\\', \\'{arrival}\\', \\'{result}\\')\\n'\n ).format(\n ip=rawpak.ip,\n querytime=rawpak.querytime,\n command=rawpak.command,\n depature=rawpak.depature,\n arrival=rawpak.arrival,\n result=rawpak.result\n )\n conn = self.connpool.connect()\n cursor = conn.cursor()\n cursor.execute(basesql)\n conn.close()\n return\n","sub_path":"utils/cache/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"363517348","text":"import os\n\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nimport yaml\n\nfrom augm_data import get_next_batch, supervised_batch, unsupervised_batch, update_eta\nfrom model import Model\n\n\nif torch.cuda.is_available():\n torch.set_default_tensor_type(torch.cuda.FloatTensor)\n device = torch.device(\"cuda\")\nelse:\n torch.set_default_tensor_type(torch.FloatTensor)\n device = torch.device(\"cpu\")\n\ntorch.manual_seed(137)\nwriter = SummaryWriter(os.getcwd())\n\n\ndef extract_classes(dataset, samples_per_class, classes):\n class_indices = {} \n count = 0\n nr_of_classes = classes \n for i in range(len(dataset)):\n _img_info, class_id = dataset.__getitem__(i)\n if class_id not in class_indices: \n class_indices[class_id] = [i] \n count += 1\n elif len(class_indices[class_id]) < samples_per_class:\n class_indices[class_id].append(i)\n count += 1\n if count >= samples_per_class*nr_of_classes:\n break\n\n concat_indices = [] \n for (_, index) in class_indices.items():\n concat_indices += index \n return concat_indices \n\n\ndef get_data_loaders(config):\n train_transform = transforms.Compose(\n [transforms.RandomCrop(28),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))])\n\n trainset = torchvision.datasets.MNIST(root='./data', train=True,\n download=True, transform=train_transform)\n extract_class_idx = extract_classes(trainset, config['samples_per_class'], config['classes']) \n subsampler_train = torch.utils.data.SubsetRandomSampler(extract_class_idx)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=config['supervised_batch_size'],\n sampler=subsampler_train)\n\n unlabeled_idx = np.setdiff1d(np.arange(len(trainset)), extract_class_idx) \n subsampler_train_unlabeled = torch.utils.data.SubsetRandomSampler(unlabeled_idx)\n trainloader_unlabeled = torch.utils.data.DataLoader(trainset, batch_size=config['unsupervised_batch_size'],\n sampler=subsampler_train_unlabeled, drop_last=True)\n\n test_transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))])\n\n testset = torchvision.datasets.MNIST(root='./data', train=False,\n download=True, transform=test_transform)\n extract_class_idx = extract_classes(testset, 100, config['classes']) \n subsampler_test = torch.utils.data.SubsetRandomSampler(extract_class_idx)\n testloader = torch.utils.data.DataLoader(testset, batch_size=10,\n sampler=subsampler_test)\n\n return trainloader, trainloader_unlabeled, testloader\n\n\ndef train_epoch(train_loader, unlabeled_iter, unsup_batch_iterator, optimizer, model, epoch, eta, lambd):\n for _, data in enumerate(train_loader, 0):\n x_unlab, unlabeled_iter = get_next_batch(unlabeled_iter, unsup_batch_iterator)\n inputs, labels = data\n data = inputs.to(device), labels.to(device)\n optimizer.zero_grad()\n\n supervised_loss = supervised_batch(model, data, eta)\n writer.add_scalar(\"loss/supervised\", supervised_loss.detach(), epoch)\n\n unsupervised_loss = unsupervised_batch(model, x_unlab)\n writer.add_scalar(\"loss/unsupervised\", unsupervised_loss.detach(), epoch)\n\n total_loss = supervised_loss + lambd*unsupervised_loss\n\n total_loss.backward()\n optimizer.step()\n writer.add_scalar(\"loss/total\", total_loss.detach(), epoch)\n print(f'[Epoch: {epoch}] loss: {total_loss.detach()}')\n\n return unlabeled_iter\n\n\ndef evaluate_model(test_loader, model, config):\n nr_classes = config['classes']\n class_correct = list(0. for i in range(nr_classes))\n class_total = list(0. for i in range(nr_classes))\n classes = config['class_names']\n with torch.no_grad():\n for data in test_loader:\n images, labels = data\n outputs = model(images.to(device))\n _, predicted = torch.max(outputs, 1)\n c = (predicted == labels).squeeze()\n for i in range(images.size(0)):\n label = labels[i]\n class_correct[label] += c[i].item()\n class_total[label] += 1\n mean = 0\n for i in range(nr_classes):\n acc = 100 * class_correct[i]/class_total[i]\n mean += acc\n print(f'Accuracy of {classes[i]} : {acc} %') \n print(f'Mean Accuracy: {mean/nr_classes}')\n\n\ndef main():\n with open('config.yaml') as f:\n config = yaml.load(f, Loader=yaml.FullLoader)\n\n train_loader, train_loader_unlabeled, test_loader = get_data_loaders(config)\n unlabeled_iter = iter(train_loader_unlabeled)\n model = Model() \n model.to(device)\n\n optimizer = optim.SGD(model.parameters(), lr=config['lr'], momentum=0.9) \n epochs = config['epochs']\n classes = config['classes']\n lambd = config['lambda']\n tsa_schedule = config['tsa_schedule']\n for epoch in range(epochs):\n eta = update_eta(tsa_schedule, epochs, classes, epoch)\n writer.add_scalar(\"eta\", eta, epoch)\n unlabeled_iter = train_epoch(train_loader, unlabeled_iter, train_loader_unlabeled, optimizer, model, epoch, eta, lambd)\n \n print('Finished Training')\n evaluate_model(test_loader, model, config)\n writer.close()\n\n\nif __name__ == \"__main__\":\n main()\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"436643010","text":"#!/usr/bin/env python\n# coding: utf-8\n__author__ = 'Danny'\n\nfrom instar import *\nfrom live_platform.Yizhibo import Yizhibo\nimport time\n\ndef run():\n plat = Yizhibo()\n instar = Instar()\n log = get_logger()\n redis_ins = get_redis()\n cf = get_conf()\n #page_num = cf.getint(\"local\",\"task_page\")\n #page_count = cf.getint(\"local\",\"task_count\")\n\n monit_list = list(redis_ins.smembers(\"vip_yizhibo\"))\n # 已经添加过的直播id\n sent_uid = redis_ins.smembers(\"passerby_living_rooms\")\n log.info(\"monit user num : \" + str(len(monit_list)))\n # 查看每一个用户的直播列表\n for i in range(0,len(monit_list)):\n #if i % page_count != page_num:\n # continue\n uid = monit_list[i]\n log.info(\"get user live info \" + str(uid))\n live_id = plat.is_user_living(uid)\n if live_id:\n if \"yizhibo-\"+str(uid) not in sent_uid:\n instar.add_living(\"yizhibo\", repr(str(live_id)), uid)\n log.info(\"sent new yizhibo live \" + str(live_id))\n else:\n log.info(\"live already sent to room monitor \" + str(live_id))\n else:\n log.info(\"not living \" + str(uid))\n continue\n log.info(\"bind user feeds monitor end\")\n\nif __name__ == '__main__':\n while True:\n run()\n time.sleep(5)\n","sub_path":"instar_srapy/feeds_monitor_yizhibo.py","file_name":"feeds_monitor_yizhibo.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"260223442","text":"from cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.asymmetric import padding\n\n#create the private and public keys\nprivate_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048,\n backend=default_backend()\n)\npublic_key = private_key.public_key()\n\nprint(private_key)\nprint(public_key)\n\n# stringify the private and public keys\n\npem_private = private_key.private_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PrivateFormat.PKCS8,\n encryption_algorithm=serialization.NoEncryption()\n)\n\npem_public = public_key.public_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyInfo\n)\n\n\nwith open('private_key.pem', 'wb') as f:\n f.write(pem_private)\n\nwith open('public_key.pem', 'wb') as f:\n f.write(pem_public)\n\n# print(pem_private)\n# print(pem_public)\n\nwith open(\"private_key.pem\", \"rb\") as key_file:\n private_key = serialization.load_pem_private_key(\n key_file.read(),\n password=None,\n backend=default_backend()\n )\n\nwith open(\"public_key.pem\", \"rb\") as key_file:\n public_key = serialization.load_pem_public_key(\n key_file.read(),\n backend=default_backend()\n )\n\n#entrypt the message\nmessage = b\"Hello World\"\nencrypted = public_key.encrypt(\n message,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n)\nprint(encrypted)\n\n#decrypt the message\noriginal_message = private_key.decrypt(\n encrypted,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n)\nprint(original_message)\n","sub_path":"test_rsa.py","file_name":"test_rsa.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"582668365","text":"import numpy as np\r\nimport tensorflow as tf\r\nfrom baselines.acktr.utils import conv, fc, dense, conv_to_fc, sample, kl_div\r\n\r\nclass CnnGenerator(object):\r\n def __init__(self, sess, obvs, ac_space, noise_size, batch_size, nstack, reuse=False):\r\n nact = ac_space.n\r\n noise = tf.placeholder(tf.float32, [None, noise_size])\r\n with tf.variable_scope(\"model\", reuse=reuse):\r\n h = conv(tf.cast(obvs, tf.float32)/255., 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2))\r\n h2 = conv(h, 'c2', nf=64, rf=4, stride=2, init_scale=np.sqrt(2))\r\n h3 = conv(h2, 'c3', nf=32, rf=3, stride=1, init_scale=np.sqrt(2))\r\n h3 = conv_to_fc(h3)\r\n generator_input = tf.concat([h3, noise],1)\r\n h4 = fc(generator_input, 'fc1', nh=512, init_scale=np.sqrt(2))\r\n pi = fc(h4, 'pi', nact, act=lambda x:x)\r\n vf = fc(h4, 'v', 1, act=lambda x:x)\r\n\r\n v0 = vf[:, 0]\r\n a0 = sample(pi)\r\n self.initial_state = [] #not stateful\r\n \r\n def step(feed_dict, *_args, **_kwargs):\r\n a, v = sess.run([a0, v0], feed_dict)\r\n return a, v, [] #dummy state\r\n\r\n self.pi = pi\r\n self.vf = vf\r\n self.noise = noise\r\n self.step = step\r\n\r\nclass CnnDiscriminator(object):\r\n def __init__(self, sess, obvs, action_pi, batch_size, nstack, reuse=False):\r\n with tf.variable_scope(\"model\", reuse=reuse):\r\n # Build a feature detection layer with the convolutional part\r\n h = conv(tf.cast(obvs, tf.float32)/255., 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2))\r\n h2 = conv(h, 'c2', nf=64, rf=4, stride=2, init_scale=np.sqrt(2))\r\n h3 = conv(h2, 'c3', nf=32, rf=3, stride=1, init_scale=np.sqrt(2))\r\n h3 = conv_to_fc(h3)\r\n # Concatenate the features with the input action\r\n discriminator_input = tf.concat([h3, action_pi],1)\r\n h4 = fc(discriminator_input, 'fc1', nh=512, init_scale=np.sqrt(2))\r\n discriminator_decision = fc(h4, 'decision', 1, act=lambda x:x)\r\n \r\n self.initial_state = [] #not stateful - ???\r\n\r\n self.discriminator_decision = discriminator_decision\r\n\r\nclass FCGenerator(object):\r\n def __init__(self, sess, features, ac_space, noise_size, batch_size, nstack, reuse=False):\r\n nact = ac_space.n\r\n with tf.variable_scope(\"model\", reuse=reuse):\r\n h4 = fc(features, 'fc1', nh=512, init_scale=np.sqrt(2))\r\n pi = fc(h4, 'pi', nact, act=lambda x:x)\r\n vf = fc(h4, 'v', 1, act=lambda x:x)\r\n\r\n v0 = vf[:, 0]\r\n a0 = sample(pi)\r\n self.initial_state = [] #not stateful\r\n \r\n def step(feed_dict, *_args, **_kwargs):\r\n a, v = sess.run([a0, v0], feed_dict)\r\n return a, v, [] #dummy state\r\n\r\n self.pi = pi\r\n self.vf = vf\r\n self.step = step\r\n\r\n# Could also have a CNN feature detector that feeds into both a generator and a discriminator","sub_path":"baselines/acktr/gan_models.py","file_name":"gan_models.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"113601114","text":"import os\n\nimport requests\n\n\ndef addUser(user_id):\n path = \"/Users/jamesccc/Downloads/django--master-2/media/\" + user_id\n folder = os.path.exists(path)\n\n if not folder: # 判断是否存在文件夹如果不存在则创建为文件夹\n os.makedirs(path) # makedirs 创建文件时如果路径不存在会创建这个路径\n print(\"--- new folder... ---\")\n print(\"--- OK ---\")\n\n else:\n print(\"--- There is this folder! ---\")\n\n\ndef addAlbum(user_id, filename):\n path = \"/Users/jamesccc/Downloads/django--master-2/media/\" + user_id + '/' + filename\n folder = os.path.exists(path)\n\n if not folder: # 判断是否存在文件夹如果不存在则创建为文件夹\n os.makedirs(path) # makedirs 创建文件时如果路径不存在会创建这个路径\n print(\"--- new folder... ---\")\n print(\"--- OK ---\")\n\n else:\n print(\"--- There is this folder! ---\")\n\n\ndef addImgToAlbum(user_id, project, filename, url):\n path = \"/Users/jamesccc/Downloads/django--master-2/web/static/media/\" + str(user_id) + '/' + project\n print(path)\n img = requests.get(url)\n folder = os.path.exists(path)\n\n if not folder: # 判断是否存在文件夹如果不存在则创建为文件夹\n os.makedirs(path) # makedirs 创建文件时如果路径不存在会创建这个路径\n print(\"--- new folder... ---\")\n print(\"--- OK ---\")\n path += '/' + str(filename)\n f = open(path + '.jpg', 'ab')\n print(f)\n f.write(img.content)\n\n\nurl = \"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fstefankanchev.com%2Fimg%2Flogos%2F84-1.gif&refer=http%3A%2F%2Fstefankanchev.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1622913206&t=ad7615abe884b4397572919b5ff217ce\"\naddImgToAlbum(str(3), \"我是毕设\", \"D\", url)\n","sub_path":"script/create_folder.py","file_name":"create_folder.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569697853","text":"#!/usr/bin/python3\n\nimport sys\nimport signal\n\n\ndef log_parsing(function_size, status_code):\n \"\"\"Write a script that reads stdin line by line and computes metrics:\n\n Args:\n function_size (int): size the funtion\n status_code (int): status code\n \"\"\"\n print('File size: {}'.format(function_size))\n for key, value in sorted(status_code.items()):\n if value != 0:\n print('{}: {}'.format(key, value))\n\nstatus_code = {\"200\": 0, \"301\": 0, \"400\": 0, \"401\": 0,\n \"403\": 0, \"404\": 0, \"405\": 0, \"500\": 0}\n\ncount = 1\nfunction_size = 0\n\n# split the line in the stdin\ntry:\n for line in sys.stdin:\n split1 = line.split()\n\n if len(split1) > 2:\n file_size = split1[-1]\n status = split1[-2]\n function_size = function_size + int(file_size)\n\n# verify if the status sent is in the diccionary created and sum to the status\n if status in status_code:\n status_code[status] = status_code[status] + 1\n\n\n# Every 10 iteractions, prints the value\n if count % 10 == 0:\n print('File size: {}'.format(function_size))\n for key, value in sorted(status_code.items()):\n if value != 0:\n print('{}: {}'.format(key, value))\n\n count = count + 1\n\nexcept KeyboardInterrupt:\n pass\n\nfinally:\n log_parsing(function_size, status_code)\n","sub_path":"0x06-log_parsing/0-stats.py","file_name":"0-stats.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"625416495","text":"N = int(input())\nweights = input().split(\" \")\noutput = []\ntemp = []\nfor i in range(len(weights)):\n if(int(weights[i]) % 2 != 0):\n if(sum(temp) > sum(output)):\n output = temp.copy()\n temp = []\n else:\n temp.append(int(weights[i]))\nif(sum(temp) > sum(output)):\n print(sum(temp))\nelse:\n print(sum(output))\n","sub_path":"UCC/2021/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"390688846","text":"from tkinter import *\nimport time\n\n\n\ntk=Tk()\ntk.title('')\ntk.resizable(0,0)\ntk.configure(bg='black')\nwd=Frame(tk,bg='black')\nwindow=Frame(wd,bg='black')\nwindow2=Frame(wd,bg='black')\nwindow3=Frame(wd,bg='black')\nplace_label=Label(window3,bg='black',fg='peru',width=19,height=8)\nphoto_frame=Canvas(tk,bg='black',width=380,height=395,borderwidth=0,highlightthickness=0)\nw1=Label(window,bg='black',fg='yellowgreen',text='O',width=2)\nw2=Label(window,bg='black',fg='red',text='O',width=2)\nw3=Label(window,bg='black',fg='red',text='O',width=2)\nw4=Label(window,bg='black',fg='red',text='O',width=2)\nw5=Label(window,bg='black',fg='red',text='O',width=2)\nw6=Label(window,bg='black',fg='red',text='O',width=2)\nw7=Label(window,bg='black',fg='red',text='O',width=2)\nw8=Label(window,bg='black',fg='red',text='O',width=2)\nw9=Label(window,bg='black',fg='red',text='O',width=2)\nw10=Label(window,bg='black',fg='red',text='O',width=2)\nw11=Label(window,bg='black',fg='red',text='O',width=2)\nw12=Label(window,bg='black',fg='red',text='O',width=2)\nw13=Label(window,bg='black',fg='red',text='O',width=2)\nw14=Label(window,bg='black',fg='red',text='O',width=2)\nw15=Label(window,bg='black',fg='red',text='O',width=2)\nplaces_=[]\nplaces_.append(w1)\nplaces_.append(w2)\nplaces_.append(w3)\nplaces_.append(w4)\nplaces_.append(w5)\nplaces_.append(w6)\nplaces_.append(w7)\nplaces_.append(w8)\nplaces_.append(w9)\nplaces_.append(w10)\nplaces_.append(w11)\nplaces_.append(w12)\nplaces_.append(w13)\nplaces_.append(w14)\nplaces_.append(w15)\nplaces={}\nnum=''\nblocked=[]\nfor window_place in range(15):\n\tplaces[window_place]=places_[window_place]\n\tfor num in blocked:\n\t\tif window_place==num:\n\t\t\tplaces[window_place]['text']='X'\n\t\t\tplaces[window_place]['fg']='hotpink'\ndel places_\ngame_map=(\n\t({},{},{},{}),\n\t({},{},{},{}),\n\t({},{},{},{}),\n\t({},{},{},{}),\n\t({},{},{},{})\n\t)\ngame_map[0][1]['place']={'title':'Start','status':'Outside'}#1\ngame_map[0][2]['place']={'title':'The old house','status':'Inside'}#2\ngame_map[0][3]['place']={'title':'First floor','status':'Inside'}#3\ngame_map[1][1]['place']={'title':'Field','status':'Outside'}#4\ngame_map[1][2]['place']={'title':'M. Street','status':'Outside'}#5\ngame_map[1][3]['place']={'title':'Shop','status':'Inside'}#6\ngame_map[2][0]['place']={'title':'Hidden room','status':'Inside'}#7\ngame_map[2][1]['place']={'title':'Cross P. Street and\\nO. Street','status':'Outside'}#8\ngame_map[2][2]['place']={'title':'Cross M. Street and\\nP. Street','status':'Outside'}#9\ngame_map[2][3]['place']={'title':'P. Street','status':'Outside'}#10\ngame_map[3][0]['place']={'title':'Hidden room shop','status':'Inside'}#11\ngame_map[3][1]['place']={'title':'O. Street','status':'Outside'}#12\ngame_map[3][2]['place']={'title':'Inside Castle','status':'Outside'}#13\ngame_map[3][3]['place']={'title':'Outside Castle','status':'Inside'}#14\ngame_map[4][1]['place']={'title':'Shop2','status':'Inside'}#15\n\ngame_map[0][1]['moves']=['b']\ngame_map[0][2]['moves']=['r','b']\ngame_map[0][3]['moves']=['l']\ngame_map[1][1]['moves']=['r','t']\ngame_map[1][2]['moves']=['t','b','l','r']\ngame_map[1][3]['moves']=['l']\ngame_map[2][0]['moves']=['b','r']\ngame_map[2][1]['moves']=['b','l','r']\ngame_map[2][2]['moves']=['t','l','r']\ngame_map[2][3]['moves']=['l','b']\ngame_map[3][0]['moves']=['t']\ngame_map[3][1]['moves']=['t','b']\ngame_map[3][2]['moves']=['r']\ngame_map[3][3]['moves']=['l','t']\ngame_map[4][1]['moves']=['t']\n\ngame_map[0][1]['id']=0\ngame_map[0][2]['id']=1\ngame_map[0][3]['id']=2\ngame_map[1][1]['id']=3\ngame_map[1][2]['id']=4\ngame_map[1][3]['id']=5\ngame_map[2][0]['id']=6\ngame_map[2][1]['id']=7\ngame_map[2][2]['id']=8\ngame_map[2][3]['id']=9\ngame_map[3][0]['id']=10\ngame_map[3][1]['id']=11\ngame_map[3][2]['id']=12\ngame_map[3][3]['id']=13\ngame_map[4][1]['id']=14\n\ngame_map[0][1]['blocked']=False\ngame_map[0][2]['blocked']=False\ngame_map[0][3]['blocked']=False\ngame_map[1][1]['blocked']=False\ngame_map[1][2]['blocked']=False\ngame_map[1][3]['blocked']=False\ngame_map[2][0]['blocked']=False\ngame_map[2][1]['blocked']=False\ngame_map[2][2]['blocked']=False\ngame_map[2][3]['blocked']=False\ngame_map[3][0]['blocked']=False\ngame_map[3][1]['blocked']=False\ngame_map[3][2]['blocked']=False\ngame_map[3][3]['blocked']=False\ngame_map[4][1]['blocked']=False\nfor y in (0,1,2,3,4):\n\tfor x in {0:(1,2,3),1:(1,2,3),2:(0,1,2,3),3:(0,1,2,3),4:(None,1)}[y]:\n\t\tif not x is None:\n\t\t\tif places[game_map[y][x]['id']]['text']=='X':\n\t\t\t\tgame_map[y][x]['blocked']=True\n\ncoords=[1,0]\nmoves=[]\nblocking=0\nout_mapping=0\nplace_label['text']='Place:\\n%s\\n\\nStatus:\\n%s'%(game_map[coords[1]][coords[0]]['place']['title'],game_map[coords[1]][coords[0]]['place']['status'])\n\n\ndef btn_config(mode):\n\tfor btn in buttons:\n\t\tif mode=='off':\n\t\t\tbtn['state']=DISABLED\n\t\telse:\n\t\t\tbtn['state']=NORMAL\n\ndef display_parameters(coords,text_display=None):\n\tplace_label['text']=''\n\tfor char in text_display:\n\t\tplace_label['text']+=char\n\t\tif char!=' ':\n\t\t\ttime.sleep(0.085)\n\t\ttk.update_idletasks()\n\ndef change_display(coords):\n\tfor x in range(15):\n\t\tif places[x]['fg']=='yellowgreen':\n\t\t\tplaces[x]['fg']='red'\n\n\tif coords==[1,0]:\n\t\tplaces[0]['fg']='yellowgreen'\n\telif coords==[2,0]:\n\t\tplaces[1]['fg']='yellowgreen'\n\telif coords==[3,0]:\n\t\tplaces[2]['fg']='yellowgreen'\n\telif coords==[1,1]:\n\t\tplaces[3]['fg']='yellowgreen'\n\telif coords==[2,1]:\n\t\tplaces[4]['fg']='yellowgreen'\n\telif coords==[3,1]:\n\t\tplaces[5]['fg']='yellowgreen'\n\telif coords==[0,2]:\n\t\tplaces[6]['fg']='yellowgreen'\n\telif coords==[1,2]:\n\t\tplaces[7]['fg']='yellowgreen'\n\telif coords==[2,2]:\n\t\tplaces[8]['fg']='yellowgreen'\n\telif coords==[3,2]:\n\t\tplaces[9]['fg']='yellowgreen'\n\telif coords==[0,3]:\n\t\tplaces[10]['fg']='yellowgreen'\n\telif coords==[1,3]:\n\t\tplaces[11]['fg']='yellowgreen'\n\telif coords==[2,3]:\n\t\tplaces[12]['fg']='yellowgreen'\n\telif coords==[3,3]:\n\t\tplaces[13]['fg']='yellowgreen'\n\telif coords==[1,4]:\n\t\tplaces[14]['fg']='yellowgreen'\n\ndef move(y,x,coords,old_coords):\n\tglobal blocking\n\tcoords[0] = coords[0] + x\n\tcoords[1] = coords[1] + y\n\tif not game_map[coords[1]][coords[0]]['blocked']:\n\t\tbtn_config('off')\n\t\tchange_display(coords)\n\t\tdisplay_parameters(coords,text_display='Place:\\n%s\\n\\nStatus:\\n%s'%(game_map[coords[1]][coords[0]]['place']['title'],game_map[coords[1]][coords[0]]['place']['status']))\n\t\tbtn_config('on')\n\telse:\n\t\tdisplay_parameters(coords,'BLOCKED')\n\t\tblocking+=1\n\t\tcoords[0] = coords[0] - x\n\t\tcoords[1] = coords[1] - y\n\ndef move_top(event=None):\n\tglobal out_mapping\n\tglobal coords\n\tif 't' in game_map[coords[1]][coords[0]]['moves']:\n\t\tmove(-1,0,coords,coords)\n\t\tmoves.append('top')\n\telse:\n\t\tdisplay_parameters(coords,'OUT OF MAP')\n\t\tout_mapping+=1\n\ndef move_bottom(event=None):\n\tglobal out_mapping\n\tglobal coords\n\tif 'b' in game_map[coords[1]][coords[0]]['moves']:\n\t\tmove(1,0,coords,coords)\n\t\tmoves.append('bottom')\n\telse:\n\t\tdisplay_parameters(coords,'OUT OF MAP')\n\t\tout_mapping+=1\n\ndef move_left(event=None):\n\tglobal out_mapping\n\tglobal coords\n\tif 'l' in game_map[coords[1]][coords[0]]['moves']:\n\t\tmove(0,-1,coords,coords)\n\t\tmoves.append('left')\n\telse:\n\t\tdisplay_parameters(coords,'OUT OF MAP')\n\t\tout_mapping+=1\n\ndef move_right(event=None):\n\tglobal out_mapping\n\tglobal coords\n\tif 'r' in game_map[coords[1]][coords[0]]['moves']:\n\t\tmove(0,1,coords,coords)\n\t\tmoves.append('right')\n\telse:\n\t\tdisplay_parameters(coords,'OUT OF MAP')\n\t\tout_mapping+=1\n\n\ndef get():\n\ttk.destroy()\n\treturn {'place':game_map[coords[1]][coords[0]]['place']['title'],'status':game_map[coords[1]][coords[0]]['place']['status'],'coords':coords,'moves':moves,'out_map':out_mapping,'blocked':blocking}\n\ndef select(event=None):\n\n\tprint(get())\n\nwd.grid(row=0,column=0)\nwindow.grid(row=0,column=0)\nwindow2.grid(row=1,column=0)\nwindow3.grid(row=2,column=0)\n\nplace_label.grid(row=0,column=0)\nphoto_frame.grid(row=0,column=1)\n\nt_button=Button(window2,bg='black',fg='dodgerblue',activebackground='black',activeforeground='dodgerblue',text='up',width=6,height=1,command=move_top)\nb_button=Button(window2,bg='black',fg='dodgerblue',activebackground='black',activeforeground='dodgerblue',text='down',width=6,height=1,command=move_bottom)\nl_button=Button(window2,bg='black',fg='dodgerblue',activebackground='black',activeforeground='dodgerblue',text='left',width=5,height=1,command=move_left)\nr_button=Button(window2,bg='black',fg='dodgerblue',activebackground='black',activeforeground='dodgerblue',text='right',width=5,height=1,command=move_right)\nok_button=Button(window2,bg='black',fg='lime',activebackground='black',activeforeground='lime',text='OK',width=5,height=1,command=select)\nbuttons=[]\nbuttons.append(t_button)\nbuttons.append(b_button)\nbuttons.append(l_button)\nbuttons.append(r_button)\nbuttons.append(ok_button)\n\nt_button.grid(row=0,column=1)\nb_button.grid(row=2,column=1)\nl_button.grid(row=1,column=0)\nr_button.grid(row=1,column=2)\nok_button.grid(row=1,column=1)\n\nw1.grid(row=0,column=2)\nw2.grid(row=0,column=4)\nw3.grid(row=0,column=6)\nw4.grid(row=2,column=2)\nw5.grid(row=2,column=4)\nw6.grid(row=2,column=6)\nw7.grid(row=4,column=0)\nw8.grid(row=4,column=2)\nw9.grid(row=4,column=4)\nw10.grid(row=4,column=6)\nw11.grid(row=6,column=0)\nw12.grid(row=6,column=2)\nw13.grid(row=6,column=4)\nw14.grid(row=6,column=6)\nw15.grid(row=8,column=2)\n\nj1=Label(window,bg='black',fg='red',text='--',width=2).grid(row=0,column=5)\nj2=Label(window,bg='black',fg='red',text='|',width=2).grid(row=1,column=2)\nj3=Label(window,bg='black',fg='red',text='|',width=2).grid(row=1,column=4)\nj4=Label(window,bg='black',fg='red',text='--',width=2).grid(row=2,column=3)\nj5=Label(window,bg='black',fg='red',text='--',width=2).grid(row=2,column=5)\nj6=Label(window,bg='black',fg='red',text='|',width=2).grid(row=3,column=4)\nj7=Label(window,bg='black',fg='red',text='--',width=2).grid(row=4,column=1)\nj8=Label(window,bg='black',fg='red',text='--',width=2).grid(row=4,column=3)\nj9=Label(window,bg='black',fg='red',text='--',width=2).grid(row=4,column=5)\nj10=Label(window,bg='black',fg='red',text='|',width=2).grid(row=5,column=0)\nj11=Label(window,bg='black',fg='red',text='|',width=2).grid(row=5,column=2)\nj12=Label(window,bg='black',fg='red',text='|',width=2).grid(row=5,column=6)\nj13=Label(window,bg='black',fg='red',text='--',width=2).grid(row=6,column=5)\nj14=Label(window,bg='black',fg='red',text='|',width=2).grid(row=7,column=2)\n\nx_coords={\n\t0:(0,1,3),\n\t1:(0,1,3,5,6),\n\t2:(0,1),\n\t3:(0,1,2,3,5,6),\n\t5:(1,3,4,5),\n\t6:(1,3),\n\t7:(0,1,3,4,5,6),\n\t8:(0,1,3,4,5,6)\n\t}\ny_coords=(0,1,2,3,5,6,7,8)\nfor y in y_coords:\n\tfor x in x_coords[y]:\n\t\tLabel(window,bg='black',width=2).grid(row=y,column=x)\n\nx_coords={\n\t0:(0,2),\n\t2:(0,2)\n\t}\ny_coords=(0,2)\nfor y in y_coords:\n\tfor x in x_coords[y]:\n\t\tLabel(window2,bg='black',width=5).grid(row=y,column=x)\n\ntk.mainloop()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"349915661","text":"from ics import Calendar, Event\nfrom flask import Flask, render_template, request\nfrom flask.helpers import send_file, send_from_directory, url_for\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nimport sys\nimport os\nimport datetime\nimport utils\nfrom werkzeug.utils import redirect\napp = Flask(__name__)\n\ndef sendemail(receiver, calendar):\n COMMASPACE = ', '\n def main():\n sender = 'tourefamily161@gmail.com'\n gmail_password = 'Be@tslapsit090400'\n recipients = [str(receiver)]\n\n # Create the enclosing (outer) message\n outer = MIMEMultipart()\n outer['Subject'] = 'Your qran Calendar '\n outer['To'] = COMMASPACE.join(recipients)\n outer['From'] = sender\n outer.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n\n # List of attachments\n attachments = [str(calendar)]\n\n # Add the attachments to the message\n for file in attachments:\n try:\n with open(file, 'rb') as fp:\n msg = MIMEBase('application', \"octet-stream\")\n msg.set_payload(fp.read())\n encoders.encode_base64(msg)\n msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))\n outer.attach(msg)\n except:\n print(\"Unable to open one of the attachments. Error: \", sys.exc_info()[0])\n raise\n\n composed = outer.as_string()\n\n # Send the email\n try:\n with smtplib.SMTP('smtp.gmail.com', 587) as s:\n s.ehlo()\n s.starttls()\n s.ehlo()\n s.login(sender, gmail_password)\n s.sendmail(sender, recipients, composed)\n s.close()\n print(\"Email sent!\")\n except:\n print(\"Unable to send the email. Error: \", sys.exc_info()[0])\n raise\n\n if __name__ == '__main__':\n main()\n\nresult = open(\"templates/surahList.html\", \"w\")\nresult.write(\"\")\nresult = open(\"templates/prediction.html\", \"w\")\nresult.write(\"\")\n\n@app.route(\"/\")\ndef main():\n result = open(\"templates/surahList.html\", \"w\")\n result.write(\"\")\n result = open(\"templates/prediction.html\", \"w\")\n result.write(\"\")\n return render_template(\"index.html\")\n\n@app.route(\"/\", methods=[\"POST\"])\ndef surah():\n result = open(\"templates/surahList.html\", \"w\")\n result.write(utils.getHeader())\n beginDateForm = request.form['beginDate']\n endDateForm = request.form['endDate']\n precision = int(request.form['precision'])\n email = request.form['email']\n beginSurah = int(request.form['beginSurah'])\n endSurah = int(request.form['endSurah'])\n beginDateForm = beginDateForm.split(\"-\")\n endDateForm = endDateForm.split(\"-\")\n beginDate = datetime.date(int(beginDateForm[0]), int(beginDateForm[1]), int(beginDateForm[2]))\n endDate = datetime.date(int(endDateForm[0]), int(endDateForm[1]), int(endDateForm[2]))\n numberOfDays = utils.diff_dates(beginDate, endDate)\n returnValue = utils.getDaysPages(numberOfDays, beginSurah, endSurah, precision)\n dailyPageGoal = returnValue[0]\n surahFinishDay = returnValue[1]\n chaptersToLearn = returnValue[2]\n c = Calendar()\n result.write(\" \")\n result.write(\"

You will have to learn \"+str(dailyPageGoal)+\" pages per day

\\n\")\n for i in reversed(chaptersToLearn):\n finishDay = beginDate+ datetime.timedelta(days=surahFinishDay[i.name])\n result.write(\"

\"+i.name+ \" Will be done on \"+str(finishDay)+\"

\")\n e = Event()\n e.name = \"Finish \" + i.name\n e.begin = str(finishDay)+\" 00:00:00\"\n c.events.add(e)\n c.events\n\n with open('calendar.ics', 'w') as f:\n f.write(str(c))\n ics = '/Users/serigne/Desktop/dev/project/python/qran/calendar.ics'\n sendemail(email, ics)\n os.remove(ics)\n # os.remove(txt)\n return redirect(url_for('surahList'))\n # return render_template(\"index.html\")\n\n\n@app.route(\"/surahList\")\ndef surahListMain():\n # result.write(\" \")\n return render_template(\"surahList.html\")\n\n@app.route(\"/surahList\", methods=[\"POST\"])\ndef surahList():\n return redirect(url_for('main'))\n # return render_template(\"surahLists.html\")\n\n\n\n\n\n\n@app.route(\"/prediction\")\ndef prediction():\n return render_template(\"prediction.html\")\n\n@app.route(\"/result\")\ndef predictionResult():\n return render_template(\"when.html\")\n\n@app.route(\"/prediction\", methods=[\"POST\"])\ndef prediction2():\n currentSurah = request.form['currentSurah']\n numAyah = int(request.form['numAyah'])\n result = open(\"templates/when.html\", \"w\")\n x = datetime.date.today\n result.write(\" \")\n return redirect(url_for('p2'))\n\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=8090, debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"445474805","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nimport xgboost\nfrom sklearn.metrics import accuracy_score\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport tensorflow as tf\n\n# Load the dataset\ntrain_df = pd.read_csv('./data/train.csv')\ntest_df = pd.read_csv('./data/test.csv')\n\nprint(train_df.shape)\nprint(test_df.shape)\n\nfor feature in train_df.columns: # Loop through all columns in the dataframe\n if train_df[feature].dtype == 'object': # Only apply for columns with categorical strings\n train_df[feature] = pd.Categorical(train_df[feature]).codes\n\nfor feature in test_df.columns: # Loop through all columns in the dataframe\n if test_df[feature].dtype == 'object': # Only apply for columns with categorical strings\n test_df[feature] = pd.Categorical(test_df[feature]).codes\n\ntrain_drops = [\"Formatted Date\",\"Visibility\"]\ntest_drops = [\"Formatted Date\"]\nX = train_df.drop(train_drops,axis=1)\ny = train_df[\"Visibility\"]\n\nstd = MinMaxScaler()\nstd.fit(X)\nX_train = std.transform(X)\nX_test = std.transform(test_df.drop(test_drops,axis=1))\n\ntrainX,validX,trainy,validy = train_test_split(X_train,y)\n\n\n\n\n\n# Build DNN\nmodel = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Dense(128,input_dim = 8, activation=\"relu\"))\nmodel.add(tf.keras.layers.BatchNormalization())\nmodel.add(tf.keras.layers.Dense(64,activation=\"relu\", kernel_regularizer=tf.keras.regularizers.l2(0.01)))\nmodel.add(tf.keras.layers.BatchNormalization())\nmodel.add(tf.keras.layers.Dense(32,activation=\"relu\", kernel_regularizer=tf.keras.regularizers.l2(0.01)))\nmodel.add(tf.keras.layers.BatchNormalization())\nmodel.add(tf.keras.layers.Dense(1,activation=\"sigmoid\"))\nmodel.summary()\n\nmodel.compile(optimizer=\"adam\",loss=\"binary_crossentropy\",metrics=[\"accuracy\"])\nmodel.fit(trainX,trainy,validation_data=(validX,validy),batch_size=128,epochs=30)\n\npred = model.predict_proba(X_test)\nouts = [x[0] for x in pred]\n\nsub = pd.DataFrame({'Formatted Date': test_df['Formatted Date'], 'Visibility':outs})\nsub.to_csv(\"submission.csv\",index=False)\n\n\n\n","sub_path":"elice/num1.py","file_name":"num1.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"590731689","text":"class RealEstateSystem:\n\n # Constructor\n def __init__(self):\n \"\"\" (RealEstateSystem)\n Initialize the homes list\n \"\"\"\n self.homes = []\n\n def add_home(self, home):\n \"\"\" (RealEstateSystem, Home) -> NoneType\n Adds a home to our system\n \"\"\"\n self.homes.append(home)\n \n def extract_minimum_price(self):\n \"\"\" (RealEstateSystem) -> int\n Return the lowest priced home in the system, or -1 if there are no houses in the system\n \"\"\"\n # mtd.1\n\n #saved_min=0\n ## iterate each of home in homes\n #for home in self.homes:\n # # save only min value \n # curr_price = home.price\n # if saved_min == 0:\n # saved_min = curr_price\n # else:\n # if saved_min >= curr_price:\n # saved_min = curr_price\n # \n #if saved_min == 0:\n # return -1 \n #else:\n # return saved_min\n\n # mtd.2\n\n prices=[]\n # iterate each of home in homes\n for home in self.homes:\n prices.append(home.price)\n\n if len(prices) == 0:\n return -1 \n else:\n return min(prices)\n\nclass Home:\n \"\"\" An instance of a home \"\"\"\n def __init__(self, price):\n \"\"\" (Home, float)\n Initialize a home\n \"\"\"\n self.price = price\n\n\n\nr=RealEstateSystem()\nh1 = Home(10)\nh2 = Home(30)\nh3 = Home(20)\nr.add_home(h1)\nr.add_home(h2)\nr.add_home(h3)\nprint(r.extract_minimum_price())\n\nr2=RealEstateSystem()\nprint(r2.extract_minimum_price())\n","sub_path":"PYTHON_CSC108/git/Exercises/141123_133720/t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"641325865","text":"#!/usr/bin/env python\n# -*- coding: utf-8\nimport json\nfrom time import time\nfrom lxml.html import fromstring\nfrom urllib.request import urlopen\nfrom selection import XpathSelector\n\nSTART_URL = 'http://hotline.ua/mobile/mobilnye-telefony-i-smartfony/?p={}'\nPAG_RANGE = [0,93]\nXPATH_ITEM = './/ul[@class=\"catalog clearfix\"]/li'\nXPATH_ITEM_AVGPRICE = './/div[@class=\"price\"]/span/node()'\nXPATH_ITEM_NAMEURL = './/div[@class=\"ttle\"]/a'\nXPATH_ITEM_FEATR = 'div/p[@class=\"tech-char\"]'\n\ndef get_urls(start_url, pag_range, save_json=''):\n \"\"\"\n { \n \"name\": str_value,\n \"avgPrice\": int_value,\n \"url\": str_url,\n \"features\": str_value\n }\n \n \"\"\"\n t = time()\n data = []\n for i in range(*pag_range):\n print(i, time()-t,'sec')\n http_resp = urlopen(start_url.format(i))\n \n if http_resp.code != 200:\n print('Problem ulr {}, Code - {}'.format(start_url.format(i),http_resp.code))\n return False\n \n html = http_resp.read()\n sel = XpathSelector(fromstring(html))\n \n for item in sel.select(XPATH_ITEM):\n name = item.select(XPATH_ITEM_NAMEURL).text()\n url = item.select(XPATH_ITEM_NAMEURL).attr('href')\n try:\n avg_price = int(item.select(XPATH_ITEM_AVGPRICE).text()[:-4].replace(' ',''))\n except:\n print(name, url, 'Error price')\n avg_price = 'nd'\n try:\n features = item.select(XPATH_ITEM_FEATR).text()\n except:\n print(name, url, 'Error features')\n features = 'None'\n \n data.append( {\n \"name\": name,\n \"avgPrice\": avg_price,\n \"url\": url,\n \"features\": features\n })\n if save_json:\n with open(save_json, 'w') as fp:\n json.dump(data, fp, indent=2, sort_keys=True, ensure_ascii=False)\n return True\n return data\n\ndef main():\n get_urls(start_url=START_URL, pag_range=PAG_RANGE, save_json='hotline_smartphones.json')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"parser_hotline/parser_hotline.py","file_name":"parser_hotline.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"13813927","text":"import time\nimport board\nfrom digitalio import DigitalInOut, Direction, Pull\n\nled = DigitalInOut(board.P1_10) # blue led\nled.direction = Direction.OUTPUT\n\nwhile True:\n led.value = True\n time.sleep(0.5)\n led.value = False\n time.sleep(0.5)","sub_path":"60_case_keyboard/firmware/code_blink.py","file_name":"code_blink.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"529367239","text":"from __future__ import print_function\nimport sys\nimport os\nsys.path.append(os.path.abspath(__file__ + \"/../../../../\"))\n\n\nimport System.DataProcessing.process_data as ptd\nfrom pprint import pprint\nfrom time import time\nimport logging\nimport pandas as pd\nimport System.Utilities.write_to_file as write\nimport numpy as np\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.svm import LinearSVC, SVC\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.cross_validation import StratifiedKFold\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.naive_bayes import MultinomialNB, BernoulliNB\nfrom sklearn.linear_model import SGDClassifier, LogisticRegression\n\nfile = write.initFile(\"ex12-linearSVC-part2\")\n\n# Display progress logs on stdout\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s')\n\n\n###############################################################################\n# Load\nstrength = 'soft'\n\n#data = pd.read_csv('../../TextFiles/data/tcp_train.csv', sep='\\t')\ndata = ptd.getTrainingData()\ndata = data[data.Stance != 'NONE']\n\ncv = StratifiedKFold(data.Stance, n_folds=10, shuffle=True, random_state=1)\n\nprint(\"%d training documents\" % len(data.Abstract))\nwrite.writeTextToFile(\"%d training documents\" % len(data.Abstract),file)\nprint(\"%d categories\" % 3)\nwrite.writeTextToFile(\"%d categories\" % 3,file)\nprint()\n\n###############################################################################\n# Classifiers\n# MultinomialNB(), BernoulliNB(), SVM(), LinearSVM(), SGDClassifier(), LogisticRegression()\nclf = MultinomialNB()\n\nprint(\"Using train, validation and test approach with clf {}\".format(clf))\nwrite.writeTextToFile(\"Using train, validation and test approach with clf {}\".format(clf), file)\n\n###############################################################################\n# define a pipeline combining a text feature extractor with a simple classifier\npipeline = Pipeline([\n ('vect', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('clf', clf)\n])\n\n# uncommenting more parameters will give better exploring power but will\n# increase processing time in a combinatorial way\nparameters = {\n 'vect__analyzer': ['word'],\n 'vect__ngram_range': [(1, 1), (1, 2), (1, 3), (2, 3)],\n 'vect__stop_words': [None, 'english'],\n #'vect__max_features': (None, 50000),\n 'tfidf__use_idf': (True, False),\n #'clf__alpha': np.logspace(-1, 0, 5),\n 'clf__fit_prior': [True, False],\n #'clf__kernel': ['linear'],\n #'clf__C': np.logspace(-1, 1.3, 6),\n #'clf__penalty': ['l2'],\n #'clf__solver': ['newton-cg', 'lbfgs']\n #'clf__loss': ['modified_huber', 'squared_hinge', 'perceptron'],\n 'clf__alpha': np.logspace(-1, 0.5, 4)\n}\nif __name__ == \"__main__\":\n # multiprocessing requires the fork to happen in a __main__ protected\n # block\n\n # find the best parameters for both the feature extraction and the\n # classifier\n grid_search = GridSearchCV(pipeline, parameters, n_jobs=10, verbose=1, cv=cv,\n scoring='f1_macro')\n\n print(\"Performing grid search...\")\n write.writeTextToFile(\"Performing grid search...\",file)\n print(\"pipeline:\", [name for name, _ in pipeline.steps])\n write.writeTextToFile(\"pipeline:\" % [name for name, _ in pipeline.steps],file)\n print(\"parameters:\")\n write.writeTextToFile(\"parameters:\",file)\n pprint(parameters)\n write.writeTextToFile(parameters,file)\n t0 = time()\n grid_search.fit(data.Abstract, data.Stance)\n print(\"done in %0.3fs\" % (time() - t0))\n write.writeTextToFile(\"Done in %0.3fs \" % (time() - t0), file)\n print()\n\n print(\"Best score: %0.3f\" % grid_search.best_score_)\n write.writeTextToFile(\"Best score: %0.3f\" % grid_search.best_score_, file)\n print(\"Best parameters set:\")\n write.writeTextToFile(\"Best parameters set:\", file)\n best_parameters = grid_search.best_estimator_.get_params()\n for param_name in sorted(parameters.keys()):\n print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))\n write.writeTextToFile(\"\\t%s: %r\" % (param_name, best_parameters[param_name]), file)\n\n\nfile.close()","sub_path":"System/ImprovedSystem/grid_search/grid_search_ex12_part2.py","file_name":"grid_search_ex12_part2.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"293467276","text":"def fastExpMod(b, n, m):\r\n result = 1\r\n n = int(n)\r\n while n != 0:\r\n if (n & 1) == 1:\r\n # ni = 1, then mul\r\n result = (result * b) % m\r\n n >>= 1\r\n # n的二进制向右移位\r\n b = (b*b) % m\r\n return result\r\n\r\n\r\ndef main():\r\n\tp = input('输入p(8k+5型素奇数):')\r\n\tp = int(p)\r\n\tarf = (p-1)/4\r\n\tx = fastExpMod(2, arf, p)\r\n\ty = 1\r\n\tm = (x*x+y*y)/p\r\n\twhile m != 1:\r\n\t\tu = x % m\r\n\t\tv = y % m\r\n\t\tx1 = (u*x+v*y)/m\r\n\t\ty1 = (u*y-v*x)/m\r\n\t\tx = x1\r\n\t\ty = y1\r\n\t\tm = (x * x + y * y) / p\r\n\tx = int(abs(x))\r\n\ty = int(abs(y))\r\n\tprint('存在正整数x=',x,', y=',y,'使得 x^2+y^2=',p,' 成立',sep='')\r\n\r\nmain()","sub_path":"第四章 二次同余式与平方剩余/x^2+y^2=p的解.py","file_name":"x^2+y^2=p的解.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"462773522","text":"import cv2\nimport numpy\nfrom feat import extractFeatures\ndef getKeyPointFeatures(l,ab):\n\tm,n = l.shape\n\tsurfDescriptorExtractor = cv2.DescriptorExtractor_create(\"SURF\")\n\tsurfDescriptorExtractor.setBool('extended', True)\n\tkeyPointFeat = []\n\tclasses = []\n\tnumberOfKeyPoints = 5000\n\tfor i in range(numberOfKeyPoints):\n\t\tx=numpy.random.uniform(m)\n\t\ty=numpy.random.uniform(n)\n\t\tkeyPointFeat.append(extractFeatures(l,x,y,surfDescriptorExtractor))\n\t\tclasses.append(ab[x][y])\n\tkeyPointFeat = numpy.array(keyPointFeat)\n\tclasses = numpy.array(classes)\n\treturn keyPointFeat,classes","sub_path":"getKeyPointFeatures.py","file_name":"getKeyPointFeatures.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"92320789","text":"import requests\nimport bs4\nimport re\nimport time\nimport pymysql\n\nfrom selenium import webdriver\n\ncon = pymysql.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"123456\",\n db=\"python\",\n port=3306,\n use_unicode=True,\n charset=\"utf8\"\n)\ncursor = con.cursor()\n\ndriver = webdriver.Chrome()\ncount = 0\nfor i in range(1, 16 , 1):\n url = 'https://zh.airbnb.com/s/Shanghai--China/homes?cdn_cn=1&s_tag=ejxIlhR7&allow_override%5B%5D=§ion_offset={}'.format(\n str(i))\n driver.get(url)\n # print(i)\n #if i == 1270:\n # elements = driver.find_elements_by_class_name('mod-1')\n # for element in elements:\n # element.click()\n\n time.sleep(2)\n html = driver.page_source#获取网页的html数据、\n soup = bs4.BeautifulSoup(html,'lxml')#对html进行解析\n r = soup.find_all('div', class_='_v72lrv')\n\n for tag in r:\n\n url = 'https://zh.airbnb.com/'+str(tag.find('a',class_=\"_j4ns53m\").get('href'))\n title = str(tag.find('div',class_=\"_ew0cqip\").text)\n priceContent = tag.find('span',class_=\"_hylizj6\")\n priceTmp = priceContent.find_all('span')[2].text\n price = priceTmp.strip().lstrip().rstrip(',')\n\n # price = str(priceContent.find('span').text)\n type = str(tag.find('small',class_='_5y5o80m').text)\n\n if tag.find('span',class_='_gb7fydm'):\n comments = tag.find('span',class_='_gb7fydm').text\n else:\n comments = 'NEW'\n\n print(url)\n print(title)\n print(price[1:].strip().lstrip().rstrip(','))\n print(type)\n print(comments + '\\n')\n\n sql = \"INSERT INTO Airbnb_Shanghai(url,title,price,type,comments) values(\" \\\n + url + \",\" + title + \",\" + price[1:] + \",\" + type + \",\" + comments +\")\"\n print(sql)\n cursor.execute(sql)\n con.commit()\n","sub_path":"python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"324426166","text":"from def_system import FileDefinition, FolderDefinition, Debug\r\nfrom rpcbgen_interface import ReprCombGenInterface\r\nfrom def_utils import GeneralUtils\r\nimport shutil\r\nimport json\r\nimport sys\r\nimport os\r\n\r\ndebug_level_arg = 9\r\n\r\n# ####################################################### ARGS ####################################################### #\r\n\r\nmodelcomb_id_arg = ReprCombGenInterface.get_modelcomb_id(sys.argv)\r\nrunset_id_arg = ReprCombGenInterface.get_runset_id(sys.argv)\r\ntimestamp_arg = ReprCombGenInterface.get_timestamp(sys.argv) # last expected observation, first forecast data\r\n# timestamp_min_arg = ReprCombGenInterface.get_min_timestamp_hist(sys.argv) # graph forced minimum interval\r\n# timestamp_max_arg = ReprCombGenInterface.get_max_timestamp_hist(sys.argv) # graph forced maximum interval\r\n\r\n\r\n# ####################################################### DEFS ####################################################### #\r\n\r\ndef update_display_files(modelcomb_id, runset_id, timestamp, debug_lvl=0):\r\n \"\"\"\r\n\r\n :param modelcomb_id:\r\n :param runset_id:\r\n :param timestamp:\r\n :param debug_lvl:\r\n :return:\r\n \"\"\"\r\n\r\n sc_reprcomp = \"hydrographmultiplespast\"\r\n ref0_frame = \"modelpaststg\"\r\n\r\n # defining effective 0-ref timestamp\r\n all_ref0_timestamps = []\r\n ref0_timestamps = None\r\n if timestamp is None:\r\n modelpaststg_model_ids = ensure_list(get_frame_model_ids(modelcomb_id, runset_id, sc_reprcomp, ref0_frame,\r\n debug_lvl=debug_lvl))\r\n\r\n if modelpaststg_model_ids is None:\r\n print(\"We got a None here!\")\r\n return\r\n\r\n # define the most recent timestamp of all models\r\n for cur_modelpaststg_model_id in modelpaststg_model_ids:\r\n cur_modelpaststg_folder_path = FolderDefinition.get_historical_reprcomb_folder_path(runset_id,\r\n represcomb_id=sc_reprcomp,\r\n frame_id=ref0_frame,\r\n model_id=cur_modelpaststg_model_id)\r\n cur_ref0_timestamp = FolderDefinition.retrive_most_recent_timestamp_in_hist_folder(cur_modelpaststg_folder_path)\r\n if cur_ref0_timestamp is None:\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: No file at '{0}'.\".format(cur_modelpaststg_folder_path), 2,\r\n debug_lvl)\r\n else:\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Most recent timestamp in '{0}' is {1}.\".format(\r\n cur_modelpaststg_folder_path, cur_ref0_timestamp), 2, debug_lvl)\r\n all_ref0_timestamps.append(cur_ref0_timestamp)\r\n\r\n # the maximum timestamp will be the minimum of all maximums\r\n ref0_timestamp = min(all_ref0_timestamps) if len(all_ref0_timestamps) > 0 else None\r\n\r\n else:\r\n ref0_timestamp = timestamp\r\n\r\n # basic check\r\n if ref0_timestamp is None:\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Impossible to establish minimum timestamp for '{0}.{1}'.\".format(\r\n runset_id, modelcomb_id), 2, debug_lvl)\r\n return\r\n\r\n #\r\n update_historical_representations_composition(modelcomb_id, sc_reprcomp, runset_id, ref0_timestamp,\r\n clean_previous=True, debug_lvl=debug_lvl)\r\n\r\n\r\ndef get_frame_model_ids(modelcomb_id, runset_id, represcomb_id, frame, debug_lvl=0):\r\n \"\"\"\r\n\r\n :param modelcomb_id:\r\n :param runset_id:\r\n :param debug_lvl:\r\n :return: A string if there is only one model of given frame, an assay of strings if there are more.\r\n \"\"\"\r\n\r\n # TODO - move to a shared place. FolderDefinition ?\r\n\r\n # get entire model comb file\r\n modelcomb_file_path = FileDefinition.obtain_modelcomb_file_path(modelcomb_id, runset_id, debug_lvl=debug_lvl)\r\n if (modelcomb_file_path is None) or (not os.path.exists(modelcomb_file_path)):\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: File '{0}' not found.\".format(modelcomb_file_path), 0, debug_lvl)\r\n return None\r\n\r\n # read file content\r\n with open(modelcomb_file_path, \"r+\") as rfile:\r\n modelcomb_json = json.load(rfile)\r\n\r\n # iterates over each stuff\r\n try:\r\n represcomb_set = modelcomb_json[\"sc_modelcombination\"][\"sc_represcomb_set\"]\r\n except KeyError:\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: File '{0}' is incomplete.\".format(modelcomb_file_path), 0, debug_lvl)\r\n return None\r\n\r\n #\r\n if represcomb_id not in represcomb_set:\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Modelcomb '{0}.{1}' has no representation comb. '{2}'.\".format(\r\n runset_id, modelcomb_id, represcomb_id), 0, debug_lvl)\r\n return None\r\n\r\n # looks for required frame\r\n frame_set = represcomb_set[represcomb_id]\r\n model_ids = []\r\n for cur_model_id in frame_set.keys():\r\n if frame_set[cur_model_id] == frame:\r\n model_ids.append(str(cur_model_id))\r\n\r\n # return None, one string or a list of strings\r\n if len(model_ids) == 0:\r\n return None\r\n elif len(model_ids) == 1:\r\n return model_ids[0]\r\n else:\r\n return model_ids\r\n\r\n\r\ndef ensure_list(get_frame_model_ids_return):\r\n \"\"\"\r\n\r\n :param get_frame_model_ids_return:\r\n :return:\r\n \"\"\"\r\n if get_frame_model_ids_return is None:\r\n return []\r\n elif isinstance(get_frame_model_ids_return, str) or isinstance(get_frame_model_ids_return, basestring):\r\n return [get_frame_model_ids_return]\r\n else:\r\n return get_frame_model_ids_return\r\n\r\n\r\ndef update_historical_representations_composition(sc_modelcomb_id, sc_reprcomp_id, sc_runset_id, ref0_timestamp,\r\n clean_previous=True, debug_lvl=0):\r\n \"\"\"\r\n\r\n :param sc_modelcomp_id:\r\n :param sc_reprcomp_id:\r\n :param sc_runset_id:\r\n :param ref0_timestamp:\r\n :param clean_previous:\r\n :param debug_lvl:\r\n :return:\r\n \"\"\"\r\n\r\n # define models\r\n modelpaststg_model_ids = ensure_list(get_frame_model_ids(sc_modelcomb_id, sc_runset_id, sc_reprcomp_id,\r\n \"modelpaststg\", debug_lvl=debug_lvl))\r\n stageref_reference_ids = ensure_list(get_frame_model_ids(sc_modelcomb_id, sc_runset_id, sc_reprcomp_id, \"stageref\",\r\n debug_lvl=debug_lvl))\r\n dischref_reference_ids = ensure_list(get_frame_model_ids(sc_modelcomb_id, sc_runset_id, sc_reprcomp_id, \"dischref\",\r\n debug_lvl=debug_lvl))\r\n\r\n # basic check\r\n if modelpaststg_model_ids == None:\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Needs at least one 'modelpaststg' model.\", 0, debug_lvl)\r\n return\r\n\r\n # replace files for 'modelpaststg' frame\r\n for cur_modelpaststg_model_id in modelpaststg_model_ids:\r\n cur_modelpaststg_dest_folder_path = FolderDefinition.get_displayed_reprcomb_folder_path(sc_runset_id,\r\n sc_modelcomb_id,\r\n represcomb_id=sc_reprcomp_id,\r\n frame_id=\"modelpaststg\",\r\n model_id=cur_modelpaststg_model_id)\r\n if clean_previous and os.path.exists(cur_modelpaststg_dest_folder_path):\r\n shutil.rmtree(cur_modelpaststg_dest_folder_path)\r\n os.makedirs(cur_modelpaststg_dest_folder_path)\r\n cur_modelpaststg_source_folder_path = FolderDefinition.get_historical_reprcomb_folder_path(sc_runset_id,\r\n represcomb_id=sc_reprcomp_id,\r\n frame_id=\"modelpaststg\",\r\n model_id=cur_modelpaststg_model_id)\r\n all_modelpaststg_hist_files = os.listdir(cur_modelpaststg_source_folder_path)\r\n count_copied = 0\r\n for cur_modelpaststg_hist_file_name in all_modelpaststg_hist_files:\r\n cur_modelpaststg_hist_file_timestamp = FileDefinition.obtain_hist_file_timestamp(cur_modelpaststg_hist_file_name)\r\n if cur_modelpaststg_hist_file_timestamp == ref0_timestamp:\r\n cur_file_path = os.path.join(cur_modelpaststg_source_folder_path, cur_modelpaststg_hist_file_name)\r\n shutil.copy(cur_file_path, cur_modelpaststg_dest_folder_path)\r\n count_copied += 1\r\n else:\r\n cur_modelpaststg_hist_file_timestamp_rounded = GeneralUtils.round_timestamp_hour(cur_modelpaststg_hist_file_timestamp)\r\n if cur_modelpaststg_hist_file_timestamp_rounded == ref0_timestamp:\r\n cur_file_path = os.path.join(cur_modelpaststg_source_folder_path, cur_modelpaststg_hist_file_name)\r\n shutil.copy(cur_file_path, cur_modelpaststg_dest_folder_path)\r\n count_copied += 1\r\n\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Filled '{0}' folder.\".format(cur_modelpaststg_dest_folder_path), 1,\r\n debug_lvl)\r\n Debug.dl(\" Copied {0} files.\".format(count_copied), 1, debug_lvl)\r\n\r\n # replace files for 'stageref_reference_ids' frame\r\n print(\"Got {0} stageref_reference_ids.\".format(len(stageref_reference_ids)))\r\n for cur_stageref_reference_id in stageref_reference_ids:\r\n # define destination and source folder paths\r\n cur_stageref_dest_folder_path = FolderDefinition.get_displayed_reprcomb_folder_path(sc_runset_id,\r\n sc_modelcomb_id,\r\n represcomb_id=sc_reprcomp_id,\r\n frame_id=\"stageref\",\r\n model_id=cur_stageref_reference_id)\r\n if clean_previous and os.path.exists(cur_stageref_dest_folder_path):\r\n shutil.rmtree(cur_stageref_dest_folder_path)\r\n os.makedirs(cur_stageref_dest_folder_path)\r\n cur_stageref_source_folder_path = FolderDefinition.get_historical_reprcomb_folder_path(sc_runset_id,\r\n represcomb_id=sc_reprcomp_id,\r\n frame_id=\"stageref\",\r\n model_id=cur_stageref_reference_id)\r\n\r\n # list all source files, getting the closest ones that is possible (range of 6 hours)\r\n ref_timestamp_dist = {}\r\n ref_timestamp_timestamp = {}\r\n all_stageref_hist_files = os.listdir(cur_stageref_source_folder_path)\r\n print(\"Evaluating {0} stageref files.\".format(len(all_stageref_hist_files)))\r\n for cur_stageref_hist_file_name in all_stageref_hist_files:\r\n cur_stageref_hist_file_timestamp = FileDefinition.obtain_hist_file_timestamp(cur_stageref_hist_file_name)\r\n cur_stageref_hist_file_linkid = FileDefinition.obtain_hist_file_linkid(cur_stageref_hist_file_name)\r\n cur_time_dist = abs(ref0_timestamp - cur_stageref_hist_file_timestamp)\r\n if cur_time_dist <= 6 * 60 * 60:\r\n if (cur_stageref_hist_file_linkid not in ref_timestamp_dist.keys()) or \\\r\n cur_time_dist < ref_timestamp_dist[cur_stageref_hist_file_linkid]:\r\n ref_timestamp_dist[cur_stageref_hist_file_linkid] = cur_time_dist\r\n ref_timestamp_timestamp[cur_stageref_hist_file_linkid] = cur_stageref_hist_file_timestamp\r\n else:\r\n print(\"Ignoring '{0}' ({1}, {2}).\".format(cur_stageref_hist_file_name,\r\n cur_stageref_hist_file_timestamp,\r\n cur_stageref_hist_file_linkid))\r\n else:\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Ignoring '{0}' ({1} > {2}).\".format(cur_stageref_hist_file_name,\r\n cur_time_dist,\r\n 6 * 60 * 60),\r\n 1, debug_lvl)\r\n\r\n # copy all selected files\r\n print(\"Listed {0} files for copying.\".format(len(ref_timestamp_timestamp)))\r\n for cur_copy_linkid in ref_timestamp_timestamp.keys():\r\n cur_stageref_file_name = \"{0}_{1}.json\".format(ref_timestamp_timestamp[cur_copy_linkid], cur_copy_linkid) # TODO - this should be in a shared library\r\n cur_file_path = os.path.join(cur_stageref_source_folder_path, cur_stageref_file_name)\r\n shutil.copy(cur_file_path, cur_stageref_dest_folder_path)\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Copying '{0}' to '{1}'.\".format(cur_file_path,\r\n cur_stageref_dest_folder_path),\r\n 1, debug_lvl)\r\n\r\n\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Filled '{0}' folder.\".format(cur_stageref_dest_folder_path), 1,\r\n debug_lvl)\r\n\r\n # replace files for 'dischref_reference_ids' frame\r\n ## min_timestamp_limit = ref0_timestamp - 3600 # old\r\n ## max_timestamp_limit = ref0_timestamp + 3600 # old\r\n print(\"Got {0} dischref_reference_ids.\".format(len(dischref_reference_ids)))\r\n for cur_dischref_reference_id in dischref_reference_ids:\r\n cur_dischref_dest_folder_path = FolderDefinition.get_displayed_reprcomb_folder_path(sc_runset_id,\r\n sc_modelcomb_id,\r\n represcomb_id=sc_reprcomp_id,\r\n frame_id=\"dischref\",\r\n model_id=cur_dischref_reference_id)\r\n if clean_previous and os.path.exists(cur_dischref_dest_folder_path):\r\n shutil.rmtree(cur_dischref_dest_folder_path)\r\n os.makedirs(cur_dischref_dest_folder_path)\r\n cur_dischref_source_folder_path = FolderDefinition.get_historical_reprcomb_folder_path(sc_runset_id,\r\n represcomb_id=sc_reprcomp_id,\r\n frame_id=\"dischref\",\r\n model_id=cur_dischref_reference_id)\r\n\r\n # list all source files, getting the closest ones that is possible (range of 6 hours)\r\n ref_timestamp_dist = {}\r\n ref_timestamp_timestamp = {}\r\n all_dischref_hist_files = os.listdir(cur_dischref_source_folder_path)\r\n print(\"Evaluating {0} dischref files.\".format(len(all_dischref_hist_files)))\r\n for cur_dischref_hist_file_name in all_dischref_hist_files:\r\n cur_dischref_hist_file_timestamp = FileDefinition.obtain_hist_file_timestamp(cur_dischref_hist_file_name)\r\n cur_dischref_hist_file_linkid = FileDefinition.obtain_hist_file_linkid(cur_dischref_hist_file_name)\r\n cur_time_dist = abs(ref0_timestamp - cur_dischref_hist_file_timestamp)\r\n if cur_time_dist <= 6 * 60 * 60:\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Considering '{0}' file.\".format(cur_dischref_hist_file_name),\r\n 1, debug_lvl)\r\n\r\n if (cur_dischref_hist_file_linkid not in ref_timestamp_dist.keys()) or \\\r\n cur_time_dist < ref_timestamp_dist[cur_dischref_hist_file_linkid]:\r\n ref_timestamp_dist[cur_dischref_hist_file_linkid] = cur_time_dist\r\n ref_timestamp_timestamp[cur_dischref_hist_file_linkid] = cur_dischref_hist_file_timestamp\r\n else:\r\n print(\"Ignoring '{0}' ({1}, {2}).\".format(cur_dischref_hist_file_name,\r\n cur_dischref_hist_file_timestamp,\r\n cur_dischref_hist_file_linkid))\r\n\r\n else:\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Ignoring '{0}' file.\".format(cur_dischref_hist_file_name), 1,\r\n debug_lvl)\r\n\r\n # copy all selected files\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Listed {0} files of dischref for copying.\".format(\r\n len(ref_timestamp_timestamp)), 4, debug_lvl)\r\n for cur_copy_linkid in ref_timestamp_timestamp.keys():\r\n cur_dischref_file_name = \"{0}_{1}.json\".format(ref_timestamp_timestamp[cur_copy_linkid], cur_copy_linkid) # TODO - this should be in a shared library\r\n cur_file_path = os.path.join(cur_dischref_source_folder_path, cur_dischref_file_name)\r\n shutil.copy(cur_file_path, cur_dischref_dest_folder_path)\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Copying '{0}' to '{1}'.\".format(cur_file_path,\r\n cur_dischref_dest_folder_path),\r\n 1, debug_lvl)\r\n\r\n # replace 'common' files\r\n common_dest_folder_path = FolderDefinition.get_displayed_reprcomb_folder_path(sc_runset_id, sc_modelcomb_id,\r\n represcomb_id=sc_reprcomp_id,\r\n frame_id=\"common\")\r\n if clean_previous and os.path.exists(common_dest_folder_path):\r\n shutil.rmtree(common_dest_folder_path)\r\n os.makedirs(common_dest_folder_path)\r\n common_source_folder_path = FolderDefinition.get_historical_reprcomb_folder_path(sc_runset_id,\r\n represcomb_id=sc_reprcomp_id,\r\n frame_id=\"common\")\r\n all_common_hist_files = os.listdir(common_source_folder_path)\r\n for cur_common_hist_file_name in all_common_hist_files:\r\n cur_file_path = os.path.join(common_source_folder_path, cur_common_hist_file_name)\r\n shutil.copy(cur_file_path, common_dest_folder_path)\r\n\r\n Debug.dl(\"rpcbupd_hydrographmultiplespast: Filled '{0}' folder.\".format(common_dest_folder_path), 1, debug_lvl)\r\n\r\n# ####################################################### CALL ####################################################### #\r\n\r\nupdate_display_files(modelcomb_id_arg, runset_id_arg, timestamp_arg, debug_lvl=debug_level_arg)\r\n","sub_path":"backend/model_3_0_scripts/python/libs/rpcbupd_hydrographmultiplespast.py","file_name":"rpcbupd_hydrographmultiplespast.py","file_ext":"py","file_size_in_byte":19783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"419705314","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 23 20:32:19 2018\n\n@author: teatimeman\n\"\"\"\n\nfrom pydub import AudioSegment\n\nimport textgrid\nimport re\n\nimport os\nfrom os import listdir\nfrom os.path import isfile , join\n\ndef slicer(folder):\n audioSignalName = [signal for signal in listdir(folder) if isfile(join(folder,signal))]\n \n textgridFolder = folder + \"TextGrids/\"\n\n for signal in audioSignalName:\n newAudio = AudioSegment.from_wav(join(folder,signal))\n \n signalNumber = signal[0:3]\n signalFolder = \"Wave_sliced/\" + signalNumber + \"_slices/\"\n signalSlices = signalNumber + \"_part_\"\n \n if not os.path.exists(signalFolder):\n os.makedirs(signalFolder)\n \n sliceName = signalFolder + signalSlices\n \n textgridName = signalNumber + \"_wav.TextGrid\"\n \n T = textgrid.TextGrid();\n T.read(textgridFolder + textgridName)\n \n T.write\n w_tier = T.getFirst(\"Vokale\").intervals\n \n # Grenze zu den Wörtern mit einer Zahl ermitteln \n i = 0\n j = len(w_tier)-1\n while i < len(w_tier):\n if w_tier[j].mark == \"\" or re.match(\"\\\\d\",w_tier[j].mark[-1]) == None:\n j -= 1\n i += 1\n j +=1\n \n # Erstellen von den Waves\n i = 1\n while i in range(j):\n \n d = (w_tier[i+1].bounds()[1] - w_tier[i+1].bounds()[0])/2\n \n \n \n start = (w_tier[i].bounds()[0] - d) * 1000\n end = (w_tier[i+4].bounds()[1] + d) * 1000\n \n part = newAudio[int(start):int(end)] \n part.export(sliceName+str(i), format = \"wav\") \n \n \n \n i = i + 6\n\n#slicer(\"new_data/\") \n\n\nsignal = AudioSegment.from_wav(\"new_data/004.wav.wav\")\npart = signal[8200:10900]\npart.export(\"base_line_signal\",format = \"wav\")\n\n","sub_path":"Wave_slicer.py","file_name":"Wave_slicer.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"110802967","text":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\ntf.compat.v1.disable_eager_execution()\n\ndata=np.array(pd.read_csv('data.csv',header=None))\nX = np.concatenate((np.ones((data.shape[0],1)),data[:,:2]), axis=1)\ny = data[:,2]\nprint(y.shape)\n\nX_pl = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, X.shape[1]])\ny_pl = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None])\nweights = tf.Variable(tf.compat.v1.random_normal([X.shape[1]])/100.0)\ny_est = tf.nn.sigmoid(tf.reduce_sum(tf.multiply(X_pl,weights), axis=1)) #[-0.90111554 0.58614016 0.43306494]\n# y_est = 1 / (1 + tf.exp(-tf.reduce_sum(tf.multiply(X_pl,weights), axis=1))) #[-0.9011158 0.5861403 0.4330649]\n\n\ndef my_foal_function(y_true, y_pred):\n y_pred = tf.minimum(tf.maximum(y_pred,1E-10),1.0-1E-107)\n z1 = tf.multiply(y_true ,tf.compat.v1.log(y_pred)) + tf.multiply(1.0-y_true , tf.compat.v1.log(1.0-y_pred))\n z2 = -tf.reduce_sum(z1)\n # z2 = tf.compat.v1.Print(z2,[tf.shape(z1[:2])])\n return z2\n\nloss = my_foal_function(y_pl, y_est)\noptimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.01)\n\n\ntrain = optimizer.minimize(loss)\ninit = tf.compat.v1.global_variables_initializer()\ntraining_epochs = 1000\n\nweights_old = np.ones(X.shape[1])*np.inf\nweights_ = - weights_old\nepoch = 0\n\n\nwith tf.compat.v1.Session() as sess:\n sess.run(init)\n # for epoch in range(training_epochs):\n while np.linalg.norm(weights_old-weights_)>0.0000001:\n epoch += 1\n weights_old = weights_\n\n _, loss_, weights_ = sess.run([train, loss, weights], feed_dict={X_pl: X,\n y_pl: y})\n print(f\"iter {epoch+1}, loss = {loss_}, weitghts = {weights_}\")\n\n weights_,loss_, y_est_ = sess.run([weights, loss, y_est], feed_dict={X_pl: X, y_pl: y})\n\n\n\nprint(weights_)\nprint(\"_\"*10)\nprint(loss_)","sub_path":"Z_Deep_Learning_SGH/z4/program5_logistic_by_tf_v_mod.py","file_name":"program5_logistic_by_tf_v_mod.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"476329756","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport msgpack\nimport urlparse\nimport time\nimport socket\n\nfrom exceptions import RPCProtocolError, RPCError\nfrom constants import MSGPACKRPC_REQUEST, MSGPACKRPC_RESPONSE, SOCKET_RECV_SIZE\n\nlogger = logging.getLogger(__name__)\n\n\nclass RPCClient(object):\n def __init__(self, address=None, timeout=None, pack_encoding='utf-8', unpack_encoding='utf-8', reconnect_delay=0,\n tcp_no_delay=False):\n self._timeout = timeout\n\n self._msg_id = 0\n self._socket = None\n self._tcp_no_delay = tcp_no_delay\n\n self._packer = msgpack.Packer(encoding=pack_encoding)\n self._unpacker = msgpack.Unpacker(encoding=unpack_encoding, use_list=False)\n\n self._reconnect_delay = reconnect_delay\n\n url = urlparse.urlparse(address)\n if url.scheme == 'tcp':\n self.open_tcp(url)\n elif url.scheme == 'ipc':\n self.open_unixsocket(url)\n\n def open_tcp(self, url):\n \"\"\"Opens a tcp connection.\n :param url: url ParseResult\n \"\"\"\n assert self._socket is None, 'The connection has already been established'\n\n logger.debug('Opening a tcp msgpackrpc connection')\n self._socket = socket.create_connection((url.hostname, url.port))\n\n # set TCP NODELAY\n if self._tcp_no_delay:\n self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\n\n if self._timeout:\n self._socket.settimeout(self._timeout)\n\n def open_unixsocket(self, url):\n \"\"\"Opens a tcp connection.\n :param url: url ParseResult\n \"\"\"\n assert self._socket is None, 'The connection has already been established'\n\n logger.debug('Opening a unix socket msgpackrpc connection')\n self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n hostname = url.hostname or ''\n path = url.path or ''\n filename = hostname + path\n self._socket.connect(filename)\n\n if self._timeout:\n self._socket.settimeout(self._timeout)\n\n def close(self):\n \"\"\"Closes the connection.\"\"\"\n assert self._socket is not None, 'Attempt to close an unopened socket'\n\n logger.debug('Closing a msgpackrpc connection')\n try:\n self._socket.close()\n except Exception as e:\n logger.exception('An error has occurred while closing the socket. %s', str(e))\n\n self._socket = None\n\n def is_connected(self):\n \"\"\"Returns whether the connection has already been established.\n :rtype: bool\n \"\"\"\n if self._socket:\n return True\n else:\n return False\n\n def _call(self, method, *args):\n \"\"\"Calls a RPC method.\n :param str method: Method name.\n :param args: Method arguments.\n \"\"\"\n req = self._create_request(method, args)\n\n self._socket.sendall(req)\n\n while True:\n data = self._socket.recv(SOCKET_RECV_SIZE)\n if not data:\n raise IOError('Connection closed')\n self._unpacker.feed(data)\n try:\n response = self._unpacker.next()\n break\n except StopIteration:\n continue\n\n return self._parse_response(response)\n\n def call(self, method, *args):\n \"\"\"Calls a RPC method.\n :param str method: Method name.\n :param args: Method arguments.\n \"\"\"\n if self._reconnect_delay is 0:\n return self._call(method, *args)\n\n try:\n return self._call(method, *args)\n except Exception as e:\n logger.debug('Call except %s', str(e))\n self.close()\n while 1:\n try:\n logger.debug('Try reconnecting...')\n self.open()\n logger.debug('Reconnected.')\n return self._call(method, *args)\n except:\n time.sleep(self._reconnect_delay)\n\n def _create_request(self, method, args):\n self._msg_id += 1\n\n req = (MSGPACKRPC_REQUEST, self._msg_id, method, args)\n\n return self._packer.pack(req)\n\n def _parse_response(self, response):\n if len(response) != 4 or response[0] != MSGPACKRPC_RESPONSE:\n raise RPCProtocolError('Invalid protocol')\n\n (_, msg_id, error, result) = response\n\n if msg_id != self._msg_id:\n raise RPCError('Invalid Message ID')\n\n if error:\n raise RPCError(str(error))\n\n return result","sub_path":"mprpc/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"502356605","text":"import numpy as np\r\nimport time\r\n\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.model_selection import cross_val_score, StratifiedKFold\r\n\r\n\r\n# Open file for reading\r\n# dpt;X;Y;offsetX;offsetY\r\ntrain = np.genfromtxt(\"in/train.txt\", delimiter=\";\", skip_header=1)\r\n\r\n# Load data\r\nX_train = train[:,0:3]\r\n\r\n# Print start time\r\nstart = time.time()\r\nprint(\"Start reg\", time.strftime(\"%d.%m.%y %H:%M:%S\"))\r\n\r\n# train model\r\ndegree = np.arange(1,20+1)\r\n\r\nfor col in [3,4]:\r\n y_train = train[:,col] #3: offsetX, 4: offsetY\r\n mse_results = []\r\n r_results = []\r\n\r\n for d in degree:\r\n # fit model\r\n pip = Pipeline([(\"polynomial_features\", PolynomialFeatures(d)), (\"linear_regression\", LinearRegression(normalize=True))])\r\n pip.fit(X_train,y_train)\r\n \r\n # compute performance\r\n mse = cross_val_score(pip, X_train, y_train, scoring=\"neg_mean_squared_error\", cv=10, n_jobs=4)\r\n mse_results.append(np.mean(mse))\r\n # r = cross_val_score(pip, X_train, y_train, scoring=\"r2\", cv=10, n_jobs=1)\r\n # r_results.append(np.mean(r))\r\n \r\n\r\n # Save results\r\n sum = \"out/regX_summary.txt\" if col==3 else \"out/regY_summary.txt\"\r\n np.savetxt(sum, np.column_stack((degree, mse_results, r_results)), delimiter=\";\", header=\"d;mse\", fmt=\"%i;%1.2f\", comments=\"\")\r\n\r\n# print done message\r\nm, s = divmod(time.time() - start, 60)\r\nh, m = divmod(m, 60)\r\n \r\nprint(\"Done reg\", time.strftime(\"%d.%m.%y %H:%M:%S\"), \"duration: \", \"%d:%02d:%02d\" % (h, m, s))\r\n\r\n# 8:30h, 1core, 2 measures\r\n\r\n","sub_path":"03_correction/crossvalidation.py","file_name":"crossvalidation.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"526054441","text":"\"\"\"\nCopy from https://stackoverflow.com/questions/23460857/create-selectfield-options-with-custom-attributes-in-wtforms\n\nThis is veeeery useful and I want to backup this code.\n\nNOTE: This is not my own idea. Instead I took it from the link above.\n\"\"\"\n\nfrom wtforms.fields import SelectField\nfrom wtforms.widgets import Select, html_params, HTMLString\n\nclass AttribSelect(Select):\n \"\"\"\n Renders a select field that supports options including additional html params.\n\n The field must provide an `iter_choices()` method which the widget will\n call on rendering; this method must yield tuples of\n `(value, label, selected, html_attribs)`.\n \"\"\"\n\n def __call__(self, field, **kwargs):\n kwargs.setdefault('id', field.id)\n if self.multiple:\n kwargs['multiple'] = True\n html = ['')\n return HTMLString(''.join(html))\n\nclass AttribSelectField(SelectField):\n widget = AttribSelect()\n\n def iter_choices(self):\n for value, label, render_args in self.choices:\n yield (value, label, self.coerce(value) == self.data, render_args)\n\n def pre_validate(self, form):\n if self.choices:\n for v, _, _ in self.choices:\n if self.data == v:\n break\n else:\n raise ValueError(self.gettext('Is Not a valid choice'))\n \n \nif __name__ == \"__main__\":\n choices = [('', 'select a name', dict(disabled='disabled'))]\n choices.append(('alex', 'Alex', dict()))\n select_field = AttribSelectField('name', choices=choices, default='')\n # output: