diff --git "a/1408.jsonl" "b/1408.jsonl" new file mode 100644--- /dev/null +++ "b/1408.jsonl" @@ -0,0 +1,779 @@ +{"seq_id":"627778719","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\n\n'''\nElman-RNN 将当前时刻的输入 x_t 和上一时刻的隐状态 h_{t-1} 作为\n输入得到 h_t, 并以 h_t 全连接输出 y_t. 即最朴素的 RNN 结构:\n\t\n\th_t = f(W_{ih}x_t + b_ih + W_{hh}h_{t - 1} + b_hh)\n\n另外,这里是单层且只有一个 cell 的 RNN. 这对于 Jordan 和 Hybird \n是相同的.\n'''\nclass ElmanRNNCell(nn.Module):\n\n\t# 这里默认隐层维度 h_t 和输出层维度 y_t 是相同的.\n\tdef __init__(self, input_size, hidden_size):\n\t\tsuper(ElmanRNNCell, self).__init__()\n\n\t\tself.input_size = input_size\n\t\tself.hidden_size = hidden_size\n\n\t\tself.i2h_fc1 = nn.Linear(input_size, hidden_size)\n\t\tself.i2h_fc2 = nn.Linear(hidden_size, hidden_size)\n\t\tself.h2o_fc = nn.Linear(hidden_size, hidden_size)\n\n\tdef forward(self, input_, hidden):\n\t\thidden = F.sigmoid(self.i2h_fc1(input_) + self.i2h_fc2(hidden))\n\t\toutput = F.sigmoid(self.h2o_fc(hidden))\n\n\t\treturn output, hidden\n\n\n'''\nJordan-RNN 将当前时刻的输入 x_t 和上一时刻输出层输出 y_{t-1} 作为输入:\n\n\th_t = f(W_{ih}x_t + b_{ih} + W_{yh}y_{t-1} + b{yh})\n\n其余均相同.\n'''\nclass JordanRNNCell(nn.Module):\n\n\tdef __init__(self, input_size, hidden_size):\n\t\tsuper(JordanRNNCell, self).__init__()\n\n\t\tself.input_size = input_size\n\t\tself.hidden_size = hidden_size\n\n\t\tself.i2h_fc1 = nn.Linear(input_size, hidden_size)\n\t\tself.i2h_fc2 = nn.Linear(hidden_size, hidden_size)\n\t\tself.h2o_fc = nn.Linear(hidden_size, hidden_size)\n\n\t\t# 注意输出 y_0 需要一个初始值. 这里设置这个初始值是可训练的,\n\t\t# 猜测是假定 y_0 是从数据中学习到的一个先验知识.\n\t\tself.y_0 = nn.Parameter(torch.randn(1, hidden_size),\n\t\t\t\t\t\t\t requires_grad=True)\n\n\t# 输入句子 {w_1, w_2, ..., w_k} 到 Jordan-RNN 时, 输入 w_1 时,\n\t# 用 self.y_0 作为初始值,然后对于 w_i, i > 1 均用迭代值 hidden.\n\tdef forward(self, input_, hidden=None):\n\t\tif hidden is None:\n\t\t\thidden = self.y_0\n\n\t\thidden = F.sigmoid(self.i2h_fc1(input_) + self.i2h_fc2(hidden))\n\t\toutput = F.sigmoid(self.h2o_fc(hidden))\n\n\t\treturn output, hidden\n\n\n'''\nHybrid-RNN 是前两个模型的综合版本, 它以上一时刻的隐层 h_{t-1}, 上一时\n刻输出层 y_{t-1}, 此时的输入 x_t 作为总输入:\n\n\th_t = f(W_{ih}x_t + b_{ih} + W_{hh}h_{t-1} + b_hh + W_{yh}y_{t-1} + b_{yh})\n\t\n'''\nclass HybridRNNCell(nn.Module):\n\n\tdef __init__(self, input_size, hidden_size):\n\n\t\tsuper(HybridRNNCell, self).__init__()\n\n\t\tself.input_size = input_size\n\t\tself.hidden_size = hidden_size\n\n\t\tself.i2h_fc1 = nn.Linear(input_size, hidden_size)\n\t\tself.i2h_fc2 = nn.Linear(hidden_size, hidden_size)\n\t\tself.i2h_fc3 = nn.Linear(hidden_size, hidden_size)\n\t\tself.h2o_fc = nn.Linear(hidden_size, hidden_size)\n\n\t\tself.y_0 = nn.Parameter(torch.randn(1, hidden_size),\n\t\t\t\t\t\t requires_grad=True)\n\n\t# 注意这里输出和隐层都必须记录下来,其中在输入 w_1 时, 应该设置\n\t# output = None 调用 self.y_0, 其余均为 True.\n\tdef forward(self, input_, hidden, output=None):\n\t\tif output is None:\n\t\t\toutput = self.y_0\n\n\t\thidden = F.sigmoid(self.i2h_fc1(input_) + self.i2h_fc2(hidden) + self.i2h_fc3(output))\n\t\toutput = F.sigmoid(self.h2o_fc(hidden))\n\n\t\treturn output, hidden\n\n\n'''\n作为 Unit-RNN(单元 RNN) 的拓展, 支持处理 序列 + Batch 的数据. 初始化时\n设置不同的 cell_mode 参数可得到不同 Sequence-RNN. \n\n另外, 注意设置 batch_first 参数控制输入序列的格式.\n'''\nclass GeneralRNN(nn.Module):\n\n\t# 这里参数 cell_mode 指示 rnn 单元的具体内容. 受限于\n\t# elman, jordan, hybrid 三种.\n\tdef __init__(self, input_size, hidden_size,\n\t\t\t\t cell_mode=\"elman\", bidirectional=False, batch_first=True):\n\n\t\tsuper(GeneralRNN, self).__init__()\n\n\t\tself.cell_mode = cell_mode \n\t\tself.input_size = input_size\n\t\tself.hidden_size = hidden_size\n\t\tself.bidirectional = bidirectional\n\t\tself.batch_first = batch_first\n\n\t\tif cell_mode == \"elman\":\n\t\t\trnnCell = ElmanRNNCell\n\t\telif cell_mode == \"jordan\":\n\t\t\trnnCell = JordanRNNCell\n\t\telif cell_mode == \"hybrid\":\n\t\t\trnnCell = HybridRNNCell\n\t\telse:\n\t\t\traise RuntimeError(mode +\" doesn't exist.\")\n\n\t\tself.forward_rnn = rnnCell(input_size, hidden_size)\n\t\t# 如果设置 bidirectional = True, 则说明是双向 RNN.d\n\t\tif bidirectional:\n\t\t\tself.backward_rnn = rnnCell(input_size, hidden_size)\n\n\tdef _forward(self, inputs, hidden):\n\t\toutputs = []\n\t\tseq_len = inputs.size(1)\n\t\t# (batch_size, seq_len, n) ----> (seq_len, batch_size, n).\n\t\tinputs = inputs.transpose(0, 1)\n\n\t\toutput = None\n\t\tfor i in range(seq_len):\n\t\t\tinput_ = inputs[i] # (batch_size, n).\n\t\t\tif self.cell_mode == \"hybrid\":\n\t\t\t\toutput, hidden = self.forward_rnn(input_, hidden, output)\n\t\t\telse:\n\t\t\t\toutput, hidden = self.forward_rnn(input_, hidden)\n\t\t\toutputs.append(output)\n\n\t\treturn outputs, hidden\n\n\t# 双向 RNN 的反向过程, 与前向过程是类似的.\n\tdef _backward(self, inputs, hidden):\n\n\t\toutputs = []\n\t\tseq_len = inputs.size(1)\n\t\tinputs = inputs.transpose(0, 1)\n\n\t\toutput = None\n\t\tfor i in range(seq_len):\n\t\t\t# print(i, seq_len)\n\t\t\t# print(inputs.size())\n\t\t\tinput_ = inputs[seq_len - i - 1]\n\t\t\tif self.cell_mode == \"hybrid\":\n\t\t\t\toutput, hidden = self.backward_rnn(input_, hidden, output)\n\t\t\telse:\n\t\t\t\toutput, hidden = self.backward_rnn(input_, hidden)\n\t\t\toutputs.append(output)\n\n\t\toutputs.reverse()\n\t\treturn outputs, hidden\n\n\tdef forward(self, inputs, hidden=None):\n\t\t# 如果是 Jordan-RNN, 初始化时要求 hidden = None.\n\t\tif hidden is None and self.cell_mode != \"jordan\":\n\t\t\tbatch_size = inputs.size(0)\n\t\t\thidden = Variable(torch.zeros(batch_size, self.hidden_size))\n\n\t\toutput_forward, hidden_forward = self._forward(inputs, hidden)\n\t\toutput_forward = torch.stack(output_forward, dim=0)\n\t\tif not self.bidirectional:\n\t\t\tif self.batch_first:\n\t\t\t\toutput_forward = output_forward.transpose(0, 1)\n\t\t\treturn output_forward, hidden_forward\n\n\t\t# print(inputs, hidden)\n\t\toutput_backward, hidden_backward = self._backward(inputs, hidden)\n\t\thidden = torch.cat([hidden_forward, hidden_backward], dim=hidden_forward.dim()-1)\n\t\toutput_backward = torch.stack(output_backward, dim=0)\n\n\t\toutput = torch.cat([output_forward, output_backward], dim=output_backward.dim()-1)\n\t\tif self.batch_first:\n\t\t\toutput = output.transpose(0, 1)\n\n\t\treturn output, hidden\n\n\n'''\n更高阶的抽象模型, 支持 LSTM 单元, 注意这里也是序列-RNN.\n'''\nclass SlotFillingRNN(nn.Module):\n\t\n\tdef __init__(self, vocab_size, label_size, cell_mode=\"elman\", \n\t\t\t\t bidirectional=False, is_training=True):\n\n\t\tsuper(SlotFillingRNN, self).__init__()\n\n\t\tself.is_training = is_training\n\t\thidden_size = 75\n\t\tembedding_dim = 100\n\n\t\tself.embedding = nn.Embedding(vocab_size, embedding_dim)\n\n\t\tif cell_mode == \"lstm\":\n\t\t\tself.rnn = nn.LSTM(input_size=embedding_dim,\n\t\t\t\t\t\t\t hidden_size=hidden_size,\n\t\t\t\t\t\t\t bidirectional=bidirectional,\n\t\t\t\t\t\t\t batch_first=True)\n\t\telse:\n\t\t\tself.rnn = GeneralRNN(input_size=embedding_dim,\n\t\t\t\t\t\t\t\t hidden_size=hidden_size,\n\t\t\t\t\t\t\t\t cell_mode=cell_mode,\n\t\t\t\t\t\t\t\t bidirectional=bidirectional,\n\t\t\t\t\t\t\t\t batch_first=True)\n\n\t\tif bidirectional:\n\t\t\tself.fc = nn.Linear(2 * hidden_size, label_size)\n\t\telse:\n\t\t\tself.fc = nn.Linear(hidden_size, label_size)\n\n\tdef forward(self, X):\n\t\tembed = self.embedding(X)\n\t\tembed = F.dropout(embed, 0.2, training=self.is_training)\n\t\toutputs, _ = self.rnn(embed)\n\t\t# print(outputs.size())\n\t\t# print(self.fc)\n\n\t\toutputs = self.fc(outputs.squeeze(0))\n\t\t# try :\n\t\t# \toutputs = self.fc(outputs.squeeze())\n\t\t# except Exception:\n\t\t# \tprint(outputs.size())\n\t\t# \tprint(outputs.squeeze(0).size())\n\t\t# \texit(0)\n\n\t\treturn outputs\t\t\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pckg/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"353108234","text":"from game_objects.battlefield_objects import Obstacle\nfrom battlefield.Cell import Cell\nfrom mechanics.damage import DamageTypes, Damage\nfrom mechanics.events import DamageEvent\nfrom mechanics.combat.Attack import Attack\nimport pytest\n\n@pytest.fixture()\ndef obstacle(game_hvsp):\n obstacle = Obstacle(\"dummy\", 500, game=game_hvsp)\n game_hvsp.add_obstacle(obstacle, Cell(1, 2))\n return obstacle\n\n\n\ndef test_can_take_damage(obstacle):\n health_before = obstacle.health\n dmg = Damage(50, DamageTypes.SONIC)\n DamageEvent(dmg, obstacle)\n\n health_after = obstacle.health\n assert health_after < health_before\n\n\ndef test_can_be_destroyed(obstacle, empty_game):\n\n empty_game.add_obstacle(obstacle)\n assert obstacle in empty_game.obstacles\n\n obstacle.health -= 999999\n assert obstacle not in empty_game.obstacles\n\n\n\ndef test_can_be_attacked(obstacle, hero, no_chances):\n health_before = obstacle.health\n\n Attack.melee_attack(hero, obstacle)\n\n health_after = obstacle.health\n\n assert health_before > health_after\n","sub_path":"tests/battlefield/obstacles/test_can_be_destroyed.py","file_name":"test_can_be_destroyed.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"367397241","text":"# Copyright (c) ONNX Project Contributors\n\n# SPDX-License-Identifier: Apache-2.0\n# pylint: disable=R0912,R0913,R0914,R0915,R1702,R1716,W0221\n\nimport numpy as np\n\nfrom onnx.reference.op_run import OpRun\n\n\nclass GridSample(OpRun):\n def _gs_denormalize(self, n, length: int, align_corners: bool): # type: ignore\n if align_corners:\n x = (n + 1) / 2.0 * (length - 1)\n else:\n x = ((n + 1) * length - 1) / 2.0\n return x\n\n def _gs_reflect(self, x, x_min, x_max): # type: ignore\n \"\"\"\n Reflect by the near border till within the borders\n Use float for borders to avoid potential issues with integer T\n \"\"\"\n fx = x\n rng = x_max - x_min\n if fx < x_min:\n dx = x_min - fx\n n = int(dx / rng)\n r = dx - n * rng\n if n % 2 == 0:\n fx = x_min + r\n else:\n fx = x_max - r\n elif fx > x_max:\n dx = fx - x_max\n n = int(dx / rng)\n r = dx - n * rng\n if n % 2 == 0:\n fx = x_max - r\n else:\n fx = x_min + r\n return fx\n\n def _gs_get_cubic_coeffs(self, x, coeffs): # type: ignore\n \"\"\"\n Calculate cubic convolution interpolation coefficients\n ROBERT G. KEYS https://ieeexplore.ieee.org/document/1163711\n Use float to avoid potential issues with integer.\n \"\"\"\n cubic_alpha = -0.75\n x = abs(x)\n coeffs[0] = (\n (cubic_alpha * (x + 1) - 5 * cubic_alpha) * (x + 1) + 8 * cubic_alpha\n ) * (x + 1) - 4 * cubic_alpha\n coeffs[1] = ((cubic_alpha + 2) * x - (cubic_alpha + 3)) * x * x + 1\n coeffs[2] = ((cubic_alpha + 2) * (1 - x) - (cubic_alpha + 3)) * (1 - x) * (\n 1 - x\n ) + 1\n coeffs[3] = (\n (cubic_alpha * (2 - x) - 5 * cubic_alpha) * (2 - x) + 8 * cubic_alpha\n ) * (2 - x) - 4 * cubic_alpha\n\n def _gs_bicubic_interpolate(self, p, x, y): # type: ignore\n v = np.empty((4,), dtype=p.dtype)\n coeffs = np.empty((4,), dtype=p.dtype)\n self._gs_get_cubic_coeffs(x, coeffs)\n for i in range(4):\n v[i] = coeffs @ p[i, :]\n self._gs_get_cubic_coeffs(y, coeffs)\n return coeffs @ v\n\n def _clamp(self, val, lo, hi): # type: ignore\n if val < lo:\n return lo\n if val > hi:\n return hi\n return val\n\n def _pixel_at_grid(self, image, r: int, c: int, border, padding_mode): # type: ignore\n H, W = image.shape\n if padding_mode == \"zeros\":\n if c >= 0 and c < W and r >= 0 and r < H:\n pixel = image[r, c] # image[r * W + c]\n else:\n pixel = 0\n elif padding_mode == \"border\":\n c = self._clamp(c, 0, W - 1)\n r = self._clamp(r, 0, H - 1)\n pixel = image[r, c]\n else: # padding_mode == \"reflection\"\n c = int(self._gs_reflect(c, border[0], border[2]))\n r = int(self._gs_reflect(r, border[1], border[3]))\n pixel = image[r, c] # image[r * W + c]\n return pixel\n\n def _run( # type: ignore\n self, X, grid, mode=None, padding_mode=None, align_corners=None\n ):\n mode = mode or self.mode # type: ignore\n padding_mode = padding_mode or self.padding_mode # type: ignore\n align_corners = align_corners or self.align_corners # type: ignore\n\n x_dims = X.shape\n grid_dims = grid.shape\n\n if len(x_dims) != 4 or len(grid_dims) != 4:\n raise RuntimeError(\n f\"X and grid must be 4D tensors not {len(x_dims)} or {len(grid_dims)}.\"\n )\n\n N = x_dims[0]\n C = x_dims[1]\n H_in = x_dims[2]\n W_in = x_dims[3]\n H_out = grid_dims[1]\n W_out = grid_dims[2]\n\n y_dims = (N, C, H_out, W_out)\n size = N * C * H_out * W_out\n if size == 0:\n return np.array([], dtype=X.dtype)\n\n Y = np.empty(y_dims, dtype=X.dtype)\n\n # Force float here to avoid possible issue in integer T case\n x_min = -0.5\n x_max = W_in - 0.5\n y_min = -0.5\n y_max = H_in - 0.5\n\n if align_corners:\n x_min = 0.0\n x_max = W_in - 1.0\n y_min = 0.0\n y_max = H_in - 1.0\n\n border = (x_min, y_min, x_max, y_max)\n\n for n in range(N):\n grid_data = grid[n]\n\n for c in range(C):\n X_data = X[n, c]\n\n for oy in range(H_out):\n for ox in range(W_out):\n gridpoint = grid_data[oy, ox]\n\n nx = gridpoint[0] # normalized location\n ny = gridpoint[1]\n x = self._gs_denormalize(\n nx, W_in, align_corners\n ) # actual location\n y = self._gs_denormalize(ny, H_in, align_corners)\n\n if mode == \"nearest\":\n x = np.rint(x) # nearbyintf(x)\n y = np.rint(y) # nearbyintf(y)\n\n if (\n x < x_min or x > x_max or y < y_min or y > y_max\n ): # out of bound\n if padding_mode == \"border\":\n # use original border in both align_corner cases\n x = self._clamp(x, 0, W_in - 1)\n y = self._clamp(y, 0, H_in - 1)\n elif padding_mode == \"reflection\":\n x = self._gs_reflect(x, x_min, x_max)\n y = self._gs_reflect(y, y_min, y_max)\n\n if mode == \"nearest\":\n # x, y are integers in all padding modes\n Y[n, c, oy, ox] = self._pixel_at_grid(\n X_data, int(y), int(x), border, padding_mode\n )\n continue\n\n if mode == \"bilinear\":\n x1 = int(np.floor(x))\n y1 = int(np.floor(y))\n x2 = x1 + 1\n y2 = y1 + 1\n\n p11 = self._pixel_at_grid(\n X_data, y1, x1, border, padding_mode\n )\n p12 = self._pixel_at_grid(\n X_data, y1, x2, border, padding_mode\n )\n p21 = self._pixel_at_grid(\n X_data, y2, x1, border, padding_mode\n )\n p22 = self._pixel_at_grid(\n X_data, y2, x2, border, padding_mode\n )\n\n dx2 = x2 - x\n dx1 = x - x1\n dy2 = y2 - y\n dy1 = y - y1\n Y[n, c, oy, ox] = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (\n dx2 * p21 + dx1 * p22\n )\n\n if mode == \"bicubic\":\n x0 = int(np.floor(x)) - 1 # top-left corner of the bbox\n y0 = int(np.floor(y)) - 1\n p = np.empty((4, 4), dtype=X.dtype)\n for h in range(4):\n for w in range(4):\n p[h, w] = self._pixel_at_grid(\n X_data, h + y0, w + x0, border, padding_mode\n )\n dx = x - x0 - 1\n dy = y - y0 - 1\n Y[n, c, oy, ox] = self._gs_bicubic_interpolate(p, dx, dy)\n return (Y.astype(X.dtype),)\n","sub_path":"onnx/reference/ops/op_grid_sample.py","file_name":"op_grid_sample.py","file_ext":"py","file_size_in_byte":8048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"44784165","text":"# Fast IO\n\nimport sys\ninput = sys.stdin.readline\ndef print(x, end='\\n'):\n sys.stdout.write(str(x) + end)\n\n# IO helpers\n\ndef get_int():\n return int(input())\ndef get_list_ints():\n return list(map(int, input().split()))\ndef get_char_list():\n s = input()\n return list(s[:len(s) - 1])\ndef get_tuple_ints():\n return tuple(map(int, input().split()))\ndef print_iterable(p):\n print(\" \".join(map(str, p)))\n\ndef main():\n\n n, m = get_tuple_ints()\n a = get_list_ints()\n\n visited = [False for i in range(n)]\n g = [[] for i in range(n)]\n components = [[] for i in range(n)]\n\n for i in range(m):\n u, v = get_tuple_ints()\n u -= 1\n v -= 1\n g[u].append(v)\n g[v].append(u)\n\n component = 0\n for v in range(n):\n if visited[v]:\n continue\n stack = [v]\n while stack:\n v = stack[-1]\n stack.pop()\n if not visited[v]:\n components[component].append(v)\n for u in g[v]:\n if not visited[u]:\n stack.append(u)\n visited[v] = True\n component += 1\n\n total_components = component\n indices = sorted([i for i in range(n)], key=lambda x : -a[x])\n components.sort(key=lambda x : -len(x))\n\n current_rank = 0\n assigned_vertex = [0 for i in range(n)]\n for component in range(total_components):\n for x in components[component]:\n assigned_vertex[indices[current_rank]] = x + 1\n current_rank += 1\n\n print_iterable(assigned_vertex)\n pass\n\nif __name__ == '__main__':\n main()\n","sub_path":"sols-to-be-published/py-sols/deserted-freshers/sol-dfs.py","file_name":"sol-dfs.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"64236047","text":"# -*- coding: utf-8 -*-\r\n# Chap 8 - ProjectileMotion IV: Uncertainty\r\n# P8.1 - Assign uncertainties to all relevant variables in your Euler’s method.\r\nfrom random import uniform\r\nfrom matplotlib import pyplot\r\nfrom numpy import *\r\n\r\ngMean = 9.8\r\ndeltag = 0.2\r\nrMean = 0.05\r\ndeltar = 0.01\r\nCMean = 1.0\r\ndeltaC = 0.0005\r\npMean = 1.3\r\ndeltap = 0.00008\r\nvMean = 5.5\r\ndeltav = 0.5\r\nthetaMean = radians(25)\r\ndeltatheta = radians(5)\r\nmMean = 0.5\r\ndeltam = 0.001\r\n\r\narea = (pi * (rMean**2))\r\nx0 = 0.0\r\ny0 = 0.0\r\ndt = 0.01\r\nt = [0]\r\n\r\nranges = []\r\npyplot.figure(1)\r\nfor i in range(50): \r\n # Will produce 10 launches.\r\n # Get a random number from a uniform distribution\r\n g = uniform(gMean - deltag, gMean + deltag)\r\n r = uniform(rMean - deltar, rMean + deltar)\r\n C = uniform(CMean - deltaC, CMean + deltaC)\r\n p = uniform(pMean - deltap, pMean + deltap)\r\n v = uniform(vMean - deltav, vMean + deltav)\r\n theta = uniform(thetaMean - deltatheta, thetaMean + deltatheta)\r\n m = uniform(mMean - deltam, mMean + deltam)\r\n\r\n B = 0.5 * p * area * C\r\n x = [x0]\r\n y = [y0]\r\n vx = [v * cos(theta)]\r\n vy = [v * sin(theta)]\r\n\r\n #Euler's loop from previous week.\r\n #Each time this loop finishes, we have\r\n #a new trajectory\r\n while y[-1] >= 0:\r\n #< Euler's loop from previous weeks >\r\n v = sqrt(vx[-1]**2 + vy[-1]**2)\r\n x.append(x[-1] + vx[-1] * dt)\r\n y.append(y[-1] + vy[-1] * dt)\r\n vx.append(vx[-1] - (B/m*v*vx[-1]*dt))\r\n vy.append(vy[-1] - (B/m*v*vy[-1]*dt)-(g*dt))\r\n t.append(t[-1] + dt)\r\n pyplot.plot(x,y) # Plot this trajectory\r\n \r\n ranges.append(x[-1]) # Save the range for this trajectory\r\n\r\n# P8.2 - Using straight line segments, build a Python function that returns the thrust force as a function of time.\r\n# This is accomplished in the code above\r\n\r\n# P8.3 - Explain to your group how this code works.\r\n# I talked to my group about how this code works and answered any questions they had.\r\n\r\n# P8.4 - Plot the histogram and print the mean and standard deviation for the range.\r\nprint (mean(ranges))\r\nprint (std(ranges))\r\n\r\npyplot.figure(2)\r\npyplot.hist(ranges)\r\npyplot.show()\r\n\r\n# Conclusion:\r\n# P8.5 (a) - Which input variable uncertainty affects the uncertainty in the range of your projectile the most?\r\n# Based on trial and error we found it to be the initial velocity uncertainty.\r\n\r\n# P8.5 (b) - Which input variable uncertainty affects the uncertainty in the impact speed of your projectile the most?\r\n# Based on trial and error we found it to be the initial velocity uncertainty.\r\n\r\n# P8.5 (c) - Which input variable uncertainty affects the uncertainty in the max height of your projectile the most?\r\n# Based on trial and error we found it to be the angle uncertainty.\r\n","sub_path":"Week 8 Lab.py","file_name":"Week 8 Lab.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"255990972","text":"from linked_lists.linked_list_node import LinkedListNode\n\n\nclass LinkedList(object):\n \"\"\"\n Singly Linked List\n \"\"\"\n\n def __init__(self):\n self.head = None\n\n def push(self, data):\n \"\"\"\n Add a node to the front of the list\n :param data: data to add\n \"\"\"\n new_head = LinkedListNode(data)\n new_head.next = self.head\n self.head = new_head\n\n def print_list(self):\n \"\"\"\n Utility to iterate over list and print each node\n \"\"\"\n head = self.head\n while head:\n print(head.data)\n head = head.next\n\n def sorted_node_insert(self, node):\n \"\"\"\n Insert a node in its sorted position\n :param node: node to insert\n \"\"\"\n if self.head is None:\n node.next = self.head\n self.head = node\n elif self.head.data >= node.data:\n node.next = self.head\n self.head = node\n else:\n curr = self.head\n while curr.next and curr.next.data < node.data:\n curr = curr.next\n\n node.next = curr.next\n curr.next = node\n\n def delete_node(self, node):\n \"\"\"\n Given a linked list node, find and remove it\n :param node: node to delete\n \"\"\"\n if self.head == node:\n if self.head.next is None:\n raise Exception(\"Cannot have empty list\")\n\n # copy next node data to head\n self.head.data = self.head.next.data\n\n # store next node link\n node = self.head.next\n\n # remove next node link\n self.head.next = node.next.next\n\n else:\n prev = self.head\n # get node before node to be deleted\n while prev.next is not None and prev.next is not node:\n prev = prev.next\n\n # check that node is in list\n if prev.next is None:\n raise Exception(\"Node to be deleted does not exist\")\n\n prev.next = prev.next.next\n","sub_path":"linked_lists/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"240364940","text":"#!/usr/bin/env python\n\"\"\"\nCalculate systematic uncertainty caused by branching fraction of D->Kpipi\n\"\"\"\n\n__author__ = \"Maoqiang JING \"\n__copyright__ = \"Copyright (c) Maoqiang JING\"\n__created__ = \"[2020-04-07 Tue 23:29]\"\n\nimport ROOT\nfrom ROOT import *\nimport sys, os\nimport logging\nfrom math import *\nlogging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\ngStyle.SetOptTitle(0)\ngStyle.SetOptTitle(0)\n\ndef usage():\n sys.stdout.write('''\nNAME\n cal_diff.py\n\nSYNOPSIS\n ./cal_diff.py\n\nAUTHOR\n Maoqiang JING \n\nDATE\n April 2020\n\\n''')\n\ndef cal_diff():\n if not os.path.exists('./txts/'):\n os.makedirs('./txts/')\n path_sys_err = './txts/sys_err_BF.txt'\n f_sys_err = open(path_sys_err, 'w')\n\n ecms = [4190, 4200, 4210, 4220, 4230, 4237, 4245, 4246, 4260, 4270, 4280, 4290, 4310, 4315, 4340, 4360, 4380, 4390, 4400, 4420, 4440, 4470, 4530, 4575, 4600, 4610, 4620, 4640, 4660, 4680, 4700, 4740, 4750, 4780, 4840, 4914, 4946]\n for ecm in ecms:\n out = str(ecm/1000.) + '\\t' + str(1.71) + '\\n'\n f_sys_err.write(out)\n f_sys_err.close()\n\nif __name__ == '__main__':\n cal_diff()\n","sub_path":"python/sys_err/BF/cal_diff.py","file_name":"cal_diff.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"473782203","text":"portion_down_payment = 0.25\nr = 0.04\ntotal_cost = 1000000.0\nsemi_annual_raise = 0.07\n\nstarting_annual_salary = float(input(\"Enter your starting annual salary: \"))\n\n\nsearch_flag = False\nbisection_search_counter = 0\nup_bound = 10000\nlow_bound = 0\nsavings_rate = up_bound\n\nwhile search_flag == False:\n\tcurrent_savings = 0.0\n\tannual_salary = starting_annual_salary\n\tfor month in range(36):\n\t\tmonthly_salary = annual_salary/12\n\n\t\tif month % 6 == 0 and month != 0:\n\t\t\tannual_salary *= 1+semi_annual_raise \n\n\t\tportion_saved = savings_rate/10000\n\t\tcurrent_savings = current_savings*(1+r/12)+portion_saved*monthly_salary\n\n\n\tif savings_rate == 10000 and total_cost*portion_down_payment > current_savings+100:\n\t\tprint(\"It is not possible to pay the down payment in three years\")\n\t\tsearch_flag = True\n\telif current_savings-total_cost*portion_down_payment > 100:\n\t\tup_bound = savings_rate\n\t\tsavings_rate = low_bound+(up_bound-low_bound)/2\n\t\tbisection_search_counter += 1\n\telif current_savings-total_cost*portion_down_payment < -100:\n\t\tlow_bound = savings_rate\n\t\tsavings_rate = low_bound+(up_bound-low_bound)/2\n\t\tbisection_search_counter += 1\n\telse:\n\t\tbisection_search_counter += 1\n\t\tprint(\"Best savings rate:\", savings_rate/10000)\n\t\tprint(\"Steps in bisection search:\", bisection_search_counter)\n\t\tsearch_flag = True\n\n\n\n","sub_path":"6.0001/ps1/ps1c.py","file_name":"ps1c.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"276465597","text":"from augmentations import CustomCutout\nfrom default_config import basic_cfg\nimport albumentations as A\nimport os\n\ncfg = basic_cfg\ncfg.debug = True\n\n# paths\ncfg.name = os.path.basename(__file__).split(\".\")[0]\ncfg.data_dir = \"input/\"\ncfg.data_folder = cfg.data_dir + \"train_05/\"\ncfg.train_df = cfg.data_dir + \"train_image_level_folded_v3.csv\"\ncfg.output_dir = f\"output/models/{os.path.basename(__file__).split('.')[0]}\"\n\ncfg.test = True\ncfg.test_df = cfg.data_dir + \"test_image_level_v2.csv\"\ncfg.test_data_folder = cfg.data_dir + \"test_05/\"\n\n# OPTIMIZATION & SCHEDULE\ncfg.lr = 0.003\ncfg.optimizer = \"AdamW\"\ncfg.epochs = 14\ncfg.batch_size = 16\ncfg.mixed_precision = True\ncfg.pin_memory = False\n# MODEL\ncfg.model = \"ps_mdl_effdet_1\"\ncfg.backbone = \"efficientdet_q2\"\ncfg.in_channels = 1\n# DATASET\ncfg.dataset = \"ps_ds_1\"\ncfg.normalization = \"simple\"\n\ncfg.scale = 0.5\n\ncfg.pool = \"gem\"\ncfg.gem_p_trainable = True\n\n# TRAINING\ncfg.gpu = 0\ncfg.num_workers = 16\n\ncfg.image_size = (768, 768)\n\ncfg.study_weight = 0.1\n\ncfg.mixup = 0.0\ncfg.cutmix = 0.0\ncfg.mosaic = 0.0\ncfg.mixadd = False\n\ncfg.loss = \"bce\"\ncfg.pp_transformation = \"softmax\"\n\ncfg.train = True\n\ncfg.train_aug = A.Compose(\n [\n A.ShiftScaleRotate(shift_limit=0.0625, scale_limit=0.1, rotate_limit=25, p=0.5),\n A.Resize(cfg.image_size[0], cfg.image_size[1], p=1.0),\n A.HorizontalFlip(p=0.5),\n A.RandomBrightnessContrast(\n brightness_limit=(-0.2, 0.2), contrast_limit=(-0.2, 0.2), p=0.5\n ),\n CustomCutout(\n fill_value=0,\n bbox_removal_threshold=0.25,\n min_cutout_size=64,\n max_cutout_size=256,\n p=1.0,\n )\n ],\n bbox_params=A.BboxParams(format=\"pascal_voc\", min_area=0, min_visibility=0),\n)\n\ncfg.val_aug = A.Compose(\n [A.Resize(cfg.image_size[0], cfg.image_size[1], p=1.0),],\n bbox_params=A.BboxParams(format=\"pascal_voc\", min_area=0, min_visibility=0),\n)\n","sub_path":"configs/cfg_ps_35.py","file_name":"cfg_ps_35.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"87494702","text":"from flask import Flask, g\nfrom flask import render_template, flash, redirect, url_for\n\n# This import makes our connection to the models\nimport models\nfrom forms import SubForm, PostForm, CommentForm\n\n\nDEBUG = True\nPORT = 8000\n\napp = Flask(__name__)\napp.secret_key = 'adkjfalj.adflja.dfnasdf.asd'\n\n\n@app.before_request\ndef before_request():\n g.db = models.DATABASE\n g.db.connect()\n\n\n@app.after_request\ndef after_request(response):\n g.db.close()\n return response\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n # A Form Variable Representing the SubForm\n form = SubForm()\n\n # check if the form submission is valid\n if form.validate_on_submit():\n # if it is, create a new Sub and redirect the user\n models.Sub.create(\n name=form.name.data.strip(),\n description=form.description.data.strip())\n\n return redirect('/r')\n # if it isn't, send them back to the form\n return render_template(\"new_sub.html\", form=form)\n\n\n@app.route('/r')\n@app.route('/r/', methods=['GET', 'POST'])\ndef r(sub=None):\n if sub == None:\n # get all subs\n subs = models.Sub.select().limit(100)\n # send the retrieved subs to our subs.html template\n return render_template(\"subs.html\", subs=subs)\n else:\n # use the Sub ID to find the right Sub\n sub_id = int(sub)\n sub = models.Sub.get(models.Sub.id == sub_id)\n posts = sub.posts\n\n form = PostForm()\n if form.validate_on_submit():\n models.Post.create(\n user=form.user.data.strip(),\n title=form.title.data.strip(),\n text=form.text.data.strip(),\n sub=sub\n )\n\n return redirect(f'/r/{sub_id}')\n # send the found sub to the template\n return render_template('sub.html', sub=sub, form=form, posts=posts)\n\n\n@app.route('/posts')\n@app.route('/posts/', methods=['GET', 'POST'])\ndef posts(id=None):\n if id == None:\n posts = models.Post.select().limit(100)\n return render_template('posts.html', posts=posts)\n else:\n post_id = int(id)\n posts = models.Post.get(models.Post.id == post_id)\n comments = posts.comments\n\n form = CommentForm()\n if form.validate_on_submit():\n models.Comment.create(\n user=form.user.data.strip(),\n text=form.text.data.strip(),\n posts=posts\n )\n\n return redirect(f'/posts/{post_id}')\n return render_template('post.html', post=posts, form=form, comments=comments)\n\n\nif __name__ == '__main__':\n models.initialize()\n app.run(debug=DEBUG, port=PORT)\n","sub_path":"brandon-vagarioustoast/week-8/Flask-Models/starter-code/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"76900648","text":"import os\nimport sys\nfrom unittest.mock import MagicMock\n\nimport pytest\n\nfrom prefect.utilities.filesystems import parse_path, read_bytes_from_path\n\n\nclass Test_parse_path:\n @pytest.mark.parametrize(\"scheme\", [None, \"local\", \"file\"])\n def test_local_file_scheme_normalized(self, scheme):\n path = \"/path/to/file.txt\"\n unparsed = f\"{scheme}://{path}\" if scheme else path\n parsed = parse_path(unparsed)\n assert parsed.scheme == \"file\"\n assert parsed.netloc == \"\"\n assert parsed.path == path\n\n @pytest.mark.skipif(os.name != \"nt\", reason=\"Windows only test\")\n @pytest.mark.parametrize(\n \"path\",\n [\n \"c:/path/to/file.txt\",\n \"c:\\\\path\\\\to\\\\file.txt\" \"\\\\path\\\\to\\\\file.txt\",\n ],\n )\n def test_windows_local_paths(self, path):\n parsed = parse_path(path)\n assert parsed.scheme == \"file\"\n assert parsed.netloc == \"\"\n assert parsed.path == path\n\n def test_all_components(self):\n parsed = parse_path(\"s3://bucket/path/to/file.txt\")\n assert parsed.scheme == \"s3\"\n assert parsed.netloc == \"bucket\"\n assert parsed.path == \"/path/to/file.txt\"\n\n\nclass Test_read_bytes_from_path:\n @pytest.mark.parametrize(\"scheme\", [\"agent\", None])\n def test_read_local_file(self, tmpdir, scheme):\n if scheme and sys.platform == \"win32\":\n pytest.skip(\"Scheme not supported for Windows file paths\")\n\n path = str(tmpdir.join(\"test.yaml\"))\n with open(path, \"wb\") as f:\n f.write(b\"hello\")\n\n path_arg = (\n path\n if scheme is None\n else \"agent://\" + os.path.splitdrive(path)[1].replace(\"\\\\\", \"/\")\n )\n res = read_bytes_from_path(path_arg)\n assert res == b\"hello\"\n\n @pytest.mark.parametrize(\"scheme\", [\"http\", \"https\"])\n def test_read_http_file(self, monkeypatch, scheme):\n pytest.importorskip(\"requests\")\n\n url = f\"{scheme}://some/file.json\"\n\n requests_get = MagicMock(return_value=MagicMock(content=b\"testing\"))\n monkeypatch.setattr(\"requests.get\", requests_get)\n\n res = read_bytes_from_path(url)\n assert requests_get.call_args[0] == (url,)\n assert res == b\"testing\"\n\n def test_read_gcs(self, monkeypatch):\n pytest.importorskip(\"prefect.utilities.gcp\")\n client = MagicMock()\n monkeypatch.setattr(\n \"prefect.utilities.gcp.get_storage_client\", MagicMock(return_value=client)\n )\n res = read_bytes_from_path(\"gcs://mybucket/path/to/thing.yaml\")\n assert client.bucket.call_args[0] == (\"mybucket\",)\n bucket = client.bucket.return_value\n assert bucket.get_blob.call_args[0] == (\"path/to/thing.yaml\",)\n blob = bucket.get_blob.return_value\n assert blob.download_as_bytes.called\n assert blob.download_as_bytes.return_value is res\n\n def test_read_s3(self, monkeypatch):\n pytest.importorskip(\"prefect.utilities.aws\")\n client = MagicMock()\n monkeypatch.setattr(\n \"prefect.utilities.aws.get_boto_client\", MagicMock(return_value=client)\n )\n res = read_bytes_from_path(\"s3://mybucket/path/to/thing.yaml\")\n assert client.download_fileobj.call_args[1][\"Bucket\"] == \"mybucket\"\n assert client.download_fileobj.call_args[1][\"Key\"] == \"path/to/thing.yaml\"\n assert isinstance(res, bytes)\n","sub_path":"tests/utilities/test_filesystems.py","file_name":"test_filesystems.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"310403031","text":"import math\nimport sys\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom scipy import stats\n\nsys.path.insert(0, \".\")\n\nfrom SSMTIA.utils import mapping, parameter_range\n\n\ndef histogram_distortion(distortion: str):\n plt.clf()\n sns.distplot(df[df[\"parameter\"] == \"original\"][\"score\"], label=\"original\")\n for change in (val for val in mapping[\"all_changes\"] if distortion in val):\n parameter, change = change.split(\";\")\n sns.distplot(df[(df[\"parameter\"] == parameter) & (df[\"change\"] == float(change))][\"score\"], label=f\"{parameter}: {change}\")\n plt.legend()\n plt.savefig(f\"/workspace/analysis/NIMA/hist_{distortion}.png\")\n plt.clf()\n\n\ndef violin_distortion(distortion: str):\n plt.clf()\n plot_frame = df[(df[\"parameter\"] == distortion) | (df[\"parameter\"] == \"original\")]\n if distortion in parameter_range:\n plot_frame.loc[plot_frame[\"parameter\"] == \"original\", \"change\"] = parameter_range[distortion][\"default\"]\n sns.violinplot(data=plot_frame, x=\"change\", y=\"score\", color=\"steelblue\")\n plt.savefig(f\"/workspace/analysis/NIMA/viol_{distortion}.png\")\n plt.clf()\n\n\ndef violin_changes_original(distortion: str):\n original_frame = df[df[\"parameter\"] == \"original\"]\n results = []\n df_index = list(original_frame.columns).index(f\"{distortion}_change_strength\")\n for index, row in original_frame.iterrows():\n for i, k in enumerate(mapping[distortion].keys()):\n results.append({\"distortion\": distortion, \"change_predict\": k, \"change_strength\": row[df_index][i]})\n results = (pd.DataFrame([val], columns=val.keys()) for val in results)\n sns.violinplot(data=pd.concat(results, ignore_index=True), x=\"change_predict\", y=\"change_strength\", color=\"steelblue\")\n\n\ndf = pd.read_csv(\"/workspace/analysis/not_uploaded/NIMA_test_dist.csv\", sep=\";\")\ndf[\"dist\"] = df[\"dist\"].apply(eval)\ndf[\"score\"] = df[\"dist\"].apply(lambda row: sum([row[i] * (i + 1) for i in range(len(row))]))\n\nsns.distplot(df[\"score\"], label=\"overall\")\nsns.distplot(df[df[\"parameter\"] == \"original\"][\"score\"], label=\"original\")\nplt.legend()\nplt.savefig(\"/workspace/analysis/NIMA/original.png\")\nplt.clf()\n\nfor dist_type in [\"styles\", \"technical\", \"composition\"]:\n for dist in mapping[dist_type].keys():\n print(dist)\n histogram_distortion(dist)\n violin_distortion(dist)\n","sub_path":"analysis_code_related/NIMA_test.py","file_name":"NIMA_test.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"185885023","text":"def Solution(A):\n if len(A) < 2:\n return 0\n s = sum(A)\n\n minDiff = 2000\n sL = 0\n\n for i in range(0, len(A)-1):\n sL += A[i]\n diff = abs(2*sL-s)\n minDiff = min(minDiff,diff)\n \n return minDiff","sub_path":"Codility/TapeEquilibrium.py","file_name":"TapeEquilibrium.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"471117266","text":"import os\n\nfrom django.conf.global_settings import MEDIA_ROOT\n\n\ntry:\n from sorl.thumbnail import delete as delete_thumbnails\nexcept ImportError:\n def delete_thumbnails(*args, **kwargs):\n pass\nimport logging\nfrom os.path import splitext\nfrom uuid import uuid4\n\nimport grequests\nimport requests\n\nfrom django.core.files import File\nfrom django.core.files.temp import NamedTemporaryFile\nfrom django.db.models import FileField\nfrom django.db.models.loading import cache\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_web_file(url):\n \"\"\"\n Retrieve the file from the specified url.\n @param url: The URL the file is located.\n @return: A File object that contains the retrieved file and has a uuid as its name prefix.\n \"\"\"\n response = requests.get(url)\n temp_file = NamedTemporaryFile()\n temp_file.write(response.content)\n temp_file.flush()\n return File(file=temp_file, name=unicode(uuid4()) + splitext(response.url)[-1])\n\n\ndef get_web_files(urls, size=25):\n \"\"\"\n Retrieve the files from the list of urls.\n @param urls: The URLS where the files are located.\n @return: A list of File objects that contain the retrieved file and has a uuid as its name prefix.\n \"\"\"\n files = []\n request_set = (grequests.get(url) for url in urls)\n responses = grequests.map(request_set, size=size)\n for response in responses:\n temp_file = NamedTemporaryFile()\n temp_file.write(response.content)\n temp_file.flush()\n files.append(File(file=temp_file, name=unicode(uuid4()) + splitext(response.url)[-1]))\n return files\n\n\ndef get_models_with_file_fields():\n \"\"\"\n Retrieve every model that has a field that is an instance of FileField.\n @return: A list of models with a FileField.\n \"\"\"\n models = []\n for app in cache.get_apps():\n model_list = cache.get_models(app)\n for model in model_list:\n for field in model._meta.fields:\n if isinstance(field, FileField):\n models.append(model)\n break\n return models\n\n\ndef delete_field_files(sender, instance, **kwargs):\n \"\"\"\n Deletes any files associated with an object's file fields.\n @param sender: The context in which this method is called. It is not used in this method but retained for\n compatibility with Django signals.\n @param instance: The Django object that is being deleted.\n @param kwargs: Additional arguments. It is not used in this method but retrained for compatibility with Django\n signals.\n \"\"\"\n for field in instance._meta.fields:\n if not isinstance(field, FileField):\n continue\n file_to_delete = getattr(instance, field.name)\n storage = file_to_delete.storage\n if file_to_delete and storage and storage.exists(file_to_delete.name):\n try:\n delete_thumbnails(file_to_delete, delete_file=False)\n storage.delete(file_to_delete.name)\n except OSError:\n logger.error(\"Unable to delete file {file_name} when deleting {class_name object.\".format(\n file_name=file_to_delete.name, class_name=instance.__class__.__name__))\n\n\ndef delete_old_field_files(sender, instance, **kwargs):\n \"\"\"\n If the specified object already exists and the the files associated with the file fields are different,\n delete the older files.\n @param sender: The context in which this method is called. It is not used in this method but retained for\n compatibility with Django signals.\n @param instance: The Django object that is being saved.\n @param kwargs: Additional arguments. It is not used in this method but retrained for compatibility with Django\n signals.\n \"\"\"\n # If this is a new object there are no old files to delete.\n if not instance.pk:\n return\n\n # If the object has a primary key, check if the object is in the database because objects that have manually\n # assigned primary keys will specify one for new instances.\n try:\n old_instance = instance.__class__.objects.get(pk=instance.pk)\n except instance.DoesNotExist:\n return\n\n # Check if each file field has a new file. If it does delete the old file.\n for field in instance._meta.fields:\n if not isinstance(field, FileField):\n continue\n old_file = getattr(old_instance, field.name)\n new_file = getattr(instance, field.name)\n storage = old_file.storage\n if old_file and old_file != new_file and storage and storage.exists(old_file.name):\n try:\n delete_thumbnails(old_file, delete_file=False)\n storage.delete(old_file.name)\n except OSError:\n logger.exception(\n \"Unable to delete file {file_name when updating {class_name} object.\".format(\n file_name=old_file.name, class_name=instance.__class__.__name__))\n\n\ndef generate_unique_file_name(instance, file_name):\n # Note: On operating systems like Windows, files are automatically appended with _%d when two files share the same\n # name. This is to cover the case where files are overwritten by default, such as AWS S3.\n return os.path.join(MEDIA_ROOT, instance._meta.app_label, unicode(uuid4()) + splitext(file_name)[-1])\n\n# TODO: Function that returns a list of what objects will get deleted based on the given object.\n# https://github.com/django/django/blob/ebd70d4d00c252d5122c13906da5bddc8de0bce5/django/contrib/admin/options.py#L1580\n# https://github.com/django/django/blob/b77f26313cddbfde20dcf2661e9bd35458c2d1bd/django/contrib/admin/utils.py#L108","sub_path":"libs/util/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"46957357","text":"import tkinter as tk\nimport pyautogui\nimport time\n\ndef bfn():\n for i in range(int(amount.get())):\n time.sleep(0.3)\n pyautogui.write(ttx.get())\n pyautogui.press('enter')\n\n\nroot = tk.Tk()\n\n\ncanvas = tk.Canvas(root, width=600, height=260)\ncanvas.pack()\nroot.title('SpamBot')\nframe = tk.Frame(root, bg='gray')\n# relx=,rely=,relwidth=,relheight=\nframe.place(relx=0.157,rely=0.1,relwidth=0.7,relheight=0.8)\nlabe1 = tk.Label(frame, text='Add Amount :', bg='gray', font=('Courier',10))\nlabe1.place(relx=0.1,rely=0.37,relwidth=0.4,relheight=0.23)\nlabe2 = tk.Label(frame, text='Add Text You Wanna Spam :', bg='gray')\nlabe2.place(relx=0.001,rely=0.01,relwidth=0.4,relheight=0.4)\nbtn = tk.Button(frame, text='Spam!', command=bfn)\nbtn.place(relx=0.38,rely=0.7,relwidth=0.23,relheight=0.23)\namount = tk.Entry(frame)\namount.place(relx=0.38,rely=0.37,relwidth=0.23,relheight=0.23)\nttx = tk.Entry(frame)\nttx.place(relx=0.38,rely=0.1,relwidth=0.23,relheight=0.23)\n\n\ntk.mainloop()","sub_path":"Spammer.py","file_name":"Spammer.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"313725954","text":"# stdlib\nimport json\nfrom typing import Dict as TypeDict\nfrom typing import Optional\nfrom typing import Union\n\n# third party\nimport requests\n\n# relative\nfrom .. import GridURL\nfrom ...core.common.message import SignedImmediateSyftMessageWithReply\nfrom ...core.common.message import SignedImmediateSyftMessageWithoutReply\nfrom ...core.common.message import SyftMessage\nfrom ...core.common.serde.deserialize import _deserialize\nfrom ...core.common.serde.serialize import _serialize\nfrom ...core.io.connection import ClientConnection\nfrom ...core.node.enums import RequestAPIFields\nfrom ...core.node.exceptions import RequestAPIException\nfrom ...telemetry import instrument\n\nDEFAULT_TIMEOUT = 30 # seconds\n\n\n@instrument\nclass HTTPConnection(ClientConnection):\n proxies: TypeDict[str, str] = {}\n\n def __init__(self, url: Union[str, GridURL]) -> None:\n self.base_url = GridURL.from_url(url) if isinstance(url, str) else url\n if self.base_url is None:\n raise Exception(f\"Invalid GridURL. {self.base_url}\")\n\n def send_immediate_msg_with_reply(\n self,\n msg: SignedImmediateSyftMessageWithReply,\n timeout: Optional[float] = None,\n return_signed: bool = False,\n ) -> SignedImmediateSyftMessageWithoutReply:\n \"\"\"\n Sends high priority messages and wait for their responses.\n\n This method implements a HTTP version of the\n ClientConnection.send_immediate_msg_with_reply\n\n :return: returns an instance of SignedImmediateSyftMessageWithReply.\n :rtype: SignedImmediateSyftMessageWithoutReply\n \"\"\"\n\n # Serializes SignedImmediateSyftMessageWithReply\n # and send it using HTTP protocol\n response = self._send_msg(msg=msg, timeout=timeout)\n\n # Deserialize node's response\n if response.status_code == requests.codes.ok:\n # Return SignedImmediateSyftMessageWithoutReply\n return _deserialize(blob=response.content, from_bytes=True)\n\n try:\n response_json = json.loads(response.content)\n raise RequestAPIException(response_json[RequestAPIFields.ERROR])\n except Exception as e:\n print(f\"Unable to json decode message. {e}\")\n raise e\n\n def send_immediate_msg_without_reply(\n self,\n msg: SignedImmediateSyftMessageWithoutReply,\n timeout: Optional[float] = None,\n ) -> None:\n \"\"\"\n Sends high priority messages without waiting for their reply.\n\n This method implements a HTTP version of the\n ClientConnection.send_immediate_msg_without_reply\n\n \"\"\"\n # Serializes SignedImmediateSyftMessageWithoutReply\n # and send it using HTTP protocol\n self._send_msg(msg=msg, timeout=timeout)\n\n def _send_msg(\n self, msg: SyftMessage, timeout: Optional[float] = None\n ) -> requests.Response:\n \"\"\"\n Serializes Syft messages in json format and send it using HTTP protocol.\n\n NOTE: Auxiliary method to avoid code duplication and modularity.\n\n :return: returns requests.Response object containing a JSON serialized\n SyftMessage\n :rtype: requests.Response\n \"\"\"\n\n # timeout = None will wait forever\n timeout = timeout if timeout is not None else DEFAULT_TIMEOUT\n\n # Perform HTTP request using base_url as a root address\n data_bytes: bytes = _serialize(msg, to_bytes=True) # type: ignore\n r = requests.post(\n url=str(self.base_url),\n data=data_bytes,\n headers={\"Content-Type\": \"application/octet-stream\"},\n timeout=timeout,\n proxies=HTTPConnection.proxies,\n )\n\n # Return request's response object\n # r.text provides the response body as a str\n return r\n","sub_path":"packages/syft/src/syft/grid/connections/http_connection.py","file_name":"http_connection.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"260226624","text":"# -------------------------------------------------------------------------\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\nSTORAGE_ACCOUNT_NAME = ''\nSTORAGE_ACCOUNT_KEY = ''\nSAS = ''\nIS_EMULATED = False\n","sub_path":"samples/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"288890688","text":"#!/usr/bin/env python3\n\"\"\"\n+===================================================+\n| © 2021 Privex Inc. |\n| https://www.privex.io |\n+===================================================+\n| |\n| CSPGen - Python Content Sec Policy Generator |\n| License: X11/MIT |\n| |\n| Core Developer(s): |\n| |\n| (+) Chris (@someguy123) [Privex] |\n| |\n+===================================================+\n\nCSPGen - A Python tool for generating Content Security Policies without constantly repeating yourself.\nCopyright (c) 2021 Privex Inc. ( https://www.privex.io )\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy,\nmodify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of\nthe Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\nOR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nExcept as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or\notherwise to promote the sale, use or other dealings in this Software without prior written authorization.\n\"\"\"\nimport configparser\nimport sys\nimport textwrap\nfrom colorama import Fore\nfrom os import getenv as env\nfrom privex.helpers import empty, empty_if, is_true, is_false, env_bool, T, K, ErrHelpParser\n\nfrom privex.cspgen import version\nfrom privex.cspgen.helpers import automark_str, clean_dict, dedup, literal, read_stdin\n\noprint = print\nfrom rich import print\nfrom pathlib import Path\nimport logging\nimport argparse\nfrom privex.loghelper import LogHelper\nfrom typing import Union, Optional, List, Tuple, Dict, Set\n\n__all__ = [\n 'CSPBuilder', 'get_builder', 'main', 'parser', 'log_level', 'PKG_DIR', 'EXAMPLE_DIR', 'EXAMPLE_INI'\n]\n\nPKG_DIR = Path(__file__).parent.resolve()\nEXAMPLE_DIR = PKG_DIR / 'examples'\nEXAMPLE_INI = EXAMPLE_DIR / 'example.ini'\n\nlog_level = env('LOG_LEVEL', 'WARNING')\n_lh = LogHelper('privex.cspgen', handler_level=logging.getLevelName(log_level))\n_lh.add_console_handler(stream=sys.stderr)\n\nlog = _lh.get_logger()\n\nargc, argv = len(sys.argv), sys.argv\n\n\nclass CSPBuilder:\n def __init__(self, filename: str = None, file_handle = None, contents: Union[str, list, tuple] = None, **kwargs):\n self.config = configparser.ConfigParser()\n self.conf_file = None\n if not empty(filename):\n self.conf_file = Path(filename).resolve()\n self.config.read(self.conf_file)\n elif file_handle is not None:\n self.config.read_file(file_handle)\n elif not empty(contents, itr=True):\n if isinstance(contents, (tuple, list)):\n contents = \"\\n\".join(contents)\n self.config.read_string(contents)\n else:\n raise ValueError(\n \"CSPBuilder expects either a filename, file handle (open()), or config string \"\n \"contents to be passed. All 3 are None / empty. Nothing to parse.\"\n )\n\n self.groups = {}\n self.config_dict = {}\n self.flags = ''\n self.excluded = kwargs.get('excluded', ['flags', 'groups', 'DEFAULT'])\n self.cleaned = False\n # self.section_split = kwargs.get('section_split', ': ')\n self.section_split = kwargs.get('section_split', ' ')\n \n\n @property\n def sections(self) -> list:\n return self.config.sections()\n\n @property\n def clean_sections(self) -> list:\n return [s for s in self.sections if s not in self.excluded]\n\n def clean(self):\n # First we extract 'groups' from the config, replace it's {{markers}}, and then deduplicate all group values\n if 'groups' in self.sections:\n self.groups = clean_dict(self.config['groups'])\n\n groups = self.groups\n # Next we iterate over the Config object and extract all sections into a standard dict\n config_dict = self.config_dict\n for k, v in self.config.items():\n v: configparser.SectionProxy\n sec_items = dict(v.items())\n config_dict[k] = sec_items\n \n # Remove auto-added 'DEFAULT' (not used), and 'groups' (already parsed and extracted into self.groups)\n if 'DEFAULT' in config_dict: del config_dict['DEFAULT']\n if 'groups' in config_dict: del config_dict['groups']\n\n # Extract 'flags' if present in the config, replace {{markers}}, and deduplicate it's contents.\n cflags = '' if 'flags' not in config_dict else config_dict['flags']['flags']\n cflags = dedup(automark_str(cflags, groups))\n \n # Then we can simply remove 'flags' from the config dict\n if 'flags' in config_dict: del config_dict['flags']\n\n # Finally we make sure all local variables are saved back to their appropriate instance attributes\n self.config_dict = {k: clean_dict(v, groups) for k, v in config_dict.items()}\n self.flags = cflags\n self.groups = groups\n self.cleaned = True\n return self\n\n def autoclean(self):\n if self.cleaned:\n return True\n return self.clean()\n\n def str_section(self, name: str):\n self.autoclean()\n sec = self.config_dict.get(name, None)\n if not sec: return None\n s = f\"{name}{self.section_split}{sec.get('zones', '')}\"\n if is_true(sec.get('unsafe-eval', False)): s += \" 'unsafe-eval'\"\n if is_true(sec.get('unsafe-inline', False)): s += \" 'unsafe-inline'\"\n s += ';'\n return s\n\n def generate(self, output='list', sep=' ', **kwargs):\n \n secs = [self.str_section(s) for s in self.clean_sections]\n secd = dict(zip(self.clean_sections, secs))\n secd['flags'] = [s + ';' for s in self.flags.split()]\n secs += secd['flags'] \n output = output.lower()\n if output == 'list': return secs\n if output == 'tuple': return tuple(secs)\n if output in ['dict', 'dictionary', 'kv', 'keyval', 'map', 'mapping']: return secd\n if output in ['str', 'string']:\n sj = sep.join(secs)\n if not sj.endswith(';'): sj += ';'\n return sj\n raise ValueError(f\"Supported: (str, string, list, tuple). Unsupported output type: {output}\")\n\n def __str__(self):\n return self.generate(output='str')\n\n def __iter__(self):\n yield from self.generate(output='list')\n\n def __len__(self):\n return len(self.generate(output='list'))\n\n def __getitem__(self, item:str):\n self.autoclean()\n if item in self.sections:\n return self.config_dict[item]\n gend = self.generate(output='dict')\n if item in gend:\n return gend[item]\n if item in self.groups:\n return self.groups[item]\n raise KeyError(f\"Item {item!r} not found in config sections, generated sections, or group keys...\")\n\n\ndef get_builder(name: str = None, file_handle = None, contents: Union[str, list, tuple] = None, **kwargs) -> CSPBuilder:\n if empty(name) and file_handle is None and empty(contents, itr=True): name = argv[1]\n return CSPBuilder(name, file_handle, contents, **kwargs)\n\n\nCOPYRIGHT = f\"\"\"\n {Fore.GREEN}Content Security Policy (CSP) Generator{Fore.RESET}\n \n {Fore.CYAN}Version: v{version.VERSION}\n Github: https://github.com/Privex/cspgen\n License: X11 / MIT\n \n (C) 2021 Privex Inc. ( https://www.privex.io ){Fore.RESET}\n\"\"\"\n\nparser = ErrHelpParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=textwrap.dedent(f\"\"\"\n{COPYRIGHT}\n \n\n {Fore.YELLOW}Generates CSP's based off of one or more INI files, with each CSP \"type\" (default-src, style-src, etc.)\n as an INI header, a 'zones' key in each type, containing the various domains you want to allow,\n 'unsafe-eval = true' / 'unsafe-inline = false' for more clear enabling/disabling unsafe-eval and unsafe-inline\n per \"type\", and two special headers:{Fore.RESET}\n {Fore.BLUE}\n 'groups' - Groups of variables that can be used in each type's 'zones = ' key, AND can also include\n other group names (as long as the included vars are defined higher up, and doesn't include\n the var including it).\n\n 'flags' - Contains \"flags\", which are CSP strings that standalone, such as 'upgrade-insecure-requests',\n instead of being a key with zones as a value.\n {Fore.RESET}\n\n {Fore.GREEN}Example INI file:{Fore.RESET}\"\"\" + \"\"\"\n \n [groups]\n # First we define cdn, onions, and i2p\n cdn = https://cdn.privex.io cdn.privex.i2p files.privex.i2p files.privex.io https://www.privex.io\n onions = privex3guvvasyer6pxz2fqcgy56auvw5egkir6ykwpptferdcb5toad.onion privexqvhkwdsdnjofrsm7reaixclmzpbpveefiu4uctfm2l4mycnwad.onion\n i2p = privex.i2p www.privex.i2p pay.privex.i2p\n # Now we can add our main websites, PLUS the onions, and i2p variables\n websites = https://www.privex.io https://pay.privex.io https://privex.io {{onions}} {{i2p}}\n # While defaultsrc will contain 'self' + websites + cdn\n defaultsrc = 'self' {{websites}} {{cdn}}\n\n images = https://i.imgur.com https://ipfs.io https://cloudflare-ipfs.com\n video = https://youtube.com https://vimeo.com\n media = {{video}} {{images}}\n\n [default-src]\n # For default-src, we can simply set zones to use the defaultsrc var\n zones = {{defaultsrc}}\n # Enable unsafe-inline and disable unsafe-eval for default-src\n unsafe-inline = true\n unsafe-eval = false\n\n [img-src]\n zones = {{defaultsrc}} {{images}} {{trustpilot}}\n\n [media-src]\n zones = {{defaultsrc}} {{media}}\n\n [flags]\n # Special header 'flags'. We can set the independent CSP flag 'upgrade-insecure-requests' here.\n flags = upgrade-insecure-requests\n \"\"\" + f\"\"\"\n\n {Fore.GREEN}End of config{Fore.RESET}\n\n \"\"\"),\n)\n\n\ndef read_example_file() -> Tuple[str, Path]:\n with open(EXAMPLE_INI, 'r') as fh:\n data = fh.read()\n return data, EXAMPLE_INI\n\n\nparser.add_argument('--section-sep', type=str, default=' ', dest='section_sep',\n help=\"Separator between each CSP section (default-src, media-src, img-src etc.) - Textual \\\\n, \\\\r, and \\\\t will \"\n \"be auto-converted into the literal characters for newline/carriage return/tab\")\nparser.add_argument('--file-sep', type=str, default='\\n\\n', dest='file_sep', help=\"Separator used between each file's config output\")\nparser.add_argument('--version', '-V', action='store_true', default=False, dest='show_version', help=\"Show version + copyright info\")\nparser.add_argument('--verbose', '-v', action='store_true', default=False, dest='verbose_mode', help=\"Verbose Mode - Show DEBUG logs\")\nparser.add_argument('--example', '-E', action='store_true', default=False, dest='show_example',\n help=\"Output the template example.ini to STDOUT for use as a CSP INI config template\")\nparser.add_argument('filenames', nargs='*', default=[], help=\"One or more INI files to parse into CSP configs\")\n\n\ndef main():\n global log\n try:\n vargs = parser.parse_args()\n except Exception as e:\n parser.error(f\"{type(e)} - {str(e)}\")\n return sys.exit(1)\n if vargs.verbose_mode:\n _lh2 = LogHelper('privex.cspgen', handler_level=logging.DEBUG)\n _lh2.add_console_handler(stream=sys.stderr)\n log = _lh2.get_logger()\n \n log.debug(f\"parser args: {vargs!r}\")\n if vargs.show_version:\n oprint(COPYRIGHT)\n return COPYRIGHT\n if vargs.show_example:\n exfile, expath = read_example_file()\n exnote = \"#####\", \"#\", \"# Privex CSPGen example.ini file\", f\"# Original Location within Python Package: {expath}\", \"#\", \"#####\\n\"\n oprint(*exnote, exfile, *exnote, sep=\"\\n\")\n return sys.exit(0)\n filenames = vargs.filenames\n file_sep, sec_sep = literal(vargs.file_sep), literal(vargs.section_sep)\n str_secs = []\n list_secs = []\n if empty(filenames, itr=True):\n if sys.stdin.isatty():\n parser.error(\"No filenames specified, and no data piped to stdin\")\n return sys.exit(1)\n log.debug(\"Assuming config piped via STDIN. Reading config from stdin.\")\n confd = read_stdin()\n builder = get_builder(contents=confd)\n str_secs += [builder.generate('string', sep=sec_sep)]\n list_secs += [builder.generate('list')]\n else:\n for fn in filenames:\n if fn in ['-', '/dev/stdin', 'STDIN']:\n log.debug(\"Assuming config piped via STDIN. Reading config from stdin.\")\n builder = get_builder(contents=read_stdin())\n else:\n builder = get_builder(fn)\n\n str_secs += [builder.generate('string', sep=sec_sep)]\n list_secs += [builder.generate('list')]\n\n # oprint('file_sep: ', repr(file_sep))\n # oprint('sec_sep: ', repr(sec_sep))\n oprint(file_sep.join(str_secs))\n return list_secs, str_secs\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"privex/cspgen/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":14103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"378352685","text":"\"\"\"\n给定一个无序数组,找到其中最小的 k 个数\n要求时间复杂度 O(N)\n思路:\n借鉴快排思想,快排的划分 partition 函数每次执行完后都能将数组分成两个部分\n小于等于分界值 pivot 的元素放在数组左边,大于它的元素放在右边,返回 pivot 在数组中的下标\n与快排不同,这里只处理划分后的一边即可\n定义函数 random_select(A, l, r, k)表示划分数组 A 的[l,r]部分,使前 k 小的元素在左侧\n调用 partition 函数,假设返回的下标是 pos,即 pivot 在数组中的最终位置\npivot 是数组中第 pos-l+1 小的数\npos-l+1 == k: pivot 即为第 k 小的数\npos-l+1 < k: 第 k 小的数在 pivot 右边,递归调用 random_select(A, pos+1, r, k-(pos-l+1))\npos-l+1 > k: 第 k 小的数在 pivot 左边,递归调用 random_select(A, l, pos-1, k)\n函数递归入口为 random_select(A, 0, len(A), k)\n返回后前 k 个数即为答案\n\"\"\"\n\nimport random\n\ndef partition(A, l, r):\n pivot = A[r]\n i = l - 1\n for j in range(l, r):\n if A[j] <= pivot:\n i += 1\n A[i], A[j] = A[j], A[i]\n A[i+1], A[r] = A[r], A[i+1]\n return i+1\n\ndef random_partition(A, l, r):\n i = random.randint(l, r)\n A[r], A[i] = A[i], A[r]\n return partition(A, l, r)\n\ndef random_select(A, l, r, k):\n pos = random_partition(A, l, r)\n num = pos - l + 1\n if k < num:\n random_select(A, l, pos-1, k)\n elif k > num:\n random_select(A, pos+1, r, k-num)\n\ndef getMinKNumbers(A, k):\n if k == 0:\n return None\n random_select(A, 0, len(A)-1, k)\n print(A[:k])\n\n\nif __name__ == \"__main__\":\n nums = [1, 5, 3, 4, 2, 6, 7]\n getMinKNumbers(nums, 3)\n","sub_path":"ArrayMatrix/getMinKNums.py","file_name":"getMinKNums.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"532740416","text":"\"\"\"\nPlotting script to create\n\nFigure 5\n\nMALDI-TOF spectra based AMR prediction using an ensemble of all species\n\"\"\"\n\nimport os\nimport json\nimport argparse\nimport glob\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.stats import ttest_ind\nfrom sklearn.metrics import roc_auc_score\n\nfrom utils import scenario_map\n\nscenarios = [\n ('Escherichia coli', 'Ceftriaxone', 'lightgbm'),\n ('Klebsiella pneumoniae', 'Ceftriaxone', 'mlp'),\n ('Staphylococcus aureus', 'Oxacillin', 'lightgbm'),\n]\n\nmap_models = {\n 'lightgbm': 'LightGBM',\n 'mlp': 'MLP',\n}\n\ndef plot_figure5(args):\n\n # --------------\n # create dataframe giving an overview of all files in path\n # --------------\n file_list = []\n for scenario in scenarios:\n searchstr = os.path.join(\n '../../results/validation_per_species_and_antibiotic',\n f'{scenario[2]}/*{scenario[1]}*.json')\n\n files = glob.glob(searchstr)\n file_list.extend(files)\n\n content = pd.DataFrame(columns=[])\n\n for filename in file_list:\n with open(filename) as f:\n data = json.load(f)\n content = content.append(\n pd.DataFrame({\n 'filename': [filename],\n 'antibiotic': [data['antibiotic']],\n 'species': [data['species']],\n 'train_site': [data['train_site']],\n 'test_site': [data['test_site']],\n 'model': [data['model']],\n 'seed': [data['seed']],\n }),\n ignore_index=True,\n )\n pd.options.display.max_rows = 999\n\n # ------------\n # for each antibiotic, get avg metrics for 'all' and 'all (w/o spectra)'\n # ------------\n\n values = [pd.DataFrame(columns=[])]*len(scenarios)\n\n for i, scenario in enumerate(scenarios):\n\n # add lines for all train-test scenarios\n content_ = content.copy()\n content_ = content_.query('species==@scenario[0]')\n content_ = content_.query('antibiotic==@scenario[1]')\n content_ = content_.query('model==@scenario[2]')\n\n for tr_site in ['DRIAMS-D','DRIAMS-C','DRIAMS-B','DRIAMS-A']:\n for te_site in ['DRIAMS-D','DRIAMS-C','DRIAMS-B','DRIAMS-A']:\n content_scenario = content_.query(\"train_site==@tr_site\")\n content_scenario = content_scenario.query(\"test_site==@te_site\")\n if content_scenario.shape[0]>0:\n assert content_scenario.shape[0]==10\n\n results = []\n for filename in content_scenario['filename'].values:\n with open(filename) as f:\n data = json.load(f)\n # TODO make dynamic for different metrics\n results.append(roc_auc_score(data['y_test'],\n [sc[1] for sc in data['y_score']]))\n assert np.all([x in [0, 1] for x in data['y_test']])\n result_mean_all = round(np.mean(results), 3)\n result_std_all = round(np.std(results), 3)\n\n # add to values dataframe\n values[i] = values[i].append(\n pd.DataFrame({\n 'antibiotic': [scenario[1]],\n 'species': [scenario[0]],\n 'train_site': [tr_site],\n 'test_site': [te_site],\n 'result': [result_mean_all],\n 'result_std_all': [result_std_all],\n }),\n ignore_index=True,\n sort=False,\n )\n else:\n values[i] = values[i].append(\n pd.DataFrame({\n 'antibiotic': [scenario[1]],\n 'species': [scenario[0]],\n 'train_site': [tr_site],\n 'test_site': [te_site],\n 'result': [np.nan],\n 'result_std_all': [np.nan],\n }),\n ignore_index=True,\n sort=False,\n )\n\n # -------------\n # plot heatplot\n # -------------\n print(f'plotting.. {args.outfile}')\n #assert len(values) == 16\n rc = {\n 'legend.fontsize': 8,\n 'axes.labelsize': 10,\n 'ytick.labelsize': 10,\n 'xtick.labelsize': 10,\n }\n\n plt.close('all')\n sns.set(style=\"whitegrid\",\n rc=rc,\n font_scale=1.1\n )\n \n fig, ax = plt.subplots(1, 3, figsize=(20,8))\n\n for i in range(len(ax)):\n # heatmap \n matrix = values[i].pivot(\"train_site\", \"test_site\", \"result\")\n print(i)\n print(matrix)\n sns.heatmap(matrix, \n annot=True, \n fmt=\".2f\",\n linewidths=.75,\n vmin=0.5, \n vmax=1,\n ax=ax[i],\n cmap=sns.cubehelix_palette(8, start=.5, rot=-.75),\n cbar=True if i==len(ax)-1 else False,\n cbar_kws={'label': 'AUROC'}\n )\n\n # adjust y axis label position\n yticks = ax[i].get_yticks()\n ax[i].set_yticks([i-0.3 for i in yticks])\n ax[i].set_yticklabels(ax[i].get_xticklabels())\n\n ax[i].set_title(f'{scenario_map[scenarios[i][0].replace(\" \", \"_\")]} ({map_models[scenarios[i][2]]})')\n ax[i].set_ylabel('training') \n ax[i].set_xlabel('testing')\n\n for ax_ in ax:\n ax_.label_outer()\n # adjust one yticks explicitly, as they are not covered\n # by the command above\n ax[2].set_yticks([])\n ax[2].set_ylabel('')\n plt.subplots_adjust(wspace=0.01)\n plt.savefig(f'../plots/validation_per_species_and_antibiotic/{args.outfile}_combined.png')\n plt.savefig(f'../plots/validation_per_species_and_antibiotic/{args.outfile}_combined.pdf')\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--metric',\n type=str,\n default='auroc')\n parser.add_argument('--outfile',\n type=str,\n default='validation_per_species_and_antibiotic')\n args = parser.parse_args()\n\n plot_figure5(args)\n","sub_path":"amr_maldi_ml/plotting/plot_validation_per_species_and_antibiotic_major_scenarios.py","file_name":"plot_validation_per_species_and_antibiotic_major_scenarios.py","file_ext":"py","file_size_in_byte":6573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"650525916","text":"##problem 14\n##The following iterative sequence is defined for the set of positive integers:\n##\n##n n/2 (n is even)\n##n 3n + 1 (n is odd)\n##\n##Which starting number, under one million, produces the longest chain?\n\nfrom time import time\n\ndef euler14():\n step_dic = {1:1}\n # dynamic programming solution\n # uses a recursive algorithm and a dictionary to store every value seen\n # on the way to one million\n def find_chain_length(number):\n if number in step_dic:\n return step_dic[number]\n else:\n if number % 2 == 0:\n step_dic[number] = 1 + find_chain_length(number / 2)\n else:\n step_dic[number] = 1 + find_chain_length((3 * number) + 1)\n return step_dic[number]\n \n best = 1\n winner = 0\n for i in range(2, 1000001):\n if find_chain_length(i) > best:\n best = find_chain_length(i)\n winner = i\n\n print(winner)\n\nt_start = time()\neuler14()\nprint(time() - t_start)\n\n \n\n#print(max(step_dic.values()))\n \n","sub_path":"code/Python/old/Euler/p14_v4.py","file_name":"p14_v4.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"217514626","text":"#!/usr/bin/env python\nimport os\nimport pickle\nimport sys\nimport unitypack\nfrom unitypack.export import OBJMesh\nfrom argparse import ArgumentParser\nfrom PIL import ImageOps\nfrom fsb5 import FSB5\n\n\ndef get_output_path(filename):\n\tbasedir = \"out\"\n\tpath = os.path.join(basedir, filename)\n\tdirs = os.path.dirname(path)\n\tif not os.path.exists(dirs):\n\t\tos.makedirs(dirs)\n\treturn path\n\n\ndef write_to_file(filename, contents, mode=\"w\"):\n\tpath = get_output_path(filename)\n\twith open(path, mode) as f:\n\t\twritten = f.write(contents)\n\n\tprint(\"Written %i bytes to %r\" % (written, path))\n\n\ndef handle_asset(asset, handle_formats):\n\tfor id, obj in asset.objects.items():\n\t\tif obj.type not in handle_formats:\n\t\t\tcontinue\n\n\t\td = obj.read()\n\n\t\tif obj.type == \"AudioClip\":\n\t\t\tif not d.data:\n\t\t\t\t# eg. StreamedResource not available\n\t\t\t\tcontinue\n\t\t\taf = FSB5(d.data)\n\t\t\tfor i, sample in enumerate(af.samples):\n\t\t\t\tif i > 0:\n\t\t\t\t\tfilename = \"%s-%i.%s\" % (d.name, i, af.get_sample_extension())\n\t\t\t\telse:\n\t\t\t\t\tfilename = \"%s.%s\" % (d.name, af.get_sample_extension())\n\t\t\t\ttry:\n\t\t\t\t\tsample = af.rebuild_sample(sample)\n\t\t\t\texcept ValueError as e:\n\t\t\t\t\tprint(\"WARNING: Could not extract %r (%s)\" % (d, e))\n\t\t\t\t\tcontinue\n\t\t\t\twrite_to_file(filename, sample, mode=\"wb\")\n\n\t\telif obj.type == \"MovieTexture\":\n\t\t\tfilename = d.name + \".ogv\"\n\t\t\twrite_to_file(filename, d.movie_data, mode=\"wb\")\n\n\t\telif obj.type == \"Shader\":\n\t\t\twrite_to_file(d.name + \".cg\", d.script)\n\n\t\telif obj.type == \"Mesh\":\n\t\t\ttry:\n\t\t\t\tmesh_data = OBJMesh(d).export()\n\t\t\t\twrite_to_file(d.name + \".obj\", mesh_data, mode=\"w\")\n\t\t\texcept NotImplementedError as e:\n\t\t\t\tprint(\"WARNING: Could not extract %r (%s)\" % (d, e))\n\t\t\t\tmesh_data = pickle.dumps(d._obj)\n\t\t\t\twrite_to_file(d.name + \".Mesh.pickle\", mesh_data, mode=\"wb\")\n\n\t\telif obj.type == \"TextAsset\":\n\t\t\tif isinstance(d.script, bytes):\n\t\t\t\twrite_to_file(d.name + \".bin\", d.script, mode=\"wb\")\n\t\t\telse:\n\t\t\t\twrite_to_file(d.name + \".txt\", d.script)\n\n\t\telif obj.type == \"Texture2D\":\n\t\t\tfilename = d.name + \".png\"\n\t\t\timage = d.image\n\t\t\tif image is None:\n\t\t\t\tprint(\"WARNING: %s is an empty image\" % (filename))\n\t\t\t\twrite_to_file(filename, \"\")\n\t\t\telse:\n\t\t\t\tprint(\"Decoding %r\" % (d))\n\t\t\t\timg = ImageOps.flip(image)\n\t\t\t\tpath = get_output_path(filename)\n\t\t\t\timg.save(path)\n\n\ndef main():\n\tp = ArgumentParser()\n\tp.add_argument(\"files\", nargs=\"+\")\n\tp.add_argument(\"--all\", action=\"store_true\")\n\tp.add_argument(\"--audio\", action=\"store_true\")\n\tp.add_argument(\"--images\", action=\"store_true\")\n\tp.add_argument(\"--models\", action=\"store_true\")\n\tp.add_argument(\"--shaders\", action=\"store_true\")\n\tp.add_argument(\"--text\", action=\"store_true\")\n\tp.add_argument(\"--video\", action=\"store_true\")\n\targs = p.parse_args(sys.argv[1:])\n\n\tformat_args = {\n\t\t\"audio\": \"AudioClip\",\n\t\t\"images\": \"Texture2D\",\n\t\t\"models\": \"Mesh\",\n\t\t\"shaders\": \"Shader\",\n\t\t\"text\": \"TextAsset\",\n\t\t\"video\": \"MovieTexture\",\n\t}\n\thandle_formats = []\n\tfor a, classname in format_args.items():\n\t\tif args.all or getattr(args, a):\n\t\t\thandle_formats.append(classname)\n\n\tfor file in args.files:\n\t\tif file.endswith(\".assets\"):\n\t\t\twith open(file, \"rb\") as f:\n\t\t\t\tasset = unitypack.Asset.from_file(f)\n\t\t\thandle_asset(asset, handle_formats)\n\t\t\tcontinue\n\n\t\twith open(file, \"rb\") as f:\n\t\t\tbundle = unitypack.load(f)\n\n\t\tfor asset in bundle.assets:\n\t\t\thandle_asset(asset, handle_formats)\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"283971484","text":"#!/usr/bin/env python \nimport rospy\n\n# Because of transformations\nimport tf_conversions\n\nimport tf2_ros\nimport geometry_msgs.msg\n# import kinova_msgs.msg\n\n\ndef handle_goal_pose(msg):\n br = tf2_ros.TransformBroadcaster()\n t = geometry_msgs.msg.TransformStamped()\n\n t.header.stamp = rospy.Time.now()\n t.header.frame_id = \"marker_frame\"\n t.child_frame_id = \"goal_frame\"\n # t.child_frame_id = \"camera_color_optical_frame\"\n t.transform.translation.x = - 0.15 # height\n t.transform.translation.y = 0.170 # distance\n t.transform.translation.z = 0\n\n # q = tf_conversions.transformations.quaternion_from_euler(0, 0, msg.theta)\n t.transform.rotation.x = -0.5# q[0]\n t.transform.rotation.y = -0.5# q[1]\n t.transform.rotation.z = 0.5# q[2]\n t.transform.rotation.w = -0.5# q[3]\n\n br.sendTransform(t) \n \n ## AFTER GOAL FRAME\n t.header.stamp = rospy.Time.now()\n t.header.frame_id = \"goal_frame\"\n t.child_frame_id = \"goal_after_frame\"\n\n t.transform.translation.x = 0.0\n t.transform.translation.y = 0.15 # Up\n t.transform.translation.z = -0.15 # Back\n\n q = tf_conversions.transformations.quaternion_from_euler(0, 0, 0)\n t.transform.rotation.x = q[0]\n t.transform.rotation.y = q[1]\n t.transform.rotation.z = q[2]\n t.transform.rotation.w = q[3]\n\n br.sendTransform(t)\n\nif __name__ == '__main__':\n rospy.init_node('tf2_goal_broadcaster')\n rospy.Subscriber('/aruco_single/pose', geometry_msgs.msg.PoseStamped, handle_goal_pose)\n rospy.spin()\n","sub_path":"goal_tf2/src/tf_goal_node.py","file_name":"tf_goal_node.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"136983700","text":"from django.core.validators import FileExtensionValidator\nfrom django.db import models\nfrom django.utils.timezone import now\n\nfrom main import storage\nfrom people.models import Worker\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=128, unique=True, verbose_name='Название')\n\n class Meta:\n verbose_name = \"Тип\"\n verbose_name_plural = \"Типы\"\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n\nclass Document(models.Model):\n DIRECTION_CHOICES = [('вхд', 'Входящий'), ('исх', 'Исходящий'), ('внт', 'Внутренний')]\n direction = models.CharField(choices=DIRECTION_CHOICES, max_length=3, verbose_name='Вид')\n category = models.ForeignKey(Category, models.CASCADE, verbose_name='Тип')\n creation_date = models.DateField(default=now, verbose_name='Дата создания')\n register_date = models.DateField(null=True, blank=True, verbose_name='Дата регистрации')\n to_whom = models.ManyToManyField(Worker, related_name='recipient', verbose_name='Кому')\n from_whom = models.ForeignKey(Worker, on_delete=models.SET_NULL, null=True, related_name='initiator',\n verbose_name='От кого')\n executor = models.ForeignKey(Worker, on_delete=models.SET_NULL, null=True, blank=True, related_name='executor',\n verbose_name='Исполнитель')\n pdf_file = models.FileField(upload_to=storage.upload_ecm_document, storage=storage.ProtectedFileSystemStorage(),\n validators=[FileExtensionValidator(allowed_extensions=['pdf'])], null=True, blank=True,\n verbose_name='PDF')\n docx_file = models.FileField(upload_to=storage.upload_ecm_document, storage=storage.ProtectedFileSystemStorage(),\n validators=[FileExtensionValidator(allowed_extensions=['docx'])], null=True,\n blank=True, verbose_name='DOCX')\n code = models.CharField(max_length=32, unique_for_month=True, verbose_name='Код', blank=True)\n\n class Meta:\n verbose_name = \"Документ\"\n verbose_name_plural = \"Документы\"\n ordering = ['-creation_date']\n\n def __str__(self):\n return f'{self.get_direction_display()} {self.category} {self.creation_date}'\n\n def save(self, *args, **kwargs):\n temp_pdf_file = self.pdf_file\n temp_docx_file = self.docx_file\n if not self.id:\n self.pdf_file = None\n self.docx_file = None\n super(Document, self).save(*args, **kwargs)\n code = self.direction + str(self.creation_date.strftime(\"%y%m\"))\n\n # map_dir = enumerate(self.DIRECTION_CHOICES, 1)\n # for m in map_dir:\n # if self.direction in m[1][0]:\n # code += str(m[0])\n\n suffix = 0\n while Document.objects.filter(code=code + str(suffix).zfill(2)):\n suffix += 1\n\n self.code = code + str(suffix).zfill(2)\n super(Document, self).save(*args, **kwargs)\n self.pdf_file = temp_pdf_file\n self.docx_file = temp_docx_file\n super(Document, self).save(*args, **kwargs)\n else:\n super(Document, self).save(*args, **kwargs)\n","sub_path":"ecm/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"368427782","text":"import sys\n\ndef f():\n wf = open('boos/xs_filter', 'w')\n product = set(ln.strip() for ln in open('标注过的/产品词', 'r'))\n brand = set(ln.strip() for ln in open('标注过的/品牌词', 'r'))\n for ln in open('boos/xs', 'r'):\n ln = ln.strip()\n if ln in product or ln in brand:\n continue\n wf.write('%s\\n' % ln)\n print('finished')\n\ndef word_freq_dict():\n r = dict()\n for ln in open('/alidata1/songwt/title/fenci/word_freq', 'r'):\n ln = ln.strip()\n k, v = ln.split(',')\n r[k] = v\n return r\n\ndef dict_get(f, cixing):\n r = word_freq_dict() \n wf = open('dict/%s_tag_dict' % f, 'w')\n wf2 = open('dict/%s_dict' % f, 'w')\n\n for ln in open('dict/%s' % f, 'r'):\n ln = ln.strip()\n freq = r.get(ln, 100)\n s = '%s%s%s%s%s%s' %(ln,'\\3', cixing, '\\2', freq, '\\1')\n s2 = '%s%s%s' % (ln, '\\1', freq)\n wf.write('%s\\n' % s)\n wf2.write('%s\\n' % s2)\n print('finished')\n\n\nif __name__ == \"__main__\":\n #f()\n dict_get(sys.argv[1], sys.argv[2])\n","sub_path":"filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"65105878","text":"\"\"\"\r\nSimple file open dialogue using tkinter, inspired by\r\nhttps://stackoverflow.com/questions/9319317/quick-and-easy-file-dialog-in-python\r\n\r\nR. Linley\r\n2019-03-20\r\n\"\"\"\r\n\r\nimport tkinter as tk\r\nfrom tkinter import filedialog\r\n\r\nroot = tk.Tk()\r\nroot.withdraw()\r\n\r\ndef get_filename_from_dialog(types):\r\n \"\"\"\r\n Returns a file open dialogue box filtering for types, a tuple of tuples,\r\n each of which consists of a brief description of a file type, e.g., 'text\r\n files', followed by an appropriate file extension, e.g., 'txt'.\r\n \"\"\"\r\n root.wm_attributes('-topmost', 1)\r\n return filedialog.askopenfilename(filetypes=types)\r\n\r\nif __name__ == '__main__':\r\n # Testing!\r\n \r\n # In addition to demonstrating the opening of a file dialogue, this test\r\n # code reads and processes a comma-separated values (csv) text file of\r\n # numbers, a file structured somewhat like this:\r\n #\r\n # 3.2,-7,33,92\r\n # 1,2.0,15,153.2\r\n # ...\r\n #\r\n # I've over-commented since the code is likely to be hard to understand.\r\n\r\n # This next statement causes an open file dialogue to appear, and loads\r\n # csv_file_path with the name of the file (if any) selected by the user.\r\n csv_file_path = get_filename_from_dialog((\r\n ('comma-separated values', 'csv'),))\r\n\r\n # If the user closed the file dialogue without selecting a file,\r\n # csv_file_path will be the empty string, '', so this next if statement\r\n # guards against that possibility.\r\n if csv_file_path != '':\r\n # If execution got here, the user chose a csv file to open.\r\n # Python 3 has a csv module for handling csv files, but they can also\r\n # be opened for reading as simple text files.\r\n file = open(csv_file_path, 'r')\r\n # The next statement reads all the lines from the file into a\r\n # potentially very long string, and strips any blank lines at the ends.\r\n file_data = file.read().strip()\r\n # First, I'll split the string into a list of lines.\r\n lines = file_data.split('\\n') # \\n is the new-line character.\r\n # Then, I'll split each line at the commas\r\n for i in range(len(lines)):\r\n lines[i] = lines[i].split(',')\r\n # Finally, I'll convert the line elements to floats (numbers)\r\n for j in range(len(lines[i])):\r\n lines[i][j] = float(lines[i][j])\r\n # Now we can process the data from the file in its new form, lines,\r\n # which is a 2-d list of floats.\r\n for line in lines:\r\n line_sum = 0.0\r\n for val in line:\r\n print(val,'',end='') # print each value (on same line)\r\n line_sum += val\r\n print(line_sum) # print the sum and a new-line\r\n else:\r\n print ('No file selected.')\r\n\r\n","sub_path":"Assignment 1/file_dialog.py","file_name":"file_dialog.py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"458162946","text":"import sys\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom nltk.stem.snowball import EnglishStemmer\nimport nltk\nimport datetime\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom collections import Counter\n\n'''\nExtracting top words from 'desc' column and generating one hot encoding of the same\n'''\n\n# ------------------------------------------------- Initializing\n\nstart_time = datetime.datetime.now()\n\nstop = set(stopwords.words(\"english\"))\nstemmer = EnglishStemmer()\n\n# ------------------------------------------------- Helper Function for tokenizing/stemming string\n\n\ndef tokenizer(x):\n words = CountVectorizer().build_tokenizer()(x)\n ret = [stemmer.stem(w) for w in words if w.lower() not in stop]\n return list(set(ret))\n\n# ------------------------------------------------- Reading files\n\ntest = pd.read_csv(\"C:\\\\Users\\\\satvi\\\\Documents\\\\Projects\\\\Hackerearth - ML 2\\\\Data Files\\\\initial_proc_test.csv\",\n header=0, usecols=range(2,3), encoding='latin-1',\n converters={'desc': tokenizer})\n\ntrain = pd.read_csv(\"C:\\\\Users\\\\satvi\\\\Documents\\\\Projects\\\\Hackerearth - ML 2\\\\Data Files\\\\initial_proc_train.csv\",\n header=0, usecols=range(2,3), encoding='latin-1',\n converters={'desc': tokenizer})\n\n# ------------------------------------------------- Helper function to extract top words from test & train\n\ndef word_generator(df1, df2, type):\n df_words = Counter(\" \".join(df1[\"desc\"].str.join(' ')).split()).most_common(400)\n print(df_words)\n df_words_list = [x[0] for x in df_words]\n print(df_words_list)\n\n def one_hot_encoding(df, word_list, type2):\n tw = pd.DataFrame()\n for word in word_list:\n print(word)\n tw[word] = df.apply(lambda x: 1 if word in x['desc'] else 0, axis=1)\n print(tw.shape)\n path = \"C:\\\\Users\\\\satvi\\\\Documents\\\\Projects\\\\Hackerearth - ML 2\\\\Data Files\\\\\"+ str(type) + \"_words_in_\" + str(type2) + \".csv\"\n tw.to_csv(path, index=False)\n\n if type == \"test\":\n one_hot_encoding(df1, df_words_list, \"test\")\n one_hot_encoding(df2, df_words_list, \"train\")\n else:\n one_hot_encoding(df1, df_words_list, \"train\")\n one_hot_encoding(df2, df_words_list, \"test\")\n\nword_generator(test, train, \"test\")\nword_generator(train, test, \"train\")\nprint(\"Time taken: \" + str(datetime.datetime.now() - start_time))\n\n","sub_path":"Hackerearth - ML 2/Extracting_words_desc.py","file_name":"Extracting_words_desc.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"152889079","text":"from django.shortcuts import render, get_object_or_404\n\nfrom django.http import HttpResponseRedirect, Http404\n\nfrom blog.models import Post, Comment\n\ndef home(request):\n response = {\n 'POSTS': Post.objects.filter(published=True)\n }\n return render(request, 'home.html', response)\n\ndef post(request, post_id):\n response = {\n 'POST': get_object_or_404(Post, id=post_id)\n }\n return render(request, 'post.html', response)\n\ndef comment(request, post_id):\n post = get_object_or_404(Post, id=post_id)\n if request.method == 'POST':\n comment = request.POST.get('comment', None)\n comment = Comment(post=post, comment=comment, user=request.user)\n comment.save()\n return HttpResponseRedirect('/%d/' % (post.id))\n raise Http404\n","sub_path":"myproject/myproject/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"453688783","text":"from selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom urllib.parse import quote\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\nbrowser = webdriver.Chrome()\nwait = WebDriverWait(browser,10)\nKEYWORD = 'ipad'\n\ndef index_page(page):\n \"\"\"\n 抓取索引页\n :param page:页码\n \"\"\"\n print(\"正在抓取第\",page,\"页\")\n try:\n url = 'https://s.taobao.com/search?q='+ quote(KEYWORD)\n browser.get(url)\n if page > 1:\n input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.form > input')))\n submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit')))\n input.clear()\n input.send_keys(page)\n submit.click()\n wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page)))\n wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-itemlist > div > div > div:nth-child(1) > div.item')))\n get_products()\n except TimeoutException:\n index_page(page)\n\nfrom pyquery import PyQuery as py\ndef get_products():\n \"\"\"\n 提取商品数据\n \"\"\"\n html = browser.page_source\n doc = py(html)\n items = doc('#mainsrp-itemlist .items .item').items()\n for item in items:\n product = {\n 'image': item.find('.pie .img').attr('data-src'),\n 'price': item.find('.price').text(),\n 'deal':item.find('.deal-cnt').text(),\n 'title': item.find('.title').text(),\n 'shop': item.find('.shop').text(),\n 'location ':item.find('.location').text()\n }\n print(product)\n # save_to_mango(product)\n\nimport pymongo\nMONGO_URL = \"localhost\"\nMONGO_DB = 'taobao'\nMONGO_COLLECTION = 'products'\nclient = pymongo.MongoClient(MONGO_URL)\ndb = client[MONGO_DB]\ndef save_to_mango(product):\n \"\"\"\n 保存至MONGODB\n \"\"\"\n try:\n if db[MONGO_COLLECTION].insert(product):\n print(\"保存成功\")\n except Exception:\n print(\"保存失败\")\n\nMAX_PAGE = 5\ndef main():\n for i in range(1,MAX_PAGE+1):\n index_page(i)\n\nif __name__ == '__main__':\n main()","sub_path":"Spider/selenium/taobao.py","file_name":"taobao.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"425410278","text":"import inspect\nimport contextlib\nimport io\nfrom discord.ext import commands\n\n\nclass AdminCog(commands.Cog, name=\"Admin\"):\n def __init__(self, client):\n self.client = client\n self.description = \"This module is meant to be used by the owner of the bot.\"\n self.tonys_a_cunt = [\n \"\\u0628\",\n \"\\u064d\",\n \"\\u0631\",\n ]\n\n @commands.command(name=\"run\", hidden=True,\n help=\"Executes Python code from Discord on the bot.\\n\"\n \"(Can be dangerous, reserved for only the owner)\",\n brief=\"Executes Python code.\",\n usage=\"```py ```\")\n @commands.is_owner()\n async def run(self, ctx, *, code):\n code = code.replace('```py', '')\n code = code.replace('```', '')\n python = '```py\\n{}\\n```'\n result = None\n env = {\n 'client': self.client,\n 'ctx': ctx,\n 'message': ctx.message,\n 'guild': ctx.message.guild,\n 'channel': ctx.message.channel,\n 'author': ctx.message.author\n }\n env.update(globals())\n str_obj = io.StringIO() # Retrieves a stream of data\n try:\n with contextlib.redirect_stdout(str_obj):\n result = exec(code, env)\n if inspect.isawaitable(result):\n await result\n return\n except Exception as e:\n return await ctx.send(f\"```{e.__class__.__name__}: {e}```\")\n if str_obj.getvalue() != \"\":\n await ctx.send(f'```{str_obj.getvalue()}```')\n\n @commands.command(name='load', hidden=True, help=\"Loads a cog into the bot to extend bot functionality.\",\n brief=\"Loads a cog.\")\n @commands.is_owner()\n async def load(self, ctx, *, cog: str):\n \"\"\"Command which Loads a Module.\"\"\"\n try:\n self.client.load_extension(cog)\n except Exception as e:\n await ctx.send(f'**`ERROR:`**\\n {type(e).__name__} - {e}')\n else:\n await ctx.send(f\"`{cog}` has been loaded!\", delete_after=5)\n\n @commands.command(name='unload', hidden=True, help=\"Unloads a cog from the bot.\", brief=\"Unloads a cog.\")\n @commands.is_owner()\n async def unload(self, ctx, *, cog: str):\n \"\"\"Command which Unloads a Module.\"\"\"\n try:\n if cog == \"modules.admin\":\n await ctx.send(\"It's not recommended to unload the admin cog.\", delete_after=5)\n return\n self.client.unload_extension(cog)\n except Exception as e:\n await ctx.send(f'**`ERROR:`**\\n {type(e).__name__} - {e}')\n else:\n await ctx.send(f\"`{cog}` has been unloaded!\", delete_after=5)\n\n @commands.command(name='reload', hidden=True,\n help=\"Reloads a cog into the bot.\\nUseful for when updating the cogs separate from the bot.\",\n brief=\"Reloads a cog.\")\n @commands.is_owner()\n async def reload(self, ctx, *, cog: str):\n \"\"\"Command which Reloads a Module.\"\"\"\n try:\n self.client.unload_extension(cog)\n self.client.load_extension(cog)\n except Exception as e:\n await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}')\n else:\n await ctx.send(f\"`{cog}` has been reloaded!\", delete_after=5)\n\n @commands.Cog.listener()\n async def on_message(self, message):\n if any(bad in message.content for bad in self.tonys_a_cunt):\n await message.delete()\n dmchannel = await message.author.create_dm()\n await dmchannel.send(\"You're a cunt for trying that.\")\n return\n\n\ndef setup(client):\n client.add_cog(AdminCog(client))\n","sub_path":"modules/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"609211636","text":"#! /usr/bin/env python\n### tensorflow==2.3.1\nimport os\nimport sys\nimport argparse\nimport numpy as np\nfrom pathlib import Path\nimport re\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\nclass Color:\n BLACK = '\\033[30m'\n RED = '\\033[31m'\n GREEN = '\\033[32m'\n YELLOW = '\\033[33m'\n BLUE = '\\033[34m'\n MAGENTA = '\\033[35m'\n CYAN = '\\033[36m'\n WHITE = '\\033[37m'\n COLOR_DEFAULT = '\\033[39m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n INVISIBLE = '\\033[08m'\n REVERCE = '\\033[07m'\n BG_BLACK = '\\033[40m'\n BG_RED = '\\033[41m'\n BG_GREEN = '\\033[42m'\n BG_YELLOW = '\\033[43m'\n BG_BLUE = '\\033[44m'\n BG_MAGENTA = '\\033[45m'\n BG_CYAN = '\\033[46m'\n BG_WHITE = '\\033[47m'\n BG_DEFAULT = '\\033[49m'\n RESET = '\\033[0m'\n\ndef convert(saved_model_dir_path,\n signature_def,\n input_shapes,\n model_output_dir_path,\n output_no_quant_float32_tflite,\n output_weight_quant_tflite,\n output_float16_quant_tflite,\n output_integer_quant_tflite,\n output_full_integer_quant_tflite,\n output_integer_quant_type,\n string_formulas_for_normalization,\n calib_ds_type,\n ds_name_for_tfds_for_calibration,\n split_name_for_tfds_for_calibration,\n download_dest_folder_path_for_the_calib_tfds,\n tfds_download_flg,\n output_tfjs,\n output_tftrt,\n output_coreml,\n output_edgetpu):\n\n print(f'{Color.REVERCE}Start conversion process from saved_model to tflite{Color.RESET}', '=' * 38)\n\n import subprocess\n import tensorflow as tf\n import tensorflow_datasets as tfds\n from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2_as_graph\n\n # Load saved_model and change input shape\n # https://github.com/tensorflow/tensorflow/issues/30180#issuecomment-505959220\n model = tf.saved_model.load(saved_model_dir_path)\n if signature_def:\n concrete_func = model.signatures[signature_def]\n else:\n concrete_func = model.signatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\n if input_shapes:\n concrete_func_input_tensors = [tensor for tensor in concrete_func.inputs if tensor.dtype != tf.resource and not 'unknown' in tensor.name]\n for conc_input, def_input in zip(concrete_func_input_tensors, input_shapes):\n print('Before changing the input shape', conc_input)\n conc_input.set_shape(def_input)\n print('After changing the input shape', conc_input)\n else:\n concrete_func_input_tensors = [tensor for tensor in concrete_func.inputs if tensor.dtype != tf.resource and not 'unknown' in tensor.name]\n for conc_input in concrete_func_input_tensors:\n input_shapes.append(conc_input.shape.as_list())\n\n # No Quantization - Input/Output=float32\n if output_no_quant_float32_tflite:\n try:\n print(f'{Color.REVERCE}tflite Float32 convertion started{Color.RESET}', '=' * 51)\n converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]\n tflite_model = converter.convert()\n with open(f'{model_output_dir_path}/model_float32.tflite', 'wb') as w:\n w.write(tflite_model)\n print(f'{Color.GREEN}tflite Float32 convertion complete!{Color.RESET} - {model_output_dir_path}/model_float32.tflite')\n except Exception as e:\n print(f'{Color.RED}ERROR:{Color.RESET}', e)\n import traceback\n traceback.print_exc()\n\n # Weight Quantization - Input/Output=float32\n if output_weight_quant_tflite:\n try:\n print(f'{Color.REVERCE}Weight Quantization started{Color.RESET}', '=' * 57)\n converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]\n converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]\n tflite_model = converter.convert()\n with open(f'{model_output_dir_path}/model_weight_quant.tflite', 'wb') as w:\n w.write(tflite_model)\n print(f'{Color.GREEN}Weight Quantization complete!{Color.RESET} - {model_output_dir_path}/model_weight_quant.tflite')\n except Exception as e:\n print(f'{Color.RED}ERROR:{Color.RESET}', e)\n import traceback\n traceback.print_exc()\n\n # Float16 Quantization - Input/Output=float32\n if output_float16_quant_tflite:\n try:\n print(f'{Color.REVERCE}Float16 Quantization started{Color.RESET}', '=' * 56)\n converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n converter.optimizations = [tf.lite.Optimize.DEFAULT]\n converter.target_spec.supported_types = [tf.float16]\n converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]\n tflite_quant_model = converter.convert()\n with open(f'{model_output_dir_path}/model_float16_quant.tflite', 'wb') as w:\n w.write(tflite_quant_model)\n print(f'{Color.GREEN}Float16 Quantization complete!{Color.RESET} - {model_output_dir_path}/model_float16_quant.tflite')\n except Exception as e:\n print(f'{Color.RED}ERROR:{Color.RESET}', e)\n import traceback\n traceback.print_exc()\n\n # Downloading datasets for calibration\n raw_test_data = None\n if output_integer_quant_tflite or output_full_integer_quant_tflite:\n if calib_ds_type == 'tfds':\n print(f'{Color.REVERCE}TFDS download started{Color.RESET}', '=' * 63)\n raw_test_data = tfds.load(name=ds_name_for_tfds_for_calibration,\n with_info=False,\n split=split_name_for_tfds_for_calibration,\n data_dir=download_dest_folder_path_for_the_calib_tfds,\n download=tfds_download_flg)\n print(f'{Color.GREEN}TFDS download complete!{Color.RESET}')\n elif calib_ds_type == 'numpy':\n pass\n else:\n pass\n\n def representative_dataset_gen():\n for data in raw_test_data.take(10):\n image = data['image'].numpy()\n images = []\n for shape in input_shapes:\n data = tf.image.resize(image, (shape[1], shape[2]))\n tmp_image = eval(string_formulas_for_normalization) # Default: (data - [127.5,127.5,127.5]) / [127.5,127.5,127.5]\n tmp_image = tf.repeat(tmp_image[np.newaxis,:,:,:], 2, axis=-1)\n print('@@@@@@@@@', tmp_image.shape)\n images.append(tmp_image)\n yield images\n\n # Integer Quantization\n if output_integer_quant_tflite:\n try:\n print(f'{Color.REVERCE}Integer Quantization started{Color.RESET}', '=' * 56)\n converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n converter.optimizations = [tf.lite.Optimize.DEFAULT]\n converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8, tf.lite.OpsSet.SELECT_TF_OPS]\n converter.representative_dataset = representative_dataset_gen\n tflite_model = converter.convert()\n with open(f'{model_output_dir_path}/model_integer_quant.tflite', 'wb') as w:\n w.write(tflite_model)\n print(f'{Color.GREEN}Integer Quantization complete!{Color.RESET} - {model_output_dir_path}/model_integer_quant.tflite')\n except Exception as e:\n print(f'{Color.RED}ERROR:{Color.RESET}', e)\n import traceback\n traceback.print_exc()\n\n # Full Integer Quantization\n if output_full_integer_quant_tflite:\n try:\n print(f'{Color.REVERCE}Full Integer Quantization started{Color.RESET}', '=' * 51)\n converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n converter.optimizations = [tf.lite.Optimize.DEFAULT]\n converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8, tf.lite.OpsSet.SELECT_TF_OPS]\n inf_type = None\n if output_integer_quant_type == 'int8':\n inf_type = tf.int8\n elif output_integer_quant_type == 'uint8':\n inf_type = tf.uint8\n else:\n inf_type = tf.int8\n converter.inference_input_type = inf_type\n converter.inference_output_type = inf_type\n converter.representative_dataset = representative_dataset_gen\n tflite_model = converter.convert()\n with open(f'{model_output_dir_path}/model_full_integer_quant.tflite', 'wb') as w:\n w.write(tflite_model)\n print(f'{Color.GREEN}Full Integer Quantization complete!{Color.RESET} - {model_output_dir_path}/model_full_integer_quant.tflite')\n except Exception as e:\n print(f'{Color.RED}ERROR:{Color.RESET}', e)\n import traceback\n traceback.print_exc()\n\n # EdgeTPU convert\n if output_edgetpu:\n try:\n print(f'{Color.REVERCE}EdgeTPU convertion started{Color.RESET}', '=' * 58)\n result = subprocess.check_output(['edgetpu_compiler',\n '-o', model_output_dir_path,\n '-s',\n f'{model_output_dir_path}/model_full_integer_quant.tflite'],\n stderr=subprocess.PIPE).decode('utf-8')\n print(result)\n print(f'{Color.GREEN}EdgeTPU convert complete!{Color.RESET} - {model_output_dir_path}/model_full_integer_quant_edgetpu.tflite')\n except subprocess.CalledProcessError as e:\n print(f'{Color.RED}ERROR:{Color.RESET}', e.stderr.decode('utf-8'))\n import traceback\n traceback.print_exc()\n print(\"-\" * 80)\n print('Please install edgetpu_compiler according to the following website.')\n print('https://coral.ai/docs/edgetpu/compiler/#system-requirements')\n\n # TensorFlow.js convert\n if output_tfjs:\n import subprocess\n try:\n print(f'{Color.REVERCE}TensorFlow.js Float32 convertion started{Color.RESET}', '=' * 44)\n result = subprocess.check_output(['tensorflowjs_converter',\n '--input_format', 'tf_saved_model',\n '--output_format', 'tfjs_graph_model',\n '--signature_name', 'serving_default',\n '--saved_model_tags', 'serve',\n saved_model_dir_path, f'{model_output_dir_path}/tfjs_model_float32'],\n stderr=subprocess.PIPE).decode('utf-8')\n print(result)\n print(f'{Color.GREEN}TensorFlow.js convertion complete!{Color.RESET} - {model_output_dir_path}/tfjs_model_float32')\n except subprocess.CalledProcessError as e:\n print(f'{Color.RED}ERROR:{Color.RESET}', e.stderr.decode('utf-8'))\n import traceback\n traceback.print_exc()\n try:\n print(f'{Color.REVERCE}TensorFlow.js Float16 convertion started{Color.RESET}', '=' * 44)\n result = subprocess.check_output(['tensorflowjs_converter',\n '--quantize_float16',\n '--input_format', 'tf_saved_model',\n '--output_format', 'tfjs_graph_model',\n '--signature_name', 'serving_default',\n '--saved_model_tags', 'serve',\n saved_model_dir_path, f'{model_output_dir_path}/tfjs_model_float16'],\n stderr=subprocess.PIPE).decode('utf-8')\n print(result)\n print(f'{Color.GREEN}TensorFlow.js convertion complete!{Color.RESET} - {model_output_dir_path}/tfjs_model_float16')\n except subprocess.CalledProcessError as e:\n print(f'{Color.RED}ERROR:{Color.RESET}', e.stderr.decode('utf-8'))\n import traceback\n traceback.print_exc()\n\n # TF-TRT (TensorRT) convert\n if output_tftrt:\n try:\n def input_fn():\n input_shapes_tmp = []\n for tf_input in input_shapes:\n input_shapes_tmp.append(np.zeros(tf_input).astype(np.float32))\n yield input_shapes_tmp\n\n print(f'{Color.REVERCE}TF-TRT (TensorRT) Float32 convertion started{Color.RESET}', '=' * 40)\n params = tf.experimental.tensorrt.ConversionParams(precision_mode='FP32', maximum_cached_engines=10000)\n converter = tf.experimental.tensorrt.Converter(input_saved_model_dir=saved_model_dir_path, conversion_params=params)\n converter.convert()\n converter.build(input_fn=input_fn)\n converter.save(f'{model_output_dir_path}/tensorrt_saved_model_float32')\n print(f'{Color.GREEN}TF-TRT (TensorRT) convertion complete!{Color.RESET} - {model_output_dir_path}/tensorrt_saved_model_float32')\n print(f'{Color.REVERCE}TF-TRT (TensorRT) Float16 convertion started{Color.RESET}', '=' * 40)\n params = tf.experimental.tensorrt.ConversionParams(precision_mode='FP16', maximum_cached_engines=10000)\n converter = tf.experimental.tensorrt.Converter(input_saved_model_dir=saved_model_dir_path, conversion_params=params)\n converter.convert()\n converter.build(input_fn=input_fn)\n converter.save(f'{model_output_dir_path}/tensorrt_saved_model_float16')\n print(f'{Color.GREEN}TF-TRT (TensorRT) convertion complete!{Color.RESET} - {model_output_dir_path}/tensorrt_saved_model_float16')\n except Exception as e:\n print(f'{Color.RED}ERROR:{Color.RESET}', e)\n import traceback\n traceback.print_exc()\n print(f'{Color.RED}The binary versions of TensorFlow and TensorRT may not be compatible. Please check the version compatibility of each package.{Color.RESET}')\n\n # CoreML convert\n if output_coreml:\n try:\n import coremltools as ct\n print(f'{Color.REVERCE}CoreML convertion started{Color.RESET}', '=' * 59)\n mlmodel = ct.convert(saved_model_dir_path, source='tensorflow')\n mlmodel.save(f'{model_output_dir_path}/model_coreml_float32.mlmodel')\n print(f'{Color.GREEN}CoreML convertion complete!{Color.RESET} - {model_output_dir_path}/model_coreml_float32.mlmodel')\n except Exception as e:\n print(f'{Color.RED}ERROR:{Color.RESET}', e)\n import traceback\n traceback.print_exc()\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--saved_model_dir_path', type=str, required=True, help='Input saved_model dir path')\n parser.add_argument('--signature_def', type=str, default='', help='Specifies the signature name to load from saved_model')\n parser.add_argument('--input_shapes', type=str, default='', help='Overwrites an undefined input dimension (None or -1). Specify the input shape in [n,h,w,c] format. For non-4D tensors, specify [a,b,c,d,e], [a,b], etc. A comma-separated list if there are multiple inputs. (e.g.) --input_shapes [1,256,256,3],[1,64,64,3],[1,2,16,16,3]')\n parser.add_argument('--model_output_dir_path', type=str, default='tflite_from_saved_model', help='The output folder path of the converted model file')\n parser.add_argument('--output_no_quant_float32_tflite', type=bool, default=False, help='float32 tflite output switch')\n parser.add_argument('--output_weight_quant_tflite', type=bool, default=False, help='weight quant tflite output switch')\n parser.add_argument('--output_float16_quant_tflite', type=bool, default=False, help='float16 quant tflite output switch')\n parser.add_argument('--output_integer_quant_tflite', type=bool, default=False, help='integer quant tflite output switch')\n parser.add_argument('--output_full_integer_quant_tflite', type=bool, default=False, help='full integer quant tflite output switch')\n parser.add_argument('--output_integer_quant_type', type=str, default='int8', help='Input and output types when doing Integer Quantization (\\'int8 (default)\\' or \\'uint8\\')')\n parser.add_argument('--string_formulas_for_normalization', type=str, default='(data - [127.5,127.5,127.5]) / [127.5,127.5,127.5]', help='String formulas for normalization. It is evaluated by Python\\'s eval() function. Default: \\'(data - [127.5,127.5,127.5]) / [127.5,127.5,127.5]\\'')\n parser.add_argument('--calib_ds_type', type=str, default='tfds', help='Types of data sets for calibration. tfds or numpy(Future Implementation)')\n parser.add_argument('--ds_name_for_tfds_for_calibration', type=str, default='coco/2017', help='Dataset name for TensorFlow Datasets for calibration. https://www.tensorflow.org/datasets/catalog/overview')\n parser.add_argument('--split_name_for_tfds_for_calibration', type=str, default='validation', help='Split name for TensorFlow Datasets for calibration. https://www.tensorflow.org/datasets/catalog/overview')\n tfds_dl_default_path = f'{str(Path.home())}/TFDS'\n parser.add_argument('--download_dest_folder_path_for_the_calib_tfds', type=str, default=tfds_dl_default_path, help='Download destination folder path for the calibration dataset. Default: $HOME/TFDS')\n parser.add_argument('--tfds_download_flg', type=bool, default=True, help='True to automatically download datasets from TensorFlow Datasets. True or False')\n parser.add_argument('--output_tfjs', type=bool, default=False, help='tfjs model output switch')\n parser.add_argument('--output_tftrt', type=bool, default=False, help='tftrt model output switch')\n parser.add_argument('--output_coreml', type=bool, default=False, help='coreml model output switch')\n parser.add_argument('--output_edgetpu', type=bool, default=False, help='edgetpu model output switch')\n\n args = parser.parse_args()\n saved_model_dir_path = args.saved_model_dir_path\n signature_def = args.signature_def\n input_shapes_tmp = args.input_shapes\n input_shapes = []\n if input_shapes_tmp:\n first_digit_reg = r'([0-9 ]+|-1)'\n next_digits_reg = r'(,{})*'.format(first_digit_reg)\n tuple_reg = r'((\\({}{}\\))|(\\[{}{}\\]))'.format(first_digit_reg, next_digits_reg, first_digit_reg, next_digits_reg)\n full_reg = r'^{}(\\s*,\\s*{})*$|^$'.format(tuple_reg, tuple_reg)\n if not re.match(full_reg, input_shapes_tmp):\n print('Input shape \"{}\" cannot be parsed.', input_shapes_tmp)\n for shape_str in re.findall(r'[(\\[]([0-9, -]+)[)\\]]', input_shapes_tmp):\n input_shapes.append([int(dim) for dim in shape_str.split(',')])\n model_output_dir_path = args.model_output_dir_path\n output_no_quant_float32_tflite = args.output_no_quant_float32_tflite\n output_weight_quant_tflite = args.output_weight_quant_tflite\n output_float16_quant_tflite = args.output_float16_quant_tflite\n output_integer_quant_tflite = args.output_integer_quant_tflite\n output_full_integer_quant_tflite = args.output_full_integer_quant_tflite\n output_integer_quant_type = args.output_integer_quant_type.lower()\n string_formulas_for_normalization = args.string_formulas_for_normalization.lower()\n calib_ds_type = args.calib_ds_type.lower()\n ds_name_for_tfds_for_calibration = args.ds_name_for_tfds_for_calibration\n split_name_for_tfds_for_calibration = args.split_name_for_tfds_for_calibration\n download_dest_folder_path_for_the_calib_tfds = args.download_dest_folder_path_for_the_calib_tfds\n tfds_download_flg = args.tfds_download_flg\n output_tfjs = args.output_tfjs\n output_tftrt = args.output_tftrt\n output_coreml = args.output_coreml\n output_edgetpu = args.output_edgetpu\n\n if not output_no_quant_float32_tflite and \\\n not output_weight_quant_tflite and \\\n not output_integer_quant_tflite and \\\n not output_full_integer_quant_tflite and \\\n not output_tfjs and \\\n not output_tftrt and \\\n not output_coreml and \\\n not output_edgetpu:\n print('Set at least one of the output switches (output_*) to true.')\n sys.exit(-1)\n\n if output_edgetpu:\n output_full_integer_quant_tflite = True\n\n from pkg_resources import working_set\n package_list = []\n for dist in working_set:\n package_list.append(dist.project_name)\n\n if output_tfjs:\n if not 'tensorflowjs' in package_list:\n print('\\'tensorflowjs\\' is not installed. Please run the following command to install \\'tensorflowjs\\'.')\n print('pip3 install --upgrade tensorflowjs')\n sys.exit(-1)\n if output_tftrt:\n if not 'tensorrt' in package_list:\n print('\\'tensorrt\\' is not installed. Please check the following website and install \\'tensorrt\\'.')\n print('https://docs.nvidia.com/deeplearning/tensorrt/install-guide/index.html')\n sys.exit(-1)\n if output_coreml:\n if not 'coremltools' in package_list:\n print('\\'coremltoos\\' is not installed. Please run the following command to install \\'coremltoos\\'.')\n print('pip3 install --upgrade coremltools')\n sys.exit(-1)\n\n if output_integer_quant_tflite or output_full_integer_quant_tflite:\n if not 'tensorflow-datasets' in package_list:\n print('\\'tensorflow-datasets\\' is not installed. Please run the following command to install \\'tensorflow-datasets\\'.')\n print('pip3 install --upgrade tensorflow-datasets')\n sys.exit(-1)\n\n if output_integer_quant_type == 'int8' or output_integer_quant_type == 'uint8':\n pass\n else:\n print('Only \\'int8\\' or \\'uint8\\' can be specified for output_integer_quant_type.')\n sys.exit(-1)\n\n if calib_ds_type == 'tfds':\n pass\n elif calib_ds_type == 'numpy':\n print('The Numpy mode of the data set for calibration will be implemented in the future.')\n sys.exit(-1)\n else:\n print('Only \\'tfds\\' or \\'numpy\\' can be specified for calib_ds_type.')\n sys.exit(-1)\n\n del package_list\n os.makedirs(model_output_dir_path, exist_ok=True)\n convert(saved_model_dir_path,\n signature_def,\n input_shapes,\n model_output_dir_path,\n output_no_quant_float32_tflite,\n output_weight_quant_tflite,\n output_float16_quant_tflite,\n output_integer_quant_tflite,\n output_full_integer_quant_tflite,\n output_integer_quant_type,\n string_formulas_for_normalization,\n calib_ds_type,\n ds_name_for_tfds_for_calibration,\n split_name_for_tfds_for_calibration,\n download_dest_folder_path_for_the_calib_tfds,\n tfds_download_flg,\n output_tfjs,\n output_tftrt,\n output_coreml,\n output_edgetpu)\n print(f'{Color.REVERCE}All the conversion process is finished!{Color.RESET}', '=' * 45)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"086_defocus-deblurring-dual-pixel/02_saved_model_to_tflite_custom.py","file_name":"02_saved_model_to_tflite_custom.py","file_ext":"py","file_size_in_byte":23767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"606109816","text":"#\n# @lc app=leetcode.cn id=138 lang=python3\n#\n# [138] 复制带随机指针的链表\n#\n# https://leetcode-cn.com/problems/copy-list-with-random-pointer/description/\n#\n# algorithms\n# Medium (47.18%)\n# Likes: 225\n# Dislikes: 0\n# Total Accepted: 23.7K\n# Total Submissions: 50.1K\n# Testcase Example: '[[7,null],[13,0],[11,4],[10,2],[1,0]]'\n#\n# 给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。\n# \n# 要求返回这个链表的 深拷贝。 \n# \n# 我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:\n# \n# \n# val:一个表示 Node.val 的整数。\n# random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为  null 。\n# \n# \n# \n# \n# 示例 1:\n# \n# \n# \n# 输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]\n# 输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]\n# \n# \n# 示例 2:\n# \n# \n# \n# 输入:head = [[1,1],[2,1]]\n# 输出:[[1,1],[2,1]]\n# \n# \n# 示例 3:\n# \n# \n# \n# 输入:head = [[3,null],[3,0],[3,null]]\n# 输出:[[3,null],[3,0],[3,null]]\n# \n# \n# 示例 4:\n# \n# 输入:head = []\n# 输出:[]\n# 解释:给定的链表为空(空指针),因此返回 null。\n# \n# \n# \n# \n# 提示:\n# \n# \n# -10000 <= Node.val <= 10000\n# Node.random 为空(null)或指向链表中的节点。\n# 节点数目不超过 1000 。\n# \n# \n#\n\n# @lc code=start\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\"\"\"\n\n# 方法一: 用一个 hashmap\nclass Solution:\n def copyRandomList(self, head: 'Node') -> 'Node':\n if not head:\n return None\n mapping = self.get_mapping(head)\n self.copy_nodes(head, mapping)\n return mapping[head]\n\n def get_mapping(self, head):\n mapping = {}\n node = head\n while node:\n new_node = Node(node.val)\n mapping[node] = new_node\n node = node.next\n return mapping\n\n def copy_nodes(self, head, mapping):\n node = head\n while node:\n new_node = mapping[node]\n new_next, new_random = None, None\n if node.random:\n new_random = mapping[node.random]\n if node.next:\n new_next = mapping[node.next]\n new_node.next = new_next\n new_node.random = new_random\n node = node.next\n \n# 方法二: 改变链表结构\nclass Solution:\n def copyRandomList(self, head: 'Node') -> 'Node':\n if not head:\n return None\n root = self.generate_new_head(head)\n while root:\n next_original = root.next.next\n root.next.next = next_original.next if next_original else None\n root.next.random = root.random.next if root.random else None\n root = next_original\n return head.next\n\n def generate_new_head(self, head):\n node = head\n while node:\n new_node = Node(node.val)\n new_node.next = node.next\n node.next = new_node\n node = new_node.next\n return head\n\n# @lc code=end\n\n","sub_path":"Week_01/G20200343030459/138.复制带随机指针的链表.py","file_name":"138.复制带随机指针的链表.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"416551945","text":"import requests\nimport sys\nimport time\nfile_url = \"http://codex.cs.yale.edu/avi/db-book/db4/slide-dir/ch1-2.pdf\"\n\n# 屏蔽warning信息,因为下面verify=False会报警告信息\nrequests.packages.urllib3.disable_warnings()\n# verify=False 这一句是为了有的网站证书问题,为True会报错\nr = requests.get(file_url, stream=True, verify=False)\nlength = float(r.headers['content-length'])\nprint(length)\n# 既然要实现下载进度,那就要知道你文件大小啊,下面这句就是得到总大小\ntotal_size = int(r.headers['Content-Length'])\ncount = 0\ntime1 = time.time()\nwith open(\"F:\\python.pdf\", \"wb\") as f:\n\n for chunk in r.iter_content(chunk_size=1024):\n if chunk:\n f.write(chunk)\n count += len(chunk)\n ############# 花哨的下载进度部分 ###############\n count += len(chunk)\n if time.time() - time1 > 2:\n p = count / length * 100\n speed = (count - count_tmp) / 1024 / 1024 / 2\n count_tmp = count\n print(\"python\" + ': ' + '{:.2f}'.format(p) + '%' + ' Speed: ' + '{:.2f}'.format(speed) + 'M/S')\n time1 = time.time()\n\n\n \n\n","sub_path":"project1/H四川省卫生委员会/工具包/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"612863388","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\n\nlogger = logging.getLogger('api')\nlogger.setLevel(logging.INFO)\n\nformatter = logging.Formatter(\n '%(asctime)s [%(levelname)s] ** %(message)s',\n datefmt='%y-%m-%d %H:%M:%S'\n)\n\nlogFile = os.path.join('log', 'api', 'serve.log')\nhandler = RotatingFileHandler(logFile, maxBytes=4999999, backupCount=9)\nhandler.setFormatter(formatter)\n\nlogger.addHandler(handler)\n","sub_path":"python/Flask/RestApiTemplate/api/common/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"376173770","text":"from . import manage\nfrom flask_login import login_required\nfrom flask import request, jsonify\nfrom .models import Attr\nfrom sqlalchemy import or_\nimport json\nfrom .models import *\nfrom ..main.models import ProjectRelation, Project\nimport math\nfrom ..main.models import ProjectData\nfrom ..models import Modification\n\n\n@manage.route('/attr/content/add', methods=['POST'])\n@login_required\ndef add_attr_content():\n from ..main.api_data import split_default_val\n from ..main.test import get_did_default_val, str_to_hex\n\n project_id = request.args.get('project_id')\n level = request.form.get('level')\n project_relation_id = request.form.get('project_relation_id')\n\n if not project_id or not project_relation_id or not level:\n return jsonify({'success': False, 'message': '提交参数缺失'})\n\n project_relation = ProjectRelation.query.get_or_404(project_relation_id)\n\n # this is byte len\n prev_pr = ProjectRelation.query.filter_by(id=project_relation.parent_id).first()\n prev_attr_content = AttrContent.query.filter_by(project_relation_id=prev_pr.id if prev_pr else 0).first()\n did_byte_len = json.loads(prev_attr_content.real_content).get('DidLength',\n 0) if prev_attr_content and prev_attr_content.real_content else 0\n\n byte_val = 0\n current = AttrContent.query.filter_by(project_relation_id=project_relation_id).first()\n if current and current.real_content:\n byte_val = json.loads(current.real_content).get('BytePosition', 0)\n\n form_data = request.form.to_dict()\n\n attr = Attr.query.filter_by(level=level).first()\n\n content = json.loads(attr.content) if attr and attr.content else []\n result = [info['item'] for info in content if info.get('item_required')]\n\n if result:\n for r in result:\n if not form_data.get(r):\n return jsonify({'success': False, 'message': '请检查【%s】,是否必须填写' % r})\n\n if form_data.get('BytePosition') and int(form_data['BytePosition']) > int(did_byte_len):\n return jsonify({'success': False, 'message': 'BytePositionc 数字在0-%s之间' % int(did_byte_len)})\n\n if form_data.get('BitPosition') and int(form_data['BitPosition']) > 7:\n return jsonify({'success': False, 'message': 'BitPosition 在0-7之间'})\n\n if form_data.get('BitLength'):\n input_number = 16 - int(form_data['BitPosition'])\n if int(form_data['BitLength']) > input_number:\n return jsonify({'success': False, 'message': '只能跨2个字节,BitLength 请输入小于等于%d数字' % input_number})\n\n if form_data.get('DidLength') and form_data.get('DefaultValue'):\n # all_default_conf = get_did_default_val(project_id)\n # is_have = str(list(all_default_conf.values())[0]).replace('0', '')\n # if not is_have:\n # form_data['DefaultValue'] = split_default_val(form_data['DefaultValue'], int(form_data['DidLength']) * 2)\n form_data['DefaultValue'] = split_default_val(form_data['DefaultValue'], int(form_data['DidLength']) * 2)\n # else:\n # form_data['DefaultValue'] = str_to_hex(all_default_conf[int(project_relation_id)])\n\n AttrContent.create_edit(form_data, project_id, project_relation_id)\n\n update_project_config_name(form_data, project_id)\n\n if level and int(level) == 3:\n Modification.add_edit(project_id)\n\n # change byte project data\n if form_data.get('BytePosition') and int(form_data['BytePosition']) != int(byte_val):\n pd_ids = ProjectRelation.query.filter_by(parent_id=project_relation.id).all()\n pd_ids = [v.id for v in pd_ids]\n # print(pd_ids)\n project_data = ProjectData.query.filter(ProjectData.project_relation_id.in_(pd_ids) if pd_ids else False).all()\n if project_data:\n for pd in project_data:\n content = json.loads(pd.content or '{}')\n # print(content)\n has_content = {k: v for k, v in content.items() if v}\n if has_content:\n info_byte = content['byte%s' % byte_val]\n content['byte%s' % byte_val] = \"\"\n content['byte%s' % form_data['BytePosition']] = info_byte\n pd.content = json.dumps(content)\n db.session.add(pd)\n\n return jsonify({'success': True, 'message': '更新成功'})\n\n\n# update project file name\ndef update_project_config_name(form_data, project_id):\n project_config_name = form_data.get('ConfigurationFileNumber')\n if project_config_name:\n project = Project.query.filter_by(id=project_id).first()\n if project:\n project.project_config_name = project_config_name\n db.session.add(project)\n","sub_path":"console/app/manage/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"472532175","text":"import json\nimport threading\nimport base64\nimport time\n\nfrom core.decorators import instance, timerevent, event\nfrom core.logger import Logger\nfrom core.dict_object import DictObject\nfrom core.setting_types import ColorSettingType, TextSettingType, HiddenSettingType, BooleanSettingType\nfrom core.private_channel_service import PrivateChannelService\nfrom modules.core.org_members.org_member_controller import OrgMemberController\nfrom modules.standard.online.online_controller import OnlineController\nfrom .websocket_relay_worker import WebsocketRelayWorker\nfrom cryptography.fernet import Fernet\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC\n\n\n@instance()\nclass WebsocketRelayController:\n MESSAGE_SOURCE = \"websocket_relay\"\n\n def __init__(self):\n self.dthread = None\n self.queue = []\n self.logger = Logger(__name__)\n self.worker = None\n self.encrypter = None\n self.channels = {}\n\n def inject(self, registry):\n self.bot = registry.get_instance(\"bot\")\n self.db = registry.get_instance(\"db\")\n self.util = registry.get_instance(\"util\")\n self.setting_service = registry.get_instance(\"setting_service\")\n self.event_service = registry.get_instance(\"event_service\")\n self.relay_controller = registry.get_instance(\"relay_controller\")\n self.character_service = registry.get_instance(\"character_service\")\n self.pork_service = registry.get_instance(\"pork_service\")\n self.online_controller = registry.get_instance(\"online_controller\")\n self.public_channel_service = registry.get_instance(\"public_channel_service\")\n self.message_hub_service = registry.get_instance(\"message_hub_service\")\n\n def pre_start(self):\n self.message_hub_service.register_message_source(self.MESSAGE_SOURCE)\n\n def start(self):\n self.message_hub_service.register_message_destination(self.MESSAGE_SOURCE,\n self.handle_message_from_hub,\n [\"private_channel\", \"org_channel\", \"discord\", \"tell_relay\"],\n [self.MESSAGE_SOURCE])\n\n self.setting_service.register(self.module_name, \"websocket_relay_enabled\", False, BooleanSettingType(), \"Enable the websocket relay\")\n self.setting_service.register(self.module_name, \"websocket_relay_server_address\", \"ws://localhost/subscribe/relay\",\n TextSettingType([\"ws://localhost/subscribe/relay\", \"wss://relay.jkbff.com/subscribe/relay\"]),\n \"The address of the websocket relay server\",\n \"All bots on the relay must connect to the same server and channel. If using the public relay server, use a unique channel name. \"\n \"Example: ws://relay.jkbff.com/subscribe/unique123 (relay.jkbff.com is the server and unique123 is the channel)\")\n self.setting_service.register(self.module_name, \"websocket_relay_channel_color\", \"#FFFF00\", ColorSettingType(), \"Color of the channel in websocket relay messages\")\n self.setting_service.register(self.module_name, \"websocket_relay_message_color\", \"#FCA712\", ColorSettingType(), \"Color of the message content in websocket relay messages\")\n self.setting_service.register(self.module_name, \"websocket_relay_sender_color\", \"#00DE42\", ColorSettingType(), \"Color of the sender in websocket relay messages\")\n self.setting_service.register(self.module_name, \"websocket_encryption_key\", \"\", HiddenSettingType(allow_empty=True), \"An encryption key used to encrypt messages over a public websocket relay\")\n\n self.initialize_encrypter(self.setting_service.get(\"websocket_encryption_key\").get_value())\n\n self.setting_service.register_change_listener(\"websocket_relay_enabled\", self.websocket_relay_update)\n self.setting_service.register_change_listener(\"websocket_relay_server_address\", self.websocket_relay_update)\n self.setting_service.register_change_listener(\"websocket_encryption_key\", self.websocket_relay_update)\n\n def initialize_encrypter(self, password):\n if password:\n salt = b\"tyrbot\" # using hard-coded salt is less secure as it nullifies the function of the salt and allows for rainbow attacks\n kdf = PBKDF2HMAC(\n algorithm=hashes.SHA256(),\n length=32,\n salt=salt,\n iterations=10000,)\n key = base64.urlsafe_b64encode(kdf.derive(password.encode(\"utf-8\")))\n self.encrypter = Fernet(key)\n else:\n self.encrypter = None\n\n @timerevent(budatime=\"1s\", description=\"Relay messages from websocket relay to the internal message hub\", is_hidden=True, is_enabled=False)\n def handle_queue_event(self, event_type, event_data):\n while self.queue:\n obj = self.queue.pop(0)\n if obj.type == \"message\":\n payload = obj.payload\n self.process_relay_message(obj.client_id, payload)\n elif obj.type == \"ping\":\n return_obj = json.dumps({\"type\": \"ping\", \"payload\": obj.payload})\n self.worker.send_message(return_obj)\n elif obj.type == \"connected\":\n self.send_relay_message({\"type\": \"online_list_request\"})\n self.send_relay_message(self.get_online_list_obj())\n elif obj.type == \"joined\":\n pass\n elif obj.type == \"left\":\n for channel in self.channels.get(obj.client_id, []):\n self.online_controller.deregister_online_channel(channel)\n\n if obj.client_id in self.channels:\n del self.channels[obj.client_id]\n\n @timerevent(budatime=\"1m\", description=\"Ensure the bot is connected to websocket relay\", is_hidden=True, is_enabled=False, run_at_startup=True)\n def handle_connect_event(self, event_type, event_data):\n if not self.worker or not self.dthread.is_alive():\n self.connect()\n\n @event(PrivateChannelService.JOINED_PRIVATE_CHANNEL_EVENT, \"Send to websocket relay when someone joins private channel\", is_hidden=True, is_enabled=False)\n def private_channel_joined_event(self, event_type, event_data):\n self.send_relay_event(event_data.char_id, \"logon\", \"private_channel\")\n\n @event(PrivateChannelService.LEFT_PRIVATE_CHANNEL_EVENT, \"Send to websocket relay when someone joins private channel\", is_hidden=True, is_enabled=False)\n def private_channel_left_event(self, event_type, event_data):\n self.send_relay_event(event_data.char_id, \"logoff\", \"private_channel\")\n\n @event(OrgMemberController.ORG_MEMBER_LOGON_EVENT, \"Send to websocket relay when org member logs on\", is_hidden=True, is_enabled=False)\n def org_member_logon_event(self, event_type, event_data):\n self.send_relay_event(event_data.char_id, \"logon\", \"org_channel\")\n\n @event(OrgMemberController.ORG_MEMBER_LOGOFF_EVENT, \"Send to websocket relay when org member logs off\", is_hidden=True, is_enabled=False)\n def org_member_logoff_event(self, event_type, event_data):\n self.send_relay_event(event_data.char_id, \"logoff\", \"org_channel\")\n\n def process_relay_message(self, client_id, message):\n if self.encrypter:\n message = self.encrypter.decrypt(message.encode('utf-8'))\n obj = DictObject(json.loads(message))\n\n if obj.type == \"message\":\n channel = self.get_channel_name(obj.source)\n\n message = \"\"\n message += \"[%s] \" % self.setting_service.get(\"websocket_relay_channel_color\").format_text(channel)\n if obj.user:\n message += \"%s: \" % self.setting_service.get(\"websocket_relay_sender_color\").format_text(obj.user.name)\n message += self.setting_service.get(\"websocket_relay_message_color\").format_text(obj.message)\n\n self.message_hub_service.send_message(self.MESSAGE_SOURCE, None, None, message)\n elif obj.type == \"logon\":\n self.add_online_char(obj.user.id, obj.user.name, obj.source, client_id)\n elif obj.type == \"logoff\":\n self.rem_online_char(obj.user.id, obj.source)\n elif obj.type == \"online_list\":\n for online_obj in obj.online:\n if online_obj.source.type not in [\"org\", \"priv\"]:\n continue\n\n channel = self.get_channel_name(online_obj.source)\n self.db.exec(\"DELETE FROM online WHERE channel = ?\", [channel])\n for user in online_obj.users:\n self.add_online_char(user.id, user.name, online_obj.source, client_id)\n elif obj.type == \"online_list_request\":\n self.send_relay_message(self.get_online_list_obj())\n\n def get_online_list_obj(self):\n sources = []\n for channel in [OnlineController.ORG_CHANNEL, OnlineController.PRIVATE_CHANNEL]:\n # TODO is this necessary?\n # if not an org bot, skip ORG_CHANNEL\n # if channel == OnlineController.ORG_CHANNEL and not self.public_channel_service.get_org_id():\n # continue\n\n sql = \"\"\"\n SELECT\n o.char_id AS id,\n COALESCE(p.name, o.char_id) AS name\n FROM online o\n LEFT JOIN player p ON (o.char_id = p.char_id)\n WHERE channel = ?\n \"\"\"\n data = self.db.query(sql, [channel])\n\n sources.append({\n \"source\": self.create_source_obj(channel),\n \"users\": data\n })\n\n return {\n \"type\": \"online_list\",\n \"online\": sources\n }\n\n def send_relay_event(self, char_id, event_type, source):\n char_name = self.character_service.resolve_char_to_name(char_id)\n obj = {\"user\": {\"id\": char_id,\n \"name\": char_name},\n \"type\": event_type,\n \"source\": self.create_source_obj(source)}\n self.send_relay_message(obj)\n\n def add_online_char(self, char_id, name, source, client_id):\n # TODO how to handle chars not on current server\n if not char_id or (source.server and source.server != self.bot.dimension):\n return\n\n self.pork_service.load_character_info(char_id, name)\n channel = self.get_channel_name(source)\n if client_id not in self.channels:\n self.channels[client_id] = []\n if channel not in self.channels[client_id]:\n self.online_controller.register_online_channel(channel)\n self.channels[client_id].append(channel)\n\n self.db.exec(\"INSERT INTO online (char_id, afk_dt, afk_reason, channel, dt) VALUES (?, ?, ?, ?, ?)\",\n [char_id, 0, \"\", channel, int(time.time())])\n\n def rem_online_char(self, char_id, source):\n channel = self.get_channel_name(source)\n self.db.exec(\"DELETE FROM online WHERE char_id = ? AND channel = ?\", [char_id, channel])\n\n def send_relay_message(self, message):\n if self.worker:\n message = json.dumps(message)\n if self.encrypter:\n message = self.encrypter.encrypt(message.encode('utf-8')).decode('utf-8')\n obj = json.dumps({\"type\": \"message\", \"payload\": message})\n self.worker.send_message(obj)\n\n def handle_message_from_hub(self, ctx):\n if self.worker:\n # TODO use relay_symbol to determine if message should be relayed or not\n\n message = ctx.message or ctx.formatted_message\n obj = {\"user\": self.create_user_obj(ctx.sender),\n \"message\": message,\n \"type\": \"message\",\n \"source\": self.create_source_obj(ctx.source)}\n self.send_relay_message(obj)\n\n def connect(self):\n self.disconnect()\n\n self.worker = WebsocketRelayWorker(self.queue, self.setting_service.get(\"websocket_relay_server_address\").get_value())\n self.dthread = threading.Thread(target=self.worker.run, daemon=True)\n self.dthread.start()\n\n def disconnect(self):\n for channels in self.channels.values():\n for channel in channels:\n self.online_controller.deregister_online_channel(channel)\n\n if self.worker:\n self.worker.close()\n self.worker = None\n self.dthread.join()\n self.dthread = None\n\n def websocket_relay_update(self, setting_name, old_value, new_value):\n if setting_name == \"websocket_relay_enabled\":\n event_handlers = [self.handle_connect_event, self.handle_queue_event, self.private_channel_joined_event, self.private_channel_left_event,\n self.org_member_logon_event, self.org_member_logoff_event, self.org_member_removed_event]\n for handler in event_handlers:\n event_handler = self.util.get_handler_name(handler)\n event_base_type, event_sub_type = self.event_service.get_event_type_parts(handler.event.event_type)\n self.event_service.update_event_status(event_base_type, event_sub_type, event_handler, 1 if new_value else 0)\n\n if not new_value:\n self.disconnect()\n elif setting_name == \"websocket_relay_server_address\":\n if self.setting_service.get(\"websocket_relay_enabled\").get_value():\n self.connect()\n elif setting_name == \"websocket_encryption_key\":\n self.initialize_encrypter(new_value)\n if self.setting_service.get(\"websocket_relay_enabled\").get_value():\n self.connect()\n\n def get_channel_name(self, source):\n channel_name = source.label or source.name\n if source.channel:\n channel_name += \" \" + source.channel\n return channel_name\n\n def create_user_obj(self, sender):\n if sender:\n return {\n \"id\": sender.get(\"char_id\", None),\n \"name\": sender.name\n }\n else:\n return None\n\n def create_source_obj(self, source):\n conn = self.bot.get_temp_conn()\n org_name = conn.get_org_name()\n\n if source == \"private_channel\" or source == OnlineController.PRIVATE_CHANNEL:\n if org_name:\n channel = \"Guest\"\n else:\n channel = \"\"\n elif org_name and (source == \"org_channel\" or source == OnlineController.ORG_CHANNEL):\n channel = \"\"\n else:\n channel = source.capitalize()\n\n channel_type = source\n if source == \"private_channel\" or source == OnlineController.PRIVATE_CHANNEL:\n channel_type = \"priv\"\n elif source == \"org_channel\" or source == OnlineController.ORG_CHANNEL:\n channel_type = \"org\"\n\n return {\n \"name\": org_name or conn.get_char_name(),\n \"label\": self.setting_service.get(\"relay_prefix\").get_value() or \"\",\n \"channel\": channel,\n \"type\": channel_type,\n \"server\": self.bot.dimension\n }\n","sub_path":"modules/standard/relay/websocket_relay_controller.py","file_name":"websocket_relay_controller.py","file_ext":"py","file_size_in_byte":15270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"288990936","text":"from grafica import *\r\nfrom ecdif import *\r\n\r\ndef df(y,t):\r\n df= exp(-t)-3*y\r\n return df\r\n\r\ny0=1\r\nh=0.01\r\nintervalo=[0,5]\r\nsol,t=euler(df,h,intervalo,y0)\r\n\r\ngrafvector(t,sol,\"y'+3y=e^(-t)\")\r\ntitulos(\"y'+3y=e^(-t)\",\"t\",\"y(t)\")\r\nmuestra()\r\n","sub_path":"Tema 3 - Ecuaciones Diferenciales Ordinarias/2013_2/Juan Pablo Herrera Musi/Examen 3/Examen Juan Pablo Herrera/Ej1/ej1b.py","file_name":"ej1b.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"215810729","text":"# encoding:utf-8
\n\n'''\n1、买家购买拍品\n'''\nimport unittest\n\nimport requests\nimport json\n\nfrom apis_test.common_methods.config import *\nfrom apis_test.common_methods.mylogs import *\nfrom apis_test.common_methods.myglobal import *\nfrom apis_test.common_methods.mysql_yj_test import *\nfrom apis_test.get_testcase.Main_process.case.seller_03_goods_add import Test_get_goods_id\n\nuserdata = {\n # USER1\n \"buyer_purchase_order\": {\n \"gid\":Test_get_goods_id(),\n }\n\n}\n\nURL1 = hosts[\"QA\"] + apis[\"取有效预订单\"][\"path\"]\ndatas = userdata[\"buyer_purchase_order\"]\nBuyer_user_cookie = {\"userinfo_cookie\": get_cookie2()}\n# print('buyer_purchase_order',userdata)\n\nclass Test_video_add(unittest.TestCase):\n u'''测试用例a的集合'''\n\n def test_01_like_add(self):\n u'''买家购买拍品'''\n response = requests.post(URL1, datas, cookies=Buyer_user_cookie)\n jsonObj = response.json()\n # print('jsonObj', jsonObj)\n assert jsonObj['code'] == 0, \"接口返回期望值code=0\"\n # 需要新增数据库查询,确认视频已新增到数据库\n # formatJsonStr = json.dumps(jsonObj, indent=4, ensure_ascii=False, sort_keys=True) # 格式化数据\n # return logger.info(formatJsonStr)\n\n\n# 获取卖家订单号提供给买家购买时入参\ndef Test_get_sellerOrder():\n sellerOrder = Test_video_add().test_01_like_add()\n return sellerOrder\n\n\n# Test_get_sellerOrder()\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"apis_test/get_testcase/Main_process/case/buyers_01_purchase.py","file_name":"buyers_01_purchase.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"536686089","text":"import os\nimport time\n\nfrom ansible import utils\nfrom ansible.module_utils import basic\nfrom ansible.utils.unicode import to_unicode, to_bytes\n\nfrom tasks.models import TaskLog, TaskExecution\n\n\nclass CallbackModule(object):\n def __init__(self):\n self.disabled = False\n self.printed_playbook = False\n self.playbook = None\n self.playbook_name = None\n self.inventory = None\n self.log_message = ''\n self.log_type = 'info'\n\n def append_to_log(self, msg):\n self.log_message += msg+\"\\n\"\n\n def flush_to_database(self, has_errors=False):\n self.log_type = 'info'\n\n if has_errors:\n self.log_type = 'error'\n\n taskexecution_id = self.inventory.get_group('tasker').get_variables().get('taskexecution_id')\n\n tasklog = TaskLog(taskexecution=TaskExecution.objects.get(pk=taskexecution_id), log=self.log_message)\n tasklog.save()\n\n def runner_on_failed(self, host, res, ignore_errors=False):\n results2 = res.copy()\n results2.pop('invocation', None)\n\n item = results2.get('item', None)\n\n if item:\n msg = \"failed: [%s] => (item=%s) => %s\" % (host, item, utils.jsonify(results2))\n else:\n msg = \"failed: [%s] => %s\" % (host, utils.jsonify(results2))\n\n self.append_to_log(msg)\n\n def runner_on_ok(self, host, res):\n results2 = res.copy()\n results2.pop('invocation', None)\n\n item = results2.get('item', None)\n\n changed = results2.get('changed', False)\n ok_or_changed = 'ok'\n if changed:\n ok_or_changed = 'changed'\n\n msg = \"%s: [%s] => (item=%s)\" % (ok_or_changed, host, item)\n\n self.append_to_log(msg)\n\n def runner_on_skipped(self, host, item=None):\n if item:\n msg = \"skipping: [%s] => (item=%s)\" % (host, item)\n else:\n msg = \"skipping: [%s]\" % host\n\n self.append_to_log(msg)\n\n def runner_on_unreachable(self, host, res):\n item = None\n\n if type(res) == dict:\n item = res.get('item', None)\n if isinstance(item, unicode):\n item = utils.unicode.to_bytes(item)\n results = basic.json_dict_unicode_to_bytes(res)\n else:\n results = utils.unicode.to_bytes(res)\n host = utils.unicode.to_bytes(host)\n if item:\n msg = \"fatal: [%s] => (item=%s) => %s\" % (host, item, results)\n else:\n msg = \"fatal: [%s] => %s\" % (host, results)\n\n self.append_to_log(msg)\n\n def runner_on_no_hosts(self):\n self.append_to_log(\"FATAL: no hosts matched or all hosts have already failed -- aborting\")\n pass\n\n def playbook_on_task_start(self, name, is_conditional):\n name = utils.unicode.to_bytes(name)\n msg = \"TASK: [%s]\" % name\n if is_conditional:\n msg = \"NOTIFIED: [%s]\" % name\n\n self.append_to_log(msg)\n\n def playbook_on_setup(self):\n self.append_to_log('GATHERING FACTS')\n pass\n\n def playbook_on_play_start(self, name):\n self.playbook = self.play.playbook\n self.inventory = self.playbook.inventory\n\n self.append_to_log(\"PLAY [%s]\" % name)\n pass\n\n def playbook_on_stats(self, stats):\n \"\"\"Complete: Flush log to database\"\"\"\n has_errors = False\n hosts = stats.processed.keys()\n\n for h in hosts:\n t = stats.summarize(h)\n\n if t['failures'] > 0 or t['unreachable'] > 0:\n has_errors = True\n\n msg = \"Host: %s, ok: %d, failures: %d, unreachable: %d, changed: %d, skipped: %d\" % (h, t['ok'], t['failures'], t['unreachable'], t['changed'], t['skipped'])\n self.append_to_log(msg)\n\n self.flush_to_database(has_errors)\n","sub_path":"callbacks/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"92270107","text":"#!/bin/env python\n\n# Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC . Under the terms of Contract\n# DE-NA0003525 with National Technology and Engineering Solutions of Sandia, LLC, the U.S. Government\n# retains certain rights in this software.\n\n\"\"\"\nStage data to hdf5 format for Slycat computation.\n\"\"\"\nimport argparse\nimport concurrent.futures\nimport h5py\nimport logging\nimport multiprocessing\nimport numpy\nimport os\nimport os.path\nimport shutil\nimport slycat.hdf5\nimport threading\nimport csv\nfrom urllib.parse import urlparse\nimport traceback\nimport paramiko\nimport functools\n\n# set up the logger\nlog_lock = threading.Lock()\nlog = logging.getLogger()\nlog.setLevel(logging.INFO)\nlog.addHandler(logging.StreamHandler())\nlog.handlers[0].setFormatter(logging.Formatter(\"%(levelname)s - %(message)s\"))\n\n\ndef _isNumeric(j):\n \"\"\"\n Check if the input object is a numerical value, i.e. a float\n :param j: object\n :return: boolean\n \"\"\"\n try:\n x = float(j)\n except ValueError:\n return False\n return True\n\n\ndef process_timeseries(timeseries_path, timeseries_name, output_directory, timeseries_index, eval_id):\n \"\"\"\n Read in the input file from a timeseries run and process the data into a HDF5\n file for the given timeseries name and index. The generated file structure is\n as follows:\n\n array\n |_ 0\n |_ attribute\n |_ 0, dataset\n ...\n |_ number_of_columns, dataset\n |_ metadata\n |_ attribute-names, dataset: column names\n |_ attribute-types, dataset: data types for each of the columns\n |_ dimension-begin, dataset\n |_ dimension-end, dataset\n |_ dimension-names, dataset\n |_ dimension-types, dataset\n |_ unique\n |_ 0, dataset\n\n :param timeseries_path:\n :param timeseries_name:\n :param timeseries_index:\n :param eval_id:\n \"\"\"\n t_add_index_column = None\n t_column_names = None\n t_column_types = None\n t_delimiter = None\n url = urlparse(timeseries_path)\n path = url.path # strips scheme and network location from timeseries_path\n\n try:\n with log_lock:\n log.info(\"Reading %s\", path)\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(hostname=\"\", username=\"\", password=\"\")\n sftp_client = ssh.open_sftp()\n # with open(\"%s\" % path, \"r\") as stream:\n with sftp_client.open(path) as stream:\n line = stream.readline()\n # detect delimiter\n sniffer = csv.Sniffer()\n dialect = sniffer.sniff(line)\n t_delimiter = dialect.delimiter\n t_column_names = [name.strip() for name in line.split(t_delimiter)]\n t_first_row = [val.strip() for val in stream.readline().split(t_delimiter)]\n\n # check if an index column is present or flag it otherwise\n if isinstance(t_first_row[0], int):\n t_add_index_column = True\n t_column_names = [\"Index\"] + t_column_names\n else:\n t_column_names[0] = \"Index\"\n t_column_types = [\"float64\" for name in t_column_names]\n t_column_names[1] = \"TIME\"\n\n # pull data from file and add an index column if flagged earlier...\n data = numpy.loadtxt(\"%s\" % path, comments=\"End\", skiprows=1, delimiter=t_delimiter)\n if t_add_index_column is True:\n data = numpy.insert(data, 0, list(range(len(data))), axis=1)\n # TODO: make sure we still need to create this dir with the next path settup\n timeseries_dir = os.path.join(output_directory, timeseries_name)\n if not os.path.exists(timeseries_dir):\n os.makedirs(timeseries_dir)\n hdf5_path = os.path.join(timeseries_dir, \"timeseries-%s.hdf5\" % timeseries_index)\n\n with log_lock:\n log.info(\"Writing %s\", hdf5_path)\n\n with h5py.File(hdf5_path, \"w\") as file:\n arrayset = slycat.hdf5.start_arrayset(file)\n dimensions = [dict(name=\"row\", end=data.shape[0])]\n attributes = [dict(name=name, type=type) for name, type in\n zip(t_column_names, t_column_types)[1:]] # leaves out the index column\n array = arrayset.start_array(0, dimensions, attributes)\n for attribute, column in enumerate(data.T[1:]):\n array.set_data(attribute, slice(0, column.shape[0]), column)\n except IOError as err:\n log.error(\"Failed reading %s: %s\", path, err)\n except:\n log.error(\"Unexpected error reading %s\", path)\n\n\ndef convert_timeseries(results, timeseries_index, eval_id, row): # range(row_count), columns[0], rows)\n \"\"\"\n Iterate over the data for the input row and checks for file paths. If file\n extension is valid, run process_timeseries method.\n\n :param timeseries_index: 0-based index\n :param eval_id: ID from ID column\n :param row: row data\n \"\"\"\n for i, val in enumerate(row):\n if results['column_types'][i] == \"string\":\n val = val.strip()\n file_ext = val[len(val) - 3:]\n if file_ext == \"csv\" or file_ext == \"dat\" or file_ext == \"txt\":\n print(\"processing\")\n process_timeseries(val, results['column_names'][i], results['output_directory'], timeseries_index,\n eval_id)\n\n\ndef check_and_build_input_and_output_directories(output_directory, inputs_file):\n \"\"\"\n builds input and output directories if they do not already exist\n :param output_directory:\n :param inputs_file:\n :param force:\n :return:\n \"\"\"\n if not os.path.exists(output_directory):\n os.makedirs(output_directory)\n if inputs_file is None:\n raise Exception(\"Inputs file is a required\")\n if not os.path.isfile(inputs_file):\n raise Exception(\"Inputs file could not be found. Check its path and verify permissions.\")\n\n\ndef convert_inputs_file_to_dictionary(inputs_file, inputs_file_delimiter, id_column):\n \"\"\"\n Ingest the input file and reorganizes the data into objects:\n\n - rows is a 2-dimensional array representation of the input file. The header\n (column names) is eventually removed from the array.\n - column_names is an array with the column names.\n - column_types is an array with the type of data for each of the columns.\n - row_count is self-explanatory\n - columns is a list of tuples for each of the columns (minus the header row).\n Each tuple is the data for each of the columns.\n\n Then repack each of the data columns as numpy arrays.\n :param inputs_file: path to inputs file\n :param inputs_file_delimiter:\n :param id_column:\n :return: a dictionary\n \"\"\"\n log.info(\"Converting %s\", inputs_file)\n results = {}\n with open(inputs_file, \"r\") as stream:\n results['rows'] = [row.split(inputs_file_delimiter) for row in stream]\n results['column_names'] = [name.strip() for name in results['rows'][0]]\n results['column_types'] = [\"string\" for name in results['column_names']]\n results['rows'] = results['rows'][1:] # removes first row (header)\n results['row_count'] = len(results['rows'])\n results['columns'] = list(zip(\n *results[\n 'rows'])) # this is the data only - no headers, now a list of tuples: [(index1, index2, ...), (voltage1, voltage2, ...) ...]\n\n if id_column is not None:\n if results['column_names'][0] != id_column:\n raise Exception(\"The first column in %s must be %s, got %s instead.\" % (\n inputs_file, id_column, results['column_names'][0]))\n results['columns'][0] = numpy.array(results['columns'][0], dtype=\"int64\") # repack the index col as numpy array\n else:\n # if the ID column isn't specified, creates one and prepend it to the columns\n results['column_names'] = [\"%eval_id\"] + results['column_names']\n results['columns'] = [numpy.array(list(range(0, results['row_count'])), dtype=\"int64\")] + results['columns']\n results['column_types'][0] = \"int64\"\n\n for index in range(1, len(results['columns'])): # repack data cols as numpy arrays\n try:\n if _isNumeric(results['columns'][index][0]):\n results['columns'][index] = numpy.array(results['columns'][index], dtype=\"float64\")\n results['column_types'][index] = \"float64\"\n else:\n string_type = \"S\" + str(\n len(results['columns'][index][0])) # using length of first string for whole column\n results['columns'][index] = numpy.array(results['columns'][index], dtype=string_type)\n results['column_types'][index] = \"string\"\n except: # TODO: build exception logic\n pass\n log.info(\"Converted %s\", results['columns'])\n return results\n\n\ndef write_out_hdf5_files(results, cpu_count=1):\n \"\"\"\n Write the inputs files data out to \"inputs.hdf5\" file. The generated HDF5 file\n has the following hierarchy:\n\n array\n |_ 0\n |_ attribute\n |_ 0, dataset\n |_ 1, dataset\n ...\n |_ number_of_columns, dataset\n |_ metadata\n |_ attribute-names, dataset: column names\n |_ attribute-types, dataset: data types for each of the columns\n |_ dimension-begin, dataset\n |_ dimension-end, dataset\n |_ dimension-names, dataset\n |_ dimension-types, dataset\n\n Note: the datasets are 1 dimensional arrays (lenght of the dataset size) and\n represent the data for each of the columns.\n :param results: dictionary of metadata\n :param cpu_count: number of cpu's for parallel jobs\n :return: status msg\n \"\"\"\n # dimensions: is a list with one dictionary with the following keys/value pair: name=\"row\"\n # and end=the numberof rows from the input file.\n dimensions = [dict(name=\"row\", end=results['row_count'])]\n # attributes: is a list of dictionaries representing the column names and their\n # types. Each dictionary has the following format: { name: column name, type: column type }.\n attributes = [dict(name=name, type=type) for name, type in zip(results['column_names'], results['column_types'])]\n\n with h5py.File(os.path.join(results['output_directory'], \"inputs.hdf5\"), \"w\") as file:\n arrayset = slycat.hdf5.start_arrayset(file)\n array = arrayset.start_array(0, dimensions, attributes)\n for attribute, column in enumerate(results['columns']):\n array.set_data(attribute, slice(0, column.shape[0]), column)\n with concurrent.futures.ProcessPoolExecutor(cpu_count) as pool:\n output = list(\n pool.map(functools.partial(convert_timeseries, results), list(range(results['row_count'])), results['columns'][0],\n results['rows']))\n return output\n\n\ndef timeseries_csv_to_hdf5(output_directory, inputs_file, id_column, inputs_file_delimiter=\",\"):\n \"\"\"\n converts a csv based timeseries to hdf5 files for faster computation later on\n :param output_directory:\n :param inputs_file:\n :param id_column:\n :param inputs_file_delimiter:\n :return:\n \"\"\"\n dir_error_msg = None\n # output_dir = s\n # output_dir = output_dir +\"/slycat-temp+\"-\"+input_file_name +\"-\"+ timestamp/\"\n # should we wrtie to scratch drive without username b4 it\n try:\n check_and_build_input_and_output_directories(output_directory, inputs_file)\n except Exception as e:\n dir_error_msg = e.message\n if dir_error_msg is not None:\n log.info(\"error with input output directories error msg: %s\", dir_error_msg)\n return False\n # create an object list of the inputs file\n results = convert_inputs_file_to_dictionary(inputs_file, inputs_file_delimiter, id_column)\n results['output_directory'] = output_directory\n print(write_out_hdf5_files(results, cpu_count=multiprocessing.cpu_count()))\n\n\nif __name__ == \"__main__\":\n timeseries_csv_to_hdf5(\"out\", \"master.csv\", \"%eval_id\", inputs_file_delimiter=\",\")\n","sub_path":"agent/timeseries_util.py","file_name":"timeseries_util.py","file_ext":"py","file_size_in_byte":12158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"641736971","text":"#!/usr/bin/env python\n\nimport os\nSCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))\nos.chdir(SCRIPT_DIR)\n\nimport sys\nimport subprocess\nimport multiprocessing\nfrom datetime import datetime\nimport json\n\nCHUNK_SIZE = 16\nRUN_SCRIPT_FILENAME = 'run_pipeline.py'\n\nSLURM_SCRIPT = '''#!/bin/sh\n#SBATCH --ntasks=1\n#SBATCH --cpus-per-task={cpus_per_task}\n#SBATCH --job-name=ns-d-{chunk_id}\n#SBATCH --mem-per-cpu=2000\n#SBATCH --output=stdout_slurm.txt\n#SBATCH --error=stderr_slurm.txt\n#SBATCH --time=0:30:00\n\necho SLURM_JOB_ID=$SLURM_JOB_ID\necho SLURM_JOB_NAME=$SLURM_JOB_NAME\necho SLURM_CPUS_ON_NODE=$SLURM_CPUS_ON_NODE\necho SLURM_JOB_NODELIST=$SLURM_JOB_NODELIST\necho SLURM_NODEID=$SLURM_NODEID\necho SLURM_TASK_PID=$SLURM_TASK_PID\n{root_dir}/run_chunk.py\n'''\n\nif not os.path.exists('jobs'):\n sys.stderr.write('jobs does not exist; must run generate_jobs.py first.\\n')\n sys.exit(1)\n\nif os.path.exists('chunks'):\n sys.stderr.write('chunks already exists; aborting.\\n')\n sys.exit(1)\n\ndef main():\n chunk_id = 0\n chunk_job_dirs = []\n for root, dirs, files in os.walk('jobs'):\n if os.path.exists(os.path.join(root, 'job_info.json')):\n chunk_job_dirs.append(os.path.abspath(root))\n if len(chunk_job_dirs) == CHUNK_SIZE:\n generate_chunk(chunk_id, chunk_job_dirs)\n chunk_id += 1\n chunk_job_dirs = []\n if len(chunk_job_dirs) > 0:\n generate_chunk(chunk_id, chunk_job_dirs)\n\ndef generate_chunk(chunk_id, chunk_job_dirs):\n chunk_dir = os.path.join('chunks', str(chunk_id))\n sys.stderr.write('{}\\n'.format(chunk_dir))\n os.makedirs(chunk_dir)\n with open(os.path.join(chunk_dir, 'job_dirs.json'), 'w') as f:\n json.dump(chunk_job_dirs, f, indent=2)\n f.write('\\n')\n chunk_sbatch_filename = os.path.join(chunk_dir, 'run_chunk.sbatch')\n with open(chunk_sbatch_filename, 'w') as f:\n f.write(SLURM_SCRIPT.format(\n chunk_id = chunk_id, cpus_per_task = len(chunk_job_dirs), root_dir = SCRIPT_DIR\n ))\n\nmain()\n","sub_path":"dataflow/in/simulations/generate_chunks.py","file_name":"generate_chunks.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"241386332","text":"from tkinter import *\n\nclass GUI(Frame):\n def __init__(self, master):\n Frame.__init__(self, master)\n self.grid()\n self.CreateWidgets()\n \n def CreateWidgets(self):\n self.entry1 = Entry(textvariable = var1)\n self.entry1.grid()\n self.entry2 = Entry(textvariable = var2)\n self.entry2.grid()\n self.button1 = Button(command = self.Solve, text = \"Solve\")\n self.button1.grid()\n\n def Solve(self):\n print(var1.get())\n print(var2.get())\n\n\nroot = Tk()\nvar1 = StringVar()\nvar2 = StringVar()\nroot.title(\"Title\")\n\ngui = GUI(root)\n\nroot.mainloop()\n","sub_path":"OOPGUI/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"499849331","text":"import time\nimport logging\nfrom datetime import datetime\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.utils.decorators import method_decorator\nfrom django.views import View\n\nfrom ...childminder_task_util import all_complete\nfrom ...decorators import group_required, user_assigned_application\nfrom ...forms.childminder_forms.form import AdultInYourHomeForm, ChildInYourHomeForm, \\\n OtherPersonPreviousRegistrationDetailsForm\nfrom ...forms.childminder_forms.form import PreviousRegistrationDetailsForm, ChildForm, ChildAddressForm\nfrom ...magic_link import generate_magic_link\nfrom ...notify import send_email\nfrom ...views.base import release_application\n\nfrom ...models import ApplicantName, ApplicantPersonalDetails, Application, Arc, ArcComments, ChildcareType, \\\n UserDetails, OtherPersonPreviousRegistrationDetails, PreviousRegistrationDetails, AdultInHome\n\ndecorators = [login_required, group_required(settings.ARC_GROUP), user_assigned_application]\n\n# Initiate logging\nlog = logging.getLogger('')\n\n\n@group_required(settings.ARC_GROUP)\ndef review(request):\n \"\"\"\n Confirmation Page\n :param request: a request object used to generate the HttpResponse\n :return: an HttpResponse object with the rendered Your App Review Confirmation template\n \"\"\"\n application_id_local = request.GET[\"id\"]\n application = Application.objects.get(application_id=application_id_local)\n app_ref = application.application_reference\n account = UserDetails.objects.get(application_id=application)\n login_id = account.pk\n first_name = ''\n\n # Get Application's related email and first_name to send an email.\n if UserDetails.objects.filter(login_id=login_id).exists():\n user_details = UserDetails.objects.get(login_id=login_id)\n email = user_details.email\n\n if ApplicantPersonalDetails.objects.filter(application_id=application_id_local).exists():\n personal_details = ApplicantPersonalDetails.objects.get(application_id=application_id_local)\n applicant_name = ApplicantName.objects.get(personal_detail_id=personal_details.personal_detail_id)\n first_name = applicant_name.first_name\n\n if all_complete(application_id_local, True):\n\n # If the application has not already been accepted.\n if application.application_status != 'ACCEPTED':\n\n # Get fresh version of application as it will have been updated in method call\n if Application.objects.filter(application_id=application_id_local).exists():\n application = Application.objects.get(application_id=application_id_local)\n application.date_accepted = datetime.now()\n application.save()\n\n personalisation = {'first_name': first_name, 'ref': app_ref}\n accepted_email(email, first_name, app_ref, application_id_local)\n send_survey_email(email, personalisation, application)\n\n # If successful\n release_application(request, application_id_local, 'ACCEPTED')\n\n variables = {\n 'application_id': application_id_local,\n }\n\n return render(request, 'review-confirmation.html', variables)\n\n else:\n if application.application_status != 'FURTHER_INFORMATION':\n magic_link = generate_magic_link()\n expiry = int(time.time())\n user_details.email_expiry_date = expiry\n user_details.magic_link_email = magic_link\n user_details.save()\n link = settings.CHILDMINDER_EMAIL_VALIDATION_URL + '/' + magic_link\n returned_email(email, first_name, app_ref, link)\n\n # Copy Arc status' to Childminder App\n if Arc.objects.filter(pk=application_id_local):\n arc = Arc.objects.get(pk=application_id_local)\n app = Application.objects.get(pk=application_id_local)\n app.login_details_status = arc.login_details_review\n app.personal_details_status = arc.personal_details_review\n app.childcare_type_status = arc.childcare_type_review\n app.first_aid_training_status = arc.first_aid_review\n app.health_status = arc.health_review\n app.childcare_training_status = arc.childcare_training_review\n app.criminal_record_check_status = arc.dbs_review\n app.references_status = arc.references_review\n app.people_in_home_status = arc.people_in_home_review\n app.save()\n\n release_application(request, application_id_local, 'FURTHER_INFORMATION')\n\n variables = {\n 'application_id': application_id_local,\n }\n\n return render(request, 'review-sent-back.html', variables)\n\n\ndef send_survey_email(email, personalisation, application):\n \"\"\"\n Sends an email if\n :param email: Applicant's email string\n :param personalisation: Applicant's details dictionary, presumed firstName and ref\n :param application: Application model instance\n :return: Void\n \"\"\"\n survey_template_id = '90580388-f10d-440a-b900-4d5f948112a5'\n send_email(email, personalisation, survey_template_id)\n\n\n# Add personalisation and create template\ndef accepted_email(email, first_name, ref, application_id):\n \"\"\"\n Method to send an email using the Notify Gateway API\n :param email: string containing the e-mail address to send the e-mail to\n :param first_name: string first name\n :param ref: string ref\n :param application_id: application ID\n :return: HTTP response\n \"\"\"\n if hasattr(settings, 'NOTIFY_URL'):\n email = str(email)\n\n childcare_type_record = ChildcareType.objects.get(application_id=application_id)\n\n # Send correct ARC accept next steps depending on whether the applicant applies for the Childcare Register only\n if childcare_type_record.zero_to_five is True:\n\n template_id = 'b973c5a2-cadd-46a5-baf7-beae65ab11dc'\n\n else:\n\n template_id = 'b3ae07da-3d14-4794-b989-9a15f961e4ee'\n\n personalisation = {'first_name': first_name, 'ref': ref}\n return send_email(email, personalisation, template_id)\n\n\n# Add personalisation and create template\ndef returned_email(email, first_name, ref, link):\n \"\"\"\n Method to send an email using the Notify Gateway API\n :param email: string containing the e-mail address to send the e-mail to\n :param first_name: string first name\n :param ref: string ref\n :return: HTTP response\n \"\"\"\n if hasattr(settings, 'NOTIFY_URL'):\n email = str(email)\n template_id = 'c9157aaa-02cd-4294-8094-df2184c12930'\n personalisation = {'first_name': first_name, 'ref': ref, 'link': link}\n return send_email(email, personalisation, template_id)\n\n\n# Including the below file elsewhere caused cyclical import error, keeping here till this can be debugged\ndef other_people_initial_population(adult, person_list):\n initial_data = []\n\n for person in person_list:\n temp_dict = {}\n\n if not adult:\n table_id = person.child_id\n\n form_instance = ChildInYourHomeForm()\n else:\n table_id = person.adult_id\n form_instance = AdultInYourHomeForm()\n\n for field in form_instance.fields:\n try:\n\n if field[-8:] == 'comments':\n field_name_local = field[:-9]\n comment = (ArcComments.objects.filter(table_pk=table_id).get(field_name=field_name_local)).comment\n temp_dict[field] = comment\n\n if field[-7:] == 'declare':\n field_name_local = field[:-8]\n checkbox = (ArcComments.objects.filter(table_pk=table_id).get(field_name=field_name_local)).flagged\n temp_dict[field] = True\n\n if adult and field == 'cygnum_relationship':\n temp_dict[field] = person.cygnum_relationship_to_childminder\n\n except ArcComments.DoesNotExist:\n pass\n\n initial_data.append(temp_dict)\n\n return initial_data\n\n\ndef children_address_initial_population(address_list):\n initial_data = []\n\n for address in address_list:\n temp_dict = {}\n table_id = address.child_address_id\n form_instance = ChildAddressForm()\n\n for field in form_instance.fields:\n try:\n\n if field[-8:] == 'comments':\n field_name_local = field[:-9]\n comment = (ArcComments.objects.filter(table_pk=table_id).get(field_name=field_name_local)).comment\n temp_dict[field] = comment\n\n # If a comment exists, set checkbox to True and show previously added comment.\n temp_dict[field_name_local + '_declare'] = True\n\n except ArcComments.DoesNotExist:\n pass\n\n initial_data.append(temp_dict)\n\n return initial_data\n\n\ndef children_initial_population(person_list):\n initial_data = []\n\n for person in person_list:\n temp_dict = {}\n table_id = person.child_id\n form_instance = ChildForm()\n\n for field in form_instance.fields:\n try:\n\n if field[-8:] == 'comments':\n field_name_local = field[:-9]\n comment = (ArcComments.objects.filter(table_pk=table_id).get(field_name=field_name_local)).comment\n temp_dict[field] = comment\n\n # If a comment exists, set checkbox to True and show previously added comment.\n temp_dict[field_name_local + '_declare'] = True\n\n except ArcComments.DoesNotExist:\n pass\n\n initial_data.append(temp_dict)\n\n return initial_data\n\n\n@method_decorator(decorators, name='dispatch')\nclass PreviousRegistrationDetailsView(View):\n\n def get(self, request):\n application_id_local = request.GET[\"id\"]\n form = PreviousRegistrationDetailsForm(id=application_id_local)\n variables = {\n 'form': form,\n 'application_id': application_id_local,\n }\n log.debug(\"Render previous registration page\")\n return render(request, 'childminder_templates/add-previous-registration.html', variables)\n\n def post(self, request):\n application_id_local = request.POST[\"id\"]\n form = PreviousRegistrationDetailsForm(request.POST, id=application_id_local)\n\n if form.is_valid():\n app = Application.objects.get(pk=application_id_local)\n previous_registration = form.cleaned_data.get('previous_registration')\n individual_id = form.cleaned_data.get('individual_id')\n five_years_in_uk = form.cleaned_data.get('five_years_in_UK')\n\n if PreviousRegistrationDetails.objects.filter(application_id=app).exists():\n previous_reg_details = PreviousRegistrationDetails.objects.get(application_id=app)\n else:\n previous_reg_details = PreviousRegistrationDetails(application_id=app)\n\n previous_reg_details.previous_registration = previous_registration\n previous_reg_details.individual_id = individual_id\n previous_reg_details.five_years_in_UK = five_years_in_uk\n previous_reg_details.save()\n\n redirect_link = '/personal-details/summary'\n log.debug(\"Handling submissions for previous registrations\")\n return HttpResponseRedirect(settings.URL_PREFIX + redirect_link + '?id=' + application_id_local)\n\n else:\n variables = {\n 'form': form,\n 'application_id': application_id_local,\n }\n log.debug(\"Render previous registration page\")\n return render(request, 'childminder_templates/add-previous-registration.html', context=variables)\n\n\n@method_decorator(decorators, name='dispatch')\nclass OtherPersonPreviousRegistrationDetailsView(View):\n\n def get(self, request):\n application_id_local = request.GET[\"id\"]\n person_id = request.GET[\"person_id\"]\n form = OtherPersonPreviousRegistrationDetailsForm(id=person_id)\n variables = {\n 'form': form,\n 'application_id': application_id_local,\n 'person_id': person_id,\n }\n log.debug(\"Render other people previous registration page\")\n return render(request, 'childminder_templates/add-previous-registration.html', context=variables)\n\n def post(self, request):\n application_id_local = request.POST[\"id\"]\n person_id = request.POST[\"person_id\"]\n person_record = AdultInHome.objects.get(adult_id=person_id)\n form = OtherPersonPreviousRegistrationDetailsForm(request.POST, id=person_id)\n\n if form.is_valid():\n app = Application.objects.get(pk=application_id_local)\n previous_registration = form.cleaned_data.get('previous_registration')\n individual_id = form.cleaned_data.get('individual_id')\n five_years_in_uk = form.cleaned_data.get('five_years_in_UK')\n\n if OtherPersonPreviousRegistrationDetails.objects.filter(person_id=person_record).exists():\n previous_reg_details = OtherPersonPreviousRegistrationDetails.objects.get(person_id=person_record)\n else:\n previous_reg_details = OtherPersonPreviousRegistrationDetails(person_id=person_record)\n\n previous_reg_details.previous_registration = previous_registration\n previous_reg_details.individual_id = individual_id\n previous_reg_details.five_years_in_UK = five_years_in_uk\n previous_reg_details.save()\n\n redirect_link = '/people/summary'\n log.debug(\"Handling submissions for other people previous registration page\")\n return HttpResponseRedirect(settings.URL_PREFIX + redirect_link + '?id=' + application_id_local)\n\n else:\n variables = {\n 'form': form,\n 'application_id': application_id_local,\n 'person_id': person_id,\n }\n log.debug(\"Render other people previous registration page\")\n return render(request, 'childminder_templates/add-previous-registration.html', context=variables)\n","sub_path":"arc_application/views/childminder_views/review.py","file_name":"review.py","file_ext":"py","file_size_in_byte":14384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"182187843","text":"repeats = int(input())\nx, y, z = 0, 0, 0\nfor i in range(repeats):\n\ti, j, k = list(map(int, input().split()))[:]\n\tx += i\n\ty += j\n\tz += k\nif not x and not y and not z:\n\tprint(\"YES\")\nelse:\n\tprint(\"NO\")","sub_path":"physics.py","file_name":"physics.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"168485651","text":"#!/usr/bin/env python3\nimport json\nimport sys\nimport os\nfrom pprint import pprint\n\ndirectory = os.fsencode(\"../intents-complex/2 - resolvedParameterPrompts/\")\n\nfor file in os.listdir(directory):\n filename = os.fsdecode(file)\n if filename.endswith(\".json\"):\n tfFile = filename.replace(\".json\", \"_rep.json\")\n\n bs = \"/\"\n bseq = (\"en_response\", tfFile)\n bpath = bs.join(bseq)\n print(bpath)\n\n cs = \"/\"\n cseq = (\"cn_response\", tfFile)\n cpath = cs.join(cseq)\n print(cpath)\n\n if(os.path.isfile(bpath) and os.path.isfile(cpath)):\n os.rename(bpath, \"en_com_response/\"+tfFile)\n os.rename(cpath, \"cn_com_response/\"+tfFile)\n\n print(\"==================\")\n else:\n print(\"END\")\n\n","sub_path":"BotAgent/Agent-Testing/filterNeededResponse.py","file_name":"filterNeededResponse.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"69439977","text":"# Matthew Lisec\r\n\r\ndef halfRed():\r\n # half is 50%\r\n return lessRed(50)\r\n\r\ndef lessRed(percentage):\r\n pic = makePicture(pickAFile())\r\n pixels = getPixels(pic)\r\n for pix in pixels:\r\n red = getRed(pix)\r\n # reduce red by percentage\r\n setRed(pix, red * percentage / 100)\r\n repaint\r\n show(pic)\r\n\r\ndef moreRed(percentage):\r\n pic = makePicture(pickAFile())\r\n pixels = getPixels(pic)\r\n for pix in pixels:\r\n red = getRed(pix)\r\n # add red by percentage of red ex: 150 + 150 / 100 * 5% = 157.5\r\n setRed(pix, red + red / 100 * percentage)\r\n repaint\r\n show(pic)\r\n \r\ndef roseColoredGlasses():\r\n pic = makePicture(pickAFile())\r\n pixels = getPixels(pic)\r\n\r\n for pix in pixels:\r\n # get red blue and green\r\n red = getRed(pix)\r\n blue = getBlue(pix)\r\n green = getGreen(pix)\r\n\r\n # since pink rgb are around ( 255, 200, 230) we multiply by 2 on each pixel will make picture more pink\r\n setRed(pix,(red + green + blue) * .25)\r\n setGreen(pix, (red + green + blue) * .12)\r\n setBlue(pix, (red + green + blue) * .18)\r\n \r\n repaint\r\n show(pic)\r\n writePictureTo(pic, 'C:/Users/lisec/Desktop/Portfolio Pictures/ACRoseColored.png')\r\n\r\ndef lightenUp():\r\n\r\n # load the picture and get pixels\r\n pic = makePicture(pickAFile())\r\n pixels = getPixels(pic)\r\n \r\n # loops\r\n for pix in pixels:\r\n # get current color by current pixel\r\n current_color = getColor(pix)\r\n \r\n # set a new color to picture\r\n setColor(pix, makeLighter(current_color))\r\n \r\n repaint\r\n show(pic)\r\n \r\ndef makeNegative():\r\n\r\n # load the picture and get pixels\r\n pic = makePicture(pickAFile())\r\n pixels = getPixels(pic)\r\n \r\n # loops\r\n for pix in pixels:\r\n # get colors\r\n red = getRed(pix)\r\n green = getGreen(pix)\r\n blue = getBlue(pix)\r\n \r\n # get negative color by substract each color by 255\r\n negative_color = makeColor(255 - red, 255 - green, 255 - blue)\r\n # set new color to picture\r\n setColor(pix, negative_color)\r\n \r\n repaint\r\n writePictureTo(pic, 'C:/Users/lisec/Desktop/Portfolio Pictures/NegativeTF.png')\r\n show(pic)\r\n \r\ndef BnW():\r\n \r\n # load the picture and get pixels\r\n pic = makePicture(pickAFile())\r\n pixels = getPixels(pic)\r\n \r\n # loops\r\n for pix in pixels:\r\n #get colors\r\n red = getRed(pix)\r\n green = getGreen(pix)\r\n blue = getBlue(pix)\r\n \r\n average_rgb = (red + green + blue) / 3\r\n setColor(pix, makeColor(average_rgb, average_rgb, average_rgb))\r\n \r\n repaint\r\n show(pic)\r\n \r\ndef betterBnW():\r\n # load the picture and get pixels\r\n pic = makePicture(pickAFile())\r\n pixels = getPixels(pic)\r\n \r\n # loops\r\n for pix in pixels:\r\n #get colors\r\n red = getRed(pix)\r\n green = getGreen(pix)\r\n blue = getBlue(pix)\r\n\r\n #luminance formula\r\n luminance = red * 0.299 + green * 0.587 + blue * 0.114\r\n setColor(pix, makeColor(luminance, luminance, luminance))\r\n \r\n repaint\r\n writePictureTo(pic, 'C:/Users/lisec/Desktop/Portfolio Pictures/BnWHalo.png')\r\n show(pic)","sub_path":"CST205/Module 1 Lab 3/one.py","file_name":"one.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"82700518","text":"import os\n\nname = input(\"name to add to fiie?\")\n\n\"\"\" we're going to add names to a file, we don't need this checkd\nif os.path.exists(\"data.txt\"):\n print(\"file exists!\")\n\"\"\"\n\n\nf = open('data.txt', 'a')\nf.write(name)\nf.close()\n \n","sub_path":"fileHandler.py","file_name":"fileHandler.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"212995630","text":"from collections import Counter\ndef mostCommonWord(paragraph, banned):\n punctuations=['!','?','\\'',',',';','.']\n paragraph=paragraph.lower()\n strippedPara=[x if(x not in punctuations) else ' ' for x in paragraph]\n strippedPara=''.join(strippedPara).split(' ')\n a=dict(Counter(strippedPara))\n while(True):\n maxKey=list(a.keys())[list(a.values()).index(max(a.values()))]\n if(maxKey in banned or maxKey==''):\n del a[maxKey]\n else:\n return maxKey\n\nif __name__ == \"__main__\":\n paragraph = \"a, a, a, a, b,b,b,c, c\"\n banned=[\"a\"]\n # banned = [\"hit\"]\n print(mostCommonWord(paragraph,banned))\n","sub_path":"MostCommonWord.py","file_name":"MostCommonWord.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"473134401","text":"## id로 원하는 요소 찾기\n# 라이브러리 읽어 들이기\nfrom bs4 import BeautifulSoup\n\n# 분석하고 싶은 HTML\nhtml = \"\"\"\n\n

스크레이핑이란?

\n

웹 페이지를 분석하는 것

\n

원하는 부분을 추출하는 것

\n\n\"\"\"\n\n# HTML 분석하기\n# BeautifulSoup 인스턴스 생성 \n# 첫번째 매개변수 : HTML, 두번쨰 매개변수 : 분석기지정 HTML 분석 시에는 html.parser\nsoup = BeautifulSoup(html, 'html.parser')\n\n# find() 메서드로 원하는 부분 추출하기\ntitle = soup.find(id=\"title\")\nbody = soup.find(id=\"body\")\n\n# 텍스트 부분 출력하기\nprint(\"#title=\" + title.string)\nprint(\"#body=\" + body.string)","sub_path":"ch1/bs-test2.py","file_name":"bs-test2.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"14876687","text":"\ndef main():\n S = input()\n\n flag = False\n for i in range(2):\n tmp = S[i]\n if tmp != S[i+1]:\n flag = True\n if flag : print(\"Yes\")\n else: print(\"No\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"python/ABC151_200/ABC_158/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"116947999","text":"\nfrom django.urls import reverse\nfrom django.http.response import HttpResponseRedirect\nfrom django.shortcuts import render\n\nfrom . import util\nfrom django import forms\nimport secrets\nimport markdown2\n\n\nclass NewPageForm(forms.Form):\n title = forms.CharField(label=\"Title\", widget=forms.TextInput(attrs={'class': 'form-control col-md-3 '}))\n content = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control col-md-9','rows': 7 }))\n edit = forms.BooleanField(initial=False,widget=forms.HiddenInput(),required=False)\n\n\ndef index(request):\n return render(request, \"encyclopedia/index.html\", {\n \"entries\": util.list_entries()\n })\n\n\ndef page(request, title):\n markdowner = markdown2.Markdown()\n titles = util.list_entries()\n if title not in titles:\n return render(request,\"encyclopedia/error.html\",{\n \"title\":title\n })\n else:\n return render(request,\"encyclopedia/page.html\",{\n \"contents\": markdowner.convert(util.get_entry(title)),\n \"title\": title,\n }) \n\n\ndef search(request):\n value = request.GET[\"q\"]\n for entries in util.list_entries():\n if(value.upper() == entries.upper()):\n value = entries\n return HttpResponseRedirect(reverse(\"page\", kwargs={'title': value })) \n \n subStringEntries = [] \n for entry in util.list_entries():\n if value.upper() in entry.upper():\n subStringEntries.append(entry)\n \n return render(request, \"encyclopedia/index.html\",{\n \"entries\": subStringEntries,\n \"search\": True,\n \"value\": value\n }) \n\n\ndef createNewPage(request):\n if request.method == \"POST\":\n form = NewPageForm(request.POST)\n if form.is_valid():\n title = form.cleaned_data[\"title\"]\n content = form.cleaned_data[\"content\"]\n edit = form.cleaned_data[\"edit\"]\n if util.get_entry(title) is None or edit is True:\n util.save_entry(title,content)\n return HttpResponseRedirect(reverse(\"page\", args=(title,)))\n else:\n return render(request,\"encyclopedia/newPage.html\",{\n \"form\": form,\n \"existing\":True,\n \"title\":title\n })\n return render(request,\"encyclopedia/newPage.html\",{\n \"form\":form,\n \"existing\": False\n })\n return render(request,\"encyclopedia/newPage.html\",{\n \"form\": NewPageForm(),\n \"existing\": False,\n })\n\n\ndef edit(request,title):\n content = util.get_entry(title)\n if content is None:\n return render(request,\"encyclopedia/error.html\",{\n \"title\":title\n })\n else:\n form = NewPageForm()\n form.fields[\"title\"].initial = title\n form.fields[\"title\"].widget = forms.HiddenInput()\n form.fields[\"content\"].initial = content\n form.fields[\"edit\"].initial = True\n return render(request,\"encyclopedia/newPage.html\",{\n \"form\": form,\n \"edit\": form.fields[\"edit\"].initial,\n \"title\":form.fields[\"title\"].initial,\n })\n \ndef random(request):\n entries = util.list_entries()\n randomEntry = secrets.choice(entries)\n return HttpResponseRedirect(reverse(\"page\",args=(randomEntry,)))\n","sub_path":"wiki/encyclopedia/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"167365485","text":"#!/usr/bin/env python3\n\nimport argparse\nimport itertools\n\ndef severity(layers):\n s = 0\n for k, v in layers.items():\n if not k % ((v-1)*2):\n s += k*v\n return s\n\ndef caught(layers, delay):\n for k, v in layers.items():\n if not (k + delay) % ((v-1)*2):\n return True\n return False\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('FILE', nargs = '?', default = 'input')\n args = parser.parse_args()\n layers = {}\n with open(args.FILE, 'r') as f:\n for line in f:\n a, b = [int(i) for i in line.strip().split(': ')]\n layers[a] = b\n print(severity(layers))\n for delay in itertools.count():\n if not caught(layers, delay):\n break\n print(delay)\n\n","sub_path":"2017/day_13/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"153889127","text":"import ppmt_interface\nimport numpy as np\nimport scipy\nimport scipy.stats\nimport sklearn\nimport sklearn.decomposition\nimport os.path\n\nfrom scipy.stats import norm\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\ndef generate_directions(d,n=100):\n v = np.random.normal(size=(n,d))\n s = np.sqrt(np.sum(v**2,axis=1))\n\n for i in range(d):\n v[:,i] /= s\n #v[:,i] /= np.linalg.norm(v[:,i])\n\n for i in range(n):\n v[i,:] /= np.linalg.norm(v[i,:])\n\n return v\n\ndef sphere(X,centered=True,trace=False):\n #This function will sphere the data. This means the data will now have a\n #mean of 0 and a covariance matrix of 1.\n n,p = X.shape\n muhat = np.mean(X,axis=0)\n\n if trace: print (\"muhat\",muhat)\n\n #covariance matrix\n cov = np.cov(X.T)\n if trace: print(cov)\n #eigenvalue/eigenvector decomposition\n D,V = np.linalg.eig(cov)\n if trace: print(\"D\",D,np.diag(D))\n if trace: print(\"V\",V)\n Dinv = np.linalg.inv(np.diag(D))\n if trace: print(\"Dinv\",Dinv)\n sq = scipy.linalg.sqrtm(Dinv)\n\n S = V@(sq@V.T)\n\n if trace: print(\"S\",S)\n\n\n Xc = X - muhat\n\n Z = Xc@S\n\n return Z,S\n\ndef max_pi(data,ndirs=100,lo=20):\n nsamples,dmin = data.shape\n #random direction for projection\n directions = generate_directions(dmin,n=ndirs)\n #directions[:,0] =\n #directions = np.diag(np.ones(nvars))\n #directions = np.asfortranarray(directions,dtype=np.float64)\n\n w = np.ones(nsamples)\n w = np.asfortranarray(w,dtype=np.float64)\n\n data = np.asfortranarray(data,dtype=np.float64)\n\n #compute pp index\n indices = np.empty(ndirs)\n\n for j in range(ndirs):\n #dir = np.zeros(nvars)\n direction = directions[j].copy()\n direction = np.asfortranarray(direction,dtype=np.float64)\n\n pi = ppmt_interface.ppmt_ext.pp_index(direction,data,w,lo)\n indices[j] = pi\n\n return np.max(indices)\n\n\ndef bootstrap_ppmt(nvars,ndirs=10,nboot=100,nsamples=100000,percentile=50,lo=20):\n #the idea is to generate samples from mutigaussian and calculate the projection index onto random directions\n np.random.seed(1634120)\n\n #random samples from mutivariate Gaussian\n mean = np.zeros(nvars)\n cov = np.diag(np.ones(nvars))\n\n #random direction for projection\n directions = generate_directions(nvars,n=ndirs)\n #directions[:,0] =\n #directions = np.diag(np.ones(nvars))\n #directions = np.asfortranarray(directions,dtype=np.float64)\n\n w = np.ones(nsamples)\n w = np.asfortranarray(w,dtype=np.float64)\n\n #compute pp index\n indices = np.empty((nboot,ndirs))\n #indices2 = np.empty((nboot,ndirs))\n\n for i in range(nboot):\n samples = np.random.multivariate_normal(mean,cov,size=nsamples)\n #samples,S = sphere(samples)\n\n samples = np.asfortranarray(samples,dtype=np.float64)\n\n for j in range(ndirs):\n #dir = np.zeros(nvars)\n dir = directions[j].copy()\n dir = np.asfortranarray(dir,dtype=np.float64)\n\n #project\n projection = samples@dir\n\n #import matplotlib.pyplot as plt\n #plt.hist(projection)\n #plt.show()\n\n pi = ppmt_interface.ppmt_ext.pp_index(dir,samples,w,lo)\n #p2 = projection_index(projection,lo)\n #print(i,j,pi,p2,dir,np.mean(projection),np.var(projection),np.min(projection),np.max(projection))\n\n #assert p1==p2,\"dir=%s INDEX: %f vs %f\"%(dir,p1,p2)\n\n ##quit()\n #indices2[i,j] = p2\n indices[i,j] = pi\n\n #calculate the percentil of the distribution of generated indices\n #per1 = np.percentile(indices1,percentile,axis=0)\n per = np.percentile(indices,percentile,axis=0)\n #print(per1,per2)\n return np.mean(per)\n\nclass PPMT(TransformerMixin, BaseEstimator):\n def __init__(self,n_vars=None,min_index=1e-4,maxiters=500,seed=1634129,trace=0):\n self.n_vars = n_vars\n self.min_index = min_index\n self.maxiters = maxiters\n self.seed = seed\n self.trace = trace\n\n assert 0 <= maxiters <= 1000\n\n def load_from_file(self,filename):\n if not os.path.exists(filename):\n raise Exception(\"not found\")\n\n #get the dimensions stored in the binary file\n nvars, ndata, iters = ppmt_interface.ppmt_ext.ppmt_extract_param_dim(filename)\n print(ndata, nvars, iters)\n\n if ndata == 0 and ndata == 0 and iters == 0:\n raise Exception(\"poblem to read binary file\")\n\n\n #make them Fortranable\n self._yd2 = np.asfortranarray(np.empty((ndata,nvars)),dtype=np.float64)\n self._snorm = np.asfortranarray(np.empty(ndata),dtype=np.float64)\n self._zd = np.asfortranarray(np.empty((ndata,nvars)),dtype=np.float64)\n self._sph_inv = np.asfortranarray(np.empty((nvars,nvars)),dtype=np.float64)\n self._Us = np.asfortranarray(np.empty((nvars,nvars,iters)),dtype=np.float64)\n self._projections = np.asfortranarray(np.empty((ndata,iters)),dtype=np.float64)\n self._zd2 = np.asfortranarray(np.empty((ndata,nvars)),dtype=np.float64)\n\n #print('calling ppmt_interface.ppmt_ext.ppmt_extract_param...')\n self._iterations = ppmt_interface.ppmt_ext.ppmt_extract_param(filename,nvars,ndata,iters,self._snorm,self._zd,self._sph_inv,self._Us,self._projections,self._zd2,self._yd2,self.trace)\n self.n_vars = nvars\n self.ndata = ndata\n #print('calling ppmt_interface.ppmt_ext.ppmt_extract_param...DONE')\n #print(self._iterations)\n #print(self._sph_inv)\n #reshape objects to hold just actual iterations\n self._Us = np.asfortranarray(self._Us[:,:,:self._iterations],dtype=np.float64)\n self_projections = np.asfortranarray(self._projections[:,:self._iterations],dtype=np.float64)\n self._sph = np.asfortranarray(np.linalg.inv(self._sph_inv),dtype=np.float64)\n\n\n def fit(self, X, y=None):\n ndata,nvars = X.shape\n\n if self.n_vars is not None:\n assert nvars == self.n_vars\n else:\n self.n_vars = nvars\n\n\n #make them Fortranable\n data = np.asfortranarray(X,dtype=np.float64)\n self._yd2 = np.asfortranarray(np.empty_like(data),dtype=np.float64)\n self._snorm = np.asfortranarray(np.empty(ndata),dtype=np.float64)\n self._zd = np.asfortranarray(np.empty_like(data),dtype=np.float64)\n self._sph = np.asfortranarray(np.empty((nvars,nvars)),dtype=np.float64)\n self._sph_inv = np.asfortranarray(np.empty((nvars,nvars)),dtype=np.float64)\n self._Us = np.asfortranarray(np.empty((nvars,nvars,self.maxiters)),dtype=np.float64)\n self._projections = np.asfortranarray(np.empty((ndata,self.maxiters)),dtype=np.float64)\n self._zd2 = np.asfortranarray(np.empty((ndata,nvars)),dtype=np.float64)\n\n #print(ppmt_interface.ppmt_ext.ppmt_fit.__doc__)\n\n self._iterations = ppmt_interface.ppmt_ext.ppmt_fit(data,self.min_index,self.maxiters,self._yd2,self._snorm,self._zd,self._sph,self._sph_inv,self._Us,self._projections,self._zd2,self.seed,self.trace)\n\n #reshape objects to hold just actual iterations\n self._Us = self._Us[:,:,:self._iterations]\n self._projections = self._projections[:,:self._iterations]\n\n return self\n\n def fit_transform(self,X, y=None):\n self.fit(X, y=None)\n return self._yd2\n\n def transform(self, X, copy=None):\n ndata,nvars = X.shape\n assert nvars == self.n_vars\n\n\n #make them Fortanable\n data = np.asfortranarray(X,dtype=np.float64)\n y = np.asfortranarray(np.empty_like(data),dtype=np.float64)\n\n st = ppmt_interface.ppmt_ext.ppmt_transform(\n data,\n self._iterations,\n self._snorm,\n self._zd,\n self._sph,\n self._projections,\n self._Us,\n y,\n self.trace)\n\n return y\n\n def inverse_transform(self, X, copy=None):\n ndata,nvars = X.shape\n assert nvars == self.n_vars\n\n #make them Fortanable\n X = np.asfortranarray(X,dtype=np.float64)\n ret = np.asfortranarray(np.empty_like(X),dtype=np.float64)\n ppmt_interface.ppmt_ext.ppmt_back_transform(\n X,\n ret,\n self._iterations,\n self._snorm,\n self._zd,\n self._sph_inv,\n self._Us,\n self._projections,\n self._zd2,\n self._yd2,\n self.trace)\n return ret\n\n\ndef departure_from_normality(X):\n V = np.cov(X,rowvar=False)\n var = np.var(X,axis=0)\n D = np.eye(X.shape[1])*var\n D_inv = np.linalg.inv(D)\n R = D_inv@V@D_inv\n\n E=np.diag(R)\n EE=R-np.diag(E)\n\n return np.sum((E-1.0)**2) + np.sum(EE**2)\n\n#==================== Normal Score =============================================\ndef normal_scores(o_data,o_weights=None,indices=None,na_value=np.nan):\n epsilon = 1.0e-7\n\n m = len(o_data)\n\n if o_weights is None:\n o_weights = np.ones(m)\n\n if indices is not None:\n data = o_data[indices]\n weights = o_weights[indices]\n else:\n data = o_data\n weights = o_weights\n\n n = len(data)\n\n data = data + np.random.random(n) * epsilon\n\n #sort data and weights\n table = np.empty((n,2))\n table[:,0] = data\n table[:,1] = weights\n\n table = table[table[:,0].argsort()]\n\n sorted_data = table[:,0]\n sorted_weights = table[:,1]\n\n #normalize weights\n wsum = np.sum(sorted_weights)\n nweights = sorted_weights/wsum #normalized weights\n\n #Cummulative distribution\n cumsum = np.cumsum(nweights) - 0.5/wsum #centroids\n weights = norm.ppf(cumsum)\n\n #transformation table\n table[:,0] = sorted_data\n table[:,1] = weights\n\n #Interpolate\n transformed_data = np.interp(data, sorted_data, weights)\n\n\n if indices is not None:\n tmp = np.empty(m)\n tmp[:] = na_value\n tmp[indices] = transformed_data\n transformed_data = tmp\n\n return transformed_data, table\n\n\ndef interpolator(xval,xlow,xhigh,ylow,yhigh,pow=1.0):\n if (xhigh - xlow) < EPSILON:\n ret = (yhigh + ylow) / 2.0\n else:\n ret = ylow + (yhigh-ylow) * (((xval-xlow)/(xhigh-xlow))**pow)\n\n return ret\n\ndef back_normal_scores(o_data,table,indices=None,na_value=np.nan,min_value=0.0,max_value=6.0,ltail=1.0,utail=2.0):\n '''exponential extrapolation'''\n epsilon = 1.0e-7\n\n m = len(o_data)\n\n if indices is not None:\n data = o_data[indices]\n else:\n data = o_data\n\n n = len(data)\n\n #apply linear interpolation to all data\n ntable = len(table)\n new_table = np.empty((ntable+2,2))\n #add extremmes\n new_table[0,0] = min_value\n new_table[0,1] = np.min(data)\n new_table[-1,0] = max_value\n new_table[-1,1] = np.max(data)\n new_table[1:-1,:] = table\n\n backtransformed_data = np.interp(data, new_table[:,1], new_table[:,0])\n\n #take care of tails\n\n #find tails\n lower_tails = np.where(data < table[0,1])[0]\n if len(lower_tails) > 0:\n if ltail != 1:\n cpow = 1.0 / ltpar\n else:\n cpow = 1.0\n\n z1 = table[0,0]\n y1 = table[0,1]\n b1 = (z1-min_value)*np.exp(-ltail*y1)\n for i in lower_tails:\n backtransformed_data[i] = min_value + b1*np.exp(ltail*data[i])\n #print('LB',i,data[i],table[0,1],z1,y1,b1,backtransformed_data[i])\n\n\n upper_tails = np.where(data > table[-1,1])[0]\n if len(upper_tails) > 0:\n zn = table[-1,0]\n yn = table[-1,1]\n\n bn = (zn-max_value)*np.exp(utail*yn)\n\n for i in upper_tails:\n backtransformed_data[i] = max_value + bn*np.exp(-utail*data[i])\n #print('UB',i,data[i],table[-1,1],zn,yn,bn,backtransformed_data[i])\n\n\n return backtransformed_data\n\ndef marginal_gaussian(X):\n n,nd = X.shape\n\n G = np.empty_like(X)\n tables = []\n for i in range(nd):\n transformed_data, table = normal_scores(X[:,i])\n G[:,i] = transformed_data\n tables += [table]\n\n return G,tables\n\ndef apply_marginal_gaussian(X,tables):\n n,nd = X.shape\n\n G = np.copy(X)\n for i in range(nd):\n table = tables[i]\n backtransformed_data = np.interp(G[:,i], table[:,0], table[:,1])\n G[:,i] = backtransformed_data\n\n return G\n\nclass MarginalMT():\n def __init__(self,max_iter=100,tol=1e-3,rot_max_iter=200,rot_tol=1e-6,seed=1634120,method='pca'):\n self.max_iter = max_iter\n self.tol = tol\n self.rot_max_iter = rot_max_iter\n self.rot_tol = rot_tol\n self.ica = []\n self.ica_algorithm = 'parallel'#'deflation'\n self.ica_fun = 'logcosh'\n self.seed = seed\n self.method = method\n\n def fit(self,X,trace=0):\n self.fit_transform(X,trace=trace)\n\n def fit_transform(self,X,trace=0):\n n,nd = X.shape\n self.ica = []\n self.tables = []\n\n Z = X.copy()\n #Z, tables_initial = marginal_gaussian(X)\n\n #whitening\n #Z = whiten(X)\n\n if trace>0:\n print(np.mean(Z,axis=0))\n print(np.std(Z,axis=0))\n\n pi = max_pi(Z)\n print('initial projection index:',pi)\n\n np.random.seed(self.seed)\n seeds = np.int32(np.random.random(self.max_iter)* 100000)\n\n for i in range(self.max_iter):\n if self.method == 'ica':\n ica = sklearn.decomposition.FastICA(n_components=None,max_iter=self.rot_max_iter,tol=self.rot_tol,algorithm=self.ica_algorithm,fun=self.ica_fun,random_state=seeds[i],whiten=True)\n else:\n ica = sklearn.decomposition.PCA(n_components=None,random_state=seeds[i],whiten=True)\n #ica.fit(Z)\n G = ica.fit_transform(Z)\n\n if trace>0:\n pi = max_pi(G)\n print('projection index at iteration %d after ICA:'%(i+1),pi)\n\n newG, tables = marginal_gaussian(G)\n self.ica += [ica]\n self.tables += [tables]\n\n Z = newG\n\n pi = max_pi(Z)\n if trace>0:\n print('projection index at iteration %d after marginal gaussian transform:'%(i+1),pi)\n\n if pi < self.tol:\n break\n\n self._iterations = i\n\n if trace>0:\n print(np.mean(Z,axis=0))\n print(np.std(Z,axis=0))\n\n self.Y = Z\n\n return self.Y\n\n def transform(self,X,trace=0):\n n,nd = X.shape\n\n Z = X.copy()\n\n if trace>0:\n print(np.mean(Z,axis=0))\n print(np.std(Z,axis=0))\n\n if trace>0: \n pi = max_pi(Z)\n print('initial pi:',pi)\n\n for i in range(self._iterations):\n G = self.ica[i].transform(Z)\n\n Z = apply_marginal_gaussian(G,self.tables[i])\n\n if trace>0: \n pi = max_pi(Z)\n print('pi at iteration %d after ICA:'%(i+1),pi)\n\n if trace>0:\n print(np.mean(Z,axis=0))\n print(np.std(Z,axis=0))\n\n return Z\n\n def inverse_transform(self,Y,trace=0):\n n,nd = Y.shape\n\n Z = Y.copy()\n for i in range(self._iterations-1,-1,-1):\n #back transform normal scores\n G = np.empty_like(Z)\n for k in range(nd):\n G[:,k] = np.interp(Z[:,k],self.tables[i][k][:,1],self.tables[i][k][:,0])\n\n #back transform ICA\n Z = self.ica[i].inverse_transform(G)\n\n return Z\n","sub_path":"pymvg/ppmt.py","file_name":"ppmt.py","file_ext":"py","file_size_in_byte":15530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"229917759","text":"#!/usr/bin/python\n\nimport sys\nfrom PyQt5 import QtCore, QtWidgets\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtWidgets import QVBoxLayout\n\n# the workload was distributed evenly between the two team members\n\n\nclass SpeedTest(QtWidgets.QWidget):\n\n # init all necessary variables\n def __init__(self, text, participant_id):\n super(SpeedTest, self).__init__()\n self.text = text\n self.id = participant_id\n self.word_list = self.text.replace('\\n', ' ').lower().split(' ')\n self.sentence_count = 0\n self.sentence_list = self.text.split('\\n')\n self.num_sentences = len(self.sentence_list)\n self.word_time = []\n self.word = \"\"\n self.sentence = \"\"\n self.timer_sentence = QtCore.QTime()\n self.timer_word = QtCore.QTime()\n self.started = False\n self.finished_word = False\n self.init_ui()\n sys.stdout.write(\"timestamp_ISO,id,sentence_count,sentence_length,sentence_time_in_ms,\"\n \"word_count,avg_word_length,avg_word_time_in_ms,words_per_minute\\n\")\n\n # init interface\n def init_ui(self):\n self.showMaximized()\n self.setWindowTitle('Speed Test')\n self.setFocusPolicy(QtCore.Qt.StrongFocus)\n # display text to be written\n self.instructions = QtWidgets.QLabel(self)\n self.instructions.setAlignment(QtCore.Qt.AlignCenter)\n self.instructions.setFont(QFont('Arial', 20))\n self.instructions.setText(self.text)\n # text edit\n self.text_edit = QtWidgets.QTextEdit(self)\n # layout\n layout = QVBoxLayout()\n layout.addWidget(self.instructions)\n layout.addWidget(self.text_edit)\n self.setLayout(layout)\n self.show()\n\n # logs test data\n def log_data(self):\n timestamp = QtCore.QDateTime.currentDateTime().toString(QtCore.Qt.ISODate)\n word_count, avg_word_len, avg_word_time = self.analyze_sentence(self.sentence_count)\n sentence_length = len(self.sentence_list[self.sentence_count-1])\n sentence_time = self.stop_time_sentence()\n wpm = self.words_per_minute(sentence_length, sentence_time, avg_word_len)\n sys.stdout.write(\"%s,%s,%d,%d,%d,%d,%d,%d,%d\\n\" %\n (timestamp, self.id, self.sentence_count, sentence_length, sentence_time,\n word_count, avg_word_len, avg_word_time, wpm))\n\n # analyzes current sentence\n def analyze_sentence(self, num):\n sentence = self.sentence_list[num-1]\n word_count = len(sentence.split(' '))\n avg_word_len = len(sentence.replace(' ', ''))/word_count\n time = 0\n for i in self.word_time:\n time += i\n avg_word_time = time / word_count\n return word_count, avg_word_len, avg_word_time\n\n # calculates word per minute\n def words_per_minute(self, sentence_len, sentence_time, avg_word_length):\n return ((sentence_len/(sentence_time/1000))*60)/avg_word_length\n\n # handles event when key is released\n # use key release, because the press event is focused on the edit text\n def keyReleaseEvent(self, event):\n letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',\n 't', 'u', 'v', 'w', 'x', 'y', 'z', 'ä', 'ö', 'ü']\n # when a sentence has not yet begun\n if not self.started:\n self.started = True\n self.start_time_sentence()\n self.start_time_word()\n self.sentence_count += 1\n self.word_time = []\n # when a word is finished\n if self.finished_word:\n self.start_time_word()\n self.finished_word = False\n # when the sentence has started\n if self.started:\n if event.text() in letters:\n self.word += event.text()\n self.sentence += event.text()\n sys.stdout.write('Key pressed: ' + str(event.text()) + '\\n')\n elif event.key() == QtCore.Qt.Key.Key_Space:\n self.word_time.append(self.stop_time_word())\n sys.stdout.write('Key pressed: Space \\n')\n sys.stdout.write('Word typed: ' + self.word + '\\n')\n self.sentence += ' '\n self.word = \"\"\n self.finished_word = True\n elif event.key() == QtCore.Qt.Key.Key_Return:\n self.word_time.append(self.stop_time_word())\n sys.stdout.write('Key pressed: Enter \\n')\n sys.stdout.write('Word typed: ' + self.word + '\\n')\n self.word = \"\"\n sys.stdout.write('Sentence typed: ' + self.sentence + '\\n')\n self.sentence = \"\"\n self.log_data()\n self.started = False\n if self.sentence_count == self.num_sentences:\n #sys.stdout.write('Test finished')\n # sys.stderr.write(\"Finished!\")\n sys.exit(1)\n elif event.key() == QtCore.Qt.Key.Key_Backspace:\n sys.stdout.write('Key pressed: Delete \\n')\n self.word = self.word[:-1]\n self.sentence = self.sentence[:-1]\n\n # start timer for sentence\n def start_time_sentence(self):\n self.timer_sentence.start()\n\n # stops timer for sentence\n def stop_time_sentence(self):\n elapsed = self.timer_sentence.elapsed()\n return elapsed\n\n # starts timer for word\n def start_time_word(self):\n self.timer_word.start()\n\n # stops timer for word\n def stop_time_word(self):\n elapsed = self.timer_word.elapsed()\n return elapsed\n\n\ndef main():\n app = QtWidgets.QApplication(sys.argv)\n if len(sys.argv) < 3:\n sys.stderr.write(\"Need .txt file with text to be written and an participant id\")\n sys.exit(1)\n text = get_text(sys.argv[1])\n speed_test = SpeedTest(text, sys.argv[2])\n sys.exit(app.exec())\n\n\n# extracts text from file\ndef get_text(filename):\n text = \"\"\n file = open(filename).readlines()\n for i in file:\n text += i\n return text\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"text_entry_speed_test.py","file_name":"text_entry_speed_test.py","file_ext":"py","file_size_in_byte":6154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"194843297","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 9 14:14:46 2016\n\n@author: kebl4230\n\"\"\"\nfrom class_race import Race, endturnFuncs, attackFuncs\nfrom collections import Counter\n\n\nclass Player(object):\n def __init__(self, name, game):\n # attributes\n self.name = name\n self.combo = None\n self.adjacent_regions = game.border_regions\n self.excess = 0\n self.score = 5\n self.declined_combo = None\n \n # work first, pretty second\n self.race_end_turn_func = self.endFunc_null\n self.power_end_turn_func = self.endFunc_null\n self.tokens = Counter()\n self.race_attack_func = self.attackFunc_null\n self.power_attack_func = self.attackFunc_null\n\n def update_combo(self, power, race, game):\n if self.combo is not None:\n print(\"Error: You must first decline.\")\n else:\n if self.declined_combo is not None:\n \"\"\"have declined already\"\"\"\n aa = self.declined_combo.split(\"_\")\n game.available_races.append(aa[1])\n game.available_powers.append(aa[0])\n power = Race(power, endturnFuncs, attackFuncs)\n race = Race(race, endturnFuncs, attackFuncs)\n self.combo = power.name + \"-\" + race.name\n self.initial_troops = race.troops + power.troops\n self.excess = self.initial_troops\n self.first_conquer = True\n\n # bonuses\n self.race_end_turn_func = race.end_turn_func\n self.power_end_turn_func = power.end_turn_func\n self.tokens = Counter()\n self.tokens.update(race.tokens)\n self.tokens.update(power.tokens)\n self.race_attack_func = race.attack_func\n self.power_attack_func = power.attack_func\n if power.name == \"wealthy\":\n self.score += 7\n\n\n def special_turn_end(self, game):\n self.race_end_turn_func(game)\n self.power_end_turn_func(game)\n \n def special_attack_func(self, game, tile):\n bonus = self.race_attack_func(game, tile)\n bonus += self.power_attack_func(game, tile)\n return bonus\n \n def endFunc_null(self, game):\n pass\n\n def attackFunc_null(self, game, tile):\n return 0\n","sub_path":"class_player.py","file_name":"class_player.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"440515390","text":"\"\"\"\n可以接受丢失数据 RDB\n建议都开启或者定期执行bgsave做快照备份,RDB方式更适合做数据的备份,AOF可以保证数据的不丢失\n\"\"\"\na = [{'source': 'iep', 'count_time': '2020-07-13', \n'alarm_type': 'Loop', 'type': 'Log', 'count': 236}, \n{'source': 'iep', 'count_time': '2020-07-13', 'alarm_type': 'Loop', 'type': 'Ins', 'count': 48068}, \n{'source': 'iep', 'count_time': '2020-07-13', 'alarm_type': 'Loop', 'type': 'Mer', 'count': 14592}, \n{'source': 'ptd', 'count_time': '2020-07-13', 'alarm_type': 'Alerts', 'type': 'Upd', 'count': 2241}, \n{'source': 'ptd', 'count_time': '2020-07-13', 'alarm_type': 'Alerts', 'type': 'Ins', 'count': 1164}, \n{'source': 'fire', 'count_time': '2020-07-13', 'alarm_type': 'Alerts', 'type': 'Upd', 'count': 2117}, \n{'source': 'fire', 'count_time': '2020-07-13', 'alarm_type': 'Alerts', 'type': 'Ins', 'count': 1}, \n{'source': 'fire', 'count_time': '2020-07-13', 'alarm_type': 'Alerts', 'type': 'Log', 'count': 21189}]\n\n\nnode = {\n\t\"collect\": {\"iep\": 0, \"ptd\": 0, \"hillstone\": 0, \"star\": 0, \"gap\": 0},\n\t\"event\": {\"iep\": 0, \"ptd\": 0, \"hillstone\": 0, \"star\": 0, \"gap\": 0},\n\t\"event_update\": {\"iep\": 0, \"ptd\": 0, \"hillstone\": 0, \"star\": 0, \"gap\": 0},\n\t\"alarm\":{\"iep\": 0, \"ptd\": 0, \"hillstone\": 0, \"star\": 0, \"gap\": 0},\n\t\"ins\": {},\n\t\"mer\":{}\n}\n\ndef fun(i,node_key):\n\tif i['source'] == 'iep':\n\t\tnode_key['iep'] = i['count']\n\tif i['source'] == 'ptd':\n\t\tnode_key['ptd'] = i['count']\n\tif i['source'] == 'fire':\n\t\tnode_key['hillstone'] =i['count']\n\t\tnode_key['star'] =i['count']\n\treturn node_key\n\n\ndef sum_dict(a,b):\n\ttemp = dict()\n\t# python3,dict_keys类似set; | 并集\n\tfor key in a.keys()| b.keys():\n\t\ttemp[key] = sum([d.get(key, 0) for d in (a, b)])\n\treturn temp\n\n\nfor i in a:\n\tif i['type'] == 'Upd':\n\t\tnode['event_update'] = fun(i ,node['event_update'])\n\tif i['type'] == 'Log':\n\t\tnode['collect'] = fun(i, node['collect'])\n\tif i['type'] == 'Ins':\n\t\tnode['ins'] = fun(i, node['ins'])\n\tif i['type'] == 'Mer':\n\t\tnode['mer'] = fun(i, node['mer'])\n\tif i['alarm_type'] == 'Alerts' and i['type'] == 'Ins':\n\t\tnode['alarm'] = fun(i, node['alarm'])\n\n\tnode['event'] = sum_dict(node['ins'], node['mer'])\n\n# print(node)\ndel node['ins']\ndel node['mer']\nfor k, v in node.items():\n\tprint(v)\n\n{'collect': {'iep': 236, 'ptd': 0, 'hillstone': 21189, 'star': 21189, 'gap': 0}, \n'event': {'ptd': 1164, 'star': 1, 'gap': 0, 'iep': 0, 'hillstone': 1}, \n'event_update': {'iep': 0, 'ptd': 2241, 'hillstone': 2117, 'star': 2117, 'gap': 0}, \n'threat_alarm': {'iep': 0, 'ptd': 1164, 'hillstone': 1, 'star': 1, 'gap': 0}, \n'malicious_alarm': {'iep': 0, 'ptd': 0, 'hillstone': 0, 'star': 0, 'gap': 0}}\n\n\ns = {\"a\": {\"a\":1, \"b\":2},\n\t\"c\": {\"b\":4, \"a\":3},\n\t\"b\": {\"a\":3, \"b\":4},}\nfrom collections import OrderedDict\nd = sorted(s.items(), key=lambda item: item[0])\nprint(dict(d))\n\n\n\n{'collect': {'iep': 236, 'ptd': 0, 'hillstone': 21189, 'star': 21189, 'gap': 0}, \n'event': {'star': 1, 'gap': 0, 'hillstone': 1, 'ptd': 1164, 'iep': 0}, \n'event_update': {'iep': 0, 'ptd': 2241, 'hillstone': 2117, 'star': 2117, 'gap': 0}, \n'threat_alarm': {'iep': 0, 'ptd': 1164, 'hillstone': 1, 'star': 1, 'gap': 0}, \n'malicious_alarm': {'iep': 0, 'ptd': 0, 'hillstone': 0, 'star': 0, 'gap': 0}}\n","sub_path":"redis/AOF和RDB选择.py","file_name":"AOF和RDB选择.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"225493591","text":"import sys\nimport mox\nimport json\nimport unittest\n\nsys.path.append(\"..\")\nfrom taguchi.activity import Activity\nfrom taguchi.activity import ActivityRevision\n\nclass TestActivityRevision(unittest.TestCase):\n\n def setUp(self):\n self.record = ActivityRevision(None, \n {\"content\": \"x\", \"approval_status\": \"y\", \"id\": 1})\n\n def tearDown(self):\n self.record = None\n\n def test_content(self):\n self.assertEqual(\"x\", self.record.content)\n self.record.content = \"new_x\"\n self.assertEqual(\"new_x\", self.record.content)\n\n def test_approval_status(self):\n self.assertEqual(\"y\", self.record.approval_status)\n self.record.approval_status = \"new_y\"\n self.assertEqual(\"new_y\", self.record.approval_status)\n\n def test_record_id(self):\n self.assertEqual(\"1\", self.record.record_id)\n\nclass TestActivity(mox.MoxTestBase):\n\n def setUp(self):\n mox.MoxTestBase.setUp(self)\n self.record = Activity(None) \n self.record.backing = {\"id\": 1, \"status\": \"\", \"revisions\": []}\n\n def tearDown(self):\n self.record = None\n mox.MoxTestBase.tearDown(self)\n\n def test_record_id(self):\n self.assertEqual(\"1\", self.record.record_id)\n\n def test_ref(self):\n self.record.ref = \"x\"\n self.assertEqual(\"x\", self.record.ref)\n\n def test_name(self):\n self.record.name = \"x\"\n self.assertEqual(\"x\", self.record.name)\n\n def test_type(self):\n self.record.type = \"x\"\n self.assertEqual(\"x\", self.record.type)\n\n def test_subtype(self):\n self.record.subtype = \"x\"\n self.assertEqual(\"x\", self.record.subtype)\n\n def test_target_lists(self):\n self.record.target_lists = \"x\"\n self.assertEqual(\"x\", self.record.target_lists)\n\n def test_target_views(self):\n self.record.target_views = \"x\"\n self.assertEqual(\"x\", self.record.target_views)\n\n def test_approval_status(self):\n self.record.approval_status = \"x\"\n self.assertEqual(\"x\", self.record.approval_status)\n\n def test_deploy_datetime(self):\n self.record.deploy_datetime = \"x\"\n self.assertEqual(\"x\", self.record.deploy_datetime)\n\n def test_template_id(self):\n self.record.template_id = 1\n self.assertEqual(\"1\", self.record.template_id)\n\n def test_campaign_id(self):\n self.record.campaign_id = 1\n self.assertEqual(\"1\", self.record.campaign_id)\n\n def test_throttle(self):\n self.record.throttle = 1\n self.assertEqual(1, self.record.throttle)\n\n def test_xml_data(self):\n self.record.xml_data = \"x\"\n self.assertEqual(\"x\", self.record.xml_data)\n\n def test_status(self):\n self.assertEqual(\"\", self.record.status)\n\n def test_latest_revision(self):\n self.assertEqual(None, self.record.latest_revision)\n self.record.latest_revision = ActivityRevision(\n self.record, {\"content\": \"x\"})\n revision = self.record.latest_revision\n self.assertEqual(\"x\", revision.content)\n\n def test_update(self):\n context = self.mox.CreateMockAnything()\n context.make_request(\"activity\", \"PUT\", record_id=1, \n data=json.dumps([{\"id\": 1, \"ref\": \"ref\", \"revisions\": []}])).AndReturn(\n json.dumps([{\"id\": 1, \"ref\": \"ref\", \"revisions\": []}]))\n self.mox.ReplayAll()\n\n record = Activity(context)\n record.backing = {\"id\": 1, \"ref\": \"ref\", \"revisions\": []}\n record.update()\n self.assertEqual(\"1\", record.record_id)\n self.assertEqual(\"ref\", record.ref)\n self.mox.VerifyAll()\n\n def test_create(self):\n context = self.mox.CreateMockAnything()\n context.make_request(\"activity\", \"POST\",\n data=json.dumps([{\"ref\": \"ref\", \"revisions\": []}])).AndReturn(\n json.dumps([{\"id\": 1, \"ref\": \"ref\", \"revisions\": []}]))\n self.mox.ReplayAll()\n\n record = Activity(context)\n record.backing = {\"ref\": \"ref\", \"revisions\": []}\n record.create()\n self.assertEqual(\"1\", record.record_id)\n self.assertEqual(\"ref\", record.ref)\n self.mox.VerifyAll()\n\n def test_proof(self):\n context = self.mox.CreateMockAnything()\n context.make_request(\"activity\", \"PROOF\", record_id=\"1\",\n data=json.dumps([{\"id\": \"1\", \"list_id\": \"1\", \"tag\": \"subject\", \n \"message\": \"hello\"}]))\n self.mox.ReplayAll()\n\n record = Activity(context)\n record.backing = {\"id\": 1}\n record.proof(\"1\", \"subject\", \"hello\")\n self.mox.VerifyAll()\n\n def test_request_approval(self):\n context = self.mox.CreateMockAnything()\n context.make_request(\"activity\", \"APPROVAL\", record_id=\"1\",\n data=json.dumps([{\"id\": \"1\", \"list_id\": \"1\", \"tag\": \"subject\", \n \"message\": \"hello\"}]))\n self.mox.ReplayAll()\n\n record = Activity(context)\n record.backing = {\"id\": 1}\n record.request_approval(\"1\", \"subject\", \"hello\")\n self.mox.VerifyAll()\n\n def test_trigger(self):\n context = self.mox.CreateMockAnything()\n context.make_request(\"activity\", \"TRIGGER\", record_id=\"1\",\n data=json.dumps([{\"id\": \"1\", \"test\": 0, \n \"request_content\": \"content\", \"conditions\": [\"1\"]}]))\n self.mox.ReplayAll()\n\n record = Activity(context)\n record.backing = {\"id\": 1}\n record.trigger([\"1\"], \"content\", False)\n self.mox.VerifyAll()\n\n def test_static_get(self):\n context = self.mox.CreateMockAnything()\n context.make_request(\"activity\", \"GET\", record_id=1, \n parameters={\"sort\": \"id\", \"order\": \"asc\"}).AndReturn(\n json.dumps([{\"id\": 1, \"revisions\": []}]))\n self.mox.ReplayAll()\n\n record = Activity.get(context, 1, {\"sort\": \"id\", \"order\": \"asc\"})\n self.assertTrue(isinstance(record, Activity))\n self.assertEqual({\"id\": 1, \"revisions\": []}, record.backing)\n self.mox.VerifyAll()\n\n def test_static_get_with_content(self):\n context = self.mox.CreateMockAnything()\n context.make_request(\"activity\", \"GET\", record_id=1, \n parameters={\"revision\": \"latest\"}).AndReturn(\n json.dumps([{\"id\": 1, \"revisions\": []}]))\n self.mox.ReplayAll()\n\n record = Activity.get_with_content(context, 1)\n self.assertTrue(isinstance(record, Activity))\n self.assertEqual({\"id\": 1, \"revisions\": []}, record.backing)\n self.mox.VerifyAll()\n\n def test_static_find(self):\n context = self.mox.CreateMockAnything()\n context.make_request(\"activity\", \"GET\", \n parameters={\"sort\": \"id\", \"order\": \"asc\", \"offset\": \"1\", \"limit\": \"100\"},\n query=[\"id-gt-1\", \"id-lt-100\"]).AndReturn(\n json.dumps([{\"id\": 1, \"revisions\": []}, {\"id\": 2, \"revisions\": []}]))\n self.mox.ReplayAll()\n\n records = Activity.find(context, \"id\", \"asc\", 1, 100, [\"id-gt-1\", \"id-lt-100\"])\n self.assertEqual(2, len(records))\n self.mox.VerifyAll()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/test_activity.py","file_name":"test_activity.py","file_ext":"py","file_size_in_byte":7066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"564704132","text":"import os\nimport unittest\nimport json\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom flaskr import create_app\nfrom models import setup_db, Question, Category\n\n\nclass TriviaTestCase(unittest.TestCase):\n \"\"\"This class represents the trivia test case\"\"\"\n\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n self.app = create_app()\n self.client = self.app.test_client\n self.database_name = \"trivia_test\"\n self.database_path = \"postgres:///{}\".format(self.database_name)\n setup_db(self.app, self.database_path)\n\n # binds the app to the current context\n with self.app.app_context():\n self.db = SQLAlchemy()\n self.db.init_app(self.app)\n # create all tables\n self.db.create_all()\n \n def tearDown(self):\n \"\"\"Executed after reach test\"\"\"\n pass\n\n\n def test_get_categories(self):\n res = self.client().get(\"/categories\")\n \n self.assertEqual(res.status_code, 200)\n \n cat_json = res.get_json()\n self.assertTrue(cat_json.get(\"success\"), \"Success should be present in the response\")\n \n cat_dict = cat_json.get(\"categories\")\n self.assertEqual(6, len(cat_dict))\n expected = {\n \"1\":\"Science\",\n \"2\":\"Art\",\n \"3\":\"Geography\",\n \"4\":\"History\",\n \"5\":\"Entertainment\",\n \"6\":\"Sports\"}\n self.assertEqual(expected, cat_dict)\n \n \n def test_method_not_allowed_categories(self):\n methods = [\"POST\", \"PATCH\", \"DELETE\", \"PUT\"]\n url = \"/categories\"\n for method in methods:\n res = getattr(self.client(), method.lower())(url) \n self.assertEqual(res.status_code, 405, f\"Expecting method not allowed error (405) for method {method}\")\n self.assertTrue(res.get_json().get(\"error\"), \"Error attribute should be present in response\")\n self.assertFalse(res.get_json().get(\"success\"), \"Success attribute should be present in response and should be false\")\n \n\n def test_get_questions_by_category(self):\n res = self.client().get(\"/categories/1/questions\")\n self.assertEqual(res.status_code, 200)\n myjson = res.get_json()\n self.assertTrue(myjson.get(\"categories\"), \"Categories key should exist in the response\")\n self.assertTrue(myjson.get(\"success\"))\n self.assertEqual(1, myjson.get(\"current_category\"), \"Current category should match the category passed in the url\")\n self.assertEqual(3, myjson.get(\"total_questions\"))\n self.assertEqual(3, len(myjson.get(\"questions\")))\n \n \n def test_get_questions_for_nonexistant_category(self):\n res = self.client().get(\"/categories/999/questions\")\n self.assertEqual(res.status_code, 404, \"Expecting page not found error (404) for a non-existent category \")\n self.assertTrue(res.get_json().get(\"error\"), \"Error attribute should be present in response\")\n self.assertFalse(res.get_json().get(\"success\"), \"Success attribute should be present in response and should be false\")\n\n \n def test_bad_url(self):\n res = self.client().get(\"/bad-url\")\n self.assertEqual(res.status_code, 404, \"Expecting page not found error (404) for a non-existent category \")\n self.assertTrue(res.get_json().get(\"error\"), \"Error attribute should be present in response\")\n self.assertFalse(res.get_json().get(\"success\"), \"Success attribute should be present in response and should be false\")\n\n \n# Make the tests conveniently executable\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"projects/02_trivia_api/starter/backend/test_flaskr.py","file_name":"test_flaskr.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"115254917","text":"def ratio(x, y):\n \"\"\"The ratio of 'x' to 'y'. \"\"\"\n return x / y\n\n\n# Functions need not have arguments\ndef answer_to_the_ultimate_question_of_life_the_universe_and_everything():\n \"\"\"Simpler program than Deep Thought's, JB bets.\"\"\"\n return 42\n\n\n# Functions need not have return statements\ndef think_too_much():\n \"\"\"Express Caeser's skepticism about Cassius\"\"\"\n\n print(\"\"\"Yond Cassius has a lean and hungry look,\n He thinks too much; such men are dangerous.\"\"\")\n\n\ndef complement_base(base, material='DNA'):\n \"\"\"Returns the Watson-Crick complement of my base.\"\"\"\n\n if base in 'Aa':\n if material == 'DNA':\n return 'T'\n elif material == 'RNA':\n return 'U'\n else:\n raise RuntimeError('Invalid material.')\n elif base in 'TtUu':\n return 'A'\n elif base in 'Gg':\n return'C'\n else:\n return 'G'\n\n\ndef reverse_complement(seq, material='DNA'):\n \"\"\"Make reverse complement of seq\"\"\"\n\n # Initialize an empty string\n rev_comp = ''\n\n # Loop through sequence in reverse\n for base in reversed(seq):\n\n # For each base, find and concatenate with complement\n rev_comp += complement_base(base, material=material)\n\n return rev_comp\n","sub_path":"function_lesson.py","file_name":"function_lesson.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"162978077","text":"import unittest\ndef bruteForece(input):\n length = len(input)\n length_max = 0\n for i in range(0,length):\n for k in range(i + 1,length+1):\n length_temp = isPalindromic(input[i:k])\n length_max = max(length_temp,length_max)\n return length_max\n\n#return the legnt of a palindromic string, 0 if not palindromic\ndef isPalindromic(input):\n i = -1\n for char in input:\n if char != input[i]:\n return 0\n i = i - 1\n return len(input)\n \n\nimport unittest\n\nclass TestStringMethods(unittest.TestCase):\n input1 = \"ab\"\n input2 = \"abc\"\n input3 = \"aba\"\n input4 = \"abba\"\n input5 = \"a\"\n input6 = \"abcdefedc\"\n input7 = \"abcbdefedbab\"\n\n def test_brute_force(self):\n input1 = \"ab\"\n input2 = \"abc\"\n input3 = \"aba\"\n input4 = \"abba\"\n input5 = \"a\"\n input6 = \"abcdefedc\"\n input7 = \"abcbdefedbab\"\n self.assertEqual(bruteForece(input1),1)\n self.assertEqual(bruteForece(input2),1)\n self.assertEqual(bruteForece(input3),3)\n self.assertEqual(bruteForece(input4),4)\n self.assertEqual(bruteForece(input5),1)\n self.assertEqual(bruteForece(input6),7)\n self.assertEqual(bruteForece(input7),7)\n\n def test_upper(self):\n self.assertEqual('foo'.upper(), 'FOO')\n\n def test_isupper(self):\n self.assertTrue('FOO'.isupper())\n self.assertFalse('Foo'.isupper())\n\n def test_split(self):\n s = 'hello world'\n self.assertEqual(s.split(), ['hello', 'world'])\n # check that s.split fails when the separator is not a string\n with self.assertRaises(TypeError):\n s.split(2)\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n\n","sub_path":"LongestPalindromic/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"555629988","text":" \ntupla = (25, \"Douglas\", 31 )\n#print(tupla[2])\n\n\"\"\"indice = 0\n\nwhile(indice < len(tupla)):\n print(tupla[indice])\n indice = indice + 1\"\"\"\n\nnumbers = (12, 35,67, 2, \"Douglas\")\n\nfor i in numbers:\n print(i)\n","sub_path":"Python/Python22.py","file_name":"Python22.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"384922048","text":"'''\nGiven an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].\n\nExample:\nInput: [1,2,3,4]\nOutput: [24,12,8,6]\nNote: Please solve it without division and in O(n).\n\nFollow up:\nCould you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)\n'''\n\n__date__ = '2018-7-22'\n\n# way 1\n# 正反两次遍历,一次遍历求每个数左侧的所有数的积,一次遍历求每个数右侧的所有数的积,最后两部分积相乘即得所求。\nclass Solution_1(object):\n def productExceptSelf(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n res = [0 for _ in range(len(nums))]\n left_mul = [1 for _ in range(len(nums))]\n right_mul = [1 for _ in range(len(nums))]\n for i in range(1, len(nums)):\n left_mul[i] = left_mul[i-1] * nums[i-1]\n for i in range(len(nums)-2, -1, -1):\n right_mul[i] = right_mul[i+1] * nums[i+1]\n for i in range(len(nums)):\n res[i] = left_mul[i] * right_mul[i]\n return res\n\n# way 2\n# 只使用一个临时常数变量\nclass Solution_2(object):\n def productExceptSelf(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n dp = [1] * len(nums)\n for i in range(1, len(nums)):\n dp[i] = dp[i - 1] * nums[i - 1]\n prod = 1\n for i in reversed(range(0, len(nums))):\n dp[i] = dp[i] * prod\n prod *= nums[i]\n return dp","sub_path":"238. Product of Array Except Self.py","file_name":"238. Product of Array Except Self.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"28466649","text":"\"\"\" Examples demonstrating how to use the Yadle aggregate API.\n\n This file contains several methods for interacting with the Yadle API.\n\n The main() function at the bottom contains an actual example of creating and\n modifying an aggregate.\n\n See https://api.yadle.com/ for full documentation of the Yadle API.\n\"\"\"\n\nimport requests\nimport json\nimport traceback\n\n\ndef logIn(apiserver, username, password):\n url = \"{0}/yadle/v2/auth/login\".format(apiserver)\n payload = \"username={0}&password={1}&undefined=\".format(username, password)\n headers = {\n 'Content-Type': \"application/x-www-form-urlencoded\",\n }\n\n response = requests.request(\"POST\", url, data=payload, headers=headers)\n \n # get Bearer\n res = json.loads(response.text)\n bearer = \"Bearer {0}:{1}\".format(res['token'], res['password'])\n return bearer\n\n\ndef get_file_info(file_id, server, bearer, app_id):\n \n url = \"{0}/yadle/v2/file/{1}\".format(server, file_id)\n payload = \"\"\n headers = {\n 'x-app-id': app_id,\n 'Authorization': bearer,\n 'cache-control': \"no-cache\"\n }\n\n response = requests.request(\"GET\", url, data=payload, headers=headers)\n\n if not response:\n print('ERROR: ' + url + ' returns a null response ' + str(response))\n print(str(json.loads(response.text)))\n return None\n\n return json.loads(response.text)\n\n\n\ndef create_aggregate(file_id, member_list, server, bearer, app_id):\n url = \"{0}/yadle/v2/file/{1}/aggregate/new\".format(server, file_id)\n\n headers = {\n 'x-app-id': app_id,\n 'Authorization': bearer,\n 'Content-Type': 'application/json'\n }\n\n response = requests.request(\"POST\", url, headers=headers, json=member_list)\n\n print(json.loads(response.text))\n return json.loads(response.text)\n\ndef remove_aggregate_members(file_id, aggregate_id, members_to_remove, server, bearer, app_id):\n url = \"{0}/yadle/v2/file/{1}/aggregate/{2}\".format(server, file_id, aggregate_id)\n\n headers = {\n 'x-app-id': app_id,\n 'Authorization': bearer,\n 'Content-Type': 'application/json'\n }\n\n response = requests.request(\"DELETE\", url, headers=headers, json=members_to_remove)\n\n print(json.loads(response.text))\n return json.loads(response.text)\n\ndef add_additional_aggregate_members(file_id, aggregate_id, files_to_add, server, bearer, app_id):\n url = \"{0}/yadle/v2/file/{1}/aggregate/{2}\".format(server, file_id, aggregate_id)\n\n headers = {\n 'x-app-id': app_id,\n 'Authorization': bearer,\n 'Content-Type': 'application/json'\n }\n\n response = requests.request(\"PATCH\", url, headers=headers, json=files_to_add)\n\n print(json.loads(response.text))\n return json.loads(response.text)\n\ndef get_aggregate(file_id, aggregate_id, server, bearer, app_id):\n url = \"{0}/yadle/v2/file/{1}/aggregate/{2}\".format(server, file_id, aggregate_id)\n\n headers = {\n 'x-app-id': app_id,\n 'Authorization': bearer,\n 'Content-Type': 'application/json'\n }\n\n response = requests.request(\"GET\", url, headers=headers)\n\n print(json.loads(response.text))\n return json.loads(response.text)\n\ndef get_all_aggregates(file_id, server, bearer, app_id):\n # get all aggregates associated with a file\n url = \"{0}/yadle/v2/file/{1}/aggregate/_all\".format(server, file_id)\n\n headers = {\n 'x-app-id': app_id,\n 'Authorization': bearer,\n 'Content-Type': 'application/json'\n }\n\n response = requests.request(\"GET\", url, headers=headers)\n\n print(json.loads(response.text))\n return json.loads(response.text)\n\ndef edit_primary_file(file_id, aggregate_id, new_primary, server, bearer, app_id):\n # edit primary file of an aggregate. The new primary file must already \n # be a member of the aggregate.\n url = \"{0}/yadle/v2/file/{1}/aggregate/{2}/edit_primary\".format(server, file_id, aggregate_id)\n \n # body must be an array containing a signle file id: the new pimary file.\n body = [new_primary]\n headers = {\n 'x-app-id': app_id,\n 'Authorization': bearer,\n 'Content-Type': 'application/json'\n }\n\n response = requests.request(\"PATCH\", url, headers=headers, json=body)\n\n print(json.loads(response.text))\n return json.loads(response.text)\n\ndef delete_entire_aggregate(file_id, aggregate_id, server, bearer, app_id):\n # Delete an entire aggregate. Note: this does not affect any constituent files themselves.\n url = \"{0}/yadle/v2/file/{1}/aggregate/{2}/entire\".format(server, file_id, aggregate_id)\n \n headers = {\n 'x-app-id': app_id,\n 'Authorization': bearer,\n 'Content-Type': 'application/json'\n }\n\n response = requests.request(\"DELETE\", url, headers=headers)\n\n print(json.loads(response.text))\n return json.loads(response.text)\n\n\ndef main():\n \n # server and authentication information\n server = 'https://example1.yadle.com'\n username = \"your_username\"\n password = \"your_password\"\n bearer = logIn(server, username, password)\n app_id = 'your_app_id'\n\n\n aggregate_head = 'file_id1'\n aggregate_members = ['file_id2', 'file_id3', 'file_id4']\n\n response = create_aggregate(aggregate_head, aggregate_members, server, bearer, app_id)\n\n # Once the aggregate has been created, we will use the new aggregate id to interact with it.\n aggregate_id = response['aggregate_id']\n\n # View the aggregate.\n aggregate = get_aggregate(aggregate_head, aggregate_id, server, bearer, app_id)\n\n # Change which file is the primary fire (the one that will be displayed in search results).\n edit_response = edit_primary_file(aggregate_head, aggregate_id, aggregate_members[0], server, bearer, app_id)\n\n if edit_response['code'] == 200:\n # aggregate_head has changed:\n aggregate_head = aggregate_members[0]\n \n\n # As an example, remove a file from the aggregate.\n files_to_remove = [aggregate_members[2]]\n remove_aggregate_members(aggregate_head, aggregate_id, files_to_remove, server, bearer, app_id)\n\n # Add the same file back into the aggregate.\n add_additional_aggregate_members(aggregate_head, aggregate_id, files_to_remove, server, bearer, app_id) \n\n # Delete the entire aggregate.\n delete_entire_aggregate(aggregate_head, aggregate_id, server, bearer, app_id)\n\nif __name__ == '__main__':\n main()","sub_path":"aggregate_methods.py","file_name":"aggregate_methods.py","file_ext":"py","file_size_in_byte":6377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"396370733","text":"from numpy import sqrt\nfrom numpy.linalg import inv, det\nimport numpy as np\n\n# testando com classe cabo abaixo\n\nclass Cable:\n\n def __init__(self, point_ancrage, sommet_source, tension_min, tension_max):\n self.point_ancrage = point_ancrage\n self.sommet_source = sommet_source\n self.vecteur = np.array ([self.point_ancrage[0]-self.sommet_source[0],\n self.point_ancrage[1]-self.sommet_source[1],\n self.point_ancrage[2]-self.sommet_source[2]])\n self.tension_min = tension_min\n self.tension_max = tension_max\n\n def longueur(self):\n return sqrt(self.vecteur[0] * self.vecteur[0] +\n self.vecteur[1] * self.vecteur[1] +\n self.vecteur[2] * self.vecteur[2])\n\n def get_sommet_source (self):\n return self.sommet_source\n\n def get_point_ancrage(self):\n return self.point_ancrage\n\n# adicionei esses metodos\n\n def get_tension_min(self):\n return self.tension_min\n\n def get_tension_max(self):\n return self.tension_max\n\n def get_unitaire(self):\n return self.vecteur / self.longueur()\n #-----------------------------------------------------\n\n\n# Calculer les tensions F :\n\ndef get_tension (cable0, cable1, cable2, cable3, cable4, cable5, cable6, cable7):\n '''\n\n :param cable0:\n :param cable1:\n :param cable2:\n :param cable3:\n :param cable4:\n :param cable5:\n :param cable6:\n :param cable7:\n :return: F, un np.array contenant 8 valeurs de tension de chaque cable\n '''\n\n # masse du cube et gravité de la Terre\n m = 2.0 # kg\n g = 9.8 # m/s^2\n\n F_min = np.array([cable0.get_tension_min(),\n cable1.get_tension_min(),\n cable2.get_tension_min(),\n cable3.get_tension_min(),\n cable4.get_tension_min(),\n cable5.get_tension_min(),\n cable6.get_tension_min(),\n cable7.get_tension_min()])\n\n F_max = np.array([cable0.get_tension_max(),\n cable1.get_tension_max(),\n cable2.get_tension_max(),\n cable3.get_tension_max(),\n cable4.get_tension_max(),\n cable5.get_tension_max(),\n cable6.get_tension_max(),\n cable7.get_tension_max()])\n\n # eq de l'equilibre: A^t . F + w = 0, F_min < Fi < F_max, A^t = transpose(A)\n\n A = np.array([\n [np.append(cable0.get_unitaire(), np.cross(cable0.get_sommet_source() - centre_masse, cable0.get_unitaire()))],\n [np.append(cable1.get_unitaire(), np.cross(cable1.get_sommet_source() - centre_masse, cable1.get_unitaire()))],\n [np.append(cable2.get_unitaire(), np.cross(cable2.get_sommet_source() - centre_masse, cable2.get_unitaire()))],\n [np.append(cable3.get_unitaire(), np.cross(cable3.get_sommet_source() - centre_masse, cable3.get_unitaire()))],\n [np.append(cable4.get_unitaire(), np.cross(cable4.get_sommet_source() - centre_masse, cable4.get_unitaire()))],\n [np.append(cable5.get_unitaire(), np.cross(cable5.get_sommet_source() - centre_masse, cable5.get_unitaire()))],\n [np.append(cable6.get_unitaire(), np.cross(cable6.get_sommet_source() - centre_masse, cable6.get_unitaire()))],\n [np.append(cable7.get_unitaire(), np.cross(cable7.get_sommet_source() - centre_masse, cable7.get_unitaire()))]\n ]).reshape(8, 6)\n\n w = np.array([0, 0, -m * g, 0, 0, 0])\n\n # algorithme retourne np.array[-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.] si la position n'appartient pas\n # au workspace de la chambre\n\n\n if (np.linalg.matrix_rank(A) < 6):\n return -1*np.ones(8)\n print(\"Wrench matrix not invetible\")\n\n F_med = (F_min+F_max)/2\n\n A_pseudo_transp = np.dot(A, np.linalg.inv(np.dot(np.transpose(A), A)))\n\n F_v = - np.dot(A_pseudo_transp, w + np.dot(np.transpose(A), F_med))\n\n F = F_med + F_v\n\n for i in range(8):\n if (F[i] < F_min[i] or F[i] > F_max[i]):\n print(\"Cable {} is not in the interval [f_min, f_max]\".format(i))\n return -1 * np.ones(8)\n\n if (np.linalg.norm(F_v) > np.linalg.norm(F_med) / 2):\n print(\"Tension not feasible\")\n return -1 * np.ones(8)\n\n return F\n\n\n\n# TESTE:\n\n\nlong = 1.0\nlarg = 1.0\nhaut = 1.0\n\npoint_ancrage = [np.array([0.0, 0.0, 5.0]), np.array([4.0, 0.0, 5.0]),\n np.array([4.0, 6.0, 5.0]), np.array([0.0, 6.0, 5.0])]\n\ncentre_masse = np.array([2.0, 3.0, 2.5])\n\nsommet_source = [centre_masse + np.array([-long / 2, -larg / 2, -haut / 2]),\n centre_masse + np.array([ long / 2, -larg / 2, -haut / 2]),\n centre_masse + np.array([ long / 2, larg / 2, -haut / 2]),\n centre_masse + np.array([-long / 2, larg / 2, -haut / 2]),\n centre_masse + np.array([-long / 2, -larg / 2, haut / 2]),\n centre_masse + np.array([ long / 2, -larg / 2, haut / 2]),\n centre_masse + np.array([ long / 2, larg / 2, haut / 2]),\n centre_masse + np.array([-long / 2, larg / 2, haut / 2])]\n\n# cables de chaque sommet\n\ncable0 = Cable(point_ancrage[0], sommet_source[4], 1., 100.)\ncable1 = Cable(point_ancrage[0], sommet_source[5], 1., 100.)\ncable2 = Cable(point_ancrage[1], sommet_source[5], 1., 100.)\ncable3 = Cable(point_ancrage[1], sommet_source[6], 1., 100.)\ncable4 = Cable(point_ancrage[2], sommet_source[6], 1., 100.)\ncable5 = Cable(point_ancrage[2], sommet_source[7], 1., 100.)\ncable6 = Cable(point_ancrage[3], sommet_source[7], 1., 100.)\ncable7 = Cable(point_ancrage[3], sommet_source[4], 1., 100.)\n\n\nF = get_tension(cable0,\ncable1,\ncable2,\ncable3,\ncable4,\ncable5,\ncable6,\ncable7,\n)\n\nprint(F)\nprint('')\n","sub_path":"src/calculs/dynamique/tension.py","file_name":"tension.py","file_ext":"py","file_size_in_byte":5863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"443040021","text":"from __future__ import print_function\n\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport nibabel as nib\nfrom random import seed, shuffle\nfrom keras.utils import to_categorical\n\n\nclass BTCDataset(object):\n\n def __init__(self,\n hgg_dir, lgg_dir,\n volume_type=\"t1ce\",\n train_prop=0.6,\n valid_prop=0.2,\n random_state=0,\n is_augment=True,\n pre_trainset_path=None,\n pre_validset_path=None,\n pre_testset_path=None,\n data_format=\".nii.gz\"):\n '''__INIT__\n '''\n\n self.hgg_dir = hgg_dir\n self.lgg_dir = lgg_dir\n self.volume_type = volume_type\n\n self.train_prop = train_prop\n self.valid_prop = valid_prop\n self.random_state = int(random_state)\n self.is_augment = is_augment\n\n self.pre_trainset = pre_trainset_path\n self.pre_validset = pre_validset_path\n self.pre_testset = pre_testset_path\n self.data_format = data_format\n\n self.train_x, self.train_y = None, None\n self.valid_x, self.valid_y = None, None\n self.test_x, self.test_y = None, None\n\n return\n\n def run(self, pre_split=False,\n save_split=False,\n save_split_dir=None):\n print(\"\\nSplitting dataset to train, valide and test.\\n\")\n trainset, validset, testset = \\\n self._get_pre_datasplit() if pre_split else \\\n self._get_new_datasplit()\n\n self._load_dataset(trainset, validset, testset)\n\n if save_split and (not pre_split):\n self.save_split_dir = save_split_dir\n self._save_dataset(trainset, validset, testset)\n return\n\n def _get_pre_datasplit(self):\n paras = {\"hgg_dir\": self.hgg_dir,\n \"lgg_dir\": self.lgg_dir,\n \"data_format\": self.data_format,\n \"csv_path\": None}\n\n paras[\"csv_path\"] = self.pre_trainset\n trainset = self.load_datasplit(**paras)\n\n paras[\"csv_path\"] = self.pre_validset\n validset = self.load_datasplit(**paras)\n\n paras[\"csv_path\"] = self.pre_testset\n testset = self.load_datasplit(**paras)\n\n return trainset, validset, testset\n\n def _get_new_datasplit(self):\n paras = {\"label\": None,\n \"dir_path\": None,\n \"volume_type\": self.volume_type,\n \"random_state\": self.random_state}\n\n paras[\"label\"], paras[\"dir_path\"] = 1, self.hgg_dir\n hgg_subjects = self.get_subjects_path(**paras)\n\n paras[\"label\"], paras[\"dir_path\"] = 0, self.lgg_dir\n lgg_subjects = self.get_subjects_path(**paras)\n\n paras = {\"subjects\": None,\n \"train_prop\": self.train_prop,\n \"valid_prop\": self.valid_prop}\n\n paras[\"subjects\"] = hgg_subjects\n hgg_train, hgg_valid, hgg_test = self.split_dataset(**paras)\n\n paras[\"subjects\"] = lgg_subjects\n lgg_train, lgg_valid, lgg_test = self.split_dataset(**paras)\n\n trainset = hgg_train + lgg_train\n validset = hgg_valid + lgg_valid\n testset = hgg_test + lgg_test\n\n return trainset, validset, testset\n\n def _load_dataset(self, trainset, validset, testset):\n\n self.test_x, test_y = self.load_data(testset, \"test set\")\n self.test_y = to_categorical(test_y, num_classes=2)\n\n self.valid_x, valid_y = self.load_data(validset, \"valid set\")\n self.valid_y = to_categorical(valid_y, num_classes=2)\n\n train_x, train_y = self.load_data(trainset, \"train set\")\n if self.is_augment:\n train_x, train_y = self.augment(train_x, train_y)\n self.train_x = train_x\n self.train_y = to_categorical(train_y, num_classes=2)\n\n return\n\n def _save_dataset(self, trainset, validset, testset):\n ap = str(self.random_state) + \".csv\"\n trainset_path = os.path.join(self.save_split_dir, \"trainset_\" + ap)\n validset_path = os.path.join(self.save_split_dir, \"validset_\" + ap)\n testset_path = os.path.join(self.save_split_dir, \"testset_\" + ap)\n\n self.save_datasplit(trainset, trainset_path)\n self.save_datasplit(validset, validset_path)\n self.save_datasplit(testset, testset_path)\n\n return\n\n @staticmethod\n def load_datasplit(hgg_dir, lgg_dir, csv_path,\n data_format=\".nii.gz\"):\n '''LOAD_DATASPLIT\n '''\n df = pd.read_csv(csv_path)\n IDs = df[\"ID\"].values.tolist()\n labels = df[\"label\"].values.tolist()\n info = []\n for ID, label in zip(IDs, labels):\n target_dir = hgg_dir if label else lgg_dir\n path = os.path.join(target_dir, ID[:-5],\n ID + data_format)\n info.append([path, label])\n return info\n\n @staticmethod\n def save_datasplit(dataset, to_path):\n IDs, labels = [], []\n for i in dataset:\n IDs.append(i[0].split(\"/\")[-1].split(\".\")[0])\n labels.append(i[1])\n\n df = pd.DataFrame(data={\"ID\": IDs, \"label\": labels})\n df.to_csv(to_path, index=False)\n return\n\n @staticmethod\n def get_subjects_path(dir_path, volume_type, label,\n random_state=0):\n subjects = os.listdir(dir_path)\n seed(random_state)\n shuffle(subjects)\n subjects_paths = []\n for subject in subjects:\n subject_dir = os.path.join(dir_path, subject)\n for scan_name in os.listdir(subject_dir):\n if volume_type not in scan_name:\n continue\n scan_path = os.path.join(subject_dir, scan_name)\n subjects_paths.append([scan_path, label])\n return subjects_paths\n\n @staticmethod\n def split_dataset(subjects, train_prop=0.6, valid_prop=0.2):\n subj_num = len(subjects)\n train_valid_num = subj_num * (train_prop + valid_prop)\n train_valid_idx = int(round(train_valid_num))\n testset = subjects[train_valid_idx:]\n\n valid_idx = int(round(subj_num * valid_prop))\n validset = subjects[:valid_idx]\n trainset = subjects[valid_idx:train_valid_idx]\n return trainset, validset, testset\n\n @staticmethod\n def load_data(dataset, mode):\n x, y = [], []\n print(\"Loading {} data ...\".format(mode))\n for subject in dataset:\n volume_path, label = subject[0], subject[1]\n volume = nib.load(volume_path).get_data()\n volume = np.transpose(volume, axes=[1, 0, 2])\n volume = np.flipud(volume)\n\n volume_obj = volume[volume > 0]\n obj_mean = np.mean(volume_obj)\n obj_std = np.std(volume_obj)\n volume = (volume - obj_mean) / obj_std\n\n volume = np.expand_dims(volume, axis=3)\n x.append(volume.astype(np.float32))\n y.append(label)\n\n x = np.array(x)\n y = np.array(y).reshape((-1, 1))\n\n return x, y\n\n @staticmethod\n def augment(train_x, train_y):\n print(\"Do Augmentation on LGG Samples ...\")\n train_x_aug, train_y_aug = [], []\n for i in range(len(train_y)):\n train_x_aug.append(train_x[i])\n train_y_aug.append(train_y[i])\n if train_y[i] == 0:\n train_x_aug.append(np.fliplr(train_x[i]))\n train_y_aug.append(np.array([0]))\n train_x = np.array(train_x_aug)\n train_y = np.array(train_y_aug).reshape((-1, 1))\n\n return train_x, train_y\n\n\nif __name__ == \"__main__\":\n\n parent_dir = os.path.dirname(os.getcwd())\n data_dir = os.path.join(parent_dir, \"data\", \"BraTS\")\n hgg_dir = os.path.join(data_dir, \"HGGSegTrimmed\")\n lgg_dir = os.path.join(data_dir, \"LGGSegTrimmed\")\n\n # Load and split dataset\n data = BTCDataset(hgg_dir, lgg_dir,\n volume_type=\"t1ce\",\n train_prop=0.6,\n valid_prop=0.2,\n random_state=0)\n data.run(save_split=True,\n save_dir=\"DataSplit\")\n\n # Load dataset which has been splitted\n data = BTCDataset(hgg_dir, lgg_dir,\n volume_type=\"t1ce\",\n pre_trainset_path=\"DataSplit/trainset.csv\",\n pre_validset_path=\"DataSplit/validset.csv\",\n pre_testset_path=\"DataSplit/testset.csv\")\n data.run(pre_split=True)\n","sub_path":"src2/btc_dataset.py","file_name":"btc_dataset.py","file_ext":"py","file_size_in_byte":8478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"598382669","text":"import http.client\nimport urllib\nimport json\nimport hashlib\n\n\n\ndef build_signature(params, secret_key):\n sign = ''\n for key in sorted(params.keys()):\n sign = sign + key + '=' + str(params[key]) +'&'\n data = sign + 'secret_key=' + secret_key\n return hashlib.md5(data.encode('utf-8')).hexdigest().upper()\n\ndef http_get(url, resource, params=''):\n conn = http.client.HTTPSConnection(url, timeout=10)\n conn.request(\"GET\",resource + '?' + params)\n response = conn.getresponse()\n data = response.read().decode('utf-8')\n return json.loads(data)\n\ndef http_post(url,resource,params):\n headers = {\n \"Content-type\" : \"application/x-www-form-urlencoded\",\n }\n conn = http.client.HTTPSConnection(url, timeout=10)\n temp_params = urllib.parse.urlencode(params)\n conn.request(\"POST\", resource, temp_params, headers)\n response = conn.getresponse()\n data = response.read().decode('utf-8')\n params.clear()\n conn.close()\n return json.loads(data)\n\nclass RestClient(object):\n\n __url = 'www.okex.com'\n def __init__(self, api_key, secret_key):\n\n self.__api_key = api_key\n self.__secret_key = secret_key\n\n def market_depth(self, symbol=''):\n DEPTH_RESOURCE = '/api/v1/depth.do'\n params = ''\n if symbol:\n params = 'symbol=%(symbol)s' % {'symbol': symbol}\n\n return http_get(self.__url, DEPTH_RESOURCE, params)\n\n def trade_history(self, symbol=''):\n TRADES_RESOURCE = '/api/v1/trades.do'\n params = ''\n if symbol:\n params = 'symbol=%(symbol)s' % {'symbol': symbol}\n\n return http_get(self.__url, TRADES_RESOURCE, params)\n\n def user_info(self):\n '''\n :return: Funds available in spot trading account\n '''\n USERINFO_RESOURCE = '/api/v1/userinfo.do'\n params = {}\n params['api_key'] = self.__api_key\n params['sign'] = build_signature(params, self.__secret_key)\n\n return http_post(self.__url, USERINFO_RESOURCE, params)\n\n def wallet_info(self):\n '''\n :return: Total funds available in wallet\n '''\n WALLETINFO_RESOURCE = '/api/v1/wallet_info.do'\n params = {}\n params['api_key'] = self.__api_key\n params['sign'] = build_signature(params, self.__secret_key)\n\n return http_post(self.__url, WALLETINFO_RESOURCE, params)\n\n def place_order(self, symbol, order_type, price='', amount=''):\n TRADE_RESOURCE = '/api/v1/trade.do'\n params = {\n 'api_key': self.__api_key,\n 'symbol': symbol,\n 'type': order_type # limit order(buy/sell) market order(buy_market/sell_market)\n }\n if price:\n params['price'] = price # For limit orders, the price must be between 0~1,000,000.\n # IMPORTANT: for market buy orders, the price is to total\n # amount you want to buy, and it must be higher than the current price\n # of 0.01 BTC (minimum buying unit), 0.1 LTC or 0.01 ETH.\n # For market sell orders, the price is not required\n if amount:\n params['amount'] = amount # Must be higher than 0.01 for BTC, 0.1 for LTC or 0.01 for ETH.\n # For market buy roders, the amount is not required\n\n params['sign'] = build_signature(params, self.__secret_key)\n\n\n return http_post(self.__url, TRADE_RESOURCE, params)\n\n def place_limit_order(self, symbol, side, price, amount):\n return self.place_order(symbol=symbol, order_type=side, price=price, amount=amount)\n\n def place_market_order(self, symbol, side, amount):\n order_type = side + '_' + 'market'\n return self.place_order(symbol=symbol, order_type=order_type, price=amount)\n\n\n def place_batch_orders(self, symbol, order_type, orders_data):\n BATCH_TRADE_RESOURCE = '/api/v1/batch_trade.do'\n params = {\n 'api_key': self.__api_key,\n 'symbol': symbol,\n 'type': order_type,\n 'orders_data': orders_data # JSON string Example: [{price:3,amount:5,type:'sell'},\n # {price:3,amount:3,type:'buy'},{price:3,amount:3}]\n # max order number is 5,for 'price' and 'amount' parameter,\n # refer to trade/API. Final order type is decided primarily by\n # 'type' field within 'orders_data' and subsequently by 'type' field\n # (if no 'type' is provided within 'orders_data' field)\n }\n params['sign'] = build_signature(params, self.__secret_key)\n\n return http_post(self.__url, BATCH_TRADE_RESOURCE, params)\n\n def cancel_order(self, symbol, order_id):\n CANCEL_ORDER_RESOURCE = '/api/v1/cancel_order.do'\n params = {\n 'api_key': self.__api_key,\n 'symbol': symbol,\n 'order_id': order_id # order ID (multiple orders are separated by a comma ',',\n # Max of 3 orders are allowed per request)\n }\n params['sign'] = build_signature(params,self.__secret_key)\n return http_post(self.__url, CANCEL_ORDER_RESOURCE, params)\n\n def get_order_info_byid(self, symbol, order_id, batch = False, fill_type=''):\n if batch == False:\n ORDER_INFO_RESOURCE = '/api/v1/order_info.do'\n else:\n ORDER_INFO_RESOURCE = '/api/v1/orders_info.do'\n\n params = {\n 'api_key': self.__api_key,\n 'symbol': symbol,\n 'order_id': order_id\n }\n if fill_type:\n params['type']: fill_type # 0: unfilled, 1: filled\n\n params['sign'] = build_signature(params, self.__secret_key)\n\n\n return http_post(self.__url, ORDER_INFO_RESOURCE, params)\n\n def get_orders_info_bysymbol(self, symbol, status, current_page=1, page_length=200):\n # only the most recent two days are returned\n ORDER_HISTORY_RESOURCE = '/api/v1/order_history.do'\n params = {\n 'api_key': self.__api_key,\n 'symbol': symbol,\n 'status': status, # returns : status: -1 = cancelled, 0 = unfilled, 1 = partially filled,\n # 2 = fully filled, 4 = cancel request in process\n 'current_page': current_page, # current page number\n 'page_length': page_length # number of orders returned per page, maximum 200\n }\n params['sign'] = build_signature(params, self.__secret_key)\n\n\n return http_post(self.__url, ORDER_HISTORY_RESOURCE, params)\n\n def withdraw(self, symbol, trade_pwd, withdraw_address, withdraw_amount, address_type='address'):\n WITHDRAW_RESOURCE = '/api/v1/withdraw.do'\n params = {\n 'api_key': self.__api_key,\n 'symbol': symbol,\n # 'chargefee': tran_fee,\n 'trade_pwd': trade_pwd,\n 'withdraw_address': withdraw_address,\n 'withdraw_amount': withdraw_amount,\n 'target': address_type # withdraw address type. okcoin.cn:\"okcn\" okcoin.com:\"okcom\"\n # okes.com:\"okex_service\" outer address:\"address\"\n }\n params['sign'] = build_signature(params, self.__secret_key)\n\n return http_post(self.__url, WITHDRAW_RESOURCE, params)\n\n def cancel_withdraw(self, symbol, withdraw_id):\n CANCEL_WITHDRAW_RESOURCE = '/api/v1/withdraw_info.do'\n params = {\n 'api_key': self.__api_key,\n 'symbol': symbol,\n 'withdraw_id': str(withdraw_id)\n\n }\n params['sign'] = build_signature(params, self.__secret_key)\n\n return http_post(self.__url, CANCEL_WITHDRAW_RESOURCE, params)\n\n def withdraw_info(self, symbol, withdraw_id):\n WITHDRAWINFO_RESOURCE = '/api/v1/withdraw_info.do'\n params = {\n 'api_key': self.__api_key,\n 'symbol': symbol,\n 'withdraw_id': str(withdraw_id)\n }\n params['sign'] = build_signature(params, self.__secret_key)\n\n return http_post(self.__url, WITHDRAWINFO_RESOURCE, params)\n\n def deposit_withdraw_record(self, symbol, dw_type, current_page, page_length):\n DW_RESOURCE = '/api/v1/account_records.do'\n params = {\n 'api_key': self.__api_key,\n 'symbol': symbol, # only xxx_usd supported\n 'type': dw_type, # 0: deposits, 1: withdraws\n 'current_page': current_page,\n 'page_length': page_length\n }\n params['sign'] = build_signature(params, self.__secret_key)\n\n return http_post(self.__url, DW_RESOURCE, params)\n\n def internal_fund_transfer(self, symbol, amount, from_acc, to_acc):\n IFTRANSFER_RESOURCE = '/api/v1/funds_transfer.do'\n params = {\n 'api_key': self.__api_key,\n 'symbol': symbol,\n 'amount': amount,\n 'from': from_acc,\n 'to': to_acc\n }\n params['sign'] = build_signature(params, self.__secret_key)\n\n return http_post(self.__url, IFTRANSFER_RESOURCE, params)\n\n def tickers_market_info(self, symbol=''):\n TICKER_RESOURCE = '/api/v1/tickers.do'\n params = ''\n if symbol:\n params = 'symbol=%(symbol)s' % {'symbol': symbol}\n\n return http_get(self.__url, TICKER_RESOURCE, params)\n\n def ticker_list(self):\n resp = self.tickers_market_info()\n result = []\n for elements in resp['tickers']:\n result.append(elements['symbol'])\n\n return result","sub_path":"exchanges/okex_service/rest_client.py","file_name":"rest_client.py","file_ext":"py","file_size_in_byte":9950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"323514686","text":"#!/usr/bin/env python3\n\"\"\"\n创建文件,不存在则创建,并写入内容,存在,则重新写名字\n\"\"\"\nimport os\n\ndef get_fname():\n while True:\n fname = input(\"input a file name:\")\n if not os.path.exists(fname):\n break\n print(\"%s already exits.Try again\")\n return fname\n\ndef get_content():\n content = []\n print(\"write something in it:end is end!\")\n while True:\n line = input(\">\")\n if line == \"end\":\n break\n content.append(line)\n return content\n\ndef create_file(fname,content):\n with open(fname,'w') as fobj:\n fobj.writelines(content)\n\nif __name__ == '__main__':\n fname = get_fname()\n content = get_content()\n content = [\"%s\\n\"%line for line in content]\n create_file(fname,content)","sub_path":"STEP05/project/python/day04/lianxi3.py","file_name":"lianxi3.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"412503465","text":"import requests\nimport json\n\n\nIP_ADDRESS = \"131.159.212.112\"\nUSERNAME = \"AE4E18BE56\"\n\n\nclass UrlValChanger:\n def __init__(self, url_section, api_id, val_convertor, val_field_name):\n self._base_url = 'http://{}/api/{}/{}/{}'.format(IP_ADDRESS, USERNAME, url_section, api_id)\n self._val_convertor = val_convertor\n self._val_field_name = val_field_name\n self._val = None\n\n def get(self):\n response = requests.get(self._base_url)\n data = response.json()\n self._val = self._val_convertor.convert_to_float(data[\"state\"][self._val_field_name])\n return self._val\n\n def set(self, val):\n put_url = self._base_url + '/state'\n put_val = self._val_convertor.convert_from_float(val)\n data = json.dumps({self._val_field_name: put_val})\n requests.put(put_url, data=data)\n\n\nclass BluetoothValReader:\n def __init__(self, board, val_field_name):\n self._val_field_name = val_field_name\n self._board = board\n\n def get(self):\n return self._board.get_values(self._val_field_name)\n # does not have set functions at all\n # def set(self, val):\n\n\n","sub_path":"devices/val_changers.py","file_name":"val_changers.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"292790676","text":"import sys\nimport math\nimport time\nimport argparse\n\n#from sklearn.metrics.pairwise import pairwise_distances\nimport numpy as np\nfrom cImage import *\nfrom kmeans import *\nimport kmedoids\n\ndef MSE(data,centres,cluster):\n MSE = 0\n for i in range(len(data)):\n MSE += np.sqrt(sum(np.power(data[i]-centres[int(cluster[i])],2)))\n return MSE\n\ndef bikmeans_MSE(data,centres,cluster):\n MSE = 0\n for i in range(len(centres)):\n for j in range(len(cluster[i])):\n MSE += np.sqrt(sum(np.power(data[cluster[i][j]]-centres[i],2)))\n return MSE\n\ndef kmedoid_MSE(data,centres,cluster):\n MSE = 0\n for i in range(len(centres)):\n for j in range(len(cluster[i])):\n MSE += np.sqrt(sum(np.power(data[cluster[i][j]]-data[centres[i]],2)))\n return MSE\n\ndef main():\n parser = argparse.ArgumentParser(description='Test kmeans algorithm.')\n parser.add_argument('imageFile', type=str, default='Earth.gif', help='Name of input graph')\n parser.add_argument('k', type=int, help='Number of clusters')\n parser.add_argument('-l', '--logFile', type=str, default='none', help='Name of log file (default:none)')\n parser.add_argument('-d', '--display', type=str, default='yes', help='Display image (default:yes)')\n \n args = parser.parse_args()\n # get sys input\n image = FileImage(args.imageFile)\n k = args.k\n \n width = image.getWidth()\n height = image.getHeight()\n \n # get data\n r = []\n g = []\n b = []\n for row in range(height):\n for col in range(width):\n pixel = image.getPixel(col,row)\n r.append([pixel[0]])\n g.append([pixel[1]])\n b.append([pixel[2]])\n pixels = np.hstack((r,g,b))\n\n nData = np.shape(pixels)[0]\n\n # perform k-mean\n print(\"--- Kmeans ---\")\n start_time = time.time()\n c1 = kmeanstrain(pixels,k)\n cluster1 = kmeansfwd(pixels,k,nData,c1)\n t1 = time.time() - start_time\n MSE1 = MSE(pixels,c1,cluster1)/len(pixels)\n print(\"Time:\",t1,\"second\")\n print(\"MSE:\",MSE1)\n\n '''\n # perform kmeans-plus\n print(\"--- Kmeans-plus ---\")\n start_time = time.time()\n c2 = k_plus(pixels,k)\n cluster2 = kmeansfwd(pixels,k,nData,c2)\n t2 = time.time() - start_time\n MSE2 = MSE(pixels,c2,cluster2)/len(pixels)\n print(\"Time:\",t2,\"second\")\n print(\"MSE:\",MSE2)\n '''\n\n # perform bi-kmeans\n print(\"--- bi-Kmeans ---\")\n start_time = time.time()\n result = biKmeans(pixels,k)\n c3 = result[0]\n cluster3 = result[1]\n t3 = time.time() - start_time\n MSE3 = bikmeans_MSE(pixels,c3,cluster3)/len(pixels)\n print(\"Time:\",t3,\"second\")\n print(\"MSE:\",MSE3)\n\n t4 = \"None\"\n MSE4 = \"None\"\n\n '''\n if(len(pixels) <= 1000):\n print(\"--- Kmedoid ---\")\n start_time = time.time()\n M,C = kmedoids.kMedoids(pairwise_distances(pixels, metric='euclidean'), k)\n t4 = time.time() - start_time\n MSE4 = kmedoid_MSE(pixels,M,C)/len(pixels)\n print(\"Time:\",t4,\"second\")\n print(\"MSE:\",MSE4)\n '''\n if args.logFile != 'none':\n fout = open(args.logFile,'w')\n fout.write(\"time\\n\")\n fout.write(str(t1)+\"\\n\"+str(t2)+\"\\n\"+str(t3)+\"\\n\"+str(t4)+\"\\n\")\n fout.write(\"MSE\\n\")\n fout.write(str(MSE1)+\"\\n\"+str(MSE2)+\"\\n\"+str(MSE3)+\"\\n\"+str(MSE4))\n\n # create images\n image1 = EmptyImage(width,height)\n #image2 = EmptyImage(width,height)\n for row in range(height):\n for col in range(width):\n p1 = c1[int(cluster1[row*width+col][0])]\n #p2 = c2[int(cluster2[row*width+col][0])]\n image1.setPixel(col,row,Pixel(int(round(p1[0])),int(round(p1[1])),int(round(p1[2]))))\n #image2.setPixel(col,row,Pixel(int(round(p2[0])),int(round(p2[1])),int(round(p2[2]))))\n\n image3 = EmptyImage(width,height)\n tempArr = pixels.tolist()\n for i in range(len(cluster3)):\n for j in range(len(cluster3[i])):\n p3 = c3[i]\n index = cluster3[i][j]\n image3.setPixel(index%width,index//width,Pixel(int(round(p3[0])),int(round(p3[1])),int(round(p3[2]))))\n\n if args.display == 'yes':\n # draw original image\n myimagewindow = ImageWin(\"newImage\",4*width,height)\n \n image.setPosition(0,0)\n image1.setPosition(width,0)\n #image2.setPosition(2*width,0)\n image3.setPosition(2*width,0)\n\n image.draw(myimagewindow)\n image1.draw(myimagewindow)\n #image2.draw(myimagewindow)\n image3.draw(myimagewindow)\n myimagewindow.exitOnClick()\n\nmain()\n\n","sub_path":"seg.py","file_name":"seg.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"509311230","text":"def count_evens(events):\n count = 0\n for i in range(len(events)):\n if events[i] % 2==0:\n count += 1\n return count\n\ndef big_diff(nums):\n return max(nums) - min(nums)\n\n\ndef centered_average(nums):\n maximum = max(nums)\n minimum = min(nums)\n foo = False\n bar = False\n buz = 0\n center = 0\n for i in range(len(nums)):\n if nums[i] != maximum and nums[i] != minimum:\n buz += nums[i]\n c += 1\n else:\n if foo and nums[i] == maximum:\n buz += maximum\n c += 1\n if bar and nums[i] == minimum:\n buz += minimum\n c += 1\n if not foo and nums[i] == maximum:\n foo = True\n if not bar and nums[i] == minimum:\n bar = True\n return buz // center\n\ndef sum13(nums):\n foo = 0\n if len(nums) == 0:\n return 0\n for i in range(1,len(nums)):\n if nums[i] != 13 and nums[i -1 ] != 13:\n foo += nums[i]\n if nums[0] != 13:\n foo += nums[0]\n return foo\n\ndef sum67(nums):\n record = True\n total = 0\n for n in nums:\n if n == 6:\n record = False\n if record:\n total += n\n continue\n if n == 7:\n record = True\n return total\n\ndef has22(nums):\n if len(nums)>=2:\n for i in range(len(nums)-1):\n if nums[i]==2 and nums[i+1]==2:\n return True\n return False","sub_path":"Week 10/CodingBat/List-2.py","file_name":"List-2.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"205931395","text":"import subprocess as cmd\nimport os\nimport sys\nfrom importlib import reload\nimport traceback\n\n\ndef hello():\n print('import successfully')\n\n\ndef write_setup_file(listfile, name=None):\n if not os.path.exists('build'):\n os.makedirs('build')\n onefile = open('build/setup.py', \"w\")\n onefile.write('from distutils.core import setup \\n')\n onefile.write('from Cython.Build import cythonize \\n')\n for anyfile in listfile:\n if type(anyfile) is not str:\n raise TypeError\n if name:\n onefile.write(\n 'setup(name=\"{}\",ext_modules=cythonize(\"{}\")) \\n'.format(name,anyfile))\n else:\n onefile.write('setup(ext_modules=cythonize(\"{}\")) \\n'.format(anyfile))\n onefile.close()\n\n\ndef write_init_file(listfile, path, name):\n file_path = os.path.abspath(os.path.join(path, name))\n if not os.path.exists(file_path+'/__init__.py'):\n onefile = open(file_path+'/__init__.py', \"w\")\n # print(listfile,file_path)\n name = name.replace('./', '').replace(\"/\", \".\")\n for anyfile in listfile:\n if type(anyfile) is not str:\n raise TypeError\n _head, tail = os.path.split(anyfile)\n onefile.write(\n 'from {} import {} \\n'.format(name, tail[:-4]))\n onefile.close()\n\n\ndef ccompile(path=None, name=None):\n if path is None:\n if name:\n cmd.call('python build/setup.py build_ext --inplace –name {}'.format(name), shell=True)\n else:\n cmd.call(\n 'python build/setup.py build_ext --inplace', shell=True)\n else:\n cmd.call(\n 'python build/setup.py build_ext --build-lib {}'.format(path), shell=True)\n\n\ndef list_file_in_folder(file_path, suffix='.pyx'):\n list_file = []\n for file in os.listdir(file_path):\n if not os.path.isdir(file) and file.endswith(suffix):\n list_file.append(file_path+\"/\"+file)\n if os.path.isdir(os.path.join(file_path, file)):\n folder_path = os.path.abspath(os.path.join(file_path, file))\n # print(folder_path)\n list_file.extend(list_file_in_folder(folder_path, suffix=suffix))\n return list_file\n\n\ndef export(path, name=None, root=None, init_file=True):\n \"\"\"Compile cython file (.pyx) into .so C-share file which can import and run in cpython as normal python package\n \n Arguments:\n path {str} -- Relative or absolute path of file or folder for import\n \n Keyword Arguments:\n root {[str]} -- is a Folder relative or absolute path. If not None, it will export to the folder as specified in root (default: {None})\n init_file {bool} -- Create __init__ file in root folder. Apply when only root is not None (default: {True})\n \n Raises:\n ValueError -- [description]\n ValueError -- [description]\n \n Returns:\n [type] -- [description]\n \"\"\"\n\n files = []\n # Get directory of modules need to compile:\n basedir = os.path.abspath(os.path.dirname(sys.argv[0]))\n # __file__ will get the current cythoncompile path\n file_path = os.path.abspath(os.path.join(basedir, path))\n # print(file_path)\n # check if file or directory exist\n if not os.path.exists(file_path):\n print('File path error:', file_path)\n raise ValueError(\n 'Cannot compile this directory or file. It is not exist')\n\n # check if it is a .pyx file\n if os.path.isdir(path):\n if file_path == sys.argv[0]:\n print('File path error:',file_path)\n raise ValueError('Cannot compile this directory or file')\n files = list_file_in_folder(file_path)\n write_setup_file(files, name=name)\n if init_file:\n write_init_file(files, basedir, path)\n # must be basedir because setup code will create a folder name as path\n if root is not None:\n basedir = os.path.abspath(os.path.join(basedir, root))\n file_path = os.path.abspath(os.path.join(basedir, path))\n if not os.path.exists(file_path):\n os.makedirs(file_path)\n if not os.path.exists(file_path+'/__init__.py'):\n onefile = open(file_path+'/__init__.py', \"w\")\n onefile.close()\n # print(file_path)\n ccompile(path=basedir, name=name)\n else:\n ccompile(path=basedir, name=name)\n else:\n files.append(path)\n write_setup_file(files, name=name)\n if root is not None:\n basedir = os.path.abspath(os.path.join(basedir, root))\n ccompile(path=basedir, name=name)\n else:\n ccompile(name=name)\n return files\n\n\ndef install(listpath):\n allpath = []\n for path in listpath:\n files = export(path)\n allpath.append(files)\n return allpath\n\n\ndef import_path(fullpath, recompile=True):\n \"\"\" \n Import a file with full path specification. Allows one to\n import from anywhere, something __import__ does not do. \n \"\"\"\n path, filename = os.path.split(fullpath)\n filename, _ext = os.path.splitext(filename)\n sys.path.append(path)\n module = __import__(filename)\n if recompile:\n reload(module) # Might be already compile\n del sys.path[-1]\n return module\n\n\ndef require(relative_path, recompile=True):\n \"\"\"Return a python module which is similar to require in nodejs\n \n Arguments:\n relative_path {str} -- Relative or absolute path of file or folder for import\n \n Keyword Arguments:\n recompile {bool} -- [description] (default: {True})\n \n Raises:\n ValueError -- [description]\n \"\"\"\n\n basedir = os.path.abspath(os.path.dirname(sys.argv[0]))\n file_path = os.path.abspath(os.path.join(basedir, relative_path))\n try:\n module = import_path(file_path, recompile=recompile)\n except:\n traceback.print_exc()\n print(file_path)\n raise ImportError('Error when importing path')\n return module\n\n\ndef requirepyx(relative_path, recompile=False):\n \"\"\"Return a cython module (.pyx) which is similar to require in nodejs. This action also export the module before import.\n \n Arguments:\n relative_path {str} -- Relative or absolute path of file or folder for import\n \n Keyword Arguments:\n recompile {bool} -- [description] (default: {True})\n \n Raises:\n ValueError -- [description]\n \"\"\"\n export(relative_path)\n module = require(relative_path, recompile=recompile)\n return module\n\n\ndef install_global(listpath, root='/usr/bin/cython_modules'):\n basedir = os.path.abspath(os.path.dirname(sys.argv[0]))\n file_path = os.path.abspath(os.path.join(basedir, root))\n for path in listpath:\n files = export(path, root=root)\n if os.path.isdir(path):\n write_init_file(files, file_path, path)\n # writing install code\n if not os.path.exists(file_path):\n os.makedirs(file_path)\n if not os.path.exists(file_path+'/__init__.py'):\n onefile = open(file_path+'/__init__.py', \"w\")\n onefile.close()\n onefile = open(file_path+'/cypm.py', \"w\")\n onefile.write(\"modules = dict() \\n\")\n for path in listpath:\n if os.path.isfile(path):\n path = path.replace('.pyx', '')\n name = path.replace('./', '').replace('.', '').replace(\"/\", \".\")\n onefile.write(\n \"import {} as x; modules['{}'] = x \\n\".format(name, path))\n onefile.write(\"def require(modulesName: str): \\n \")\n onefile.write(\" cython=modules[modulesName] \\n \")\n onefile.write(\" return cython \\n \")\n onefile.close()\n\n\n# python setup.py build_ext --inplace\n","sub_path":"cython_npm/cythoncompile.py","file_name":"cythoncompile.py","file_ext":"py","file_size_in_byte":7649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"306657818","text":"\"\"\"\nDeletes all lines in the labels file that does not point to a data file\nThis is the 'reversed' version of filterlabels.py.\n\"\"\"\nimport shutil\nfrom os import listdir\nfrom os.path import isfile, join, splitext\n\nprint(\"Welcome to the labels file filtering tool!\")\n\nprint(\"Data directory:\")\ndir = input()\nlabels = join(dir, 'labels.txt')\nd = join(dir, 'depth')\nfilenames = {splitext(f)[0] for f in listdir(d) if isfile(join(d, f))}\n\nlab = open(labels)\n\nlines = lab.readlines()\ntotal = lines[0]\n\nlines = lines[1:]\nlab.close()\n\nprint(\"Output file path:\")\noutpath = input()\n\nout = open(outpath, 'w')\nout.truncate()\n\nvals = [x for x in lines if x.split()[0] in filenames]\n\nout.write(str(len(vals)) + '\\n')\n\nfor v in vals:\n out.write(v)\n \nout.close()\n ","sub_path":"tools/filterlabelsr.py","file_name":"filterlabelsr.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"626786620","text":"# -*- coding: utf-8 -*-\n__author__ = 'Yuan'\nfrom sqlite3 import connect\nfrom os import path\n\n'''used to initialize the client dbs'''\n\ntable_topic = '''CREATE TABLE IF NOT EXISTS topics\n (title text, relative_url text PRIMARY KEY)'''\ntable_images = '''CREATE TABLE IF NOT EXISTS images\n (topic_url text NOT NULL, url text, store_path text, downloaded int, retry int)'''\n\ndb_name = \"topic.db\"\n\n\ndef init_db(db_path):\n try:\n con = connect(db_path)\n c = con.cursor()\n c.execute(table_topic)\n c.execute(table_images)\n con.commit()\n finally:\n con.close()\n\n\ndef init(base_dir):\n init_db(path.join(base_dir, db_name))\n\n\nif __name__ == \"__main__\":\n init(\"d:\\ceshi\")","sub_path":"datastore/initdatastore.py","file_name":"initdatastore.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"57822260","text":"from ToolPathGeneration import ToolPathTools as tpt\n\n\ndef Make_TPGen_Data(material):\n TPGen_Data = {}\n\n # Material naming\n TPGen_Data['materialname'] = material\n\n # Structure Geometry\n TPGen_Data['length'] = 5\n TPGen_Data['tiph'] = 0.8 # offset from printing surface\n\n # Computational Geometry Tolerances\n TPGen_Data['disttol'] = 1e-12 # Distance tolerance\n TPGen_Data['angtol'] = 1e-7 # Angular tolerance\n\n # Utility parameters\n TPGen_Data['Xoffset'] = 0\n TPGen_Data['Yoffset'] = 0\n TPGen_Data['Zoffset'] = 0\n\n # Graphing information\n materials = []\n materials.append(\n {\n 'material': TPGen_Data['materialname'],\n 'color': 'b',\n 'linestyle': '-',\n 'linewidth': 3,\n 'alpha': 0.5,\n }\n )\n materials.append(\n {\n 'material': TPGen_Data['materialname'] + 'slide',\n 'color': 'r',\n 'linestyle': ':',\n 'linewidth': 2,\n 'alpha': 1,\n }\n )\n\n TPGen_Data['materials'] = materials\n\n return TPGen_Data\n\ndef GenerateToolpath(data, target):\n # Unpack data\n\n # Dimensional tolerances for computational geometry\n disttol = data['disttol']\n\n # line dimensions\n length = data['length']\n\n # Print parameters\n tiph = data['tiph']\n materialname = data['materialname']\n\n x_offset = data['Xoffset']\n y_offset = data['Yoffset']\n z_offset = data['Zoffset']\n # -----------------STUFF-----------------------------#\n\n toolpath3D = []\n toolpath3D.append({'parse': 'start'})\n zpos = tiph\n # CONSTRUCTING TOOLPATH\n # Defining the points\n pointlist= []\n pointlist.append({'X': x_offset, 'Y': y_offset})\n pointlist.append({'X': x_offset + length, 'Y': y_offset})\n \n toolpath2D = tpt.nPt2ToolPath(pointlist, materialname)\n toolpath3D = [*toolpath3D, *tpt.Toolpath2Dto3D(toolpath2D, zpos+z_offset)]\n\n toolpath3D.append({'parse': 'end'})\n # ADDING in Parsing\n\n # toolpath_parsed = tpt.expandpoints(toolpath3D, ['startpoint','endpoint'], ['X','Y','Z'])\n toolpath_parsed = tpt.parse_endofmotion(toolpath3D, disttol)\n toolpath_parsed = tpt.parse_startofmotion(toolpath_parsed)\n toolpath_parsed = tpt.parse_changemat(toolpath_parsed)\n hierarchylist = [\n 'start',\n 'changemat',\n 'endofmotion',\n 'endoflayer',\n 'startofmotion',\n 'end',\n ]\n toolpath_parsed = tpt.parse_heirarchy(toolpath_parsed, hierarchylist)\n target[0] = toolpath_parsed\n\n\nif __name__ == '__main__':\n data = Make_TPGen_Data('bleh')\n target = [0]\n GenerateToolpath(data, target)\n\n","sub_path":"Examples/FlexPrinter Monolith/TemplateTPGen.py","file_name":"TemplateTPGen.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"597185124","text":"import numpy as np\nfrom bezier._geometric_intersection import linearization_error\nimport bezier\nimport math\nimport itertools\nfrom slider.curve import *\n\nBEZIER_TOLERANCE = 0.2\nCATMULL_REFINEMENT = 20\nCATMULL_SAMPLES = np.linspace(0, 1, CATMULL_REFINEMENT, endpoint=False)\nCATMULL_SAMPLES_2 = CATMULL_SAMPLES * CATMULL_SAMPLES\nCATMULL_SAMPLES_3 = CATMULL_SAMPLES_2 * CATMULL_SAMPLES\n\n\ndef bezier_linearize_helper(curve, eps):\n if linearization_error(curve.nodes) < eps:\n return [curve.nodes.T[-1]]\n curve_left, curve_right = curve.subdivide()\n return (bezier_linearize_helper(curve_left, eps) +\n bezier_linearize_helper(curve_right, eps))\n\n\ndef bezier_linearize(curve):\n if len(curve.points) <= 2:\n return curve.points\n points = np.array(curve.points, dtype=np.double)\n bezier_curve = bezier.Curve.from_nodes(points.T)\n return ([points[0]] +\n bezier_linearize_helper(bezier_curve, BEZIER_TOLERANCE))\n\n\ndef perfect_at(curve, t):\n p_x, p_y = curve.points[0]\n c_x, c_y = curve._center\n radians = curve._angle * t\n\n x_dist = p_x - c_x\n y_dist = p_y - c_y\n\n cosr = np.cos(radians, dtype=np.float32)\n sinr = np.sin(radians, dtype=np.float32)\n\n return np.stack(\n [(x_dist * cosr - y_dist * sinr) + c_x,\n (x_dist * sinr + y_dist * cosr) + c_y],\n ).T\n\n\ndef perfect_linearize(curve):\n num_points = math.ceil(curve.req_length / 4)\n return perfect_at(curve, np.linspace(0, 1, num_points))\n\n\ndef linear_linearize(curve):\n return np.array(curve.points, dtype=np.float32)\n\n\ndef multibezier_linearize(curve):\n return list(itertools.chain(bezier_linearize(curve._curves[0]),\n *(bezier_linearize(c)[1:]\n for c in curve._curves[1:])))\n\n\ndef catmull_linearize(curve):\n to_expand = np.array(curve.points[-2:])\n expanded = to_expand[1] + to_expand[1] - to_expand[0]\n raw_points = list(itertools.chain(\n [curve.points[0]], curve.points, [expanded]))\n points = np.array(raw_points, dtype=np.float32)\n shape = (2, points.shape[0] - 3, 4)\n strides = (points.itemsize, 2 * points.itemsize, 2 * points.itemsize)\n catmull_pieces = np.lib.stride_tricks.as_strided(\n points, shape=shape, strides=strides)\n steps, idx = np.meshgrid(CATMULL_SAMPLES, np.arange(shape[1]))\n result_grid = (0.5 *\n (2 * catmull_pieces[:, idx, 1] +\n steps * (catmull_pieces[:, idx, 2] -\n catmull_pieces[:, idx, 0]) +\n CATMULL_SAMPLES_2 * (2 * catmull_pieces[:, idx, 0] -\n 5 * catmull_pieces[:, idx, 1] +\n 4 * catmull_pieces[:, idx, 2] -\n catmull_pieces[:, idx, 3]) +\n CATMULL_SAMPLES_3 * (-catmull_pieces[:, idx, 0] +\n 3 * catmull_pieces[:, idx, 1] -\n 3 * catmull_pieces[:, idx, 2] +\n catmull_pieces[:, idx, 3])))\n return result_grid.reshape((2, shape[1] * CATMULL_REFINEMENT)).T\n\n\ndef linearize(curve, time_scale):\n if isinstance(curve, Bezier):\n points = np.array(bezier_linearize(curve), dtype=np.float32)\n elif isinstance(curve, Perfect):\n points = perfect_linearize(curve)\n elif isinstance(curve, Linear):\n points = linear_linearize(curve)\n elif isinstance(curve, MultiBezier):\n points = np.array(multibezier_linearize(curve), dtype=np.float32)\n elif isinstance(curve, Catmull):\n points = catmull_linearize(curve)\n\n vectors = np.diff(points, axis=0)\n output = np.empty((points.shape[0] + 2, 3), dtype=np.float32)\n output[1:-1, 0:2] = points\n distance = np.linalg.norm(vectors, ord=2, axis=1)\n np.cumsum(distance, out=output[2:-1, 2])\n output[1, 2] = 0\n output[0], output[-1] = output[1], output[-2]\n output[:, 2] *= time_scale / output[-1, 2]\n return output\n","sub_path":"beatmapml_trajectory/slider_process.py","file_name":"slider_process.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"139782086","text":"import random\nimport sys\nimport math\nimport time\nfrom box import *\n\n\nif len(sys.argv) != 3:\n print(\"Exactly two extra command line arguments are required\")\n print(\"System Arguments:\", sys.argv)\n sys.exit()\n\nnumbers = list(range(1, 10))\ntime_limit = float(sys.argv[2])\nstart_time = time.time()\n\ndef play_round(numbers):\n \n if sum(numbers) < 6:\n roll = random.randint(1, 6)\n else:\n roll = random.randint(1, 6) + random.randint(1, 6)\n \n print(f\"Seconds left: {time_limit - (round(time.time() - start_time))}\")\n print(f\"Roll: {roll}\")\n \n if isvalid(roll, numbers):\n eliminate = input(\"Numbers to eliminate: \")\n choices = parse_input(eliminate, numbers)\n while len(choices) == 0:\n print(\"Invalid input\")\n print(f\"Seconds left: {time_limit - (round(time.time() - start_time))}\")\n eliminate = input(\"Numbers to eliminate: \")\n choices = parse_input(eliminate, numbers)\n if sum(choices) == roll:\n for i in choices:\n numbers.remove(i)\n else:\n isvalid(roll, numbers)\n else:\n print(\"Game over!\")\n end_game(numbers)\n \ndef end_game(numbers):\n print(f\"Score for player {sys.argv[1]}: {sum(numbers)}\")\n print(f\"Time played: {round(time.time() - start_time, 2)}\")\n if len(numbers) == 0:\n print(\"Congratulations!! You shut the box!\")\n else:\n print(\"Better luck next time >:\")\n sys.exit()\n\nwhile len(numbers) > 0:\n print(f\"Numbers left: {numbers}\")\n elapsed_time = time.time() - start_time\n if elapsed_time > time_limit:\n print(\"Game over!\")\n end_game(numbers)\n play_round(numbers)\n \nend_game(numbers)","sub_path":"Probsets/Comp/Probset1/standard_library.py","file_name":"standard_library.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"400869710","text":"from bs4 import BeautifulSoup as bs\r\nimport requests\r\nimport re\r\nimport json\r\n\r\ndef _parser_item_hh(item):\r\n vacancy_date = {}\r\n\r\n # vacancy_name\r\n vacancy_name = item.find('a', {'data-qa': 'vacancy-serp__vacancy-title'}).getText()\r\n\r\n vacancy_date['vacancy_name'] = vacancy_name\r\n\r\n # company_name\r\n company_name = item.find('div', {'class': 'vacancy-serp-item__meta-info-company'}).find('a').getText()\r\n\r\n vacancy_date['company_name'] = company_name\r\n\r\n # city\r\n city = item.find('span', {'data-qa': 'vacancy-serp__vacancy-address'}).getText()\r\n\r\n vacancy_date['city'] = city\r\n\r\n # metro station\r\n metro_station = item.find('span', {'class': 'vacancy-serp-item__meta-info'}).findChild()\r\n if not metro_station:\r\n metro_station = None\r\n else:\r\n metro_station = metro_station.getText()\r\n\r\n vacancy_date['metro_station'] = metro_station\r\n\r\n # salary\r\n salary = item.find('span', {'data-qa': 'vacancy-serp__vacancy-compensation'})\r\n if not salary:\r\n salary_min = None\r\n salary_max = None\r\n salary_currency = None\r\n else:\r\n salary = salary.getText().replace(u'\\u202f', u'')\r\n salary = re.split(r'\\s|-', salary)\r\n if salary[0] == 'до':\r\n salary_min = None\r\n salary_max = int(salary[1])\r\n elif salary[0] == 'от':\r\n salary_min = int(salary[1])\r\n salary_max = None\r\n else:\r\n salary_min = int(salary[0])\r\n salary_max = int(salary[2])\r\n\r\n salary_currency = salary[-1]\r\n vacancy_date['salary_min'] = salary_min\r\n vacancy_date['salary_max'] = salary_max\r\n vacancy_date['salary_currency'] = salary_currency\r\n\r\n # link\r\n is_ad = item.find('div', {'class': 'vacancy-serp-item__row vacancy-serp-item__row_controls'}).getText()\r\n vacancy_link = item.find('a', {'data-qa': 'vacancy-serp__vacancy-title'}).get('href')\r\n if is_ad != 'ОткликнутьсяРеклама':\r\n vacancy_link = vacancy_link.split('?')[0]\r\n vacancy_date['vacancy_link'] = vacancy_link\r\n\r\n\r\n # site\r\n vacancy_date['site'] = 'hh.ru'\r\n return vacancy_date\r\n\r\ndef _parser_hh(vacancy):\r\n global last_page\r\n vacancy_date = []\r\n\r\n params = {\r\n 'text': vacancy,\r\n 'search_field': 'name',\r\n 'items_on_page': '100',\r\n 'page': ''\r\n }\r\n\r\n headers = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.135 YaBrowser/21.6.3.757 Yowser/2.5 Safari/537.36'}\r\n\r\n url = 'https://hh.ru/search/vacancy'\r\n\r\n response = requests.get(url, headers=headers, params=params)\r\n\r\n if response.ok:\r\n parsed_url = bs(response.text, 'html.parser')\r\n if not parsed_url:\r\n last_page = '1'\r\n else:\r\n last_page = int(parsed_url.find_all('a', {'data-qa': 'pager-page'})[-1].getText())\r\n\r\n for page in range(0, last_page):\r\n params['page'] = page\r\n html = requests.get(url, params=params, headers=headers)\r\n\r\n if html.ok:\r\n parsed_url = bs(response.text, 'html.parser')\r\n\r\n vacancy_items = parsed_url.find('div', {'data-qa': 'vacancy-serp__results'}) \\\r\n .find_all('div', {'class': 'vacancy-serp-item'})\r\n\r\n for item in vacancy_items:\r\n vacancy_date.append(_parser_item_hh(item))\r\n return vacancy_date\r\n\r\n\r\n\r\n\r\n\r\nvacancy = 'Python'\r\nvacancy_date = []\r\nvacancy_date.extend(_parser_hh(vacancy))\r\n\r\nwith open('data2.json', 'w') as f:\r\n json.dump(vacancy_date, f)\r\n","sub_path":"lesson 2/lesson_2.py","file_name":"lesson_2.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"376459743","text":"\"\"\"\n Capstone Project. Code written by Anesu Chinoda.\n Fall term, 2018-2019.\n\"\"\"\n\nimport rosebotics_new as rb\nimport ev3dev.ev3 as ev3\n\n\ndef main():\n \"\"\" Runs YOUR specific part of the project \"\"\"\n print('hello')\n robot = rb.Snatch3rRobot()\n print('goodbye')\n #polyogon(robot, 4, 5)\n #follow_black_line(robot)\n #go_to_color(robot, 5)\n beep_when_in_front_of_camera(robot)\ndef polyogon(robot, n, inches):\n for k in range(n):\n robot.drive_system.go_straight_inches(inches)\n robot.drive_system.spin_in_place_degrees(360/n)\n\ndef follow_black_line(robot):\n robot.drive_system.start_moving(50, 50)\n while True:\n i = robot.color_sensor.get_reflected_intensity()\n print(i)\n if i > 30:\n robot.drive_system.start_moving(25, 50)\n else:\n robot.drive_system.start_moving(50, 50)\n\n\ndef go_to_color(robot, color):\n robot.drive_system.start_moving(20, 20)\n while True:\n print(robot.color_sensor.get_color())\n if robot.color_sensor.get_color() == color:\n robot.drive_system.stop_moving()\n print(robot.color_sensor.get_color())\n break\n\ndef beep_when_in_front_of_camera(robot):\n while True:\n if robot.camera.get_biggest_blob().get_area() > 1000:\n ev3.Sound.beep().wait()\nmain()\n","sub_path":"src/Chinoda.py","file_name":"Chinoda.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"602840541","text":"from __future__ import print_function\n\nfrom keras.models import Model, Sequential\nfrom keras.layers import Dense, Dropout, Input\nfrom keras.regularizers import l2, activity_l2\n\nimport p1b2\n\n# (X_train, y_train), (X_test, y_test) = p1b2.load_data(n_cols=10000)\n(X_train, y_train), (X_test, y_test) = p1b2.load_data()\n\ninput_dim = X_train.shape[1]\noutput_dim = y_train.shape[1]\n\nmodel = Sequential()\n\npenalty = 0.01\nact = 'sigmoid'\n\nmodel.add(Dense(1024, input_dim=input_dim, activation=act, W_regularizer=l2(penalty), activity_regularizer=activity_l2(penalty)))\n# model.add(Dropout(0.2))\nmodel.add(Dense(512, activation=act, W_regularizer=l2(penalty), activity_regularizer=activity_l2(penalty)))\n# model.add(Dropout(0.2))\nmodel.add(Dense(256, activation=act, W_regularizer=l2(penalty), activity_regularizer=activity_l2(penalty)))\nmodel.add(Dense(output_dim, activation=act))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\nprint(model.summary())\n\nmodel.fit(X_train, y_train,\n batch_size = 64,\n nb_epoch = 500,\n validation_split = 0.2)\n\ny_pred = model.predict(X_test)\n\nscores = p1b2.evaluate(y_pred, y_test)\nprint(scores)\n\nsubmission = {'scores': scores,\n 'model': model.summary(),\n 'submitter': 'Developer Name' }\n\nprint('Submitting to leaderboard...')\n# leaderboard.submit(submission)\n","sub_path":"P1B3/p1b2_baseline.py","file_name":"p1b2_baseline.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"598620925","text":"\n'''\nclass Solution:\n def Permutation(self,A,B):\n list1 = [i for i in A]\n list2 = [j for j in B]\n list1.sort()\n list2.sort()\n if list1 == list2:\n return True\n else:\n return False\n\nA = Solution()\na = input()\nb = input()\nprint(A.Permutation(a,b))\n'''\n\n\n#2019/9/9\n#算法:字符的ASCI11码作为index,对字符串进行字符频率统计\n#过程:1,开辟256个空间��数组,用于统计频率\n#2,扫描数组A,统计频率,以相加的方式\n#3,扫描数组B,统计频率,以相减的方式\n#4,检查频率数组,查看是否有没有消除的频率\n\n#\n# class Solution:\n# def Permutation(self,A,B):\n# cnt =[0]*256\n# for c in A:\n# cnt[ord(c)]+=1\n#\n# for c in B:\n# cnt[ord(c)]-=1\n# for freq in cnt:\n# if freq != 0:\n# return False\n#\n# return True\n#\n# A = Solution()\n# a = input()\n# b = input()\n# print(A.Permutation(a,b))\n\ndef Permutation_2(A,B):\n from collections import Counter\n return Counter(A)==Counter(B)\n\na = input()\nb = input()\nprint(Permutation_2(a,b))\n","sub_path":"lintcode/第八层/211_字符串的置换.py","file_name":"211_字符串的置换.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"100959681","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom geoservicios.models import *\nfrom django.template import RequestContext\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect # , Http404\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.contrib.auth import login, authenticate, logout\nfrom django.contrib.auth.models import User\nfrom datetime import datetime # , date\nimport re\n\n# xDEPURAR:\nANIO_INICIO_CH = 2014 # CH: cuadro de honor\nIDIOMAS_DISPONIBLES = [\"es\", \"en\"]\n\t# \"es\":\n\t# \"en-US\":\n\t# \"pt-BR\":\n\t# \"ru-RU\":\n\t# \"hi\": # india?\n\t# \"en-ZA\": # sudafrica or \"af\" or \"zu\":\n\t# \"zh-CN\":\n\t# \"fr-FR\":\n\t# \"da-DE\": # or \"de-DE\":\n\n\ndef uerelizar(cad): # que tiene forma de URL\n\treturn cad.replace(\" \", \"-\").replace(u\"ñ\", \"n\").replace(u\"á\", \"a\").replace(u\"é\", \"e\").replace(u\"í\", \"i\").replace(u\"ó\", \"o\").replace(u\"ú\", \"u\").lower()\n\n\ndef inicio(request):\n\tnuevos_geos = ServicioVirtual.objects.all()[:8]\n\tlista_servis = Valoracion.objects.all()[:8]\n\tidioma = request.LANGUAGE_CODE\n\n\t#li = get_language_info(\"de\")\n\t#print(li[’name’], li[’name_local’], li[’bidi’])\n\tdatos = {\n\t\t'nuevos_geos': nuevos_geos,\n\t\t'idioma': idioma,\n\t\t'servicios_valorados': lista_servis,\n\t\t# 'LANGUAGES': settings.LANGUAGES,\n\t\t'idiomas_disponibles': IDIOMAS_DISPONIBLES,\n\t}\n\tif request.user.is_authenticated():\n\t\tu = request.user\n\t\tu = get_object_or_404(Perfil, usuario=u)\n\t\tdatos['perfil'] = u\n\t\tdatos['perfil_logueado'] = u\n\t\tdatos['logueado'] = True\n\tdatos[\"pag_activa\"] = idioma+\"/index.html\"\n\treturn render_to_response(\"base.html\", datos, RequestContext(request))\n\n\ndef sesionar_usr(request):\n\tif request.user.is_authenticated():\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.inicio'))\n\telse:\n\t\tidioma = request.LANGUAGE_CODE\n\t\tdatos = {\n\t\t\t\"pag_activa\": idioma+\"/index.html\",\n\t\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t\t}\n\t\ttry:\n\t\t\t# xHACER: Post deberia estar sin filtrar?\n\t\t\tusuario = authenticate(username = request.POST['usuario'], password = request.POST['pw'])\n\t\texcept KeyError:\n\t\t\tdatos[\"mensaje\"] = 'Rellene todos los campos'\n\t\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\t\tif usuario is not None:\n\t\t\tif usuario.is_active:\n\t\t\t\tlogin(request, usuario)\n\t\t\telse:\n\t\t\t\tdatos[\"mensaje\"] = 'El usuario ha sido eliminado'\n\t\t\t\treturn render_to_response('base.html', datos,\n\t\t\t\tRequestContext(request))\n\t\telse:\n\t\t\tdatos[\"mensaje\"] = 'Ingrese los datos correctamente'\n\t\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.perfil', args=[usuario]))\n\n\ndef cerrar_sesion(request):\n\t# xHACER: \t# idioma = request.LANGUAGE_CODE\n\tlogout(request)\n\treturn HttpResponseRedirect(reverse('geoservicios.views.inicio'))\n\n\ndef sugerir(request):\n\tif request.user.is_authenticated():\n\t\tusr = request.user\n\t\tusr = Perfil.objects.get(usuario=usr)\n\t\tasunto = request.POST['asunto']\n\t\ttxt = request.POST['txt']\n\t\t# xHACER: deberia validar q no sean chimbos los datos\n\t\tSugerencia.objects.create(texto=txt, asunto= asunto, usuario=usr)\n\treturn HttpResponseRedirect(reverse('geoservicios.views.inicio'))\n\n\n# xHACER: validar q no pasa nada si hago sql-injection\ndef registrar_usr(request):\n\ttry:\n\t\tidioma = request.LANGUAGE_CODE\n\t\tdatos = {\n\t\t\t\"pag_activa\": idioma+\"/index.html\",\n\t\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t\t}\n\t\tif not re.match('^[a-zA-Z0-9_]+$', request.POST['usuario']):\n\t\t\tdatos[\"mensaje\"] = 'El nombre de usuario solo puede contener letras, numeros y _'\n\t\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\t\tif not re.match('^[a-zA-Z][a-zA-Z0-9_]*[@][a-zA-Z0-9_.]+[.][a-zA-Z0-9_]+$', request.POST['correo']):\n\t\t\tdatos[\"mensaje\"] = 'Ingrese un correo valido'\n\t\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\n\t\tusr = request.POST['usuario'].lower()\n\t\tif User.objects.filter(username__iexact = usr):\n\t\t\tdatos[\"mensaje\"] = 'El usuario ya existe'\n\t\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\t\tu = User.objects.create_user(\n\t\t\tusr,\n\t\t\trequest.POST['correo'],\n\t\t\trequest.POST['pw'],\n\t\t)\n\t\tu.first_name = ''\n\t\tu.last_name = ''\n\t\tu.save()\n\n\t\tp = Perfil.objects.create(\n\t\t\tusuario = u,\n\t\t\t# ubicado_en = '',\n\t\t)\n\t\tp.save()\n\t\tusr = authenticate(username = usr, password = request.POST['pw'])\n\t\tlogin(request, usr)\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.perfil', args=[usr]))\n\texcept KeyError:\n\t\tdatos[\"mensaje\"] = 'Rellene todos los campos'\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\n\ndef ver_cuadro_honor(request): # , mes, anio):\n\t\"\"\"Muestra el cuadro de honor y sus respectivos valores y usuarios\"\"\"\n\t# xHACER:\n\t\t# -- seria bueno un calendario o una busqueda para\n\t\t# ubicar un usr q estuvo en el cuadro hace time\n\t\t# -- q le puedas suministrar el año y mes\n\t\t# if (mes >= 1) and (mes <= m and anio <= a) and (anio >= ANIO_INICIO_CH):\n\t\t# ch = CuadroHonor.objects.filter(mes=m, anio=a)\n\t\t# else:\n\t\t# \terror fecha invalida\n\tahorita = datetime.now()\n\tfecha = datetime.date(ahorita)\n\tm = fecha.month\n\ta = fecha.year\n\tlista_atencion = []\n\tlista_tiempo_entrega = []\n\tlista_calidad = []\n\tlista_promedio = []\n\tlista_experiencia = []\n\tq = CuadroHonor.objects.filter(tipo_puntaje=0, mes=m, anio=a)\n\tfor l in q:\n\t\tlista_atencion.append([l.puntaje, l.usuario])\n\n\tq = CuadroHonor.objects.filter(tipo_puntaje=1, mes=m, anio=a)\n\tfor l in q:\n\t\tlista_tiempo_entrega.append([l.puntaje, l.usuario])\n\n\tq = CuadroHonor.objects.filter(tipo_puntaje=2, mes=m, anio=a)\n\tfor l in q:\n\t\tlista_calidad.append([l.puntaje, l.usuario])\n\n\tq = CuadroHonor.objects.filter(tipo_puntaje=3, mes=m, anio=a)\n\tfor l in q:\n\t\tlista_promedio.append([l.puntaje, l.usuario])\n\n\tq = CuadroHonor.objects.filter(tipo_puntaje=4, mes=m, anio=a)\n\tfor l in q:\n\t\tlista_experiencia.append([l.puntaje, l.usuario])\n\n\t# xHACER: cambiar None este por algo mas elegante\n\tusr = None\n\tif request.user.is_authenticated():\n\t\tusr = request.user\n\t\tusr = get_object_or_404(Perfil, usuario__username = usr)\n\tidioma = request.LANGUAGE_CODE\n\treturn render_to_response('base.html', {\n\t\t\"pag_activa\": idioma+\"/cuadroHonor.html\",\n\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t\t'perfil': usr if usr else None,\n\t\t'perfil_logueado': usr if usr else None,\n\t\t'logueado': True if usr else None,\n\t\t'lista_atencion': lista_atencion,\n\t\t'lista_tiempo_entrega': lista_tiempo_entrega,\n\t\t'lista_calidad': lista_calidad,\n\t\t'lista_promedio': lista_promedio,\n\t\t'lista_experiencia': lista_experiencia,\n\t\t}, RequestContext(request))\n\n\ndef crear_cuadro_honor():\n\t\"\"\"Crea un cuadro el primero de cada mes\"\"\"\n\t# xHACER: crear un trigger q corra en django independientemente de su backend\n\tahorita = datetime.now()\n\tfecha = datetime.date(ahorita)\n\tanio = fecha.year\n\tdia = fecha.day\n\tmes = fecha.month\n\tif dia == 1 and anio >= ANIO_INICIO_CH: # (mes >= 1 and mes <= 12)\n\t\ttry:\n\t\t\tatencion = Contador.objects.all().order_by(\"-atencion\")[5]\n\t\t\tte = Contador.objects.all().order_by(\"-tiempo_entrega\")[5]\n\t\t\tcalidad = Contador.objects.all().order_by(\"-calidad\")[5]\n\t\t\tpromedio = Contador.objects.all.order_by(\"-promedio\")[5]\n\t\t\texp = Contador.objects.all.order_by(\"-experiencia\")[5]\n\n\t\t\tfor n in range(len(atencion)):\n\t\t\t\tCuadroHonor.objects.create(mes=mes, anio= anio, usuario=atencion[n].usuario, puntaje=atencion[n].atencion, tipo_puntaje=0)\n\t\t\tfor n in range(len(te)):\n\t\t\t\tCuadroHonor.objects.create(mes=mes, anio= anio, usuario=te[n].usuario, puntaje=te[n].tiempo_entrega, tipo_puntaje=1)\n\t\t\tfor n in range(len(calidad)):\n\t\t\t\tCuadroHonor.objects.create(mes=mes, anio= anio, usuario=calidad[n].usuario, puntaje=calidad[n].calidad, tipo_puntaje=2)\n\t\t\tfor n in range(len(promedio)):\n\t\t\t\tCuadroHonor.objects.create(mes=mes, anio= anio, usuario=promedio[n].usuario, puntaje=promedio[n].promedio, tipo_puntaje=3)\n\t\t\tfor n in range(len(exp)):\n\t\t\t\tCuadroHonor.objects.create(mes=mes, anio= anio, usuario=exp[n].usuario, puntaje=exp[n].experiencia, tipo_puntaje=4)\n\t\texcept:\n\t\t\treturn \"Hubo un error\"\n\n\t\treturn u\"Proceso de generación de valores exitoso!\"\n\telse:\n\t\treturn \"Hubo un error de fecha\"\n\n\ndef ver_categoria(request, cat):\n\t# xHACER: usar un paginador, validar cat, usar el promedio para ordenar las cat\n\tcat = get_object_or_404(Categoria, url=cat)\n\tsubcats = Categoria.objects.filter(padre=cat)\n\tservs = ServicioVirtual.objects.filter(activo=True, subcategoria__in=subcats)[:20]\n\tidioma = request.LANGUAGE_CODE\n\tdatos = {\n\t\t'categoria': cat,\n\t\t'servicios': servs,\n\t\t'subcategorias': subcats,\n\t\t\"pag_activa\": idioma+\"/categoria.html\",\n\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t}\n\tif request.user.is_authenticated():\n\t\tusr = request.user\n\t\tp = get_object_or_404(Perfil, usuario=usr)\n\t\tdatos['perfil'] = p\n\t\tdatos['perfil_logueado'] = p\n\t\tdatos['logueado'] = True\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\telse:\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\n\ndef ver_subcategoria(request, cat, subcat):\n\t# xHACER: usar un paginador, limpiar subcat\n\tcat = get_object_or_404(Categoria, url=cat)\n\tsubcategorias = Categoria.objects.filter(padre=cat)\n\tsubcat = get_object_or_404(Categoria, url=subcat, padre=cat)\n\tservs = ServicioVirtual.objects.filter(activo=True, subcategoria=subcat)[:20]\n\tidioma = request.LANGUAGE_CODE\n\tdatos = {\n\t\t'categoria': cat,\n\t\t'servicios': servs,\n\t\t'subcategorias': subcategorias,\n\t\t'nomb_subcategoria': subcat,\n\t\t\"pag_activa\": idioma+\"/categoria.html\",\n\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t}\n\tif request.user.is_authenticated():\n\t\tusr = request.user\n\t\tp = get_object_or_404(Perfil, usuario=usr)\n\t\tdatos['perfil'] = p\n\t\tdatos['perfil_logueado'] = p\n\t\tdatos['logueado'] = True\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\telse:\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\n\ndef ver_servicio(request, cat, serv):\n\t# xHACER: usar un paginador, limpiar subcat\n\t# debe estar activo por si alguien lo save en favs y lo usa cuando este eliminado\n\tcat = get_object_or_404(Categoria, url=cat)\n\tserv = get_object_or_404(ServicioVirtual, url=serv)\n\ttry:\n\t\tval = Contador.objects.get(servicio=serv)\n\t\tte = val.tiempo_entrega/val.experiencia\n\t\texp = val.experiencia\n\t\tatencion = val.atencion/val.experiencia\n\t\tcalidad = val.calidad/val.experiencia\n\texcept:\n\t\tte, exp, atencion, calidad = 0, 0, 0, 0\n\n\tcontrato = serv.contrato.split(\"
\")\n\textras = ServicioSatelite.objects.filter(servicio=serv)\n\tidioma = request.LANGUAGE_CODE\n\tdatos = {\n\t\t\"pag_activa\": idioma+\"/servicio.html\",\n\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t\t'exp': val.experiencia,\n\t\t'te': val.tiempo_entrega,\n\t\t'calidad': val.calidad,\n\t\t'atencion': val.atencion,\n\t\t'servicio': serv,\n\t\t'contrato': contrato,\n\t\t'categoria': cat,\n\t\t'servs_satelite': extras,\n\t}\n\tif request.user.is_authenticated():\n\t\tusr = request.user\n\t\tp = get_object_or_404(Perfil, usuario=usr)\n\t\tdatos['perfil'] = p\n\t\tdatos['logueado'] = True\n\t\tdatos['perfil_logueado'] = p\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\telse:\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\n\ndef perfil(request, usr):\n\t# xHACER: tiempo estimado de entrega por cada servicio, x semana\n\t# numero de impresiones de anuncios en las busquedas\n\t# cant de usuarios atendidos por servicio\n\t# cant de servicios mutualmente rechazados\n\tusr = get_object_or_404(User, username=usr)\n\tperfil = get_object_or_404(Perfil, usuario=usr)\n\tservis = ServicioVirtual.objects.filter(vendedor=perfil)\n\tcant_servicios = servis.count()\n\tfacturas = Factura.objects.filter(vendedor=perfil)\n\tn_facturas = facturas.count()\n\tlista_servis = []\n\t# visitas = Visitas.objects.filter(usuario=perfil).count()\n\n\tganancias = 0\n\ttry:\n\t\tfor s in servis:\n\t\t\tc = Cola.objects.filter(servicio=s)\n\t\t\tpedidos = c.filter(estatus=0).count()\n\t\t\tcancelados = c.filter(estatus=1).count()\n\t\t\tfacturados = Factura.objects.filter(servicio=s).count()\n\t\t\tlista_servis.append([ s, pedidos, facturados, cancelados ])\n\n\t\tfor f in facturas:\n\t\t\tganancias += f.pago\n\t\tvalores = Contador.objects.get(usuario=perfil)\n\t\tprom = valores.promedio/valores.experiencia\n\t\tte = valores.tiempo_entrega/valores.experiencia\n\t\texp = valores.experiencia\n\t\tatencion = valores.atencion/valores.experiencia\n\t\tcalidad = valores.calidad/valores.experiencia\n\texcept:\n\t\tprom, te, exp, atencion, calidad = 0, 0, 0, 0, 0\n\n\tcategorias = []\n\tlista_subcat = []\n\tlista = Categoria.objects.filter(padre=None)\n\tfor i, cat in enumerate(lista):\n\t\tcategorias.append(cat)\n\t\tsublista = Categoria.objects.filter(padre=cat)\n\t\tlista_subcat.append([i, sublista])\n\n\t# u_extras = get_object_or_404(DatosExtraPerfil, usuario__iexact=usuario)\n\tidioma = request.LANGUAGE_CODE\n\tdatos = {\n\t\t'vacacionando': \"Vacacionando\" if perfil.vacacionando else \"Trabajando\",\n\t\t'prom': prom,\n\t\t'tiempo_entrega': te,\n\t\t'perfil': perfil,\n\t\t'atencion': atencion,\n\t\t'calidad': calidad,\n\t\t'exp': exp,\n\t\t'categorias': categorias,\n\t\t'lista_subcat': lista_subcat,\n\t\t'ganancias': ganancias,\n\t\t'lista_servis': lista_servis,\n\t\t'n_servicios': cant_servicios,\n\t\t'n_compradores': n_facturas,\n\t\t# 'visitas': visitas,\n\t\t# 'n_servicios_progreso': x_comprar,\n\t\t# 'n_servicios_cancelados': cancelada,\n\t\t\"pag_activa\": idioma+\"/perfil.html\",\n\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t}\n\tif request.user.is_authenticated():\n\t\tu = get_object_or_404(User, username = request.user)\n\t\tdatos['logueado'] = True\n\t\tif usr != u:\n\t\t\tp = get_object_or_404(Perfil, usuario = u)\n\t\t\tdatos['perfil_logueado'] = p\n\t\telse:\n\t\t\tdatos['perfil_propio'] = True\n\treturn render_to_response('base.html', datos, RequestContext(request))\n\n\ndef crear_servicio(request):\n\tif request.user.is_authenticated():\n\t\t# xDEPURAR: crear un servicio fisico??\n\t\tusr = request.user\n\t\tp = Perfil.objects.get(usuario=usr)\n\t\t# xHACER:\n\t\t\t# si añade una categoria como tratarla?\n\t\t\t# limpiar todos los datos de entrada\n\t\tnomb = request.POST['nomb']\n\t\turl = uerelizar(nomb)\n\t\tprecio = int(request.POST['precio'])\n\t\tdescrip = request.POST['descrip']\n\t\tcont = \"\"\n\t\tn_clausulas = int(request.POST['Nclausulas'])+1\n\t\tfor k in range(n_clausulas):\n\t\t\tn = 'clausula-'+str(k)\n\t\t\tcont += request.POST[n] + \"
\"\n\t\tcont = cont[: len(cont)-4 ]\n\t\tid_subc = int(request.POST['subc'])\n\t\tid_cat = int(request.POST['subcategoria'])\n\t\tcat = Categoria.objects.filter(padre=None)[id_cat]\n\t\tsubc = Categoria.objects.filter(padre=cat)[id_subc]\n\n\t\ts = ServicioVirtual.objects.create(nombre=nomb, url=url, descripcion=descrip, contrato=cont, precio=precio, subcategoria=subc, vendedor=p)\n\t\tContador.objects.create(usuario=p, servicio=s, experiencia=0, atencion=0, calidad=0, promedio=0, tiempo_entrega=0)\n\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.perfil', args=[usr]))\n\telse:\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.inicio'))\n\n\ndef crear_complemento_servicio(request, servicio):\n\t\"\"\"este debe permanecer individual xq deberia ser capaz de procesar N numero de servicios extras\"\"\"\n\tif request.user.is_authenticated():\n\t\tusr = request.user\n\t\tusr = Perfil.objects.get(usuario=usr)\n\n\t\ttry:\n\t\t\t# xHACER: sera q acepto servicio via get or post?? y ademas debo limpiar el dato!!\n\t\t\tserv = get_object_or_404(ServicioVirtual, id=servicio)\n\t\t\tnomb_complemento = request.POST['nomb-complemento']\n\t\t\tdesc_complemento = request.POST['desc-complemento']\n\t\t\tprecio_complemento = request.POST['precio-complemento']\n\t\t\tServicioSatelite.objects.create(servicio_v=serv, usuario=usr, nombre=nomb_complemento, descripcion=desc_complemento, precio=precio_complemento)\n\t\texcept:\n\t\t\tpass # xHACER: q pasa si no se envia y q retorna al final\n\t\treturn usr\n\telse:\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.sesionar_usr'))\n\n\ndef enlistar_usuario(request, usr):\n\t\"\"\"Enlistar solicitudes de servicio\"\"\"\n\tif request.user.is_authenticated():\n\t\tu = get_object_or_404(Perfil, usuario__username=usr)\n\t\tserv = request.POST[\"serv\"]\n\t\tserv = get_object_or_404(ServicioVirtual, url=serv)\n\t\tcont = \"\"\n\t\tn_clausulas = int(request.POST['Nclausulas'])+1\n\t\tfor k in range(n_clausulas):\n\t\t\tn = 'clausula-'+str(k)\n\t\t\tcont += request.POST[n] + \"
\"\n\t\tcont = cont[: len(cont)-4 ]\n\t\tCola.objects.create(servicio=serv, estatus=0, vendedor=serv.vendedor, comprador=u, contrato=cont)\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.perfil', args=[u]))\n\telse:\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.inicio'))\n\n\ndef lista_solicitudes_servicio(request):\n\t\"\"\"Aceptar o rechazar solicitudes y mostrar la lista\"\"\"\n\tif request.user.is_authenticated():\n\t\tu = get_object_or_404(Perfil, usuario__username=request.user)\n\t\ttry:\n\t\t\topc = request.POST[\"opc\"]\n\t\t\tif opc == \"1\": # cancelar\n\t\t\t\tident = request.POST[\"ident\"]\n\t\t\t\tCola.objects.filter(id=ident).delete()\n\t\t\t\t# xHACER: falta verificar q sea el servicio q quiero eliminar\n\t\t\tif opc == \"2\": # aceptar\n\t\t\t\tpass # xHACER:\n\t\texcept:\n\t\t\tpass\n\t\tlista = []\n\t\tservis = Cola.objects.filter(estatus=0, vendedor=u)\n\t\tfor sec in servis: # sec= servicio en cola\n\t\t\tif sec.servicio.contrato != sec.contrato:\n\t\t\t\tx = sec.contrato.split(\"
\")\n\t\t\telse:\n\t\t\t\tx = []\n\t\t\tlista.append([sec, x])\n\t\tidioma = request.LANGUAGE_CODE\n\t\tdatos = {\n\t\t\t'perfil': u,\n\t\t\t'perfil_logueado': u,\n\t\t\t'logueado': True,\n\t\t\t'lista': lista,\n\t\t\t\"pag_activa\": idioma+\"/encolados.html\",\n\t\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t\t}\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\telse:\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.inicio'))\n\n\ndef buscar(request):\n\t# xHACER: limpiar variables POST y busqueda\n\tconsulta = request.GET['c']\n\tusrs = Perfil.objects.filter(usuario__username__icontains=consulta)\n\tservis = ServicioVirtual.objects.filter(nombre__icontains=consulta)\n\t# elif request.POST['tipo'] == \"medalla\":\n\t\t# obj = Medalla.objects.filter(nombre=busqueda)\n\tidioma = request.LANGUAGE_CODE\n\tdatos = {\n\t\t'lista_usuarios': usrs,\n\t\t'lista_servicios': servis,\n\t\t'consulta': consulta,\n\t\t\"pag_activa\": idioma+\"/busqueda.html\",\n\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t}\n\tif request.user.is_authenticated():\n\t\tu = request.user\n\t\tu = get_object_or_404(Perfil, usuario=u)\n\t\tdatos['perfil'] = u\n\t\tdatos['perfil_logueado'] = u\n\t\tdatos['logueado'] = True\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\telse:\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\n\ndef configurar_cta(request):\n\tif request.user.is_authenticated():\n\t\tusr = request.user\n\t\tp = get_object_or_404(Perfil, usuario=usr)\n\t\tidioma = request.LANGUAGE_CODE\n\t\tdatos = {\n\t\t\t\"pag_activa\": idioma+\"/config.html\",\n\t\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t\t\t'perfil': p,\n\t\t\t'logueado': True,\n\t\t\t'perfil_logueado': p,\n\t\t}\n\t\ttry:\n\t\t\tif request.POST:\n\t\t\t\tnomb = request.POST['nombre']\n\t\t\t\tvacas = request.POST['vacas']\n\t\t\t\tedad = request.POST['edad']\n\t\t\t\tdatos[\"edad\"] = edad\n\t\t\t\tdatos[\"vacas\"] = vacas\n\t\t\t\tdatos[\"nombre_completo\"] = nomb\n\t\t\t\tPerfil.objects.filter(usuario=p).update(nombre_completo=nomb, edad=edad, vacacionando=vacas)\n\t\t\t\tdatos[\"mensaje\"] = \"Se guardaron tus cambios! :)\"\n\t\t\telse:\n\t\t\t\tdatos[\"edad\"] = p.edad\n\t\t\t\tdatos[\"vacas\"] = p.vacacionando\n\t\t\t\tdatos[\"nombre_completo\"] = p.nombre_completo\n\t\texcept:\n\t\t\tpass\n\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\telse:\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.inicio'))\n\n\ndef contactarnos(request):\n\tidioma = request.LANGUAGE_CODE\n\tdatos = {\n\t\t\"pag_activa\": idioma+\"/contacto.html\",\n\t\t\"idiomas_disponibles\": IDIOMAS_DISPONIBLES,\n\t}\n\tif request.user.is_authenticated():\n\t\tusr = request.user\n\t\tp = get_object_or_404(Perfil, usuario=usr)\n\t\tdatos['logueado'] = p\n\t\tdatos['perfil_logueado'] = p\n\t\tdatos['logueado'] = True\n\t\treturn render_to_response('base.html', datos\t, RequestContext(request))\n\telse:\n\t\treturn render_to_response('base.html', datos, RequestContext(request))\n\n\ndef comprar(request):\n\t\"\"\"Este modulo realiza:\n\t\t* Aceptar_compra (confirmar el cobro)\n\t\t* Confirmar_entrega (Facturada)\n\t\t* Cancelacion de la compra\n\testos son seciones enlazados a paypal, mercadopago, bitpay o RIPPLE\"\"\"\n\tif request.user.is_authenticated():\n\t\tfactura = request.POST[\"orden\"]\n\t\t# xHACER: implementar algo q no permita q se pueda ver la facturas de otras personas\n\t\t# falta valorar la compra en caso de confirmar\n\t\ttry:\n\t\t\tfactura = Factura.objects.get(id=factura)\n\t\texcept:\n\t\t\t# esto significa q es para crear una nva factura\n\t\t\tFactura.objects.create()\n\n\t\tusr_sesionado = request.user\n\t\tusr_sesionado = Perfil.objects.get(usuario=usr)\n\t\tif usr_sesionado != factura.comprador or usr_sesionado != factura.vendedor:\n\t\t\treturn \"no me jodas\"\n\telse:\n\t\treturn HttpResponseRedirect(reverse('geoservicios.views.sesionar_usr'))\n\n\n# xHACER: cargar en el index las categorias desde la BD y no estaticamente\ndef inicializar_categorias():\n\tc = Categoria.objects.create(nombre=u\"Gráficos, Diseño y Fotografía\", url=\"graficos-diseno-fotografia\")\n\tCategoria.objects.create(nombre=u\"Historietas, Caricaturas y Personajes\", padre=c, url=\"historietas-caricaturas-personajes\")\n\tCategoria.objects.create(nombre=u\"Diseño de Logos\", padre=c, url=\"diseno-logos\")\n\tCategoria.objects.create(nombre=u\"Ilustración\", padre=c, url=\"ilustracion\")\n\tCategoria.objects.create(nombre=u\"Portada de Libros y Paquetes\", padre=c, url=\"portada-libros-paquetes\")\n\tCategoria.objects.create(nombre=u\"Diseño Web e Interfaz de Usuario (IU)\", padre=c, url=\"diseno-web-iu\")\n\tCategoria.objects.create(nombre=u\"Fotografía y Edición Fotográfica\", padre=c, url=\"fotografia-edicion-fotografica\")\n\tCategoria.objects.create(nombre=u\"Diseño de Presentaciones\", padre=c, url=\"diseno-presentaciones\")\n\tCategoria.objects.create(nombre=u\"Tarjetas de Negocios\", padre=c, url=\"tarjetas-negocios\")\n\tCategoria.objects.create(nombre=u\"Encabezados y Anuncios\", padre=c, url=\"encabezados-anuncios\")\n\tCategoria.objects.create(nombre=u\"Arquitectura\", padre=c, url=\"arquitectura\")\n\tCategoria.objects.create(nombre=u\"Página Web Estática\", padre=c, url=\"pagina-web-estatica\")\n\tCategoria.objects.create(nombre=u\"Mobiliario\", padre=c, url=\"mobiliario\")\n\tCategoria.objects.create(nombre=u\"Videojuegos\", padre=c, url=\"videojuegos\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n\t# termino\n\n\tc = Categoria.objects.create(nombre=u\"Transcripción, Traducción y Redacción\", url=\"transcripcion-traduccion-redaccion\")\n\tCategoria.objects.create(nombre=u\"Redacción y Escritura Creativa\", padre=c, url=\"redaccion-escritura-creativa\")\n\tCategoria.objects.create(nombre=u\"Traducción\", padre=c, url=\"traduccion\")\n\tCategoria.objects.create(nombre=u\"Transcripción\", padre=c, url=\"transcripcion\")\n\tCategoria.objects.create(nombre=u\"Contenido para Sitios Web\", padre=c, url=\"contenido-sitios-web\")\n\tCategoria.objects.create(nombre=u\"Reseña/Crítica\", padre=c, url=\"resena-critica\")\n\tCategoria.objects.create(nombre=u\"Curriculum, Cartas de Presentación\", padre=c, url=\"curriculum-cartas-presentacion\")\n\tCategoria.objects.create(nombre=u\"Redacción de Discursos\", padre=c, url=\"redaccion-discursos\")\n\tCategoria.objects.create(nombre=u\"Edición y Revisión de Escritos\", padre=c, url=\"edicion-revision-escritos\")\n\tCategoria.objects.create(nombre=u\"Comunicado de Prensa\", padre=c, url=\"comunicado-prensa\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n\t# termino\n\n\tc = Categoria.objects.create(nombre=u\"Audio y Música\", url=\"audio-musica\")\n\tCategoria.objects.create(nombre=u\"Edición y Masterizadó de Audio\", padre=c, url=\"edicion-masterizado-audio\")\n\tCategoria.objects.create(nombre=u\"Canciones\", padre=c, url=\"canciones\")\n\tCategoria.objects.create(nombre=u\"Composición de canciones\", padre=c, url=\"composicion-canciones\")\n\tCategoria.objects.create(nombre=u\"Lecciones de Música\", padre=c, url=\"lecciones-musica\")\n\tCategoria.objects.create(nombre=u\"Música Rap\", padre=c, url=\"musica-rap\")\n\tCategoria.objects.create(nombre=u\"Narración y Edición Doblaje\", padre=c, url=\"narracion-edicion-doblaje\")\n\tCategoria.objects.create(nombre=u\"Efectos de sonido\", padre=c, url=\"efectos-sonido\")\n\tCategoria.objects.create(nombre=u\"Tonos de Llamada Personalizados\", padre=c, url=\"tonos-llamada-personalizados\")\n\tCategoria.objects.create(nombre=u\"Felicitaciones por Correo de Voz\", padre=c, url=\"felicitaciones-correo-voz\")\n\tCategoria.objects.create(nombre=u\"Canciones Personalizadas\", padre=c, url=\"canciones-personalizadas\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n\t# termino\n\n\tc = Categoria.objects.create(nombre=u\"Programación y Tecnología\", url=\"programacion-tecnologia\")\n\tCategoria.objects.create(nombre=u\".Net\", padre=c, url=\".net\")\n\tCategoria.objects.create(nombre=u\"C/C++\", padre=c, url=\"c-c++\")\n\tCategoria.objects.create(nombre=u\"CSS y HTML\", padre=c, url=\"css-html\")\n\tCategoria.objects.create(nombre=u\"Joomla y Drupal\", padre=c, url=\"joomla-drupal\")\n\tCategoria.objects.create(nombre=u\"Base de Datos\", padre=c, url=\"base-datos\")\n\tCategoria.objects.create(nombre=u\"Java\", padre=c, url=\"java\")\n\tCategoria.objects.create(nombre=u\"JavaScript\", padre=c, url=\"javascript\")\n\tCategoria.objects.create(nombre=u\"PSD a HTML\", padre=c, url=\"psd-html\")\n\tCategoria.objects.create(nombre=u\"WordPress\", padre=c, url=\"wordpress\")\n\tCategoria.objects.create(nombre=u\"Flash\", padre=c, url=\"flash\")\n\tCategoria.objects.create(nombre=u\"iOS, Android y Móviles\", padre=c, url=\"ios-android-moviles\")\n\tCategoria.objects.create(nombre=u\"PHP\", padre=c, url=\"php\")\n\tCategoria.objects.create(nombre=u\"Preguntas y Respuestas (PR) y Pruebas de Software\", padre=c, url=\"pr-pruebas-software\")\n\tCategoria.objects.create(nombre=u\"Tecnología\", padre=c, url=\"tecnologia\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n\t# termino\n\n\tc = Categoria.objects.create(nombre=u\"Marketing Digital\", url=\"marketing-digital\")\n\tCategoria.objects.create(nombre=u\"Análisis Web\", padre=c, url=\"analisis-web\")\n\tCategoria.objects.create(nombre=u\"Artículos y Envíos de RP\", padre=c, url=\"articulos-envios-rp\")\n\tCategoria.objects.create(nombre=u\"Menciones en Blogs\", padre=c, url=\"menciones-blogs\")\n\tCategoria.objects.create(nombre=u\"Búsqueda de Dominios\", padre=c, url=\"busqueda-dominios\")\n\tCategoria.objects.create(nombre=u\"Páginas de Fans\", padre=c, url=\"paginas-fans\")\n\tCategoria.objects.create(nombre=u\"Optimización para Motores de Búsqueda (SEO)\", padre=c, url=\"seo\")\n\tCategoria.objects.create(nombre=u\"Marketing en Redes Sociales\", padre=c, url=\"marketing-redes-sociales\")\n\tCategoria.objects.create(nombre=u\"Generar Tráfico Web\", padre=c, url=\"generar-trafico-web\")\n\tCategoria.objects.create(nombre=u\"Marketing en Videos\", padre=c, url=\"marketing-videos\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n\t# termino\n\n\tc = Categoria.objects.create(nombre=u\"Publicidad y Propaganda\", url=\"publicidad-propaganda\")\n\tCategoria.objects.create(nombre=u\"Tu mensaje en/con...\", padre=c, url=\"tu-mensaje-en-con\")\n\tCategoria.objects.create(nombre=u\"Volantes, Folletos y Regalos\", padre=c, url=\"volantes-folletos-regalos\")\n\tCategoria.objects.create(nombre=u\"Anuncios Humanos\", padre=c, url=\"anuncios-humanos\")\n\tCategoria.objects.create(nombre=u\"Comerciales\", padre=c, url=\"comerciales\")\n\tCategoria.objects.create(nombre=u\"Mascotas Modelos\", padre=c, url=\"mascotas-modelos\")\n\tCategoria.objects.create(nombre=u\"Publicidad en Exteriores\", padre=c, url=\"publicidad-exteriores\")\n\tCategoria.objects.create(nombre=u\"Radio\", padre=c, url=\"radio\")\n\tCategoria.objects.create(nombre=u\"Promoción Musical\", padre=c, url=\"promocion-musical\")\n\tCategoria.objects.create(nombre=u\"Publicidad en Anuncios Web\", padre=c, url=\"publicidad-anuncios-web\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n\t# termino\n\n\tc = Categoria.objects.create(nombre=u\"Negocios\", url=\"negocios\")\n\tCategoria.objects.create(nombre=u\"Planes de Negocios\", padre=c, url=\"planes-negocios\")\n\tCategoria.objects.create(nombre=u\"Consejos para tu Carrera Profesional\", padre=c, url=\"consejos-carrera-profesional\")\n\tCategoria.objects.create(nombre=u\"Estudio de Mercado\", padre=c, url=\"estudio-mercado\")\n\tCategoria.objects.create(nombre=u\"Presentaciones\", padre=c, url=\"presentaciones\")\n\tCategoria.objects.create(nombre=u\"Asistentecia Virtual\", padre=c, url=\"asistentecia-virtual\")\n\tCategoria.objects.create(nombre=u\"Consejos para Negocios\", padre=c, url=\"consejos-negocios\")\n\tCategoria.objects.create(nombre=u\"Servicios de Marca\", padre=c, url=\"servicios-marca\")\n\tCategoria.objects.create(nombre=u\"Consultoría Financiera\", padre=c, url=\"consultoria-financiera\")\n\tCategoria.objects.create(nombre=u\"Consultoría Legal\", padre=c, url=\"consultoria-legal\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n\t# termino\n\n\tc = Categoria.objects.create(nombre=u\"Video y Animación\", url=\"video-animacion\")\n\tCategoria.objects.create(nombre=u\"Comerciales\", padre=c, url=\"comerciales\")\n\t# xPENSAR:\n\t\t# deberia cambiar la estrategia (q un servicio elija las categorias)??\n\t\t# comerciales puede estar en video y en publicidad\n\tCategoria.objects.create(nombre=u\"Edición, Efectos y Post Producción\", padre=c, url=\"edicion-efectos-post-produccion\")\n\tCategoria.objects.create(nombre=u\"Animación y 3D\", padre=c, url=\"animacion-3d\")\n\tCategoria.objects.create(nombre=u\"Testimonios y Comentarios\", padre=c, url=\"testimonios-comentarios\")\n\tCategoria.objects.create(nombre=u\"Marionetas\", padre=c, url=\"marionetas\")\n\tCategoria.objects.create(nombre=u\"Stop Motion\", padre=c, url=\"stop-motion\")\n\tCategoria.objects.create(nombre=u\"Intros\", padre=c, url=\"intros\")\n\tCategoria.objects.create(nombre=u\"Storyboarding\", padre=c, url=\"storyboarding\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n\t# termino\n\n\tc = Categoria.objects.create(nombre=u\"Diversión y Entretenimiento\", url=\"diversion-entretenimiento\")\n\tCategoria.objects.create(nombre=u\"Video StandUp sobre Tema/Evento\", padre=c, url=\"video-standup-sobre-tema-evento\")\n\tCategoria.objects.create(nombre=u\"Chistes Escritos\", padre=c, url=\"chistes-escritos\")\n\tCategoria.objects.create(nombre=u\"Chistes en Vivo\", padre=c, url=\"chistes-vivo\")\n\tCategoria.objects.create(nombre=u\"Discurso Gracioso para Evento\", padre=c, url=\"discurso-gracioso-evento\")\n\tCategoria.objects.create(nombre=u\"Personificación de Celebridades\", padre=c, url=\"personificacion-celebridades\")\n\tCategoria.objects.create(nombre=u\"Truco de Magia Personalizable\", padre=c, url=\"truco-magia-personalizable\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n\t# termino\n\n\tc = Categoria.objects.create(nombre=u\"Estilo de vida\", url=\"estilo-vida\")\n\tCategoria.objects.create(nombre=u\"Cuidado de Animales y Mascotas\", padre=c, url=\"cuidado-animales-mascotas\")\n\tCategoria.objects.create(nombre=u\"Consejos sobre Relaciones\", padre=c, url=\"consejos-relaciones\")\n\tCategoria.objects.create(nombre=u\"Maquillaje, Estilo y Belleza\", padre=c, url=\"maquillaje-estilo-belleza\")\n\tCategoria.objects.create(nombre=u\"Astrología y Tarot\", padre=c, url=\"astrologia-tarot\")\n\tCategoria.objects.create(nombre=u\"Recetas de Cocina\", padre=c, url=\"recetas-cocina\")\n\tCategoria.objects.create(nombre=u\"Consejos para Padres\", padre=c, url=\"consejos-padres\")\n\tCategoria.objects.create(nombre=u\"Viajes\", padre=c, url=\"viajes\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n\t# termino\n\n\tc = Categoria.objects.create(nombre=u\"Regalos\", url=\"regalos\")\n\tCategoria.objects.create(nombre=u\"Tarjetas de Felicitación\", padre=c, url=\"tarjetas-felicitacion\")\n\tCategoria.objects.create(nombre=u\"Video Felicitaciones\", padre=c, url=\"video-felicitaciones\")\n\tCategoria.objects.create(nombre=u\"Arte y Manualidades\", padre=c, url=\"arte-manualidades\")\n\tCategoria.objects.create(nombre=u\"Joyería Hecha a Mano\", padre=c, url=\"joyeria-hecha-mano\")\n\tCategoria.objects.create(nombre=u\"Regalos para Nerdos\", padre=c, url=\"regalos-nerdos\")\n\tCategoria.objects.create(nombre=u\"Otros\", padre=c, url=\"otros\")\n","sub_path":"geoservicios/views CON idiomas.py","file_name":"views CON idiomas.py","file_ext":"py","file_size_in_byte":31799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"108973007","text":"\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 5 15:57:17 2020\n\n@author: zlibn\n\"\"\"\nimport sys\nsys.path.append(\"D:/Google Drive/HKUST-Office/Research/4th Work/Source\")\n\nimport numpy as np\nimport pandas as pd\nimport random\nimport math\nimport gensim\nfrom scipy.special import psi, loggamma, polygamma\n#from Telegram_chatbot import MTRobot\nfrom Telegram_multi_chatbot import MTRobot\nfrom sklearn.preprocessing import normalize\nfrom module_GR_TensorLDA_OnlineLearning_setting4 import GR_OnlineTensorLDA\nfrom module_GR_TensorLDA_BatchLearning import GR_TensorLDA\nimport time\n# In[]:\ndef doc_generator_odt(user_tensor):\n docs = []\n list_docs_o = []\n list_docs_d = []\n list_docs_t = []\n wordcount = []\n for i in range(user_tensor.shape[0]):\n user = user_tensor[i,:,:,:]\n O, D, T = np.nonzero(user)\n count = user[np.nonzero(user)]\n \n wordcount.append(sum(count))\n \n doc = []\n for j in range(len(O)):\n word_o = 'O' + str(O[j]) #+ '_D' + str(D[j]) + '_T' + str(T[j])\n doc += int(count[j]) * [word_o]\n list_docs_o.append(doc)\n \n doc = []\n for k in range(len(D)):\n word_d = 'D' + str(D[k]) #+ '_D' + str(D[j]) + '_T' + str(T[j])\n doc += int(count[k]) * [word_d]\n list_docs_d.append(doc)\n \n doc = []\n for l in range(len(T)):\n word_t = 'T' + str(T[l]) #+ '_D' + str(D[j]) + '_T' + str(T[j])\n doc += int(count[l]) * [word_t]\n list_docs_t.append(doc)\n \n docs = pd.concat([pd.Series(list_docs_o), pd.Series(list_docs_d), pd.Series(list_docs_t), pd.Series(wordcount)], axis=1)\n docs.columns = ['O', 'D', 'T', 'wordcount']\n dictionary_o = gensim.corpora.Dictionary(docs['O'])\n dictionary_d = gensim.corpora.Dictionary(docs['D'])\n dictionary_t = gensim.corpora.Dictionary(docs['T'])\n #bow_corpus_o = [dictionary_o.doc2bow(doc) for doc in docs['O']]\n #bow_corpus_d = [dictionary_d.doc2bow(doc) for doc in docs['D']]\n #bow_corpus_t = [dictionary_t.doc2bow(doc) for doc in docs['T']]\n idx_corpus_o = [dictionary_o.doc2idx(doc) for doc in docs['O']]\n idx_corpus_d = [dictionary_d.doc2idx(doc) for doc in docs['D']]\n idx_corpus_t = [dictionary_t.doc2idx(doc) for doc in docs['T']]\n \n return docs, dictionary_o, dictionary_d, dictionary_t, idx_corpus_o, idx_corpus_d, idx_corpus_t\n \n\ndef perlexity(test_docs, idx_corpus, alpha, count_uz, beta):\n beta = np.exp(beta)\n num_topic = beta.shape[0]\n log_per = 0\n wordcount_sum = 0\n Kalpha = num_topic * alpha\n for u in range(len(test_docs)):\n theta = count_uz[u] / (len(test_docs.iloc[u]) + Kalpha)\n for w in range(len(test_docs.iloc[u])):\n log_per -= np.log( np.inner(beta[:,idx_corpus[u][w]], theta) + 1e-6 ) # phi[:,w]: R^(K*1)\n wordcount_sum += len(test_docs.iloc[u])\n return np.exp(log_per / wordcount_sum)\n\ndef word_doc_freq(word_id, idx_corpus):\n freq = 0\n for u in range(len(idx_corpus)):\n if word_id in idx_corpus[u]:\n freq += idx_corpus[u].count(word_id)\n return freq\n\ndef words_doc_cofreq(word1_id, word2_id, idx_corpus):\n freq = 0\n for u in range(len(idx_corpus)):\n if word1_id in idx_corpus[u] and word2_id in idx_corpus[u]:\n freq += ( idx_corpus[u].count(word1_id) * idx_corpus[u].count(word2_id) )\n return freq\n\ndef topic_k_coherence(sub_topic, idx_corpus, epsilon=1):\n \"\"\"\n sub_topic: one imcomplete row in beta (the top r largest element in topic k), e.g.: sorted(range(len(betaD[k])), key=lambda x: betaD[k][x])[-r:]\n \"\"\"\n tc_sum = 0\n for index, w1 in enumerate(sub_topic[1:]):\n m_index = index + 1\n sublist = sub_topic[:m_index]\n \n for w2 in sublist:\n fre_w2 = word_doc_freq(w2, idx_corpus)\n cofre_w1_w2 = words_doc_cofreq(w1, w2, idx_corpus)\n #print(f'cofre_w1{w1}_w2{w2} / fre_w2{w2}: {cofre_w1_w2}/{fre_w2}')\n if fre_w2 > 0:\n tc_sum += np.log(float(cofre_w1_w2 + epsilon) / fre_w2)\n return tc_sum\n\ndef topic_coherence(beta, toprank, idx_corpus):\n num_topic = beta.shape[0]\n TC = []\n for z in range(num_topic):\n sub_topic = sorted(range(len(beta[z])), key=lambda x: beta[z][x])[-toprank:]\n tc_sum = topic_k_coherence(sub_topic, idx_corpus, epsilon=1)\n TC.append(tc_sum)\n return TC\n\n# In[]\ndocs_arr = np.load('D:/Google Drive/HKUST-Office/Research/4th Work/Data/passenger data/docs_5k_jan_feb_arr.npy', allow_pickle=True)\ndocs = pd.DataFrame(data=docs_arr, columns=['TY', 'O', 'D', 'T', 'wordcount'])\n\n#docs = docs_df[docs_df['wordcount'] >= 90]\n#docs = docs.iloc[0:1024]\n#indx = list(range(len(docs_90)))\n#random.shuffle(indx)\n#docs = docs_90.iloc[indx[0:600]]\n\n\ndictionary_o = gensim.corpora.Dictionary(docs['O'])\ndictionary_d = gensim.corpora.Dictionary(docs['D'])\ndictionary_t = gensim.corpora.Dictionary(docs['T'])\n\nidx_corpus_o = [dictionary_o.doc2idx(doc) for doc in docs['O']]\nidx_corpus_d = [dictionary_d.doc2idx(doc) for doc in docs['D']]\nidx_corpus_t = [dictionary_t.doc2idx(doc) for doc in docs['T']]\n\n# In[]\nnum_user = docs.shape[0]\nnum_station = max(len(dictionary_o), len(dictionary_d))\nnum_time = len(dictionary_t)\n\n# In[1.2] Define global parameters and Initialization\n\n# number of passengers for training\nM = 76*64 #1024#num_user\nS = 64 # batch size: 64, 128, 256\nnum_batch = int(M/S)\n# number of topic\nJ = 10\nK = 10\nL = 4\n# iteration times of variational EM algorithm\niterEM = 3 - 1\nEM_CONVERGED = 0.001\nEM_CONVERGED_fine_tune = 0.002\n# iteration times of variational inference\niterInference = 10 # instead of 20 since we only have 64 passengers in a batch\nVAR_CONVERGED = 0.0001\n\ntau0 = 16\nkappa = 0.5\n\nnum_epoch = 1\n\n# initial value of hyperparameter alpha\nalpha = 5\n# sufficient statistic of alpha\nalphaSS = 0\n# the topic-word distribution (beta in D. Blei's paper)\nbetaO = np.zeros([J, num_station]) #+ 1e-5\nbetaD = np.zeros([K, num_station]) #+ 1e-5\nbetaT = np.zeros([L, num_time]) #+ 1e-5\n# topic-word count, this is a sufficient statistic to calculate beta\ncount_zwo = np.zeros((J, num_station)) # sufficient statistic for beta^O\ncount_zwd = np.zeros((K, num_station)) # sufficient statistic for beta^D\ncount_zwt = np.zeros((L, num_time)) # sufficient statistic for beta^T\n# topic count, sum of nzw with w ranging from [0, M-1], for calculating varphi\ncount_zo = np.zeros(J)\ncount_zd = np.zeros(K)\ncount_zt = np.zeros(L)\n\n# inference parameter gamma\ngamma = np.zeros((M, J, K, L))\n# inference parameter phi\n#phiO = np.zeros([maxItemNum(), J])\n#phiD = np.zeros([maxItemNum(), K])\n#phiT = np.zeros([maxItemNum(), L])\n\n#likelihood = 0\n#likelihood_old = 0\n\nG_net = np.random.randint(2, size=(num_station, num_station))\nG_poi = np.load('D:/Google Drive/HKUST-Office/Research/4th Work/Data/poi_sim.npy') \n# In[]\nworker_idx = 1 -1\nLAMBDA = [0.1]\nmu = 0 # only POI graph on origin\nnu = 0 # only POI graph on destination\nsave_dir = 'C:/Users/zlibn/Desktop/online_5k'\n# In[2] variational EM Algorithm\n###############################################################################\n#while (converged < 0 or converged > EM_CONVERGED or iteration<=2) and (i <= iterEM):\nperplexity_matrix = np.zeros((len(LAMBDA),4))\nlikelihood_matrix = np.zeros((len(LAMBDA),2))\n\n\n#likelihood_evolu = 0\n\n#likelihood_evolu_i = np.zeros((num_batch, 2))\nmb_inter = 7 #minibatch interval to fetch the result and plot\nnum_point = int(num_batch/mb_inter) # = 10 # number of plot point within each epoch\nlikelihood_evolu_e = np.zeros((num_point, 2))#np.zeros((num_epoch, 2))\n\n# perO_evolu_i = np.zeros((num_batch, 2))\n# perD_evolu_i = np.zeros((num_batch, 2))\n# perT_evolu_i = np.zeros((num_batch, 2))\n\nperO_evolu_e = np.zeros((num_point, 2))#np.zeros((num_epoch, 2))\nperD_evolu_e = np.zeros((num_point, 2))#np.zeros((num_epoch, 2))\nperT_evolu_e = np.zeros((num_point, 2))#np.zeros((num_epoch, 2))\n\n\ntest_docs = docs.iloc[M:]\n\nfor lam_k, lam_v in enumerate(LAMBDA):\n \n MTRobot.sendtext(worker_idx, \" Start Lambda: {}\".format(lam_v))\n print(f'Start Lambda: {lam_v}')\n betaO = np.zeros([J, num_station]) #+ 1e-5\n betaD = np.zeros([K, num_station]) #+ 1e-5\n betaT = np.zeros([L, num_time]) #+ 1e-5\n \n model_test = GR_TensorLDA(worker_idx, alpha, J, K, L, M, test_docs, iterEM, EM_CONVERGED, EM_CONVERGED_fine_tune, iterInference, VAR_CONVERGED)\n time_0 = int(time.time())\n # Begin for-loop-2 iterating e: num_epoch\n for e in range(num_epoch):\n MTRobot.sendtext(worker_idx, \" Start {}-th epoch\".format(e))\n _updatect = e*S\n model = GR_OnlineTensorLDA(worker_idx, alpha, num_station, num_time, J, K, L, M, S, \\\n iterEM, EM_CONVERGED, EM_CONVERGED_fine_tune, iterInference, VAR_CONVERGED, tau0, kappa, _updatect)\n if e ==0:\n # only need to initialize model for once in the first beginning\n count_zwo, count_zo, count_zwd, count_zd, count_zwt, count_zt, betaO, betaD, betaT = model.initialLdaModel(num_batch, num_station, num_time)\n # this model initialization needs to be set for every epoch since betaO_o, betaD_o, betaT_o from last epoch need to be passed to next epoch\n # Begin for-loop-1 iterating i: num_btach\n for i in range(num_batch):\n docs_minibatch = docs[i*S:(i+1)*S] # mini-batch as a moving window to feed the model #!!!\n count_uzo, count_uzd, count_uzt, betaO, betaD, betaT, gamma, theta, likelihood_mb, time_lkh \\\n = model.fit(i=i, docs_minibatch=docs_minibatch, lam=lam_v, mu=mu, nu=nu, G_net=G_net, G_poi=G_poi, \\\n dictionary_o=dictionary_o, dictionary_d=dictionary_d, dictionary_t=dictionary_t, idx_corpus_o=idx_corpus_o, idx_corpus_d=idx_corpus_d, idx_corpus_t=idx_corpus_t, num_user=num_user, num_station=num_station, num_time=num_time, \\\n betaO=betaO, betaD=betaD, betaT=betaT)\n \n # likelihood_evolu += likelihood_mb \n # likelihood_evolu_i[i,0] = time_lkh - time_0\n # likelihood_evolu_i[i,1] = likelihood_evolu\n \n # perO = perlexity(docs[\"O\"].loc[0:M], idx_corpus_o, alpha, count_uzo, betaO_o)\n # perD = perlexity(docs[\"D\"].loc[0:M], idx_corpus_d, alpha, count_uzd, betaD_o)\n # perT = perlexity(docs[\"T\"].loc[0:M], idx_corpus_t, alpha, count_uzt, betaT_o)\n # time_1 = int(time.time())\n \n # perO_evolu_i[i,0] = time_1 - time_0\n # perO_evolu_i[i,1] = perO\n # perD_evolu_i[i,0] = time_1 - time_0\n # perD_evolu_i[i,1] = perD\n # perT_evolu_i[i,0] = time_1 - time_0\n # perT_evolu_i[i,1] = perT\n # print(f'log-likelihood {likelihood_evolu} after minibatch-{i} at time {time_1- time_0}')\n if (i+1) % mb_inter ==0:\n e1 = int((i+1) / mb_inter) - 1 #from 0 to 9\n time_1 = int(time.time()) # record the time when betaO, D, T are completely updated after the whole epoch\n count_uzo_t, count_uzd_t, count_uzt_t, likelihood_t = \\\n model_test.new_doc_infer(test_docs=test_docs, betaO=betaO, betaD=betaD, betaT=betaT, \\\n idx_corpus_o=idx_corpus_o, idx_corpus_d=idx_corpus_d, idx_corpus_t=idx_corpus_t)\n \n likelihood_evolu_e[e1,0] = time_1 - time_0\n likelihood_evolu_e[e1,1] = likelihood_t\n \n perO = perlexity(test_docs[\"O\"], idx_corpus_o[M:], alpha, count_uzo_t, betaO)\n perD = perlexity(test_docs[\"D\"], idx_corpus_d[M:], alpha, count_uzd_t, betaD)\n perT = perlexity(test_docs[\"T\"], idx_corpus_t[M:], alpha, count_uzt_t, betaT)\n \n perO_evolu_e[e1,0] = time_1 - time_0\n perO_evolu_e[e1,1] = perO\n perD_evolu_e[e1,0] = time_1 - time_0\n perD_evolu_e[e1,1] = perD\n perT_evolu_e[e1,0] = time_1 - time_0\n perT_evolu_e[e1,1] = perT\n # End for-loop-1 iterating i: num_btach\n # time_1 = int(time.time()) # record the time when betaO, D, T are completely updated after the whole epoch\n # count_uzo_t, count_uzd_t, count_uzt_t, likelihood_t = \\\n # model_test.new_doc_infer(test_docs=test_docs, betaO=betaO, betaD=betaD, betaT=betaT, \\\n # idx_corpus_o=idx_corpus_o, idx_corpus_d=idx_corpus_d, idx_corpus_t=idx_corpus_t)\n \n # likelihood_evolu_e[e,0] = time_1 - time_0\n # likelihood_evolu_e[e,1] = likelihood_t\n \n # perO = perlexity(test_docs[\"O\"], idx_corpus_o[M:], alpha, count_uzo_t, betaO)\n # perD = perlexity(test_docs[\"D\"], idx_corpus_d[M:], alpha, count_uzd_t, betaD)\n # perT = perlexity(test_docs[\"T\"], idx_corpus_t[M:], alpha, count_uzt_t, betaT)\n \n # perO_evolu_e[e,0] = time_1 - time_0\n # perO_evolu_e[e,1] = perO\n # perD_evolu_e[e,0] = time_1 - time_0\n # perD_evolu_e[e,1] = perD\n # perT_evolu_e[e,0] = time_1 - time_0\n # perT_evolu_e[e,1] = perT\n #!!! then we need to normalize betaO,D,T again\n # End for-loop-2 iterating e: num_epoch\n \n perplexity_matrix[lam_k,:] = [lam_v, perO, perD, perT]\n #np.save(save_dir+'/perplexity'+'_lam'+f'_{lam_v}'+'_.npy', perplexity_matrix)\n \n likelihood_matrix[lam_k,:] = [lam_v, likelihood_t]\n #np.save(save_dir+'/likelihood'+'_lam'+f'_{lam_v}'+'_.npy', likelihood_matrix)\n\n np.save(save_dir+'/betaO'+'_lam'+f'_{lam_v}'+'_.npy', betaO)\n #np.save(save_dir+'/gradientO'+'_lam'+f'_{lam_v}'+'_.npy', gradientO)\n #np.save(save_dir+'/hessianO'+'_lam'+f'_{lam_v}'+'_.npy', hessianO)\n \n np.save(save_dir+'/betaD'+'_lam'+f'_{lam_v}'+'_.npy', betaD)\n np.save(save_dir+'/betaT'+'_lam'+f'_{lam_v}'+'_.npy', betaT)\n \n np.save(save_dir+'/gamma'+'_lam'+f'_{lam_v}'+'_.npy', gamma)\n np.save(save_dir+'/theta'+'_lam'+f'_{lam_v}'+'_.npy', theta)\n MTRobot.sendtext(worker_idx, f'saved all results for lambda {lam_v}')\n \n \n \n \n\n\n\n \n","sub_path":"Source/main_GR_TensorLDA_OnlineLearning_setting4_for_5k.py","file_name":"main_GR_TensorLDA_OnlineLearning_setting4_for_5k.py","file_ext":"py","file_size_in_byte":14173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"29026549","text":"from __future__ import division\nimport itertools\nimport logging\nfrom multiprocessing import cpu_count\nimport os\nimport os.path as op\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.spatial import cKDTree\n\nfrom catalog import read_catalog\nfrom parimap import parimap\nfrom util import set_percentage\n\n\nlogging.basicConfig()\n\n\ndef set_phases(p):\n if isinstance(p, basestring):\n return list(p)\n return p\n\n\ndef set_outdir(d=None):\n if not d:\n return os.getcwd()\n return op.abspath(d)\n\n\ndef set_nprocs(n):\n if n <= -1:\n return cpu_count()\n return n\n\n\ndef calcSTATIC(hypfiles, nres_min, phases='P', outdir=None, nprocs=1,\n **kwargs):\n logger = logging.getLogger('calcSTATIC')\n logger.setLevel(logging.INFO)\n\n phases = set_phases(phases)\n nprocs = set_nprocs(nprocs)\n outdir = set_outdir(outdir)\n\n # Get the raw data and select picks whose phase types are in `phases`\n logger.info(\" Extract raw data from input hypocenter-phase files:\")\n DST = DataForST(hypfiles, nprocs=nprocs)\n subitems = [x for x in DST.picks.items if x[1] in phases]\n PhPicks = DST.picks.loc[subitems].copy(True)\n\n # Important: open output delay file in `append` mode\n delayFile = op.join(outdir, 'static.timecorr')\n header = \"# Event Phase Nres TimeCorr[s]\\n\"\n linefmt = \"LOCDELAY %s %s %6d %8.4f\\n\"\n\n logger.info(' Started station terms calculation')\n with open(delayFile, 'a') as f:\n f.write(header)\n for (st, ph) in PhPicks.items:\n R = PhPicks[st, ph]['Residual'].dropna().get_values()\n if R.shape[0] < nres_min:\n tcorr, nres = 0.0, -1\n else:\n tcorr, nres = np.mean(R), R.shape[0]\n\n f.write(str(linefmt % (st.ljust(8), ph.ljust(5), nres, tcorr)))\n msg = \" Finished. Saved delay file.\"\n logger.info(msg)\n\n return delayFile\n\n\ndef calcSSST(hypfiles, K_max, K_min, R, phases='P', outdir=None, nprocs=1):\n logger = logging.getLogger('calcSSST')\n logger.setLevel(logging.INFO)\n\n phases = set_phases(phases)\n nprocs = set_nprocs(nprocs)\n\n # Get the raw data and select picks whose phase types are in `phases`\n logger.info(\" Extract raw data from input hypocenter-phase files:\")\n DST = DataForST(hypfiles, nprocs=nprocs)\n subitems = [x for x in DST.picks.items if x[1] in phases]\n PhPicks = DST.picks.loc[subitems].copy(True)\n\n # Add a new column indicationg \"number of neighbors\"\n PhPicks.loc[:, :, 'k_NN'] = -1\n\n # Index of data-frames in `PhPicks` panel for which finding k-nearest-\n # neighbors (k-NN) makes sense (use Ne-1 to exclude the center point)\n ind = [j for j in range(PhPicks.shape[0]) if\n (PhPicks.iloc[j, :, :].dropna().shape[0] - 1) >= K_min]\n\n # Used later for logger INFO\n Nsp = len(ind)\n D = set_percentage(Nsp, 5)\n\n logger.info(' Started station terms calculation')\n for ii, (st, ph) in enumerate(PhPicks.items):\n # Catch the picks data-frame\n phDF = PhPicks.loc[(st, ph)].copy(deep=True)\n phDF.dropna(axis='index', how='any', inplace=True)\n\n # Check if finding k-nearest neighbors makes sense\n # (set Ne-1 to exclude the center point)\n if (phDF.shape[0] - 1) <= K_min:\n continue\n\n # Grab the events recorded at station `st`\n eqDF = DST.events.loc[phDF.index, ('X', 'Y', 'Z')]\n\n points = eqDF.get_values()\n for ip, p in enumerate(points):\n try:\n # Set K+1 since the `center` point is also in `points`\n weights, idx = findNN(p, points, K_max+1, K_min+1, R,\n nprocs=nprocs)\n\n residuals = phDF.Residual[idx].get_values()\n tcorr = np.average(residuals, weights=weights)\n knn = len(residuals)\n except TypeError:\n tcorr = 0.0\n knn = 0\n\n phDF.ix[ip, 'TimeCorr'] += tcorr\n phDF.ix[ip, 'k_NN'] += knn\n\n # Import calculated values to the main data-frame\n PhPicks.loc[(st, ph)].update(phDF)\n\n if (ii+1) in D:\n logger.info(\"%4.0f%% done, %7i station-phase pairs\" %\n (D[ii+1], ii+1))\n\n # Return those events for which new ssst is avilable\n PhPicks = PhPicks.transpose(1, 0, 2)\n d = PhPicks.minor_xs('k_NN')\n eq = [x for x in d.columns if any(d[x] != -1)]\n result = PhPicks[eq]\n\n if result.shape[0] == 0:\n logger.info(' Finished (But no station terms calculated).')\n return\n\n if not outdir:\n logger.info(' Finished.')\n return result\n else:\n def _save(item):\n cols = ('TimeCorr', 'k_NN')\n data = result.loc[item, :, cols].dropna(axis='index', how='any')\n # Convert `k_NN` column dtype to int (see NLLoc LOCDELAY)\n data.loc[:, 'k_NN'] = data.loc[:, 'k_NN'].astype(int)\n\n linefmt = \"LOCDELAY %s %s %6d %8.4f\\n\"\n delfile = op.join(outdir, item + '.ssst.timecorr')\n with open(delfile, 'w') as f:\n f.write(\"# Event Phase k_NN TimeCorr[s]\\n\")\n for d in sorted(data.itertuples()):\n st, ph = d[0]\n f.write(str(linefmt % (st.ljust(8), ph.ljust(5),\n d[-1], d[-2])))\n return delfile\n\n # Save to ascii files and return delay file names\n items_all = result.items\n if nprocs == 1:\n df = list(itertools.imap(_save, items_all))\n else:\n df = list(parimap(_save, items_all, nprocs=nprocs))\n\n logger.info(\" Finished. Saved delay files.\")\n return df\n\n\nclass DataForST(object):\n \"\"\"\n Read located event files and prepare information required for station terms\n calculation.\n \"\"\"\n\n def __init__(self, hypfiles, nprocs=1):\n self._hypfiles = hypfiles\n self._nprocs = set_nprocs(nprocs)\n self.events, self.picks = self._extract()\n\n def _extract(self):\n \"\"\"\n Make a Pandas DataFrame of all earthquakes in the bulletin data set\n and also a Panel in which the items are station codes and major axis\n are event IDs.\n\n :returns: A data frame of all located events in the catalog.\n :rtype: pandas.core.frame.DataFrame\n :returns: If requested, a panel of phase information.\n :rtpe: pandas.core.panel.Panel\n\n ### The output events data-frame:\n\n | index | X | Y | Z |\n |:------:|:---:|:---:|:---:|\n | EQid_1 | X_1 | Y_1 | Z_1 |\n | EQid_n | X_2 | Y_2 | Z_n |\n\n\n ### The output station-phase panel:\n It has a 2-level MultiIndex items, so that the values of the 1st and\n 2nd levels are station codes and phase types, respectively, i.e. Item\n axis: (StaCode, Phase). The data-frames of the output panel for a given\n station-phase pair would be like this:\n Example:\n\n | index | Residual | TimeCorr |\n |:------:|:--------:|:--------:|\n | EQid_1 | res_1 | t_1 |\n | EQid_n | res_n | t_n |\n\n \"\"\"\n earthquakes = read_catalog(self._hypfiles, 'NLLOC_OBS',\n phase_data=True, nprocs=self._nprocs)\n\n Ne = len(earthquakes)\n index = xrange(Ne)\n columns = ['X', 'Y', 'Z']\n events_df = pd.DataFrame(index=index, columns=columns, dtype=np.float)\n eq2sta = {}\n\n for ieq, eq in enumerate(earthquakes):\n # Just to be on the safe side\n if eq:\n events_df.ix[ieq, columns] = (eq.X, eq.Y, eq.Z)\n\n eqID = op.basename(eq.obsfile).split('.')[0]\n events_df.rename(index={ieq: eqID}, inplace=True)\n scols = ['Residual', 'TimeCorr']\n eq2sta[eqID] = eq.phase_data[scols].transpose()\n else:\n continue\n\n # --- Make a Panel for picks ---\n picks_pnl = None\n if eq2sta:\n picks_pnl = pd.Panel.from_dict(eq2sta,\n orient='minor',\n dtype=np.float)\n picks_pnl = picks_pnl.transpose(0, 2, 1)\n\n return (events_df, picks_pnl)\n\n\ndef findNN(x, points, k_max, k_min, r, dist_weight=False, nprocs=1):\n \"\"\"\n Find the neighbors of point x located within distance r by searching\n against `points`. Suppose K is the total number of neighbors within radius\n r from x;\n If K >= k_max, it returns k_max nearest neighbors.\n If k_min <= K < k_max, it returns all K neighbors.\n If K < k_min, it returns None.\n\n :param array_like x: The point to search for neighbors of (center point).\n :param array_like points: The data points to be indexed.\n :param int k_max: The maximum number of nearest neighbors to return.\n :param int k_min: The minimum number of neighbors to return.\n :param float r: Returns only neighbors within this distance.\n :param bool dist_weight: If True, gives distance weights to neighbors.\n :returns w: Weight values.\n :rtype: array of floats\n :returns i: The index of neighbors in the original points cloud.\n :rtype: ndarray of ints\n \"\"\"\n tree = cKDTree(points)\n\n # To include neighbors exactly located at distance r\n r_dummy = r + 1e-6\n\n # The index of neighbors in the KDTree\n dist, idxT = tree.query(x, k=k_max, eps=0, p=2,\n distance_upper_bound=r_dummy, n_jobs=nprocs)\n\n if np.any(np.isinf(dist)):\n # found less than k_max neighbors\n b = ~np.isinf(dist)\n N = np.sum(b)\n if N < k_min:\n return\n else:\n dist = dist[b]\n idxT = idxT[b]\n else:\n N = k_max\n\n if dist_weight:\n weights = np.apply_along_axis(np.vectorize(calcWd), 0, dist, r)\n else:\n weights = np.ones(N)\n\n # The neighboring points in the KDTree\n neighbors = tree.data[idxT]\n\n # The index of neighbors in the original points cloud\n # Unnecessary! Just to be on the safe side?!\n idxP = np.all(points[:, None, :] == neighbors[None, :, :], axis=-1)\n idxP = np.where(np.any(idxP, axis=1))[0].tolist()\n\n return (weights, idxP)\n\n\ndef calcWd(dist, cutoff, a=3, b=3):\n \"\"\"\n Calculate distance weight using a biweight function.\n\n :param float d: Hypocentral separation distance of two events.\n :param float c: Cutoff value (maximum separation).\n :param int a, b:\n Exponents defining the shape of the weighting curve (default: bicubic\n function (a=b=3)).\n :returns float w: Distance weight value.\n \"\"\"\n\n if dist > cutoff:\n return 0.0\n return pow(1-(dist/cutoff)**a, b)\n","sub_path":"stacorr.py","file_name":"stacorr.py","file_ext":"py","file_size_in_byte":10773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"208819569","text":"from django import forms\n\nfrom questions.models import Question\nfrom questions.tables import QUESTION_FIELD_SEQUENCE\nfrom tags.models import Tag\n\n\nQUESTION_READONLY_FORM_FIELDS = [\"author\", \"validation_status\"]\nQUESTION_REQUIRED_FORM_FIELDS = [\"answer_option_a\", \"answer_option_b\", \"answer_correct\"]\nQUESTION_FORM_FIELDS = [\n field_name for field_name in QUESTION_FIELD_SEQUENCE if field_name not in Question.QUESTION_READONLY_FIELDS\n]\n\n\nclass QuestionCreateForm(forms.ModelForm):\n class Meta:\n model = Question\n fields = QUESTION_FORM_FIELDS + QUESTION_READONLY_FORM_FIELDS\n widgets = {\n \"text\": forms.Textarea(attrs={\"rows\": 1}),\n \"hint\": forms.Textarea(attrs={\"rows\": 1}),\n \"answer_explanation\": forms.Textarea(attrs={\"rows\": 3}),\n \"answer_reading_recommendation\": forms.Textarea(attrs={\"rows\": 1}),\n \"answer_image_explanation\": forms.Textarea(attrs={\"rows\": 1}),\n \"answer_extra_info\": forms.Textarea(attrs={\"rows\": 3}),\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields[\"tags\"].queryset = Tag.objects.all().order_by(\"name\")\n for field_name in QUESTION_READONLY_FORM_FIELDS:\n self.fields[field_name].disabled = True\n for field_name in QUESTION_REQUIRED_FORM_FIELDS:\n self.fields[field_name].required = True\n\n\nclass QuestionEditForm(QuestionCreateForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields[\"validation_status\"].disabled = False\n","sub_path":"backend/questions/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"218488553","text":"def combine(inp):\n return combine_helper(inp, [], [])\n\nclass my_dictionary(dict):\n def init(self):\n self = dict()\n\n def add(self, key, value):\n self[key] = value\n\ndef combine_helper(inp, temp, ans):\n for i in range(len(inp)):\n current = inp[i]\n remaining = inp[i + 1:]\n temp.append(current)\n ans.append(tuple(temp))\n combine_helper(remaining, temp, ans)\n temp.pop()\n return ans\n\ncount = 0;\ngoodieDict = my_dictionary()\nfile1 = open(\"sample_input.txt\",\"r\")\nfor x in file1:\n count+=1\n if count>=5 :\n (key, val) = x.split(\": \")\n if val[-1]==\"\\n\":\n val = val.rstrip(val[-1])\n goodieDict[(key)] = val;\n elif count==1 :\n (numEmpTxt, numEmp) = x.split(\": \")\n\nprint(goodieDict)\npriceList = list(goodieDict.values())\nfor i in range(0, len(priceList)):\n priceList[i] = int(priceList[i])\n\ndict_obj = my_dictionary()\na = combine(priceList)\nfor i in a:\n if(len(i) == (int(numEmp))):\n nt = sorted(i)\n diffValue = nt[(int(numEmp)-1)] - nt[0]\n dict_obj.key = diffValue\n dict_obj.value = nt\n dict_obj.add(dict_obj.key, dict_obj.value)\n\nkeyList = dict_obj.keys()\nsortedKeyList = sorted(keyList)\n\nfinalPriceList = dict_obj.get(sortedKeyList[0])\n\nf = open(\"sample_output.txt\", \"w\")\nf.write(\"The goodies selected for distribution are:\\n\\n\")\nfor pricee in finalPriceList:\n for keey in goodieDict.keys():\n if pricee == int(goodieDict[keey]):\n f.write(keey+\": \"+str(pricee)+\"\\n\")\nf.write(\"\\n\")\n\ndifferencePrice = finalPriceList[(int(numEmp)-1)] - finalPriceList[0]\nf.write(\"And the difference between the chosen goodie with highest price and the lowest price is \"+str(differencePrice))\nf.close()","sub_path":"harshitha solution.py","file_name":"harshitha solution.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"338200255","text":"import os\nimport numpy as np\nimport networkx as nx\n\nimport ccmgp.utils.utils as utils\nfrom ccmgp.utils.judge import Judge\nimport ccmgp.utils.tag_manager as tagM\nfrom ccmgp.utils.data_helper import DataHelper\nfrom ccmgp.mgenre_embedding.graph_mappers import GraphDistanceMapper\nfrom ccmgp.mgenre_embedding.mappers import RetrofitEmbsMapper\n\n\nfrom datetime import datetime\nstartTime = datetime.now()\nfor source in utils.langs:\n for target in utils.langs:\n if target == 'en':\n continue\n if source == target:\n target = 'en'\n print(source, '->', target)\n tm = tagM.TagManager.get([source], target)\n datapath = os.path.join(utils.FOLDS_DIR, \"{0}_from_{1}_3-fold.tsv\".format(target, source))\n print(datapath)\n dhelper = DataHelper(tm, dataset_path=datapath)\n judge = Judge()\n mappers = {}\n graph_file = ''.join([utils.GRAPH_DIR, '_'.join(sorted([source, target])), \"_graph.graphml\"])\n G = nx.read_graphml(graph_file)\n mappers['dbp_nndist'] = GraphDistanceMapper(tm, G)\n f = '_'.join(['wavg'] + sorted([source, target]) + ['graph_unaligned_weighted.csv'])\n mappers['rfit_unaligned_ft_wavg'] = RetrofitEmbsMapper(tm, os.path.join(utils.RETRO_EMB_DIR, f), 'wavg')\n f = '_'.join(['wavg'] + sorted([source, target]) + ['graph_unknown', target, 'weighted.csv'])\n mappers['rfit_aligned_ft_wavg_unknown_target'] = RetrofitEmbsMapper(tm, os.path.join(utils.RETRO_EMB_DIR, f), 'wavg')\n f = '_'.join(['wavg'] + sorted([source, target]) + ['graph_unknown', source, 'weighted.csv'])\n mappers['rfit_aligned_ft_wavg_unknown_source'] = RetrofitEmbsMapper(tm, os.path.join(utils.RETRO_EMB_DIR, f), 'wavg')\n for name in mappers:\n print(name)\n mapper = mappers[name]\n results = []\n for fold in range(3):\n eval_data, eval_target = dhelper.get_test_data(fold=fold)\n eval_predicted = mapper.predict_scores(eval_data)\n res = judge.compute_macro_metrics(eval_target, eval_predicted)\n results.append(res)\n print('auc_macro mean ', \"%.1f\" % (np.mean(results) * 100))\n print('auc_macro std ', \"%.1f\" % (np.std(results) * 100))\nprint(datetime.now() - startTime)\n","sub_path":"ccmgp/experiments/compute_table6_results.py","file_name":"compute_table6_results.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"168887935","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nThe MIT License (MIT)\nCopyright (c) 2018-2019 laggycomputer\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport asyncio\nimport logging\nimport platform\nimport random\nimport traceback\n\nimport discord\nfrom discord.ext import commands\nfrom ext.utils import apiToHuman\n\nimport config\nimport redis\n\nlogger = logging.getLogger(\"discord\")\nlogger.setLevel(config.loglevel)\nif config.clearLog:\n handler = logging.FileHandler(filename=config.logpath, encoding=\"utf-8\", mode=\"w\")\nelse:\n handler = logging.FileHandler(filename=config.logpath, encoding=\"utf-8\", mode=\"a\")\nhandler.setFormatter(logging.Formatter(\"%(asctime)s: %(levelname)s: %(name)s: %(message)s\"))\nlogger.addHandler(handler)\n\nclass theBot(commands.Bot):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.redis = None\n self.bg_task = self.loop.create_task(self.playingstatus())\n\n startup_extensions = [\"jishaku\", \"ext.text\", \"ext.rand\", \"ext.docs\", \"ext.mod\", \"ext.info\", \"ext.help\"]\n\n for extension in startup_extensions:\n try:\n self.load_extension(extension)\n print(f\"Loaded module {extension}. yay\")\n except Exception as e:\n exc = f\"{e.__name__}: {e}\"\n print(f\"Failed to load extension {extension}\\n{exc}\")\n\n async def on_ready(self):\n\n if not self.redis:\n self.redis = redis.Redis()\n await self.redis.connect()\n\n print(f\"Logged in as {self.user.name} (UID {self.user.id}) | Connected to {len(self.guilds)} servers and their combined {len(set(client.get_all_members()))} members\")\n print(\"-\" * 8)\n print(f\"Current discord.py version: {discord.__version__} | Current Python version: {platform.python_version()}\")\n print(\"-\" * 8)\n print(f\"Use this link to invite this bot:\")\n print(f\"https://discordapp.com/oauth2/authorize?client_id={self.user.id}&scope=bot&permissions=8\")\n print(\"-\" * 8)\n\n async def on_message(self, message):\n try:\n print(f\"Got message '{message.content}'\")\n except UnicodeDecodeError:\n print(\"Message content not printable\")\n\n if len(message.embeds) > 0:\n embeds = \"\"\n for emb in message.embeds:\n embeds += str(emb.to_dict())\n print(f\"With embed(s):\\n{embeds}\")\n\n print(f\"From @{message.author}\")\n print(f\"In server {message.guild}\")\n print(f\"In channel {message.channel}\")\n\n if message.author.bot:\n return\n else:\n await self.track_message(f\"tracked_message {message.id}\")\n\n if isinstance(message.channel, discord.abc.GuildChannel):\n if message.channel.permissions_for(message.guild.me).send_messages:\n\n if message.content.startswith(message.guild.me.mention):\n await message.channel.send(f\":eyes: Who pinged? My prefix is `s!`. If you are in a DM with me, I do not require a prefix.\")\n\n await self.process_commands(message)\n\n else:\n if message.content.startswith(\"s!\"):\n await message.author.send(\":x: I can't send messages there! Perhaps try again elsewhere?\")\n else:\n await self.process_commands(message)\n\n\n async def track_message(self, message):\n if await self.redis.exists(message):\n return\n\n await self.redis.rpush(message, 0)\n await self.redis.expire(message, 3600)\n\n async def on_raw_message_edit(self, payload):\n if \"content\" not in payload.data:\n return\n\n channel = self.get_channel(int(payload.data[\"channel_id\"]))\n\n if channel is None:\n return\n\n message = channel._state._get_message(payload.message_id)\n if message is None:\n try:\n message = await channel.fetch_message(payload.message_id)\n except discord.HTTPException:\n return\n\n if await self.redis.exists(f\"tracked_message {payload.message_id}\"):\n await self.clear_messages(f\"tracked_message {payload.message_id}\")\n await self.process_commands(message)\n\n async def on_raw_message_delete(self, payload):\n if await self.redis.exists(payload.message_id):\n await self.clear_messages(payload.message_id)\n await self.redis.delete(payload.message_id)\n\n async def clear_messages(self, tracked_message):\n for message_data in await self.redis.lrange(tracked_message, 1, -1):\n channel_id, message_id = message_data.split(\":\")\n try:\n await self.http.delete_message(\n int(channel_id), int(message_id))\n except discord.NotFound:\n pass\n\n await self.redis.execute(\"LTRIM\", tracked_message, 0, 0)\n\n async def register_response(self, response, request):\n if await self.redis.exists(f\"tracked_message {request.id}\"):\n await self.redis.rpush(\n f\"tracked_message {request.id}\",\n f\"{response.channel.id}:{response.id}\"\n )\n\n async def playingstatus(self):\n\n await self.wait_until_ready()\n\n playing_statuses = [\n \" \",\n \"and plotting pranks\",\n \"at a robot party, brb in a bit\",\n \"being improved!\",\n \"being open source\",\n \"being SuprKewl!\",\n \"chess with Kasparov\",\n \"creeping through the shadows\",\n \"eating robot food, brb\",\n \"github.com/laggycomputer/suprkewl-bot\",\n \"helping the community\",\n \"I don't game...\",\n \"idling\",\n \"living under the MIT license!\",\n \"mafia\",\n \"meme-scrolling\",\n \"ping and run\",\n \"tag with other robots\",\n \"the attention game\",\n \"waiting for you to call me!\",\n \"werewolf\",\n \"with my dad, Too Laggy\",\n \"with my Raspberry Pi\",\n \"with the community\",\n \"with the Discord API\"\n ]\n\n while client.is_ready():\n status = f\"{random.choice(playing_statuses)} | lurking in {len(self.guilds)} servers and watching over {len(self.users)} users...\"\n\n await self.change_presence(activity=discord.Game(name=status))\n await asyncio.sleep(120)\n\n async def on_command_error(self, ctx, error):\n\n if hasattr(ctx.command, \"on_error\"):\n return\n\n ignored = (commands.CommandNotFound, commands.UserInputError)\n\n error = getattr(error, \"original\", error)\n\n def permsList(perms):\n\n if len(perms) == 0:\n return None\n else:\n if len(perms) == 1:\n return apiToHuman[perms[0]]\n else:\n fmt = \"\"\n for i in range(0, len(perms)):\n fmt += apiToHuman[i]\n fmt += \", \"\n fmt += f\"and {perms[-1]}\"\n\n return fmt\n\n if isinstance(error, ignored):\n return\n\n elif isinstance(error, commands.DisabledCommand):\n\n emb = discord.Embed(color=0xf92f2f)\n emb.add_field(name=\"Disabled Command\", value=f\":x: `{ctx.prefix}{ctx.command}` has been disabled!\")\n emb.set_thumbnail(url=self.user.avatar_url)\n emb.set_author(name=self.user.name, icon_url=self.user.avatar_url)\n emb.set_footer(text=f\"{self.description} Requested by {ctx.author}\", icon_url=ctx.author.avatar_url)\n\n return await ctx.send(embed=emb)\n\n elif isinstance(error, commands.NoPrivateMessage):\n\n emb = discord.Embed(color=0xf92f2f)\n emb.add_field(name=\"This command is disabled in DMs\", value=f\":x: `{ctx.prefix}{ctx.command}` can only be used in servers, not in DMs or DM groups.\")\n emb.set_thumbnail(url=self.user.avatar_url)\n emb.set_author(name=self.user.name, icon_url=self.user.avatar_url)\n emb.set_footer(text=f\"{self.description} Requested by {ctx.author}\", icon_url=ctx.author.avatar_url)\n\n return await ctx.send(embed=emb)\n\n elif isinstance(error, commands.CommandOnCooldown):\n\n retry = round(error.retry_after, 2)\n\n emb = discord.Embed(color=0xf92f2f)\n emb.add_field(name=\"Command on Cooldown\",\n value=f\"Woah there! You just triggered a cooldown trying to run `{ctx.prefix}{ctx.command}`. I'll let you know you can start it after the cooldown of {retry} seconds is over.\")\n emb.set_thumbnail(url=self.user.avatar_url)\n emb.set_author(name=self.user.name, icon_url=self.user.avatar_url)\n emb.set_footer(text=f\"{self.description} Requested by {ctx.author}\", icon_url=ctx.author.avatar_url)\n\n msg = await ctx.send(embed=emb)\n\n await asyncio.sleep(retry)\n\n await ctx.send(f\"{ctx.author.mention} The cooldown is over!\")\n\n return msg\n\n elif isinstance(error, commands.MissingPermissions):\n\n emb = discord.Embed(color=0xf92f2f)\n missingPerms = permsList(error.missing_perms)\n emb.add_field(name=\"User Missing Permissions\", value=f\":x: Permission denied to run `{ctx.prefix}{ctx.command}`. You need to be able to {missingPerms}.\")\n emb.set_thumbnail(url=self.user.avatar_url)\n emb.set_author(name=self.user.name, icon_url=self.user.avatar_url)\n emb.set_footer(text=f\"{self.description} Requested by {ctx.author}\", icon_url=ctx.author.avatar_url)\n\n return await ctx.send(embed=emb)\n\n elif isinstance(error, commands.BotMissingPermissions):\n\n emb = discord.Embed(color=0xf92f2f)\n missingPerms = permsList(error.missing_perms)\n emb.add_field(name=\"Bot Missing Permissions\", value=f\":x: I don't have the proper permissions to run `{ctx.prefix}{ctx.command}`. I need to be allowed to {missingPerms}.\")\n emb.set_thumbnail(url=self.user.avatar_url)\n emb.set_author(name=self.user.name, icon_url=self.user.avatar_url)\n emb.set_footer(text=f\"{self.description} Requested by {ctx.author}\", icon_url=ctx.author.avatar_url)\n\n return await ctx.send(embed=emb)\n\n print(f\"Ignoring exception in command {ctx.prefix}{ctx.command}:\")\n\n traceback.print_exception(type(error), error, error.__traceback__)\n\n\nasync def get_pre(bot, message):\n if isinstance(message.channel, discord.DMChannel):\n return [\"s!\", \"\"]\n else:\n return \"s!\"\n\nclient = theBot(\n status=discord.Status.idle,\n command_prefix=get_pre,\n description=\"Did you know? If you are in a DM with me, you don't need a prefix!\",\n)\n\nif config.token == \"\":\n raise ValueError(\"Please set your token in the config file.\")\nelse:\n try:\n client.run(config.token)\n except discord.LoginFailure:\n print(\"Invalid token passed, exiting.\")\n","sub_path":"suprkewl-bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"137087076","text":"# Copyright (C) 2019 The Raphielscape Company LLC.\n#\n# Licensed under the Raphielscape Public License, Version 1.b (the \"License\");\n# you may not use this file except in compliance with the License.\n#\n\nfrom telethon.errors import ImageProcessFailedError, PhotoCropSizeSmallError\nfrom telethon.errors.rpcerrorlist import UsernameOccupiedError\nfrom telethon.tl.functions.account import (UpdateProfileRequest,\n UpdateUsernameRequest)\nfrom telethon.tl.functions.photos import UploadProfilePhotoRequest\nfrom telethon.tl.types import MessageMediaPhoto\n\nfrom userbot import bot, HELPER\nfrom userbot.events import register\n\n\n# ====================== CONSTANT ===============================\nINVALID_MEDIA = \"```The extension of the media entity is invalid.```\"\nPP_CHANGED = \"```Profile Picture Changed```\"\nPP_TOO_SMOL = \"```The image is too small```\"\nPP_ERROR = \"```Failure while processing image```\"\n\nBIO_SUCCESS = \"```Successfully edited Bio```\"\n\nNAME_OK = \"```Your name was succesfully changed```\"\nUSERNAME_SUCCESS = \"```Your username was succesfully changed```\"\nUSERNAME_TAKEN = \"```This username is already taken```\"\n#===============================================================\n\n@register(outgoing=True, pattern=\"^.name \")\nasync def update_name(name):\n if not name.text[0].isalpha() and name.text[0] not in (\"/\", \"#\", \"@\", \"!\"):\n text = name.text.split(\" \", 1)[1]\n name = text.split(\"\\\\n\", 1)\n\n firstname = name[0]\n lastname = \" \"\n if len(name) == 2:\n lastname = name[1]\n\n await UpdateProfileRequest(\n first_name=firstname,\n last_name=lastname)\n await name.edit(NAME_OK)\n\n@register(outgoing=True, pattern=\"^.profilepic$\")\nasync def set_profilepic(propic):\n if not propic.text[0].isalpha() and propic.text[0] not in (\"/\", \"#\", \"@\", \"!\"):\n replymsg = await propic.get_reply_message()\n photo = None\n if replymsg.media:\n if isinstance(replymsg.media, MessageMediaPhoto):\n photo = await bot.download_media(message=replymsg.photo)\n elif \"image\" in replymsg.media.document.mime_type.split('/'):\n photo = await bot.download_file(replymsg.media.document)\n else:\n await propic.edit(INVALID_MEDIA)\n\n if photo:\n try:\n await bot(UploadProfilePhotoRequest(\n await bot.upload_file(photo)\n ))\n await propic.edit(PP_CHANGED)\n except PhotoCropSizeSmallError:\n await propic.edit(PP_TOO_SMOL)\n except ImageProcessFailedError:\n await propic.edit(PP_ERROR)\n\n\n@register(outgoing=True, pattern=\"^.setbio \")\nasync def set_biograph(setbio):\n if not setbio.text[0].isalpha() and setbio.text[0] not in (\"/\", \"#\", \"@\", \"!\"):\n newbio = setbio.text.split(\" \", 1)[1]\n await UpdateProfileRequest(about=newbio)\n await setbio.edit(BIO_SUCCESS)\n\n\n@register(outgoing=True, pattern=\"^.username \")\nasync def update_username(username):\n if not username.text[0].isalpha() and username.text[0] not in (\"/\", \"#\", \"@\", \"!\"):\n text = username.text.split(\" \", 1)[1]\n try:\n await bot(UpdateUsernameRequest(text))\n await username.edit(USERNAME_SUCCESS)\n except UsernameOccupiedError:\n await username.edit(USERNAME_TAKEN)\n","sub_path":"userbot/modules/userdata.py","file_name":"userdata.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"558646684","text":"#!/usr/bin/env python\n\n\"\"\"Create initial database scheme.\"\"\"\n\nimport argparse\n\nfrom sqlalchemy import (\n create_engine,\n Column, Integer, String, ForeignKey\n)\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, sessionmaker\n\nfrom kisqpy.common import config\n\n\nBase = declarative_base()\n\n\nclass Client(Base):\n \"\"\"Client DAO representation.\"\"\"\n\n __tablename__ = \"client\"\n\n id = Column(Integer, primary_key=True)\n first_name = Column(String(64), nullable=False)\n last_name = Column(String(64), nullable=False)\n\n\nclass Address(Base):\n \"\"\"Address DAO representation.\"\"\"\n\n __tablename__ = \"address\"\n\n id = Column(Integer, primary_key=True)\n street_name = Column(String(64))\n street_number = Column(String(64))\n post_code = Column(String(64), nullable=False)\n client_id = Column(Integer, ForeignKey(\"client.id\"))\n client = relationship(Client)\n\n\ndef create_scheme(args):\n \"\"\"Create initial scheme.\"\"\"\n\n if not args.yes:\n return\n\n engine = create_engine(config.DB_URI)\n Base.metadata.create_all(engine)\n\n\ndef create_testing(args):\n \"\"\"Fill database by testing entities.\"\"\"\n\n if not args.yes:\n return\n\n engine = create_engine(config.DB_URI)\n Base.metadata.bind = engine\n DBSession = sessionmaker(bind=engine)\n session = DBSession()\n\n new_client = Client(first_name=\"Tasty\", last_name=\"Tester\")\n session.add(new_client)\n session.commit()\n\n session.add(Address(post_code=\"00000\", client=new_client))\n session.commit()\n\n\ndef parse_args():\n \"\"\"Parse incoming arguments.\"\"\"\n\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers()\n\n # sub_drop = subparsers.add_parser(\"drop\", help=\"drop selected DB\")\n # sub_drop.add_argument(\"dbname\", help=\"DB name to drop\")\n\n sub_scheme = subparsers.add_parser(\"scheme\", help=\"create DB scheme\")\n sub_scheme.add_argument(\"--yes\", action=\"store_true\", help=\"really create\")\n sub_scheme.set_defaults(func=create_scheme)\n\n sub_testing = subparsers.add_parser(\"testing\", help=\"fill DB by some data\")\n sub_testing.add_argument(\n \"--yes\", action=\"store_true\", help=\"really create\")\n sub_testing.set_defaults(func=create_testing)\n\n args = parser.parse_args()\n return args\n\n\ndef main():\n \"\"\"Entry point.\"\"\"\n\n args = parse_args()\n args.func(args)\n","sub_path":"kisqpy/createdb.py","file_name":"createdb.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"126637962","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Flask-markdown-blog\n\nfrom flask import (Flask, render_template, request, g, redirect, url_for,\n session, flash)\nfrom flask.ext.bcrypt import Bcrypt\nfrom models import *\nfrom playhouse.flask_utils import object_list, get_object_or_404\nfrom slugify import slugify\nfrom datetime import datetime\nimport functools\n\n\napp = Flask(__name__)\napp.secret_key = 'shhh, secret!'\nbcrypt = Bcrypt(app)\n\n\n@app.before_request\ndef before_request():\n g.db = db\n g.db.connect()\n\n\n@app.after_request\ndef after_request(response):\n g.db.close()\n return response\n\n\ndef login_required(fn):\n @functools.wraps(fn)\n def inner(*args, **kwargs):\n if session.get('logged_in'):\n return fn(*args, **kwargs)\n return redirect(url_for('login', next=request.path))\n return inner\n\n\n# Routes\n@app.route('/')\ndef index():\n blog_posts = Post.select().where(Post.published==True).order_by(\n Post.timestamp.desc())\n return object_list('index.html', query=blog_posts, context_variable='posts',\n paginate_by=5)\n\n\n@app.route('/')\ndef post(slug):\n entry = get_object_or_404(Post, (Post.slug == slug))\n return render_template('post.html', post=entry)\n\n\n@app.route('/login/', methods=['GET', 'POST'])\ndef login():\n next_url = request.args.get('next') or request.form.get('next')\n if request.method == 'POST':\n username = request.form.get('username')\n password = request.form.get('password')\n try:\n user = User.get(User.username == username)\n except User.DoesNotExist:\n flash('Incorrect username or password.', 'danger')\n return render_template('login.html', next_url=next_url)\n if bcrypt.check_password_hash(user.password, password):\n session['logged_in'] = True\n session['username'] = user.username\n session.permanent = True # Use cookie to store session.\n flash('Logged in.', 'success')\n return redirect(next_url or url_for('index'))\n else:\n flash('Incorrect username or password.', 'danger')\n return render_template('login.html', next_url=next_url)\n\n\n@app.route('/logout/')\n@login_required\ndef logout():\n session.clear()\n return redirect(url_for('index'))\n\n\n@app.route('/create/', methods=['GET', 'POST'])\n@login_required\ndef create():\n if request.method == 'GET':\n return render_template('create.html')\n else:\n # If preview button has been clicked\n if request.form.get('preview'):\n entry = Post()\n entry.title = request.form.get('title')\n entry.subtitle = request.form.get('subtitle')\n entry.content = request.form.get('content')\n return render_template('preview.html', post=entry)\n Post.create(title=request.form.get('title'),\n slug=slugify(request.form.get('title')),\n subtitle=request.form.get('subtitle'),\n content=request.form.get('content'),\n published=request.form.get('published') or False,\n timestamp=datetime.now()\n )\n return redirect(url_for('index'))\n\n\n@app.route('//edit/', methods=['GET', 'POST'])\n@login_required\ndef edit(slug):\n entry = get_object_or_404(Post, (Post.slug == slug))\n if request.method == 'GET':\n return render_template('edit.html', post=entry)\n else:\n # If preview button has been clicked\n if request.form.get('preview'):\n entry = Post()\n entry.title = request.form.get('title')\n entry.subtitle = request.form.get('subtitle')\n entry.content = request.form.get('content')\n return render_template('preview.html', post=entry)\n entry.title = request.form.get('title')\n entry.subtitle = request.form.get('subtitle')\n entry.content = request.form.get('content')\n entry.published = request.form.get('published') or False\n if request.form.get('timestamp'):\n entry.timestamp = datetime.now()\n entry.save()\n return redirect(url_for('index'))\n\n\n@app.route('//delete/', methods=['GET'])\n@login_required\ndef delete(slug):\n entry = get_object_or_404(Post, (Post.slug == slug))\n entry.delete_instance()\n return redirect(url_for('admin'))\n\n\n@app.route('/admin/')\n@login_required\ndef admin():\n blog_posts = Post.select().order_by(Post.timestamp.desc())\n return object_list('admin.html', query=blog_posts, context_variable='posts',\n paginate_by=5)\n\n\n@app.route('/about/')\ndef about():\n return render_template('about.html')\n\n\n@app.route('/projects/')\ndef projects():\n return render_template('projects.html')\n\n@app.route('/contact/')\ndef contact():\n return render_template('contact.html')\n\n\n# Run app\nif __name__ == \"__main__\":\n db.create_tables([User, Post], safe=True)\n app.run(host='0.0.0.0')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"124810000","text":"'''\n\tDeveloper: Cesar Herdenez\n\tE-mail:bash5426@gmail.com\n'''\nimport webapp2 \nfrom asciichan import * \nfrom user_tool import *\n\n## Inicio de la aplicaion\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n self.response.write('Usando Modulos')\n self.response.write('Hello, Udacity!')\n## \nclass HBD(webapp2.RequestHandler):\n def write_form(self, error=\"\", month=\"\", day=\"\", year=\"\"):\n self.response.out.write(form %{\"error\": error, \n \t\t\t\t\t\t\t\t\"month\":escape_html(month), \n \t\t\t\t\t\t\t\t\"day\": escape_html(day),\n \t\t\t\t\t\t\t\t\"year\":escape_html(year) })\n\n def get(self):\n self.write_form()\n\n def post(self):\n user_month = self.request.get('month')\n user_day = self.request.get('day')\n user_year = self.request.get('year')\n\n month = valid_month(user_month)\n day = valid_day(user_day)\n year = valid_year(user_year)\n\n if not(month and day and year):\n self.write_form(\"That doesn't look valid to me, friend.\", \n\t\t\t\t\t\t\tuser_month, user_day, user_year)\n else:\n self.redirect(\"/unit2/thanks\")\n \t\n\nclass ThanskHandler(webapp2.RequestHandler):\n\tdef get(self):\n self.response.out.write(\"Thanks! That's a totally valid day!\")\n##\n\nclass ROT13(webapp2.RequestHandler):\n\t\n\tdef get(self,texto = \"\"):\n\t\tself.response.out.write(form2 %{\"texto\":texto})\n\t\t\n\tdef post(self):\n\t\ttexto = self.request.get('texto')\n\t\tif texto :\n\t\t\tself.response.out.write( form2 %{\"texto\":texto.encode('rot13')})\n\n##\nclass SignIn(webapp2.RequestHandler):\n\tdef write_form2(self,username = \"\", password = \"\", verify = \"\",\tmail = \"\"):\n\t\tself.response.out.write(form3 %{\"username\":username, \n\t\t\t\t\t\t\t\t\t\t\"password\":password, \n\t\t\t\t\t\t\t\t\t\t\"verify\":verify, \t\n\t\t\t\t\t\t\t\t\t\t\"mail\":mail}) \n\tdef get(self):\n\t\tself.write_form2()\n###\n\napp = webapp2.WSGIApplication([('/', MainPage),\n\t\t\t\t\t\t\t\t('/unit2/HBD',HBD),\n\t\t\t\t\t\t\t\t('/unit2/thanks',ThanskHandler),\n\t\t\t\t\t\t\t\t('/unit2/rot13',ROT13),\n\t\t\t\t\t\t\t\t('/unit2/SignIn',SignIn),\n\t\t\t\t\t\t\t\t('/unit3/art',AsciiArt)],debug=True)\n","sub_path":"helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"198528270","text":"\"\"\"\n\ndataset = AbstractDataset()\n\n\"\"\"\n\n\nfrom collections import OrderedDict, defaultdict\nimport json\n\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport random\n\n\ndef make_perfect_forecast(prices, horizon):\n prices = np.array(prices).reshape(-1, 1)\n forecast = np.hstack([np.roll(prices, -i) for i in range(0, horizon)])\n return forecast[:-(horizon-1), :]\n\n\ndef load_episodes(path):\n # pass in list of filepaths\n if isinstance(path, list):\n if isinstance(path[0], pd.DataFrame):\n # list of dataframes?\n return path\n else:\n # list of paths\n episodes = [Path(p) for p in path]\n print(f'loading {len(episodes)} from list')\n csvs = [pd.read_csv(p, index_col=0) for p in tqdm(episodes) if p.suffix == '.csv']\n parquets = [pd.read_parquet(p) for p in tqdm(episodes) if p.suffix == '.parquet']\n\n eps = csvs + parquets\n print(f'loaded {len(episodes)} from list')\n return eps\n\n # pass in directory\n elif Path(path).is_dir() or isinstance(path, str):\n path = Path(path)\n episodes = [p for p in path.iterdir() if p.suffix == '.csv']\n else:\n path = Path(path)\n assert path.is_file() and path.suffix == '.csv'\n episodes = [path, ]\n\n print(f'loading {len(episodes)} from {path.name}')\n eps = [pd.read_csv(p, index_col=0) for p in tqdm(episodes)]\n print(f'loaded {len(episodes)} from {path.name}')\n return eps\n\n\ndef round_nearest(x, divisor):\n return x - (x % divisor)\n\nfrom abc import ABC, abstractmethod\n\n\nclass AbstractDataset(ABC):\n def get_data(self, cursor):\n # relies on self.dataset\n return OrderedDict({k: d[cursor] for k, d in self.dataset.items()})\n\n def reset(self, mode=None):\n # can dispatch based on mode, or just reset\n # should return first obs using get_data\n return self.get_data(0)\n\n def setup_test(self):\n # called by energypy.main\n # not optional - even if dataset doesn't have the concept of test data\n # no test data -> setup_test should return True\n return True\n\n def reset_train(self):\n # optional - depends on how reset works\n raise NotImplementedError()\n\n def reset_test(self, mode=None):\n # optional - depends on how reset works\n raise NotImplementedError()\n\n\nclass RandomDataset(AbstractDataset):\n def __init__(self, n=1000, n_features=3, n_batteries=1, logger=None):\n self.dataset = self.make_random_dataset(n, n_features, n_batteries)\n self.test_done = True # no notion of test data for random data\n self.reset()\n\n def make_random_dataset(self, n, n_features, n_batteries):\n np.random.seed(42)\n # (timestep, batteries, features)\n prices = np.random.uniform(0, 100, n*n_batteries).reshape(n, n_batteries, 1)\n features = np.random.uniform(0, 100, n*n_features*n_batteries).reshape(n, n_batteries, n_features)\n return {'prices': prices, 'features': features}\n\n\nclass NEMDataset(AbstractDataset):\n def __init__(\n self,\n n_batteries,\n train_episodes=None,\n test_episodes=None,\n price_col='price [$/MWh]',\n logger=None\n ):\n self.n_batteries = n_batteries\n self.price_col = price_col\n\n train_episodes = load_episodes(train_episodes)\n self.episodes = {\n 'train': train_episodes,\n # our random sampling done on train episodes\n 'random': train_episodes,\n 'test': load_episodes(test_episodes),\n }\n\n # want test episodes to be a multiple of the number of batteries\n episodes_before = len(self.episodes['test'])\n lim = round_nearest(len(self.episodes['test'][:]), self.n_batteries)\n self.episodes['test'] = self.episodes['test'][:lim]\n assert len(self.episodes['test']) % self.n_batteries == 0\n episodes_after = len(self.episodes['test'])\n print(f'lost {episodes_before - episodes_after} test episodes due to even multiple')\n\n # test_done is a flag used to control which dataset we sample from\n # it's a bit hacky\n self.test_done = True\n self.reset()\n\n def reset(self, mode='train'):\n if mode == 'test':\n return self.reset_test()\n else:\n return self.reset_train()\n\n def setup_test(self):\n # called by energypy.main\n self.test_done = False\n self.test_episodes_idx = list(range(0, len(self.episodes['test'])))\n return self.test_done\n\n def reset_train(self):\n episodes = random.sample(self.episodes['train'], self.n_batteries)\n\n ds = defaultdict(list)\n for episode in episodes:\n episode = episode.copy()\n prices = episode.pop(self.price_col)\n ds['prices'].append(prices.reset_index(drop=True).values.reshape(-1, 1, 1))\n ds['features'].append(episode.reset_index(drop=True).values.reshape(prices.shape[0], 1, -1))\n\n # TODO could call this episode\n self.dataset = {\n 'prices': np.concatenate(ds['prices'], axis=1),\n 'features': np.concatenate(ds['features'], axis=1),\n }\n return self.get_data(0)\n\n def reset_test(self):\n episodes = self.test_episodes_idx[:self.n_batteries]\n self.test_episodes_idx = self.test_episodes_idx[self.n_batteries:]\n\n ds = defaultdict(list)\n for episode in episodes:\n episode = self.episodes['test'][episode].copy()\n prices = episode.pop(self.price_col)\n ds['prices'].append(prices.reset_index(drop=True))\n ds['features'].append(episode.reset_index(drop=True))\n\n # TODO could call this episode\n self.dataset = {\n 'prices': pd.concat(ds['prices'], axis=1).values,\n 'features': pd.concat(ds['features'], axis=1).values,\n }\n\n if len(self.test_episodes_idx) == 0:\n self.test_done = True\n\n return self.get_data(0)\n","sub_path":"energypy/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":6098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"520465910","text":"import telebot\r\nimport pyowm\r\nfrom pyowm import OWM\r\nfrom pyowm.utils import config\r\nfrom pyowm.utils import timestamps\r\nfrom pyowm.utils.config import get_default_config\r\n\r\nconfig_dict = get_default_config()\r\nconfig_dict['language'] = 'ru' \r\n\r\nowm = pyowm.OWM('6d00d1d4e704068d70191bad2673e0cc')\r\nmgr = owm.weather_manager()\r\nbot = telebot.TeleBot(\"1333118982:AAHZDvk-hwSrR8a0iYXfD49FfBcYmEjfkyo\") # You can set parse_mode by default. HTML or MARKDOWN\r\n\r\nkeyboard1 = telebot.types.ReplyKeyboardMarkup(True, True )\r\nkeyboard1.row(\"/pogoda\")\r\n\r\ngoroda = telebot.types.ReplyKeyboardMarkup(True, True )\r\ngoroda.row(\"Москва\", \"Новомосковск\", \"Тула\")\r\n\r\n@bot.message_handler(commands=[\"start\"])\r\ndef start_message(message):\r\n\tbot.send_message(message.chat.id, 'Привет\\nЭтот бот показывает осадки, температуру и скорость ветра в любом существующем городе!\\nДля начала введи /pogoda', reply_markup=keyboard1)\r\n\r\n@bot.message_handler(commands=[\"pogoda\"])\r\ndef send_pogoda(message):\r\n\tbot.send_message(message.chat.id, \"Выберите название города: \", reply_markup=goroda)\r\n\tbot.register_next_step_handler(message, pogoda)\r\n\r\n@bot.message_handler()\r\ndef pogoda(message):\r\n\tplace = message.text\r\n\ttry:\r\n\t\tobservation = mgr.weather_at_place(place)\r\n\t\tw = observation.weather\r\n\t\twild = w.wind('meters_sec')[\"speed\"]\r\n\t\twild = round(wild)\r\n\t\ttemp = w.temperature('celsius')['temp']\r\n\t\ttemp = round(temp)\r\n\t\tstat = observation.weather.detailed_status\r\n\t\tstr(stat)\r\n\r\n\t\tif wild == 1:\r\n\t\t\twmd = str(\"метр\")\r\n\t\telif temp == 2:\r\n\t\t\twmd = str(\"метра\")\r\n\t\telif wild == 3:\r\n\t\t\twmd = str(\"метра\")\r\n\t\telif wild == 4:\r\n\t\t\twmd = str(\"метра\")\r\n\t\telse:\r\n\t\t\twmd = str(\"метров\")\r\n\r\n\t\tif temp == 1:\r\n\t\t\tgradus = str(\"градус\")\r\n\t\telif temp == 2:\r\n\t\t\tgradus = str(\"градуса\")\r\n\t\telif temp == 3:\r\n\t\t\tgradus = str(\"градуса\")\r\n\t\telif temp == 4:\r\n\t\t\tgradus = str(\"градуса\")\r\n\t\telse:\r\n\t\t\tgradus = str(\"градусов\")\r\n\r\n\t\tanswer = \"В городе \" + place + \" \"+ str(stat) + \"\\n\"\r\n\t\tanswer += str(temp) + \" \" + gradus + \" по цельсию\" +\"\\n\"\r\n\t\tanswer += \"Ветер со скоростью \" + str(wild) + \" \" + wmd + \" в секунду\"\r\n\t\tbot.send_message(message.chat.id, answer)\r\n\texcept:\r\n\t\tbot.send_message(message.chat.id,'Ошибка! Город не найден.')\r\n\t\treturn\r\n\r\n\r\n\r\nbot.polling(none_stop=True)","sub_path":"tgbot.py","file_name":"tgbot.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"563158312","text":"import os\nimport shutil\nimport boto3\nfrom aws_lambda_powertools.logging import Logger\nfrom botocore.exceptions import ClientError\n\nINPUT_BUCKET = os.getenv(\"S3_INPUT_BUCKET_NAME\")\nOUTPUT_BUCKET = os.getenv(\"S3_OUTPUT_BUCKET_NAME\")\nDIRECTORY = \"/mnt/lambda\"\n\ns3 = boto3.resource(\"s3\")\nlogger = Logger()\n\n\ndef download_movie(event, context):\n \"\"\"\n 元となる動画ファイル、および書き起こしデータを\n S3 から EFS へダウンロードする関数\n\n Parameter\n ----------\n - event: Step Functions からの入力\n - job_name: Step Functions の実行名\n - file_name: S3 にアップロードされた動画のファイル名\n - context: Lambda 関数の実行コンテキスト\n\n Return\n ----------\n None\n\n \"\"\"\n\n logger.info({\"event\": event})\n job_name = event[\"job_name\"]\n file_name = event[\"file_name\"]\n\n input_dir = f\"{DIRECTORY}/{job_name}/input\"\n clipped_dir = f\"{DIRECTORY}/{job_name}/clipped\"\n os.makedirs(input_dir, exist_ok=True)\n os.makedirs(clipped_dir, exist_ok=True)\n\n transcription_file_name = f\"{job_name}.json\"\n try:\n s3.Bucket(INPUT_BUCKET).download_file(\n file_name, f\"{input_dir}/{file_name}\"\n )\n s3.Bucket(OUTPUT_BUCKET).download_file(\n transcription_file_name, f\"{input_dir}/transcription.json\"\n )\n s3.Object(OUTPUT_BUCKET, transcription_file_name).delete()\n except ClientError as e:\n logger.error({\"error\": e})\n raise\n\n return\n\n\ndef upload_movie(event, context):\n \"\"\"\n 完成した動画を S3 へアップロードする関数\n\n Parameter\n ----------\n - event: Step Functions からの入力\n - job_name: Step Functions の実行名\n - file_name: S3 にアップロードされた動画のファイル名\n - context: Lambda 関数の実行コンテキスト\n\n Return\n ----------\n None\n\n \"\"\"\n\n job_name = event[\"job_name\"]\n file_name = event[\"file_name\"]\n\n output_dir = f\"{DIRECTORY}/{job_name}/output\"\n try:\n s3.Bucket(OUTPUT_BUCKET).upload_file(\n f\"{output_dir}/{file_name}\", file_name\n )\n except ClientError as e:\n logger.error({\"error\": e})\n raise\n\n shutil.rmtree(f\"{DIRECTORY}/{job_name}\", ignore_errors=True)\n return\n","sub_path":"aws_controllers/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"325262214","text":"# -*- coding:utf-8 -*-\r\nimport os, time, requests, re\r\nfrom PIL import Image\r\nfrom tkinter import filedialog, Tk\r\nfrom time import sleep\r\nimport xml.etree.ElementTree as ET\r\nfrom hashlib import md5\r\nfrom json import loads\r\nfrom traceback import format_exc\r\nfrom re import search\r\n\r\n\r\n# 每一部jav的“结构体”\r\nclass JavFile(object):\r\n def __init__(self):\r\n self.file = 'ABC-123.mp4' # 文件名\r\n self.num = 'ABC-123' # 车牌\r\n self.search = 'ABC%20123' # 用于搜索的车牌,javbus处理不了“-”“_”,把这两个换成了“%20”\r\n self.episodes = 1 # 第几集\r\n self.subt = '' # 字幕文件名 ABC-123.srt\r\n\r\n\r\n# 获取用户选取的文件夹路径,返回路径str\r\ndef get_directory():\r\n directory_root = Tk()\r\n directory_root.withdraw()\r\n work_path = filedialog.askdirectory()\r\n if work_path == '':\r\n print('你没有选择目录! 请重新选:')\r\n sleep(2)\r\n return get_directory()\r\n else:\r\n # askdirectory 获得是 正斜杠 路径C:/,所以下面要把 / 换成 反斜杠\\\r\n return work_path.replace('/', os.sep)\r\n\r\n\r\n# 记录错误txt,无返回。记录在jav搜索后的错误。 这两个函数的区别是,“>>”和“>”,就为了能在显示报错时“整整齐齐”。\r\ndef record_fail(fail_msg):\r\n print(fail_msg, end='')\r\n txt_fai = open('【记得清理它】失败记录.txt', 'a', encoding=\"utf-8\")\r\n txt_fai.write(fail_msg)\r\n txt_fai.close()\r\n\r\n\r\n# 判断是否有除了“.actors”\"extrafanrt”的其他文件夹,存在返回True\r\ndef exist_other_folders(lst_folders):\r\n for folder in lst_folders:\r\n if folder != '.actors' and folder != 'extrafanart':\r\n return True\r\n return False\r\n\r\n\r\n# 调用百度翻译API接口,返回中文简介str\r\ndef tran(api_id, key, word, to_lang, retry):\r\n if retry == 10:\r\n print(' >翻译简介失败...请截图联系作者...')\r\n return '【百度翻译出错】' + word\r\n # 把账户、翻译的内容、时间 混合md5加密,传给百度验证\r\n salt = str(time.time())[:10]\r\n final_sign = api_id + word + salt + key\r\n final_sign = md5(final_sign.encode(\"utf-8\")).hexdigest()\r\n # 表单paramas\r\n paramas = {\r\n 'q': word,\r\n 'from': 'jp',\r\n 'to': to_lang,\r\n 'appid': '%s' % api_id,\r\n 'salt': '%s' % salt,\r\n 'sign': '%s' % final_sign\r\n }\r\n try:\r\n response = requests.get('http://api.fanyi.baidu.com/api/trans/vip/translate', params=paramas, timeout=(6, 7))\r\n except requests.exceptions.ConnectTimeout:\r\n print(' >百度翻译又拉闸了...重新翻译...')\r\n return tran(api_id, key, word, to_lang, retry)\r\n content = str(response.content, encoding=\"utf-8\")\r\n # 百度返回为空\r\n if not content:\r\n retry += 1\r\n print(' >百度翻译返回为空...重新翻译...')\r\n sleep(1)\r\n return tran(api_id, key, word, to_lang, retry)\r\n # 百度返回了dict json\r\n json_reads = loads(content)\r\n if 'error_code' in json_reads: # 返回错误码\r\n error_code = json_reads['error_code']\r\n if error_code == '54003':\r\n print(' >请求百度翻译太快...技能冷却1秒...')\r\n sleep(1)\r\n elif error_code == '54005':\r\n print(' >发送了太多超长的简介给百度翻译...技能冷却3秒...')\r\n sleep(3)\r\n elif error_code == '52001':\r\n print(' >连接百度翻译超时...重新翻译...')\r\n elif error_code == '52002':\r\n print(' >百度翻译拉闸了...重新翻译...')\r\n elif error_code == '52003':\r\n print(' >请正确输入百度翻译API账号,请阅读【使用说明】!')\r\n print('>>javsdt已停止工作。。。')\r\n os.system('pause')\r\n elif error_code == '58003':\r\n print(' >你的百度翻译API账户被百度封禁了,请联系作者,告诉你解封办法!“')\r\n print('>>javsdt已停止工作。。。')\r\n os.system('pause')\r\n elif error_code == '90107':\r\n print(' >你的百度翻译API账户还未通过认证或者失效,请前往API控制台解决问题!“')\r\n print('>>javsdt已停止工作。。。')\r\n os.system('pause')\r\n else:\r\n print(' >百度翻译error_code!请截图联系作者!', error_code)\r\n retry += 1\r\n return tran(api_id, key, word, to_lang, retry)\r\n else: # 返回正确信息\r\n return json_reads['trans_result'][0]['dst']\r\n\r\n\r\n# 获取一个arzon_cookie,返回cookie\r\ndef get_acook(prox, retry):\r\n if retry == 10:\r\n print('>>请检查你的网络环境是否可以打开:https://www.arzon.jp/')\r\n os.system('pause')\r\n try:\r\n if prox:\r\n session = requests.Session()\r\n session.get('https://www.arzon.jp/index.php?action=adult_customer_agecheck&agecheck=1&redirect=https%3A%2F%2Fwww.arzon.jp%2F', proxies=prox, timeout=(6, 7))\r\n return session.cookies.get_dict()\r\n else:\r\n session = requests.Session()\r\n session.get('https://www.arzon.jp/index.php?action=adult_customer_agecheck&agecheck=1&redirect=https%3A%2F%2Fwww.arzon.jp%2F', timeout=(6, 7))\r\n return session.cookies.get_dict()\r\n except:\r\n print('通过arzon的成人验证失败,正在重新尝试...')\r\n return get_acook(prox, retry)\r\n\r\n\r\n# 获取网页源码,返回网页html\r\ndef get_library_html(list_url): # 0尝试次数 1报错信息 2url 3 proxy\r\n if list_url[0] == 10:\r\n print('>>请检查你的网络环境是否可以打开:', list_url[2])\r\n os.system('pause')\r\n try:\r\n if len(list_url) == 3:\r\n rqs = requests.get(list_url[2], timeout=(6, 7))\r\n else:\r\n rqs = requests.get(list_url[2], proxies=list_url[3], timeout=(6, 7))\r\n except:\r\n list_url[0] += 1\r\n print(list_url[1], list_url[2])\r\n return get_library_html(list_url)\r\n rqs.encoding = 'utf-8'\r\n rqs_content = rqs.text\r\n if search(r'JAVLibrary', rqs_content):\r\n return rqs_content\r\n else:\r\n list_url[0] += 1\r\n print(list_url[1], '空返回...', list_url[2])\r\n return get_library_html(list_url)\r\n\r\n\r\ndef get_bus_html(list_url): # 0尝试次数 1报错信息 2url 3 proxy\r\n if list_url[0] == 10:\r\n print('>>请检查你的网络环境是否可以打开:', list_url[2])\r\n os.system('pause')\r\n try:\r\n if len(list_url) == 3:\r\n rqs = requests.get(list_url[2], timeout=(6, 7), headers={'Cookie': 'existmag=all'})\r\n else: # cookie 为了 获得所有影片,而不是默认的有磁力的链接\r\n rqs = requests.get(list_url[2], proxies=list_url[3], timeout=(6, 7), headers={'Cookie': 'existmag=all'})\r\n except:\r\n list_url[0] += 1\r\n print(list_url[1], list_url[2])\r\n return get_bus_html(list_url)\r\n rqs.encoding = 'utf-8'\r\n rqs_content = rqs.text\r\n if search(r'JavBus', rqs_content):\r\n return rqs_content\r\n else:\r\n list_url[0] += 1\r\n print(list_url[1], '空返回...', list_url[2])\r\n return get_bus_html(list_url)\r\n\r\n\r\ndef search_db_html(list_url): # 0尝试次数 1报错信息 2url 3proxy\r\n # print(list_url)\r\n if list_url[0] == 11:\r\n print('>>请检查你的网络环境是否可以打开:', list_url[2])\r\n os.system('pause')\r\n if list_url[0] % 3 == 0:\r\n print(list_url[1], '休息300秒...', list_url[2])\r\n list_url[0] += 1\r\n sleep(300)\r\n return search_db_html(list_url)\r\n try:\r\n if len(list_url) == 3:\r\n rqs = requests.get(list_url[2], timeout=(6, 7))\r\n else:\r\n rqs = requests.get(list_url[2], proxies=list_url[3], timeout=(6, 7))\r\n except:\r\n # print(format_exc())\r\n list_url[0] += 1\r\n print(list_url[1], list_url[2])\r\n return search_db_html(list_url)\r\n rqs.encoding = 'utf-8'\r\n rqs_content = rqs.text\r\n if search(r'搜索結果', rqs_content):\r\n return rqs_content\r\n else:\r\n # print('!!!!!!!!!失败!')\r\n # sleep(300)\r\n list_url[0] += 1\r\n print(list_url[1], '空返回...', list_url[2])\r\n return search_db_html(list_url)\r\n\r\n\r\ndef get_db_html(list_url): # 0尝试次数 1报错信息 2url 3proxy\r\n # print(list_url)\r\n if list_url[0] == 10:\r\n print('>>请检查你的网络环境是否可以打开:', list_url[2])\r\n os.system('pause')\r\n if list_url[0] % 3 == 0:\r\n print(list_url[1], '休息20秒...', list_url[2])\r\n list_url[0] += 1\r\n sleep(20)\r\n return get_db_html(list_url)\r\n try:\r\n if len(list_url) == 3:\r\n rqs = requests.get(list_url[2], timeout=(6, 7))\r\n else:\r\n rqs = requests.get(list_url[2], proxies=list_url[3], timeout=(6, 7))\r\n except:\r\n # print(format_exc())\r\n list_url[0] += 1\r\n print(list_url[1], list_url[2])\r\n return get_db_html(list_url)\r\n rqs.encoding = 'utf-8'\r\n rqs_content = rqs.text\r\n if search(r'JavDB', rqs_content):\r\n return rqs_content\r\n else:\r\n list_url[0] += 1\r\n print(list_url[1], '空返回...', list_url[2])\r\n return get_db_html(list_url)\r\n\r\n\r\ndef get_arzon_html(list_url): # 0 尝试次数 1报错信息 2url 3 cookies 4 proxy\r\n if list_url[0] == 10:\r\n print('>>请检查你的网络环境是否可以打开:', list_url[2])\r\n os.system('pause')\r\n try:\r\n if len(list_url) == 4:\r\n rqs = requests.get(list_url[2], cookies=list_url[3], timeout=(6, 7))\r\n else:\r\n rqs = requests.get(list_url[2], cookies=list_url[3], proxies=list_url[4], timeout=(6, 7))\r\n except:\r\n list_url[0] += 1\r\n print(list_url[1], list_url[2])\r\n return get_arzon_html(list_url)\r\n rqs.encoding = 'utf-8'\r\n rqs_content = rqs.text\r\n if search(r'arzon', rqs_content):\r\n return rqs_content\r\n else:\r\n list_url[0] += 1\r\n print(list_url[1], '空返回...', list_url[2])\r\n return get_arzon_html(list_url)\r\n\r\n\r\ndef get_321_html(list_url): # 0尝试次数 1报错信息 2url 3 proxy\r\n if list_url[0] == 10:\r\n print('>>请检查你的网络环境是否可以打开:', list_url[2])\r\n os.system('pause')\r\n try:\r\n if len(list_url) == 3:\r\n rqs = requests.get(list_url[2], timeout=(6, 7))\r\n else:\r\n rqs = requests.get(list_url[2], proxies=list_url[3], timeout=(6, 7))\r\n except:\r\n list_url[0] += 1\r\n print(list_url[1], list_url[2])\r\n return get_321_html(list_url)\r\n rqs.encoding = 'utf-8'\r\n rqs_content = rqs.text\r\n if search(r'JAV321', rqs_content):\r\n return rqs_content\r\n else:\r\n list_url[0] += 1\r\n print(list_url[1], '空返回...', list_url[2])\r\n return get_321_html(list_url)\r\n\r\n\r\ndef post_321_html(list_url): # 0尝试次数 1报错信息 2url 3data 4proxy\r\n if list_url[0] == 10:\r\n print('>>请检查你的网络环境是否可以打开:', list_url[2])\r\n os.system('pause')\r\n try:\r\n if len(list_url) == 4:\r\n rqs = requests.post(list_url[2], data=list_url[3], timeout=(6, 7))\r\n else:\r\n rqs = requests.post(list_url[2], data=list_url[3], proxies=list_url[4], timeout=(6, 7))\r\n except:\r\n # print(format_exc())\r\n list_url[0] += 1\r\n print(list_url[1], list_url[2])\r\n return post_321_html(list_url)\r\n rqs.encoding = 'utf-8'\r\n rqs_content = rqs.text\r\n if search(r'JAV321', rqs_content):\r\n return rqs_content\r\n else:\r\n list_url[0] += 1\r\n print(list_url[1], '空返回...', list_url[2])\r\n return post_321_html(list_url)\r\n\r\n\r\n# 下载图片,无返回\r\ndef download_pic(list_cov):\r\n # print(list_cov)\r\n # 0错误次数 1图片url 2图片路径 3proxies\r\n if list_cov[0] < 5:\r\n try:\r\n if len(list_cov) == 3:\r\n r = requests.get(list_cov[1], stream=True, timeout=(6, 10))\r\n with open(list_cov[2], 'wb') as pic:\r\n for chunk in r:\r\n pic.write(chunk)\r\n else:\r\n r = requests.get(list_cov[1], proxies=list_cov[3], stream=True, timeout=(6, 10))\r\n with open(list_cov[2], 'wb') as pic:\r\n for chunk in r:\r\n pic.write(chunk)\r\n except:\r\n # print(format_exc())\r\n print(' >下载失败,重新下载...')\r\n list_cov[0] += 1\r\n download_pic(list_cov)\r\n # 下载的图片打不开,重新下载\r\n try:\r\n Image.open(list_cov[2])\r\n except OSError:\r\n print(' >下载失败,重新下载....')\r\n list_cov[0] += 1\r\n download_pic(list_cov)\r\n else:\r\n raise Exception(' >下载多次,仍然失败!')\r\n\r\n\r\n# 人体识别,返回鼻子位置\r\ndef image_cut(file_name, cli):\r\n with open(file_name, 'rb') as fp:\r\n image = fp.read()\r\n try:\r\n result = cli.bodyAnalysis(image)\r\n return int(result[\"person_info\"][0]['body_parts']['nose']['x'])\r\n except:\r\n print(' >人体分析出现错误,请对照“人体分析错误表格”:', result)\r\n print(' >正在尝试重新人体检测...')\r\n return image_cut(file_name, cli)\r\n\r\n\r\n##################################################################################################################\r\n# 判断文件夹是否含有“中字、㊥”,返回布尔值\r\ndef if_word_file(lst, file):\r\n subs = False\r\n for word in lst:\r\n if word in file: # 原文件名包含“-c、-C、中字”这些字符\r\n subs = True\r\n break\r\n return subs\r\n\r\n\r\n# 判断nfo中的title和genre也没有“中文字幕”\r\ndef if_word_nfo(lst, path):\r\n try:\r\n tree = ET.parse(path)\r\n except ET.ParseError: # nfo可能损坏\r\n return False\r\n for child in tree.getroot():\r\n if child.tag == 'title':\r\n for word in lst:\r\n if word in child.text:\r\n # print('有中文')\r\n return True\r\n if child.text == '中文字幕':\r\n # print('有中文!!!')\r\n return True\r\n return False\r\n\r\n\r\n# 为nfo加上“中文字幕特征\r\ndef append_subt(path, cus_subt, cus_title):\r\n # 读取原nfo\r\n file_old = open(path, 'r', encoding=\"utf-8\")\r\n list_lines = [i for i in file_old]\r\n file_old.close()\r\n # 原nfo还没有“中字”特征\r\n if ' 中文字幕\\n' not in list_lines:\r\n if cus_title.startswith('车牌+空格+是否中字+标题'):\r\n for i in range(len(list_lines)):\r\n if list_lines[i].startswith(' '):\r\n title = search(r'>(.+?)<', list_lines[i]).group(1)\r\n title = title.replace(' ', ' ' + cus_subt, 1)\r\n list_lines[i] = ' <title>' + title + '\\n'\r\n break\r\n # print(list_lines)\r\n list_lines.insert(list_lines.index(' \\n'), ' 中文字幕\\n 中文字幕\\n')\r\n # 再覆盖写入\r\n file_new = open(path, 'w', encoding=\"utf-8\")\r\n file_new.write(''.join(list_lines))\r\n file_new.close()\r\n print('重写nfo:', path)\r\n","sub_path":"pre_versions/1.0.4/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":15680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"138851098","text":"import spacy\nnlp = spacy.load(\"en_core_web_sm\")\nimport random\n\n\n\n\nclass QuestionAsker:\n\t'''\n\tClass to ask questions about sentences---basically to reverse them into questions.\n\t'''\n\n\tdef __init__(self):\n\t\t#self.sents = []\n\t\tself.questions = []\n\t\tself.question_types = [self.getVerbQuestion,self.getAdjQuestion]\n\n\n\tdef getQuestion(self,sent):\n\t\t# for s in sents:\n\t\ttry:\n\t\t\tqs = self.metaQuestion(sent)\n\t\t\tqs_ok = [q for q in qs if q not in self.questions]\n\t\t\tq_choice = random.choice(qs_ok)\n\t\t\tself.questions.append(q_choice)\n\t\t\treturn q_choice\n\t\texcept:\n\t\t \treturn None\n\n\n\tdef metaQuestion(self,sent):\n\t\tqs = []\n\t\tfor q in self.question_types:\n\t\t\ttry:\n\t\t\t\tqs.append(q(sent))\n\t\t\texcept:\n\t\t\t\tpass\n\t\treturn qs\n\n\n\n\tdef format_verb_question(self,noun,verb,number):\n\t\tauxverb = \"does\"\n\t\tif number==\"NNS\":\n\t\t\tauxverb = \"do\"\n\t\treturn \"Why %s the %s %s?\" % (auxverb,noun.lower(),verb.lower())\n\n\n\n\tdef getVerbQuestion(self,sent):\n\t\tspacified = nlp(sent)\n\t\tnoun_verb_number = []\n\t\tfor token in spacified:\n\t\t\tif (token.pos_ == \"VERB\" and token.text.isalpha()):\n\t\t\t\tif token.lemma_ != 'be':\n\t\t\t\t\tnouns = [t for t in token.children if (t.pos_==u'NOUN' and t.dep_==\"nsubj\" and t.text.isalpha())]\n\t\t\t\t\tif nouns!=[]:\n\t\t\t\t\t\tnoun = random.choice(nouns)\n\t\t\t\t\t\tnoun_verb_number.append((noun.text,token.text,noun.tag_))\n\t\treturn self.format_verb_question(*random.choice(noun_verb_number))\t\t\n\n\n\n\tdef format_adj_question(self,adj,noun,number):\n\t\tverb = \"is\"\n\t\tif number==\"NNS\":\n\t\t\tverb = \"are\"\n\t\treturn \"Why %s the %s %s?\" % (verb,noun.lower(),adj.lower())\n\n\n\n\tdef getAdjQuestion(self,sent):\n\t\tspacified = nlp(sent)\n\t\tadj_n_number = []\n\t\tfor token in spacified:\n\t\t\tif (token.tag_ in [\"NN\",\"NNS\"] and token.text.isalpha()):\n\t\t\t\tadjectives = [t.text for t in token.children if t.dep_==u'amod' and t.text.isalpha()]\n\t\t\t\tif adjectives!=[]:\n\t\t\t\t\tadj_n_number.append((random.choice(adjectives),token.text,token.tag_))\n\t\treturn self.format_adj_question(*random.choice(adj_n_number))\n\n\n\ndef main():\n\tqa = QuestionAsker()\n\tprint(qa.getQuestion(u\"The good men drink beer.\"))\n\tprint(qa.getQuestion(u\"The good men drink beer.\"))\n\tprint(qa.getQuestion(u\"The good men drink beer.\"))\n\n\n\n\n\nif __name__ == '__main__':\n\tmain()\n\n","sub_path":"QuestionAsker.py","file_name":"QuestionAsker.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"480410805","text":"import requests\nimport json\n\n####\n# inputs\n####\nusername = 'nicKLas-317'\n\n# from https://github.com/user/settings/tokens\ntoken = ''\n\nrepos_url = 'https://api.github.com/user/repos'\n\n# create a re-usable session object with the user creds in-built\ngh_session = requests.Session()\ngh_session.auth = (username, token)\n\n# get the list of repos belonging to me\nrepos = json.loads(gh_session.get(repos_url).text)\n\n# print the repo names\nfor repo in repos:\n print(repo['name'])\n\n# make more requests using \"gh_session\" to create repos, list issues, etc.","sub_path":"github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"429496159","text":"from kinto.authorization import PERMISSIONS_INHERITANCE_TREE\nfrom pyramid.exceptions import ConfigurationError\n\n\ndef includeme(config):\n config.add_api_capability(\n 'accounts',\n description='Manage user accounts.',\n url='https://kinto.readthedocs.io/en/latest/api/1.x/accounts.html')\n\n config.scan('kinto.plugins.accounts.views')\n\n PERMISSIONS_INHERITANCE_TREE[''].update({\n 'account:create': {}\n })\n PERMISSIONS_INHERITANCE_TREE['account'] = {\n 'write': {'account': ['write']},\n 'read': {'account': ['write', 'read']}\n }\n\n # Add some safety to avoid weird behaviour with basicauth default policy.\n settings = config.get_settings()\n auth_policies = settings['multiauth.policies']\n if 'basicauth' in auth_policies and 'account' in auth_policies:\n if auth_policies.index('basicauth') < auth_policies.index('account'):\n error_msg = (\"'basicauth' should not be mentioned before 'account' \"\n \"in 'multiauth.policies' setting.\")\n raise ConfigurationError(error_msg)\n\n # We assume anyone in account_create_principals is to create\n # accounts for other people.\n # No one can create accounts for other people unless they are an\n # \"admin\", defined as someone matching account_write_principals.\n # Therefore any account that is in account_create_principals\n # should be in account_write_principals too.\n creators = set(settings.get('account_create_principals', '').split())\n admins = set(settings.get('account_write_principals', '').split())\n cant_create_anything = creators.difference(admins)\n # system.Everyone isn't an account.\n cant_create_anything.discard('system.Everyone')\n if cant_create_anything:\n message = ('Configuration has some principals in account_create_principals '\n 'but not in account_write_principals. These principals will only be '\n 'able to create their own accounts. This may not be what you want.\\n'\n 'If you want these users to be able to create accounts for other users, '\n 'add them to account_write_principals.\\n'\n 'Affected users: {}'.format(list(cant_create_anything)))\n\n raise ConfigurationError(message)\n","sub_path":"kinto/plugins/accounts/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"513059157","text":"import ael\n\ndef call_current_rate(temp,trd,*rest):\n t = ael.Trade[(int)(trd)]\n cf_end = ael.date('1970-01-01')\n cfnbr = 0\n reset_end = ael.date('1970-01-01')\n resetnbr = 0\n \n for c in t.insaddr.legs()[0].cash_flows():\n if c.end_day > cf_end:\n cf_end = c.end_day\n cfnbr = c.cfwnbr\n \n for cf in t.insaddr.legs()[0].cash_flows():\n if cf.cfwnbr == cfnbr:\n for r in cf.resets():\n if r.end_day > reset_end:\n reset_end = r.end_day\n resetnbr = r.resnbr\n \n for r in cf.resets():\n if r.resnbr == resetnbr:\n return (str)(r.value)\n","sub_path":"Python modules/CallCurrentRate.py","file_name":"CallCurrentRate.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"140780694","text":"import numpy as np\nimport os\nimport cv2\n\n\ndef Process(k, image, size):\n processed_data = np.memmap(image, dtype=np.uint8, shape = size)\n criteria = (cv2.TERM_CRITERIA_EPS, 1000, 1.0)\n Z = np.float32(processed_data)\n compactness, labels, (centers) = cv2.kmeans(Z, k, None, criteria, 10, cv2.KMEANS_PP_CENTERS)\n centers = np.uint8(centers)\n labels = labels.flatten()\n segmented_image = centers[labels.flatten()]\n segmented_image = segmented_image.reshape(size)\n print(compactness)\n return segmented_image\n\ncurrent_dir = os.getcwd()\nKU_path = current_dir + '/K_means/KU.raw'\nGolf_path = current_dir + '/K_means/Golf.raw'\nGun_path = current_dir + '/K_means/Gundam.raw'\n\ncv2.imwrite('KU_out.jpg', Process(2,KU_path,(560,720)))\ncv2.imwrite('Golf_out.jpg',Process(4,Golf_path,(540,800)))\ncv2.imwrite('Gun_out.jpg',Process(8,Gun_path,(600,600)))\n","sub_path":"codes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"389293912","text":"from sys import argv\n\nscript, filename = argv\n\nprint(f\"We are going to erase {filename}.\")\nprint(\"If you don't want that, hit CRTL-C(^C).\")\nprint(\"If you do want that, hit RETURN.\")\n\ninput(\"?\")\n\nprint(\"Opening the file...\")\ntarget = open(filename, 'w')# 'w' to say you want to write a file\n# open() just doing open file in 'r' read mode\n\nprint(\"Truncating the file. Goodbye!\")\ntarget.truncate()\n\nprint(\"Now I am going to ask you for three lines.\")\n\nline1 = input(\"line1: \")\nline2 = input(\"line2: \")\nline3 = input(\"line3: \")\n\nprint(\"I'm going to write these to the file.\")\n\ntarget.write(line1)\ntarget.write(\"\\n\")\ntarget.write(line2)\ntarget.write(\"\\n\")\ntarget.write(line3)\ntarget.write(\"\\n\")\n\nprint(\"And finally, we close it.\")\ntarget.close() # close function means save and close the file\n","sub_path":"drill16.py","file_name":"drill16.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"211719476","text":"\"\"\" Userman: Simple account handling system for use with web services.\n\nThis implementation uses Tornado (3.2 or later) and CouchDB (1.0.1 or later).\n\"\"\"\n\n__version__ = '14.7'\n\n# These values are minimal default values appropriate for debugging.\n# The actual values are read in by utils.load_settings()\nsettings = dict(BASE_URL='http://localhost:8880/',\n DB_SERVER='http://localhost:5984/',\n DB_DATABASE='userman',\n TORNADO_DEBUG=True,\n LOGGING_DEBUG=True,\n LOGGING_FORMAT='%(levelname)s [%(asctime)s] %(message)s',\n API_KEYS=[],\n ACTIVATION_EMAIL='messages/activation_email.txt',\n RESET_EMAIL='messages/reset_email.txt',\n ACTIVATION_PERIOD=7.0, # Unit: days\n )\n","sub_path":"userman/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"518081997","text":"\n\nfrom socket import *\nfrom time import sleep\n\n# dest = ('176.215.155.255', 22222)\ndest = ('', 9999)\n\ns = socket(AF_INET, SOCK_DGRAM)\ns.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)\n\nwhile True:\n sleep(1)\n s.sendto(b'1234567', dest)\n data, addr = s.recvfrom(1024)\n print('received from %s:%s' % (addr, data.decode()))\n","sub_path":"pythonNet/day02/mycode_in/broadcast_send.py","file_name":"broadcast_send.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"137638835","text":"import unittest\n\nfrom datetime import datetime, timedelta\nfrom twitter import Status\n\nfrom twitterstars.decorator import Decorator\nfrom twitterstars.tweet import Tweet\nfrom twitterstars.base_model import BaseModel\n\nclass Api(object):\n def __init__(self):\n self.calls_made = {\n 'GetStatus': 0\n }\n\n def GetStatus(self, status_id):\n self.calls_made['GetStatus'] += 1\n status_args = {\n 1234567890: {\n 'favorite_count': 12,\n 'retweet_count': 6,\n },\n 1234567893: {\n 'favorite_count': 0,\n 'retweet_count': 0,\n },\n }[status_id]\n if status_args == None:\n raise Exception('Unexpected GetStatus request')\n return Status(**status_args)\n\nclass TestDecorator(unittest.TestCase):\n\n def test_decorator(self):\n database = BaseModel._meta.database\n database.drop_tables([Tweet])\n database.create_tables([Tweet])\n\n # sufficiently high favorite_count or retweet_count\n Tweet.create(\n posted_at = datetime.now() - timedelta(hours=2),\n text = 'Tweet #1',\n twitter_tweet_id = 1234567890,\n twitter_user_id = 9876543210,\n )\n\n # counts already populated\n Tweet.create(\n favorite_count = 3,\n retweet_count = 7,\n posted_at = datetime.now() - timedelta(hours=3),\n text = 'Tweet #2',\n twitter_tweet_id = 1234567891,\n twitter_user_id = 9876543210,\n )\n\n # too young\n Tweet.create(\n posted_at = datetime.now() - timedelta(minutes=30),\n text = 'Tweet #3',\n twitter_tweet_id = 1234567892,\n twitter_user_id = 9876543210,\n )\n\n # counts too low\n Tweet.create(\n posted_at = datetime.now() - timedelta(days=1),\n text = 'Tweet #4',\n twitter_tweet_id = 1234567893,\n twitter_user_id = 9876543210,\n )\n\n api = Api()\n decorator = Decorator(api)\n decorator.process_once()\n\n self.assertEqual(\n api.calls_made['GetStatus'], 2,\n '2 tweet in timeframe without counts'\n )\n\n tweet = Tweet.select().where(Tweet.twitter_tweet_id == 1234567890).get()\n\n self.assertEqual(tweet.favorite_count, 12)\n self.assertEqual(tweet.retweet_count, 6)\n\n self.assertEqual(\n Tweet.select().where(Tweet.twitter_tweet_id == 1234567893).count(),\n 0,\n 'Tweet deleted due to low tweet count',\n )\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_decorator.py","file_name":"test_decorator.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"353332429","text":"from pyramid.config import Configurator\nfrom pyramid.authentication import AuthTktAuthenticationPolicy\nfrom pyramid.authorization import ACLAuthorizationPolicy\nfrom sqlalchemy import engine_from_config\n\nfrom flog.models import DBSession, Base\nfrom flog.models.rootfactory import RootFactory\nfrom flog.models.settings import Settings\nfrom flog.models.postings import Posting\n\n\ndef main(global_config, **settings):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n engine = engine_from_config(settings, 'sqlalchemy.')\n DBSession.configure(bind=engine)\n Base.metadata.bind = engine\n config = Configurator(settings=settings, root_factory='flog.models.rootfactory.RootFactory')\n \n config.set_authentication_policy(AuthTktAuthenticationPolicy('flogkrit', hashalg='sha512'))\n config.set_authorization_policy(ACLAuthorizationPolicy())\n config.set_default_permission('edit')\n\n config.add_static_view('static', 'static', cache_max_age=3600)\n config.add_route('home', '/')\n config.add_route('shift', '/shift/{date}')\n config.add_route('show', '/show/{id}')\n config.add_route('about', '/about')\n config.add_route('admin', '/admin/')\n config.add_route('settings', '/admin/settings')\n config.add_route('create', '/admin/create/{date}')\n config.add_route('delete', '/admin/delete/{id}')\n config.add_route('login', '/login')\n config.add_route('logout', '/logout')\n\n config.scan()\n return config.make_wsgi_app()\n","sub_path":"flog/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"37628711","text":"from iview_class import *\n\nART = 'art-default.jpg'\nICON = 'icon-default.jpg'\n\ndef Start():\n Plugin.AddViewGroup('List', viewMode='List', mediaType='items')\n Plugin.AddViewGroup('InfoList', viewMode='InfoList', mediaType='items')\n\n\n@handler('/video/aubciview', 'Australian ABC iView', art=ART, thumb=ICON)\ndef MainMenu():\n oc = ObjectContainer(view_group='List', title2='ABC iView')\n\n oc.add(DirectoryObject(\n key=Callback(list_menu, title=u'Channels', item_list=u'channel'),\n title=u'Channels'\n ))\n\n oc.add(DirectoryObject(\n key=Callback(list_menu, title=u'Categories', item_list=u'category'),\n title=u'Categories'\n ))\n\n # oc.add(DirectoryObject(\n # key=Callback(LatestMenu),\n # title=u'Latest'\n # ))\n #\n # oc.add(DirectoryObject(\n # key=Callback(PopularMenu),\n # title=u'Popular'\n # ))\n\n\n #oc.add(VideoClipObject(key = RTMPVideoURL(url = 'rtmp://203.18.195.10/ondemand' + '?auth=7B8F0402DD370FF9299E', clip = 'mp4:comedy/madashell_02_08', swf_url = 'http://www.abc.net.au/iview/images/iview.jpg'), rating_key = '123',title = 'TEST'))\n\n # cats = iView_Config.List_Categories()\n #\n # for key in cats:\n # oc.add(DirectoryObject(\n # key=Callback(GetSeriesByCaegory, category=key),\n # title=cats[key]\n # ))\n\n oc.objects.sort(key=lambda obj: obj.title)\n\n return oc\n\n\n@route('/video/aubciview/list_menu/{item_list}')\ndef list_menu(title, item_list):\n oc = ObjectContainer(view_group='List', title2=title)\n if item_list == u'category':\n item_list = iview_plugin.category_list\n elif item_list == u'channel':\n item_list = iview_plugin.channel_list\n else:\n item_list = []\n\n for item in item_list:\n channel = JSON.ObjectFromURL(iview_plugin.API_URL + item['href'])\n thumb = channel['featuredImage'] if 'featuredImage' in channel else None\n oc.add(DirectoryObject(\n key=Callback(get_series_by_channel, channel=item['id'], title=item['title'], href=item['href']),\n title=item['title'],\n thumb=thumb\n ))\n oc.objects.sort(key=lambda obj: obj.title)\n\n return oc\n\n\n@route('/video/aubciview/channel/{channel}')\ndef get_series_by_channel(channel, title, href):\n Log(u'get_series_by_channel:: channel={0}, title={1}, href={2}'.format(channel, title, href))\n oc = ObjectContainer(view_group='List', title2=title)\n\n href = iview_plugin.API_URL + href\n json = JSON.ObjectFromURL( href)\n\n for item in json['carousels']:\n Log(item)\n oc.add(DirectoryObject(\n key=Callback(get_episodes, href=href, cat=u'carousels', title=item['title']),\n title=item['title']))\n try:\n for item in json['collections']:\n Log(item)\n oc.add(DirectoryObject(\n key=Callback(get_episodes, href=href, cat=u'collections', title=item['title']),\n title=item['title']))\n except:\n pass\n \n for item in json['index']:\n Log(item)\n oc.add(DirectoryObject(\n key=Callback(get_episodes, href=href, cat=u'index', title=item['title']),\n title=item['title']))\n # oc.objects.sort(key=lambda obj: obj.title)\n\n return oc\n\n\n@route('/video/aubciview/get_episodes')\ndef get_episodes(href, cat, title):\n Log(u'get_episodes:: href={0}, cat={1}'.format(href, cat))\n oc = ObjectContainer(view_group='List', title2=title)\n\n cat_list = JSON.ObjectFromURL(href)[cat]\n episodes = []\n for cat in cat_list:\n if 'title' in cat and cat['title'] == title:\n episodes = cat['episodes']\n break\n\n Log(episodes)\n\n for e in episodes:\n Log(e)\n episode_href = e[u'href']\n details = JSON.ObjectFromURL(iview_plugin.API_URL + episode_href)\n Log(details)\n title = u'{0} {1}'.format(\n details['seriesTitle'] if u'seriesTitle' in details else u'',\n details['title'] if u'title' in details else u'',\n )\n duration = int(details[u'duration'])*1000 if 'duration' in details else None\n\n streams = details[u'streams']\n url = streams[u'hls-high'][-1]\n # url = u'\"http://iviewhls-i.akamaihd.net/i/playback/_definst_/_video/beautifullieextras_01_05_,650000,495000,206000,41046,.mp4.csmil/master.m3u8'\n\n oc.add(create_video_clip(\n url=url,\n title=title,\n summary=details[u'description'] if u'description' in details else u'',\n # originally_available_at=details[u'description'],\n duration=duration,\n # season=season,\n # index=index,\n thumb=Resource.ContentsOfURLWithFallback(url=e['thumbnail'])\n ))\n\n return oc\n\n\n@route('/video/aubciview/cvc')\ndef create_video_clip(url, title=u'', summary=u'', duration=None, thumb=None, container=False):\n Log(u'create_video_clip:: url={0}'.format(url))\n vco = VideoClipObject(\n key = Callback(create_video_clip, url=url, title=title, thumb=thumb, container=True),\n #rating_key = url,\n url=url,\n title=title,\n summary=summary,\n duration=duration,\n thumb=thumb,\n items=[MediaObject(\n parts=[PartObject(key=HTTPLiveStreamURL(url=url))],\n optimized_for_streaming = True\n )\n ]\n )\n\n if container:\n return ObjectContainer(objects=[vco])\n else:\n return vco\n","sub_path":"ABCiView.bundle/Contents/Code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"529057857","text":"\nfrom pathlib import Path\n\nimport os\nimport yaml\nimport stat\nimport subprocess\nimport shutil\n\n\ndef command(command_str, stdin=None):\n process = subprocess.Popen(command_str,\n shell=True,\n stdin=stdin,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n \n stdoutdata, stderrdata = process.communicate()\n \n return {\n 'stdout': stdoutdata, \n 'stderr': stderrdata, \n 'status': process.returncode\n }\n\n\ndef generate_dev_inventory():\n inventory_file = \"hosts/inventory.dev.yml\"\n inventory = {\"masters\": [], \"nodes\": []}\n \n if os.path.isfile(\"vagrant/config.yml\"):\n vagrant_config_file = \"vagrant/config.yml\"\n else:\n vagrant_config_file = \"vagrant/default.config.yml\"\n \n istream = open(vagrant_config_file, 'r')\n config = yaml.load(istream)\n istream.close()\n \n for index in range(1, config[\"masters\"] + 1):\n inventory[\"masters\"].append({\n \"ip\": config[\"master_{}_ip\".format(index)],\n \"hostname\": config[\"master_{}_hostname\".format(index)],\n \"os\": config[\"os\"],\n \"user\": config[\"user\"],\n \"etcd\": config[\"master_{}_etcd\".format(index)],\n \"vault\": config[\"master_{}_vault\".format(index)]\n })\n \n for index in range(1, config[\"nodes\"] + 1):\n inventory[\"nodes\"].append({\n \"ip\": config[\"node_{}_ip\".format(index)],\n \"hostname\": config[\"node_{}_hostname\".format(index)],\n \"os\": config[\"os\"],\n \"user\": config[\"user\"],\n \"etcd\": config[\"node_{}_etcd\".format(index)],\n \"vault\": config[\"node_{}_vault\".format(index)]\n })\n \n ostream = open(inventory_file, 'w')\n yaml.dump(inventory, ostream, default_flow_style=False)\n ostream.close()\n\n\ndef load_inventory(environment):\n inventory = None\n \n with open(\"hosts/inventory.{}.yml\".format(environment), 'r') as stream:\n try:\n inventory = yaml.load(stream)\n\n except yaml.YAMLError as error:\n print(error)\n \n return inventory\n\n\ndef update_keys(environment):\n home = str(Path.home())\n home_ssh_key = \"{}/.ssh/id_rsa\".format(home)\n home_ssh_pub_key = \"{}/.ssh/id_rsa.pub\".format(home)\n \n if environment == \"dev\":\n ssh_key = \"vagrant/private_key\"\n info = command(\"ssh-keygen -y -f {}\".format(ssh_key))\n \n if info['status'] != 0:\n raise Exception(\"Error reading SSH key from Vagrant {}\".format(ssh_key))\n \n ostream = open(home_ssh_pub_key, \"w\")\n ostream.write(info['stdout'].decode(\"utf-8\"))\n ostream.close()\n else:\n ssh_key = \"keys/id_rsa.{}\".format(environment)\n \n shutil.copyfile(ssh_key, home_ssh_key)\n os.chmod(home_ssh_key, stat.S_IRUSR | stat.S_IWUSR)\n \n if environment != \"dev\":\n shutil.copyfile(\"{}.pub\".format(ssh_key), home_ssh_pub_key)\n","sub_path":"scripts/shared.py","file_name":"shared.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"438535132","text":"# 2007 / print len of word in string\nfor T in range(int(input())):\n data = input().strip()\n\n res = ''\n for char in data:\n if len(res): # compare word\n if res == data[len(res):len(res) * 2]:\n break\n res += char\n\n print(f'#{T + 1} {len(res)}')\n","sub_path":"D2/2007.py","file_name":"2007.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"109388996","text":"import time\nfrom sqlalchemy import create_engine\nimport tushare as ts\nimport get_date as gd\nimport argparse\nimport concurrent.futures\nimport multiprocessing\nimport Qtrac\n\ndef get_ticks():\n concurrency, Sdate, Edate = handle_commandline()\n codefile = 'codes'\n Qtrac.report(\"starting...\")\n futures = set()\n dates = gd.get_date(Sdate, Edate)\n codes = []\n datas = []\n with open(codefile) as cf:\n for each in cf:\n codes.append(each.strip())\n for a in codes:\n for b in dates:\n datas.append([a,b])\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=concurrency) as executor:\n for data in datas:\n future = executor.submit(get_tick, data)\n futures.add(future)\n done, canceled = process(futures)\n if canceled:\n executor.shutdown()\n Qtrac.report(\"read {}/{} tickdata using {} threads{}\".format(done,\n len(futures),concurrency, \"[canceled]\" if canceled else \"\"))\n print()\n if not canceled:\n print('not canceled')\n\ndef process(futures):\n canceled = False\n done = 0\n engine = create_engine('mysql://root:770607@127.0.0.1/tickdata?charset=utf8')\n canceled, results = wait_for(futures)\n if not canceled:\n for result in(result for ok,result in results if ok and \n result is not None):\n done +=1\n result[2].to_sql(result[0]+'t'+result[1], engine)\n else:\n done = sum(1 for ok, result in results if of and result is not None)\n return done, canceled\n\ndef wait_for(futures):\n canceled = False\n results = []\n try:\n for future in concurrent.futures.as_completed(futures):\n err = future.exception()\n if err is None:\n ok, result = future.result()\n if not ok:\n Qtrca.report(result, True)\n elif result is not None:\n Qtrac.report(\"read {}\".format(result[2]['time'][0:5]))\n results.append((ok, result))\n else:\n raise err\n except KeyboardInterrupt:\n Qtrac.report('canceling...')\n canceled = True\n for future in futures:\n future.cancel()\n return canceled, results\n\ndef get_tick(s):\n try:\n df = ts.get_tick_data(s[0], s[1], retry_count=10)\n try:\n df['time'][5]\n except KeyError:\n return True, None\n return True, [s[0], s[1], df]\n except TimeoutError:\n return False, \"Error: {}: {}\".format(s[0]+s[1], err)\n\ndef handle_commandline():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", \"--concurrency\", type=int,\n default=multiprocessing.cpu_count()*4,\n help=\"specify the concurrency (for debugging and \"\n \"timing) [default: %(default)d]\")\n parser.add_argument(\"-s\", \"--startdate\", type=str,\n default='2016-12-28')\n parser.add_argument(\"-e\", \"--enddate\", type=str,\n default='2016-12-29')\n args = parser.parse_args()\n return args.concurrency, args.startdate, args.enddate\n\nif __name__ == '__main__':\n get_ticks()\n","sub_path":"get_tick1.py","file_name":"get_tick1.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"111076071","text":"from django.shortcuts import render, get_object_or_404\n\nfrom .models import Entry, Client, Project\n\n\ndef entries(request):\n entry_list = Entry.objects.all()\n return render(request, 'entries.html', {\n 'entry_list': entry_list,\n })\n\ndef projects(request):\n project_list = Project.objects.all()\n return render(request, 'projects.html', {\n 'project_list': project_list,\n })\n\ndef clients(request):\n client_list = Client.objects.all()\n return render(request, 'clients.html', {\n 'client_list': client_list,\n })\n\ndef client_summary(request, id):\n client = get_object_or_404(Client, pk=id)\n\n # This could also be done in the template with {{ client.project_set }}\n projects_list = Project.objects.filter(client=client)\n\n return render(request, 'client_summary.html', {\n 'client': client,\n 'projects_list': projects_list,\n })\n","sub_path":"timetracker/entries/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"560146171","text":"def QtoPhred33(Q):\r\n \"\"\" Turn Q into Phred+33 ASCII-encoded quality \"\"\"\r\n return chr(Q + 33)\r\n\r\ndef phred33ToQ(qual):\r\n \"\"\" Turn Phred+33 ASCII-encoded quality into Q \"\"\"\r\n return ord(qual) - 33\r\n\r\ndef readFastq(filename):\r\n \tsequences = []\r\n \tqualities = []\r\n \twith open(filename) as fh:\r\n \t\twhile True:\r\n \t\t\tfh.readline()\r\n \t\t\tseq = fh.readline().rsrip()\r\n \t\t\tfh.readline()\r\n \t\t\tqual = fh.readline().rstrip()\r\n \t\t\tif len(seq) == 0:\r\n \t\t\t\tbreak\r\n \t\t\tsequences.append(qual)\r\n \treturn sequences, qualities\r\n\r\nseqs, quals = readfastq('SRR835775_1.first1000.fastq')","sub_path":"fastQfiles.py","file_name":"fastQfiles.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"399332180","text":"import json\nfrom django.core import serializers\nfrom django.utils.timezone import utc\nimport datetime\nimport sys\nfrom toilet.models import Toilet, Flag, FlagRanking\nfrom review.models import Review\n\n#turns post data into a json object\ndef post_to_dict(post):\n return remove_json_characters(dict(post))\n\n#removes the json characters from the strings in the data from request\ndef remove_json_characters(dictionary):\n for elm in dictionary:\n dictionary[elm] = json.dumps(dictionary[elm]).replace(\"]\",\"\").replace(\"[\",\"\").replace(\"\\\"\", \"\")\n return dictionary\n\n\n#returns the time in a django timezone frinedly way\ndef currentTime():\n return datetime.datetime.utcnow().replace(tzinfo=utc)\n\n\n#serialize a thing(s)\ndef serialize(obj):\n return serializers.serialize('json', obj)\n \n\n#adds error to beginning of response if required\ndef package_error(response, error):\n if error != '':\n return json.dumps({ 'error' : error })\n return response\n\n\n\n#login stuff\nfrom django.contrib.auth import login as django_login\nfrom django.contrib.auth import logout as django_logout\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponse\n\n#creates a new user\ndef create_user(request):\n error = ''\n response = ''\n status = 201\n\n if request.method == 'POST':\n data = request.POST\n try:\n User.objects.get(username=data['username'])#try to find someone with that name\n error = 'A user with that name already exists.'\n status = 200\n except ObjectDoesNotExist:#if it fails, we can create that user\n user = User.objects.create_user(data['username'],data['email'],data['password']) \n user.save()\n response = '\"' + data['username'] + ' created.\"'\n else:\n error += 'No POST data in request\\n'\n status = 415\n return HttpResponse(package_error(response,error),status=status)\n\n\n#logs in an existing user\ndef login(request):\n error = ''\n response = ''\n status = 200\n \n if request.method == 'POST':\n data = request.POST\n user = authenticate(username=data['username'],password=data['password'])\n if user is not None:\n if user.is_active:\n django_login(request, user)\n response = '\\\"Success\\\"'\n else:\n error = 'Your account has been disabled\\n'\n else:\n error += 'Invalid Login\\n'\n else:\n error += 'No POST data in request.\\n'\n status = 415\n return HttpResponse(package_error(response,error),status=status)\n\n\n#its this simple\ndef logout(request):\n django_logout(request)\n response = '\"Logged out\"'\n\n return HttpResponse(package_error(response,''),status=200)\n\n\n\"\"\"\nCOMMON OBJECT RETRIEVAL FUNCTIONS\n\"\"\"\n\ndef str_to_class(str):\n lookup = {'Toilet': Toilet\n , 'Review': Review\n , 'FlagRanking': FlagRanking\n , 'Flag' : Flag}\n return lookup.get(str)\n\n# We need to actually add in all of the large expesnive queries here \ndef security_check(k, v):\n return v\n\ndef get_obj(request, name):\n if request.POST:\n #get start and end for pagination \n start = request.POST.get('start')\n end = request.POST.get('end')\n filters = json.loads(request.POST.get('filters'))\n #map over all of the filter objects to amke sure they aren't expensive queries\n filters = {k: security_check(k,v) for k, v in filters.items()}\n #convert the string from name into an object, apply all of the filters to the object\n qs = str_to_class(name).objects.all().filter(**filters)[start:end] \n return HttpResponse(serializers.serialize('json', qs))\n\n else:\n return HttpResponse(\"DUDE WTF GIOMME A POST\", status=412)\n","sub_path":"common/middletier.py","file_name":"middletier.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"232653634","text":"import numpy as np\nfrom PIL import Image\nimport cv2\nimport random\nimport pickle\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import style\n\nfrom constants import SIZE, MOVE_PENALTY, PICK_UP_REWARD, DROP_OFF_REWARD\nfrom environment import Agent, PickUpCell, DropOffCell\nfrom helper_functions import initialize_q_table, pRandom, pExploit, get_state, perform_action, calculate_new_q, create_display_environment\n\nstyle.use(\"ggplot\")\n\nLEARNING_RATE = 0.3\nDISCOUNT = 0.5\nHM_STEPS = 6000\n\nseed = int(input(\"Seed: \"))\nrandom.seed(seed)\n\nq_table = initialize_q_table()\nstep = 0\nall_rewards = []\nterminated = 0\nwhile step < HM_STEPS:\n # initial environment state\n if terminated < 3:\n drop_cells = [DropOffCell(0,0), DropOffCell(0,4), DropOffCell(2,2), DropOffCell(4,4)]\n pick_cells = [PickUpCell(2,4), PickUpCell(3,1)]\n agent = Agent(4, 0)\n elif terminated == 6:\n break\n else:\n drop_cells = [DropOffCell(0,0), DropOffCell(0,4), DropOffCell(2,2), DropOffCell(4,4)]\n pick_cells = [PickUpCell(2,0), PickUpCell(0,2)]\n agent = Agent(4, 0)\n\n # while ai has not reached a terminal state\n session_reward = 0\n while True:\n current_state = get_state(agent, drop_cells, pick_cells)\n \n if step < 500:\n action = pRandom()\n else:\n action = pExploit(current_state, q_table)\n \n step += 1\n reward, new_state = perform_action(agent, action, drop_cells, pick_cells)\n q_table[current_state][action] = calculate_new_q(LEARNING_RATE, DISCOUNT, reward, action, current_state, new_state, q_table)\n session_reward += reward\n\n # visualization removed\n \n # all drop off locations are filled\n if len(list(filter(lambda cell: cell.has_space() == False, drop_cells))) == len(drop_cells) or step == HM_STEPS:\n if step != HM_STEPS:\n terminated += 1\n break\n all_rewards.append(session_reward)\n\nplt.plot([i for i in range(len(all_rewards))], all_rewards)\nplt.ylabel(\"Reward Collected\")\nplt.xlabel(\"Session\")\nplt.show()\n\nprint(f\"max reward reached: {max(all_rewards)}\")\n\nwith open(f\"qtable-experiment-4.pickle\", \"wb\") as f:\n pickle.dump(q_table, f)\n","sub_path":"experiment_4_no_vis.py","file_name":"experiment_4_no_vis.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"400465564","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport ntpath\n\ndef run_video_capture(w_name = \"Video Capture\",\n screenshot_directory = None,\n process_frame = None):\n\n cap = cv2.VideoCapture(0)\n w_name += \" (press q to quit, space to take screenshot if directory specified)\"\n cv2.namedWindow(w_name)\n screenshot_idx = 0\n\n while(True):\n\n ret, frame = cap.read()\n if process_frame is not None:\n frame = process_frame(frame)\n \n cv2.imshow(w_name, frame)\n\n # Press Q to stop\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n if cv2.waitKey(1) & 0xFF == ord(' ') and screenshot_directory is not None:\n path = ntpath.join(screenshot_directory, \"screenshot_{}.jpg\".format(screenshot_idx))\n print(\"saving to {}\".format(path))\n cv2.imwrite(path, frame)\n continue\n\n # When everything done, release the capture\n cap.release()\n cv2.destroyAllWindows()\n\ndef resize_image(image, factor, interpolation):\n \n assert factor != 0.\n\n image_h = image.shape[0]\n image_w = image.shape[1]\n \n new_image_h = int(image_h*factor)\n new_image_w = int(image_w*factor)\n \n return cv2.resize(image, (new_image_w, new_image_h), interpolation = interpolation)\n\ndef shift_rgb_values(input_color_rgb, show = False, red = 0, green = 0, blue = 0):\n \n # Switch to uint16 to be able to go above 256\n shifted_img_color_rgb = input_color_rgb.copy().astype(np.uint16)\n \n # We use clip and not modulo to avoid cycling\n shifted_img_color_rgb[:,:,0] = np.clip(shifted_img_color_rgb[:,:,0] + red, 0, 255)\n shifted_img_color_rgb[:,:,1] = np.clip(shifted_img_color_rgb[:,:,1] + green, 0, 255)\n shifted_img_color_rgb[:,:,2] = np.clip(shifted_img_color_rgb[:,:,2] + blue, 0, 255)\n \n # Switch back to uint8 since with clip we went back below 256\n shifted_img_color_rgb = shifted_img_color_rgb.astype(np.uint8)\n\n # Show image\n if show:\n plt.imshow(shifted_img_color_rgb, interpolation = 'bicubic')\n plt.axis('off')\n plt.show()\n\n return\n else:\n return shifted_img_color_rgb\n\ndef shift_hsv_values(input_color_hsv, show = False, hue = 0, saturation = 0, value = 0):\n \n # Switch to uint16 to be able to go above 256\n shifted_img_color_hsv = input_color_hsv.copy().astype(np.uint16)\n \n # We use clip and not modulo to avoid cycling\n shifted_img_color_hsv[:,:,0] = np.clip(shifted_img_color_hsv[:,:,0] + hue, 0, 179)\n shifted_img_color_hsv[:,:,1] = np.clip(shifted_img_color_hsv[:,:,1] + saturation, 0, 255)\n shifted_img_color_hsv[:,:,2] = np.clip(shifted_img_color_hsv[:,:,2] + value, 0, 255)\n \n # Switch back to uint8 since with clip we went back below 256\n shifted_img_color_rgb = cv2.cvtColor(shifted_img_color_hsv.astype(np.uint8), cv2.COLOR_HSV2RGB)\n \n # Show image\n if show:\n plt.imshow(shifted_img_color_rgb, interpolation = 'bicubic')\n plt.axis('off')\n plt.show()\n return\n else:\n return shifted_img_color_rgb\n\ndef plot_2_images(first, \n second, \n mode,\n first_title = None, \n second_title = None, \n interpolation = None):\n\n plt.subplot(1, 2, 1)\n plt.title(first_title)\n if mode==\"gray\":\n plt.imshow(first, cmap='gray', interpolation = interpolation, vmin=0, vmax=255)\n elif mode==\"rgb\":\n plt.imshow(first, interpolation = interpolation, vmin=0, vmax=255)\n else: \n raise ValueError(\"Unknown mode = {}\".format(mode))\n plt.axis('off')\n\n plt.subplot(1, 2, 2)\n plt.title(second_title)\n if mode==\"gray\":\n plt.imshow(second, cmap='gray', interpolation = interpolation, vmin=0, vmax=255)\n elif mode==\"rgb\":\n plt.imshow(second, interpolation = interpolation, vmin=0, vmax=255)\n else: \n raise ValueError(\"Unknown mode = {}\".format(mode))\n plt.axis('off')\n plt.show()","sub_path":"2. Feature Detection/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"361047151","text":"scoville = [1, 2, 3, 9, 10, 12]\nk = 7\n\nimport heapq\n\n\ndef solution(scoville, k):\n answer = 0\n # scoville.sort()\n #\n # if scoville[0] > k:\n # return answer\n #\n # while len(scoville) > 1:\n # small = scoville.pop(0)\n # ssmall = scoville.pop(0)\n # newscoville = small + (ssmall * 2)\n\n heapq.heapify(scoville)\n while True:\n min1 = heapq.heappop(scoville)\n if min1 >= k:\n break\n elif len(scoville) == 0:\n answer = -1\n break\n min2 = heapq.heappop(scoville)\n new_scoville = min1 + 2 * min2\n heapq.heappush(scoville, new_scoville)\n answer += 1\n\n return answer\n\n\nprint(solution(scoville, k))\n","sub_path":"더 맵게.py","file_name":"더 맵게.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"200480179","text":"# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.sdk_response import SdkResponse\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass ShowIpcResponse(SdkResponse):\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'camera_id': 'str',\n 'v2x_edge_id': 'str',\n 'name': 'str',\n 'cross_id': 'str',\n 'focal_type': 'str',\n 'parent_connect_code': 'str',\n 'connect_code': 'str',\n 'description': 'str',\n 'esn': 'str',\n 'ip': 'str',\n 'status': 'str',\n 'created_time': 'datetime',\n 'last_modified_time': 'datetime',\n 'last_online_time': 'datetime'\n }\n\n attribute_map = {\n 'camera_id': 'camera_id',\n 'v2x_edge_id': 'v2x_edge_id',\n 'name': 'name',\n 'cross_id': 'cross_id',\n 'focal_type': 'focal_type',\n 'parent_connect_code': 'parent_connect_code',\n 'connect_code': 'connect_code',\n 'description': 'description',\n 'esn': 'esn',\n 'ip': 'ip',\n 'status': 'status',\n 'created_time': 'created_time',\n 'last_modified_time': 'last_modified_time',\n 'last_online_time': 'last_online_time'\n }\n\n def __init__(self, camera_id=None, v2x_edge_id=None, name=None, cross_id=None, focal_type=None, parent_connect_code=None, connect_code=None, description=None, esn=None, ip=None, status=None, created_time=None, last_modified_time=None, last_online_time=None):\n \"\"\"ShowIpcResponse\n\n The model defined in huaweicloud sdk\n\n :param camera_id: **参数说明**:摄像头ID,console界面查询摄像头IPC列表中的设备Id。\n :type camera_id: str\n :param v2x_edge_id: **参数说明**:Edge ID,用于唯一标识一个Edge,创建Edge后获得。方法参见 [创建Edge](https://support.huaweicloud.com/api-v2x/v2x_04_0078.html)。\n :type v2x_edge_id: str\n :param name: **参数说明**:摄像头名称。\n :type name: str\n :param cross_id: **参数说明**:摄像头所感知的路口或者路段的Id。\n :type cross_id: str\n :param focal_type: **参数说明**:摄像头聚焦类型。 - long:长焦 - short:短焦\n :type focal_type: str\n :param parent_connect_code: **参数说明**:摄像头连接的ITS800的互联编码。\n :type parent_connect_code: str\n :param connect_code: **参数说明**:摄像头的互联编码。\n :type connect_code: str\n :param description: **参数说明**:描述。\n :type description: str\n :param esn: **参数说明**:IPC的设备编码。\n :type esn: str\n :param ip: **参数说明**:该摄像头的ip地址。\n :type ip: str\n :param status: **参数说明**:摄像机的状态。 **取值范围**: - ONLINE:在线 - OFFLINE:离线 - INITIAL:初始化 - UNKNOWN:未知 - SLEEP:休眠\n :type status: str\n :param created_time: **参数说明**:创建时间。 格式:yyyy-MM-dd''T''HH:mm:ss''Z''。 例如 2020-09-01T01:37:01Z。\n :type created_time: datetime\n :param last_modified_time: **参数说明**:最后修改时间。 格式:yyyy-MM-dd''T''HH:mm:ss''Z''。 例如 2020-09-01T01:37:01Z。\n :type last_modified_time: datetime\n :param last_online_time: **参数说明**:最后在线时间。 格式:yyyy-MM-dd''T''HH:mm:ss''Z''。 例如 2020-09-01T01:37:01Z。\n :type last_online_time: datetime\n \"\"\"\n \n super(ShowIpcResponse, self).__init__()\n\n self._camera_id = None\n self._v2x_edge_id = None\n self._name = None\n self._cross_id = None\n self._focal_type = None\n self._parent_connect_code = None\n self._connect_code = None\n self._description = None\n self._esn = None\n self._ip = None\n self._status = None\n self._created_time = None\n self._last_modified_time = None\n self._last_online_time = None\n self.discriminator = None\n\n if camera_id is not None:\n self.camera_id = camera_id\n if v2x_edge_id is not None:\n self.v2x_edge_id = v2x_edge_id\n if name is not None:\n self.name = name\n if cross_id is not None:\n self.cross_id = cross_id\n if focal_type is not None:\n self.focal_type = focal_type\n if parent_connect_code is not None:\n self.parent_connect_code = parent_connect_code\n if connect_code is not None:\n self.connect_code = connect_code\n if description is not None:\n self.description = description\n if esn is not None:\n self.esn = esn\n if ip is not None:\n self.ip = ip\n if status is not None:\n self.status = status\n if created_time is not None:\n self.created_time = created_time\n if last_modified_time is not None:\n self.last_modified_time = last_modified_time\n if last_online_time is not None:\n self.last_online_time = last_online_time\n\n @property\n def camera_id(self):\n \"\"\"Gets the camera_id of this ShowIpcResponse.\n\n **参数说明**:摄像头ID,console界面查询摄像头IPC列表中的设备Id。\n\n :return: The camera_id of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._camera_id\n\n @camera_id.setter\n def camera_id(self, camera_id):\n \"\"\"Sets the camera_id of this ShowIpcResponse.\n\n **参数说明**:摄像头ID,console界面查询摄像头IPC列表中的设备Id。\n\n :param camera_id: The camera_id of this ShowIpcResponse.\n :type camera_id: str\n \"\"\"\n self._camera_id = camera_id\n\n @property\n def v2x_edge_id(self):\n \"\"\"Gets the v2x_edge_id of this ShowIpcResponse.\n\n **参数说明**:Edge ID,用于唯一标识一个Edge,创建Edge后获得。方法参见 [创建Edge](https://support.huaweicloud.com/api-v2x/v2x_04_0078.html)。\n\n :return: The v2x_edge_id of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._v2x_edge_id\n\n @v2x_edge_id.setter\n def v2x_edge_id(self, v2x_edge_id):\n \"\"\"Sets the v2x_edge_id of this ShowIpcResponse.\n\n **参数说明**:Edge ID,用于唯一标识一个Edge,创建Edge后获得。方法参见 [创建Edge](https://support.huaweicloud.com/api-v2x/v2x_04_0078.html)。\n\n :param v2x_edge_id: The v2x_edge_id of this ShowIpcResponse.\n :type v2x_edge_id: str\n \"\"\"\n self._v2x_edge_id = v2x_edge_id\n\n @property\n def name(self):\n \"\"\"Gets the name of this ShowIpcResponse.\n\n **参数说明**:摄像头名称。\n\n :return: The name of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this ShowIpcResponse.\n\n **参数说明**:摄像头名称。\n\n :param name: The name of this ShowIpcResponse.\n :type name: str\n \"\"\"\n self._name = name\n\n @property\n def cross_id(self):\n \"\"\"Gets the cross_id of this ShowIpcResponse.\n\n **参数说明**:摄像头所感知的路口或者路段的Id。\n\n :return: The cross_id of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._cross_id\n\n @cross_id.setter\n def cross_id(self, cross_id):\n \"\"\"Sets the cross_id of this ShowIpcResponse.\n\n **参数说明**:摄像头所感知的路口或者路段的Id。\n\n :param cross_id: The cross_id of this ShowIpcResponse.\n :type cross_id: str\n \"\"\"\n self._cross_id = cross_id\n\n @property\n def focal_type(self):\n \"\"\"Gets the focal_type of this ShowIpcResponse.\n\n **参数说明**:摄像头聚焦类型。 - long:长焦 - short:短焦\n\n :return: The focal_type of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._focal_type\n\n @focal_type.setter\n def focal_type(self, focal_type):\n \"\"\"Sets the focal_type of this ShowIpcResponse.\n\n **参数说明**:摄像头聚焦类型。 - long:长焦 - short:短焦\n\n :param focal_type: The focal_type of this ShowIpcResponse.\n :type focal_type: str\n \"\"\"\n self._focal_type = focal_type\n\n @property\n def parent_connect_code(self):\n \"\"\"Gets the parent_connect_code of this ShowIpcResponse.\n\n **参数说明**:摄像头连接的ITS800的互联编码。\n\n :return: The parent_connect_code of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._parent_connect_code\n\n @parent_connect_code.setter\n def parent_connect_code(self, parent_connect_code):\n \"\"\"Sets the parent_connect_code of this ShowIpcResponse.\n\n **参数说明**:摄像头连接的ITS800的互联编码。\n\n :param parent_connect_code: The parent_connect_code of this ShowIpcResponse.\n :type parent_connect_code: str\n \"\"\"\n self._parent_connect_code = parent_connect_code\n\n @property\n def connect_code(self):\n \"\"\"Gets the connect_code of this ShowIpcResponse.\n\n **参数说明**:摄像头的互联编码。\n\n :return: The connect_code of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._connect_code\n\n @connect_code.setter\n def connect_code(self, connect_code):\n \"\"\"Sets the connect_code of this ShowIpcResponse.\n\n **参数说明**:摄像头的互联编码。\n\n :param connect_code: The connect_code of this ShowIpcResponse.\n :type connect_code: str\n \"\"\"\n self._connect_code = connect_code\n\n @property\n def description(self):\n \"\"\"Gets the description of this ShowIpcResponse.\n\n **参数说明**:描述。\n\n :return: The description of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._description\n\n @description.setter\n def description(self, description):\n \"\"\"Sets the description of this ShowIpcResponse.\n\n **参数说明**:描述。\n\n :param description: The description of this ShowIpcResponse.\n :type description: str\n \"\"\"\n self._description = description\n\n @property\n def esn(self):\n \"\"\"Gets the esn of this ShowIpcResponse.\n\n **参数说明**:IPC的设备编码。\n\n :return: The esn of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._esn\n\n @esn.setter\n def esn(self, esn):\n \"\"\"Sets the esn of this ShowIpcResponse.\n\n **参数说明**:IPC的设备编码。\n\n :param esn: The esn of this ShowIpcResponse.\n :type esn: str\n \"\"\"\n self._esn = esn\n\n @property\n def ip(self):\n \"\"\"Gets the ip of this ShowIpcResponse.\n\n **参数说明**:该摄像头的ip地址。\n\n :return: The ip of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._ip\n\n @ip.setter\n def ip(self, ip):\n \"\"\"Sets the ip of this ShowIpcResponse.\n\n **参数说明**:该摄像头的ip地址。\n\n :param ip: The ip of this ShowIpcResponse.\n :type ip: str\n \"\"\"\n self._ip = ip\n\n @property\n def status(self):\n \"\"\"Gets the status of this ShowIpcResponse.\n\n **参数说明**:摄像机的状态。 **取值范围**: - ONLINE:在线 - OFFLINE:离线 - INITIAL:初始化 - UNKNOWN:未知 - SLEEP:休眠\n\n :return: The status of this ShowIpcResponse.\n :rtype: str\n \"\"\"\n return self._status\n\n @status.setter\n def status(self, status):\n \"\"\"Sets the status of this ShowIpcResponse.\n\n **参数说明**:摄像机的状态。 **取值范围**: - ONLINE:在线 - OFFLINE:离线 - INITIAL:初始化 - UNKNOWN:未知 - SLEEP:休眠\n\n :param status: The status of this ShowIpcResponse.\n :type status: str\n \"\"\"\n self._status = status\n\n @property\n def created_time(self):\n \"\"\"Gets the created_time of this ShowIpcResponse.\n\n **参数说明**:创建时间。 格式:yyyy-MM-dd''T''HH:mm:ss''Z''。 例如 2020-09-01T01:37:01Z。\n\n :return: The created_time of this ShowIpcResponse.\n :rtype: datetime\n \"\"\"\n return self._created_time\n\n @created_time.setter\n def created_time(self, created_time):\n \"\"\"Sets the created_time of this ShowIpcResponse.\n\n **参数说明**:创建时间。 格式:yyyy-MM-dd''T''HH:mm:ss''Z''。 例如 2020-09-01T01:37:01Z。\n\n :param created_time: The created_time of this ShowIpcResponse.\n :type created_time: datetime\n \"\"\"\n self._created_time = created_time\n\n @property\n def last_modified_time(self):\n \"\"\"Gets the last_modified_time of this ShowIpcResponse.\n\n **参数说明**:最后修改时间。 格式:yyyy-MM-dd''T''HH:mm:ss''Z''。 例如 2020-09-01T01:37:01Z。\n\n :return: The last_modified_time of this ShowIpcResponse.\n :rtype: datetime\n \"\"\"\n return self._last_modified_time\n\n @last_modified_time.setter\n def last_modified_time(self, last_modified_time):\n \"\"\"Sets the last_modified_time of this ShowIpcResponse.\n\n **参数说明**:最后修改时间。 格式:yyyy-MM-dd''T''HH:mm:ss''Z''。 例如 2020-09-01T01:37:01Z。\n\n :param last_modified_time: The last_modified_time of this ShowIpcResponse.\n :type last_modified_time: datetime\n \"\"\"\n self._last_modified_time = last_modified_time\n\n @property\n def last_online_time(self):\n \"\"\"Gets the last_online_time of this ShowIpcResponse.\n\n **参数说明**:最后在线时间。 格式:yyyy-MM-dd''T''HH:mm:ss''Z''。 例如 2020-09-01T01:37:01Z。\n\n :return: The last_online_time of this ShowIpcResponse.\n :rtype: datetime\n \"\"\"\n return self._last_online_time\n\n @last_online_time.setter\n def last_online_time(self, last_online_time):\n \"\"\"Sets the last_online_time of this ShowIpcResponse.\n\n **参数说明**:最后在线时间。 格式:yyyy-MM-dd''T''HH:mm:ss''Z''。 例如 2020-09-01T01:37:01Z。\n\n :param last_online_time: The last_online_time of this ShowIpcResponse.\n :type last_online_time: datetime\n \"\"\"\n self._last_online_time = last_online_time\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ShowIpcResponse):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"huaweicloud-sdk-dris/huaweicloudsdkdris/v1/model/show_ipc_response.py","file_name":"show_ipc_response.py","file_ext":"py","file_size_in_byte":16681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"424815455","text":"# -*- coding: utf-8 -*-\n# Copyright 2015 Hewlett-Packard Development Company, L.P.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport uuid\n\nfrom cue import client\nfrom cue.tests.functional import base\nfrom cue.tests.functional.fixtures import nova\nimport os_tasklib.nova.create_vm_group as create_vm_group\n\nfrom taskflow import engines\nfrom taskflow.patterns import linear_flow\n\n\nclass CreateVmGroupTests(base.FunctionalTestCase):\n additional_fixtures = [\n nova.NovaClient\n ]\n\n def setUp(self):\n super(CreateVmGroupTests, self).setUp()\n\n self.nova_client = client.nova_client()\n\n self.new_vm_group_name = str(uuid.uuid4())\n self.new_vm_group_id = None\n\n self.flow = linear_flow.Flow(\"create vm group flow\")\n self.flow.add(\n create_vm_group.CreateVmGroup(\n os_client=self.nova_client,\n requires=('name', 'policies'),\n provides='new_vm_group',\n rebind={'name': 'vm_group_name'}\n )\n )\n\n def test_create_vm_group(self):\n \"\"\"Verifies CreateVMGroup task directly.\"\"\"\n\n flow_store = {\n 'vm_group_name': self.new_vm_group_name,\n 'policies': ['anti-affinity']\n }\n\n result = engines.run(self.flow, store=flow_store)\n self.new_vm_group_id = result['new_vm_group']['id']\n vm_group = self.nova_client.server_groups.get(self.new_vm_group_id)\n self.assertEqual(self.new_vm_group_name, vm_group.name)\n","sub_path":"cue/tests/functional/taskflow/task/test_create_vm_group.py","file_name":"test_create_vm_group.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"77501300","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 19 09:11:59 2017\n\n@author: xinyuyang\n\"\"\"\nfrom utils.dataset import DataSet\n\ndataset=DataSet()\nstan=dataset.stances\nart=dataset.articles\natrain=[]\nadev=[]\natest=[]\nwith open('splits/training_ids.txt','r') as tr:\n for line in tr:\n i=int(line)\n for index, st in enumerate (stan):\n if i== st['Body ID']:\n atrain.append(index) \nwith open('splits/test_ids.txt','r') as te:\n for line in te:\n i=int(line)\n for index, st in enumerate (stan):\n if i== st['Body ID']:\n atest.append(index) \nwith open('splits/dev_ids.txt','r') as de:\n for line in de:\n i=int(line)\n for index, st in enumerate (stan):\n if i== st['Body ID']:\n adev.append(index)","sub_path":"fnc/datasplit.py","file_name":"datasplit.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"487274031","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis implementation of WriteBaseTransformer is responsible for writing References\n\"\"\"\nfrom typing import Optional\n\nfrom borb.io.read.types import AnyPDFType, Reference\nfrom borb.io.write.write_base_transformer import (\n WriteBaseTransformer,\n WriteTransformerState,\n)\n\n\nclass WriteReferenceTransform(WriteBaseTransformer):\n \"\"\"\n This implementation of WriteBaseTransformer is responsible for writing References\n \"\"\"\n\n def can_be_transformed(self, any: AnyPDFType):\n \"\"\"\n This function returns True if the object to be converted represents a Reference\n \"\"\"\n return isinstance(any, Reference)\n\n def transform(\n self,\n object_to_transform: AnyPDFType,\n context: Optional[WriteTransformerState] = None,\n ):\n \"\"\"\n This method writes a Reference to a byte stream\n \"\"\"\n assert (\n context is not None\n ), \"A WriteTransformerState must be defined in order to write Reference objects.\"\n assert context.destination is not None\n assert isinstance(object_to_transform, Reference)\n\n assert object_to_transform.object_number is not None\n context.destination.write(\n bytes(\n \"%d %d R\"\n % (\n object_to_transform.object_number,\n object_to_transform.generation_number or 0,\n ),\n \"latin1\",\n )\n )\n","sub_path":"lamda-ocr/merge-files/borb/io/write/reference/write_reference_transformer.py","file_name":"write_reference_transformer.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"461504029","text":"\"\"\"\nRetrieve timeline of UFC events from wikipedia and output as json.\n\nTODO: sanitize inputs (e.g. could be vulnerable to XSS)\n\"\"\"\n# pip install bs4\nfrom bs4 import BeautifulSoup\nimport json\nimport sys\nimport shelve\nimport logging\nfrom collections import OrderedDict\n\nfrom async_request import async_urlopen\n\nlogging.getLogger('async_request').addHandler(logging.StreamHandler())\nlogging.getLogger('async_request').setLevel(logging.DEBUG)\n\nEVENTS_URL = 'https://en.wikipedia.org/wiki/List_of_UFC_events'\nBASE_URL = 'https://en.wikipedia.org'\nNUM_PARALLEL_REQUESTS = 20\n\n\ndef main():\n output = OrderedDict((\n ('title', 'UFC Events'),\n ('events', get_events())\n ))\n print(json.dumps(output, indent=2))\n\n\ndef get_events():\n request = RequestCache()\n event_list_page = request.getOne(EVENTS_URL)\n\n future_events = EventsListPage.getFutureEvents(event_list_page)\n future_events_results = _get_event_details(request, future_events)\n\n past_events = EventsListPage.getPastEvents(event_list_page)\n past_events_results = _get_event_details(request, past_events)\n\n request.close()\n return future_events_results + past_events_results\n\n\ndef _get_event_details(request_obj, events_list):\n \"\"\"\n Given a list of dictionary events, add a 'fight_card' field with the event\n details.\n \"\"\"\n event_urls = [e['event_url']\n for e in events_list if e['event_url'] is not None]\n events_data = iter(request_obj.getMany(event_urls))\n for e in events_list:\n if e['event_url'] is not None:\n e['fight_card'] = EventPage.getJson(e['text'], next(events_data))\n else:\n e['fight_card'] = None\n\n return events_list\n\n\nclass EventPage:\n\n \"\"\"\n Parse the 'Results' table (for past events) or 'Official fight card'\n table (for future events) on a UFC event page.\n \"\"\"\n\n @classmethod\n def getJson(cls, title, data, as_dict=True):\n table = cls._getTable(title, data)\n if table is None:\n return None\n trs = table.findAll('tr')\n results = map(cls._parseRow, trs[1:])\n results = [x for x in results if x is not None]\n return results if as_dict else json.dumps(results, indent=2)\n\n @staticmethod\n def _getTable(event_title, data):\n title = data.find('h1', attrs={'id': 'firstHeading'})\n table = None\n\n # Special case where event is on a \"2012_in_UFC\" aggregated page\n if title.text.lower().endswith('in ufc'):\n debug(\"Title={}\".format(title.text))\n headlines = data.findAll('span', attrs={'class': 'mw-headline'})\n headline = [x for x in headlines if x.text == event_title]\n table = headline[0].find_next(\n 'table', attrs={'class': 'toccolours'}) if len(headline) > 0 else None\n # Normal case where event is on its own page\n else:\n table = data.find('table', attrs={'class': 'toccolours'})\n return table\n\n @staticmethod\n def _parseRow(row):\n tds = row.findAll('td')\n\n # Skip header rows (there are multiple midway through the table)\n if len(tds) == 0:\n return None\n\n try:\n # weight, winner, _, loser, result, rounds, time, notes\n weight, winner, _, loser, result, \\\n rounds, time = tds[:7] # pylint: disable=W0612\n except ValueError:\n debug(row)\n raise\n\n winner, _ = _getTextAndLink(winner)\n loser, _ = _getTextAndLink(loser)\n\n return OrderedDict((\n ('winner', winner),\n ('loser', loser),\n ('result', result.text),\n ('weight_class', weight.text)\n ))\n\n\nclass EventsListPage:\n\n \"\"\" Parse the 'Scheduled Events' or 'Past Events' table on List_of_UFC_events to a dictionary. \"\"\"\n\n @classmethod\n def getPastEvents(cls, data):\n tables = data.findAll('table')\n # As of now Past Events is the 2nd table on the page\n return cls._getJson(tables[1], cls._parsePastRow)\n\n @classmethod\n def getFutureEvents(cls, data):\n table = data.find('table', attrs={'id': 'Scheduled_events'})\n return cls._getJson(table, cls._parseFutureRow)\n\n @classmethod\n def _getJson(cls, table, row_parser_func):\n trs = table.findAll('tr')\n events = [row_parser_func(tr) for tr in trs[1:]]\n return events\n\n @staticmethod\n def _parseDateSpan(date_td):\n \"\"\"\n Retrieves the human readable date from the following td element pattern:\n 000000002016-01-17-0000\n Jan 17, 2016\n \"\"\"\n date_spans = date_td.findAll('span')\n date = date_spans[1] if len(date_spans) > 1 else date_td\n return date\n\n @staticmethod\n def _parseFutureRow(row):\n event, date, venue, location = row.findAll('td')\n\n date = EventsListPage._parseDateSpan(date)\n text, link = _getTextAndLink(event)\n link = BASE_URL + link if link is not None else None\n\n return OrderedDict((\n ('text', text),\n ('date', date.text),\n ('venue', venue.text),\n ('location', location.text),\n ('event_url', link)\n ))\n\n @staticmethod\n def _parsePastRow(row):\n num, event, date, venue, location, attendance = row.findAll( # pylint: disable=W0612\n 'td')\n\n date = EventsListPage._parseDateSpan(date)\n text, link = _getTextAndLink(event)\n link = BASE_URL + link if link is not None else None\n\n return OrderedDict((\n ('number', num.text),\n ('text', text),\n ('date', date.text),\n ('venue', venue.text),\n ('location', location.text),\n ('event_url', link)\n ))\n\n\ndef _getTextAndLink(el):\n \"\"\" Returns (text, link) out of an element \"\"\"\n a = el.find('a')\n if a is not None:\n link = a.get('href')\n text = a.text\n else:\n link = None\n text = el.text\n return (text, link)\n\n\nclass RequestCache:\n\n def __init__(self):\n self.cache = shelve.open('bs_cache.shelve')\n\n def getOne(self, url=EVENTS_URL):\n if url not in self.cache:\n self.cache[url] = async_urlopen([url])[0]\n else:\n debug('Cache hit: ' + url)\n return BeautifulSoup(self.cache[url], \"html.parser\")\n\n def getMany(self, urls):\n not_cached_urls = [x for x in urls if (x not in self.cache)]\n responses = []\n if len(not_cached_urls) > 0:\n responses = async_urlopen(not_cached_urls, NUM_PARALLEL_REQUESTS)\n for req, res in zip(not_cached_urls, responses):\n self.cache[req] = res\n\n return [BeautifulSoup(self.cache[x], \"html.parser\") for x in urls]\n\n def close(self):\n self.cache.close()\n\n\ndef debug(s):\n sys.stderr.write(\"DEBUG: %s\\n\" % (s))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"timeline/scripts/get_ufc_events.py","file_name":"get_ufc_events.py","file_ext":"py","file_size_in_byte":7031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"574980718","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport resource\n\n\n# In[2]:\n\n\n#Memory usage (in bytes) before running program\nresource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n\n\n# In[4]:\n\n\nimport numpy\nimport matplotlib.pyplot as plt\nimport pandas\nimport math\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\n\nimport time\n\n\n# In[5]:\n\n\n#Reading data\ndataframe = pandas.read_csv('RNN_data.csv', usecols=[1], engine='python')\ndataset = dataframe.values\ndataset = dataset.astype('float32')\n\n\n# In[6]:\n\n\n#Normalize the data\nscaler = MinMaxScaler(feature_range=(0, 1))\ndataset = scaler.fit_transform(dataset)\n\n\n# In[7]:\n\n\n#Train, Test set Split\ntrain_size = int(len(dataset) * 0.7)\ntest_size = len(dataset) - train_size\ntrain, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]\nprint(len(train), len(test))\n\n\n# In[8]:\n\n\n#Function to generate time series data matrix from given data\ndef create_dataset(dataset, look_back=1):\n dataX, dataY = [], []\n for i in range(len(dataset)-look_back-1):\n a = dataset[i:(i+look_back), 0]\n dataX.append(a)\n dataY.append(dataset[i + look_back, 0])\n return numpy.array(dataX), numpy.array(dataY)\n\n\n# In[9]:\n\n\n#reshape into X=t and Y=t+1 using create_dataset function defined above\nlook_back = 2\ntrainX, trainY = create_dataset(train, look_back)\ntestX, testY = create_dataset(test, look_back)\n\n\n# In[10]:\n\n\n#LSTM Sequential model takes input in form of [samples, time steps, features]\n#so reshape input to [samples, time steps, features]\ntrainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\ntestX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n\n\n# In[11]:\n\n\ntime_start = time.clock()\n#Sequential Model from Keras library used\nmodel = Sequential()\n\n#add LSTM layer and a regular densely-connected NN layer\nmodel.add(LSTM(25, input_shape=(1, look_back)))\nmodel.add(Dense(1))\n\n#Compile, set optimizer to adam and then fit the training data\nmodel.compile(loss='mean_squared_error', optimizer='adam')\nmodel.fit(trainX, trainY, epochs=200, batch_size=1, verbose=2)\n\n\n# In[12]:\n\n\n#Predicting for test set & train set and calculating loss \ntrainPredict = model.predict(trainX)\ntestPredict = model.predict(testX)\n\n#inverting predictions before calculating error so that performance is reported in the same units as the original data\n#reverse of normalizing\ntrainPredict = scaler.inverse_transform(trainPredict)\ntrainY = scaler.inverse_transform([trainY])\ntestPredict = scaler.inverse_transform(testPredict)\ntestY = scaler.inverse_transform([testY])\n\n#calculating root mean squared error\ntrainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))\nprint('Train Score: %.2f RMSE' % (trainScore))\ntestScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))\nprint('Test Score: %.2f RMSE' % (testScore))\n\n\n# In[13]:\n\n\n#time taken by the whole process\ntime_elapsed = (time.clock() - time_start)\ntime_elapsed\n\n\n# In[17]:\n\n\n#Shifting axis for plotting\ntrainPredictPlot = numpy.empty_like(dataset)\ntrainPredictPlot[:, :] = numpy.nan\ntrainPredictPlot[0:len(trainPredict), :] = trainPredict\n\ntestPredictPlot = numpy.empty_like(dataset)\ntestPredictPlot[:, :] = numpy.nan\ntestPredictPlot[len(trainPredict)+(look_back)+1:len(dataset)-1-(look_back), :] = testPredict\n\n#Plotting baseline and predictions\nplt.plot(scaler.inverse_transform(dataset))\nplt.plot(trainPredictPlot)\nplt.plot(testPredictPlot)\nplt.show()\n\n\n# In[14]:\n\n\n#Memory usage (in bytes) after running program\nresource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n\n\n# In[15]:\n\n\nmin(trainPredict)\n\n\n# In[16]:\n\n\nmax(trainPredict)\n\n","sub_path":"LSTM_based_RNN/RNN_LSTM.py","file_name":"RNN_LSTM.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"622128221","text":"# ===========================================================================\n#\n# file : gf_lcd_spi.py\n# part of : godafoss micropython library\n# url : https://www.github.com/wovo/godafoss\n# author : Wouter van Ooijen (wouter@voti.nl) 2023\n# license : MIT license, see license variable in the __init__.py\n#\n# This file is part of the Godafoss perhiperal interface library.\n#\n# This file contains the lcd_spi class.\n#\n# ===========================================================================\n\nimport machine\nfrom godafoss.gf_pins import *\nfrom godafoss.gf_make_pins import *\n\n\n# ===========================================================================\n\nclass lcd_spi:\n \"\"\"\n spi lcd command / data\n \n :param spi: (machine.SPI)\n spi interface (miso not used)\n \n :param data_command: ($macro_insert make_pin_out_types)\n data / command pin, high for data, low for command\n \n :param chip_select: ($macro_insert make_pin_out_types)\n chip select pin, active low\n \n This class provides the basic command & data interface\n for a spi LCD with a command / data pin.\n \"\"\"\n\n # ======================================================================= \n\n def __init__(\n self,\n spi: machine.SPI, \n data_command: [ int, pin_out, pin_in_out, pin_oc ],\n chip_select: [ int, pin_out, pin_in_out, pin_oc ]\n ) -> None:\n self._spi = spi\n self._data_command = make_pin_out( data_command )\n self._chip_select = make_pin_out( chip_select )\n\n # ======================================================================= \n\n def write_command(\n self, \n command: int = None, \n data = None,\n buffer = None\n ) -> None:\n \"\"\"\n write command and/or data\n \n :param command: (None, int)\n a command byte to be send to the lcd\n \n :param data: (None, sequence of bytes)\n data bytes to be send to the lcd\n \n This method writes a command (integer, optional)\n and data (also optional) to the lcd.\n The data must be acceptabel for a bytes() call.\n \"\"\"\n \n self._chip_select.write( 0 )\n\n if command is not None: \n self._data_command.write( 0 )\n self._spi.write( bytearray( [ command ] ) )\n #self._chip_select.write( 1 )\n \n if data is not None:\n self._data_command.write( 1 )\n #self._chip_select.write( 0 )\n self._spi.write( bytes( data ) )\n \n if buffer is not None:\n self._data_command.write( 1 )\n #self._chip_select.write( 0 )\n self._spi.write( buffer )\n \n self._chip_select.write( 1 ) \n\n # ======================================================================= \n\n# =========================================================================== \n","sub_path":"source/godafoss/gf_lcd_spi.py","file_name":"gf_lcd_spi.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"205066847","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom numpy import pi, cos, sin, zeros\nfrom numpy.random import random\nfrom modules.growth import spawn_curl\nfrom numpy import floor\n\nNMAX = 10**5\nSIZE = 1000\nONE = 1./SIZE\n\nSTP = ONE*0.1\nNEARL = 15*ONE\nFARL = 0.235\n\nPROCS = 1\n\nMID = 0.5\n\nLINEWIDTH = 5.*ONE\n\nINIT_NUM = 7\n\nBACK = [1,1,1,1]\nFRONT = [0,0,0,0.05]\n\nTWOPI = pi*2.\n\ndef get_grains():\n if random()<0.5:\n g = 10 + floor(random()*10)\n def f():\n while True:\n yield g\n\n else:\n g = [10]\n def f():\n while True:\n g[0] += (-1)**floor(2*random())\n if g[0]<1:\n g[0] = 0\n yield g[0]\n\n return f\n\ndef run(fn):\n from time import time\n from itertools import count\n from numpy.random import randint\n\n from differentialLine import DifferentialLine\n from render.render import Render\n from modules.helpers import print_stats\n from modules.show import sandstroke\n from modules.show import dots\n\n np_coords = zeros(shape=(NMAX,4), dtype='float')\n np_vert_coords = zeros(shape=(NMAX,2), dtype='float')\n\n\n DF = DifferentialLine(NMAX, FARL*2, NEARL, FARL, PROCS)\n\n render = Render(SIZE, BACK, FRONT)\n\n render.ctx.set_source_rgba(*FRONT)\n render.ctx.set_line_width(LINEWIDTH)\n\n rnd = randint(2)\n\n if rnd == 0: # circle\n print('circle')\n\n angles = sorted(random(INIT_NUM)*TWOPI)\n DF.init_circle_segment(MID,MID,0.2, angles)\n\n elif rnd == 1: # arc\n print('arc')\n\n angles = sorted((random()*2+random(INIT_NUM)*1.5)*pi)\n xys = []\n for a in angles:\n r = 0.1+random()*0.1\n x = 0.5 + cos(a)*r\n y = 0.5 + sin(a)*r\n xys.append((x,y))\n DF.init_line_segment(xys, lock_edges=1)\n\n else:\n print('no selection')\n return\n\n grains = get_grains()\n\n render.set_front(FRONT)\n for i in count():\n t_start = time()\n\n DF.optimize_position(STP)\n spawn_curl(DF, NEARL, 0.016)\n\n coord_num = DF.np_get_edges_coordinates(np_coords)\n\n g = grains().next()\n sandstroke(render,np_coords[:coord_num,:],g)\n\n vert_num = DF.np_get_vert_coordinates(np_vert_coords)\n\n if random()<0.9:\n dots(render,np_vert_coords[:vert_num,:])\n\n if random()<0.1:\n sandstroke(render,np_coords[:coord_num,:],g)\n\n mi = np_vert_coords[:vert_num, :].min()\n ma = np_vert_coords[:vert_num, :].max()\n\n if ma>0.93 or mi<0.07:\n\n render.transparent_pix()\n print(fn)\n render.write_to_png(fn)\n\n return\n\n t_stop = time()\n\n if not i%300:\n print('grains', g)\n print('min, max', mi, ma)\n print_stats(i,t_stop-t_start,DF)\n\n\nif __name__ == '__main__':\n run(fn='./example.png')\n\n","sub_path":"_differentialLine/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"176650291","text":"\n# coding: utf-8\n\nimport time\nimport pandas as pd\nimport os\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql import HiveContext\nfrom pyspark.sql.window import Window\nimport pyspark.sql.functions as F\nfrom pyspark.sql.types import FloatType\n\n\nconf = SparkConf().setAppName(\"Calcul trends 24h\")\nsc = SparkContext(conf=conf)\nhc = HiveContext(sc)\n\nwikipediadata = hc.read.format(\"org.apache.spark.sql.cassandra\") \\\n .load(keyspace=\"projet\", table=\"wikipediadata\")\n\n\ndef filename(day):\n return '/home/ubuntu/projetnosql/day_{}_24htrending.csv'.format(day)\n\n\ndef compute(day):\n # On veut les 24 dernieres heures de day\n sums = wikipediadata.where(wikipediadata.day == day)\n # Sous-ensemble de test\n #sums = sums.where((sums.page == 'Cadillac_Brougham') | ((sums.page == 'Roald_Dahl') & (sums.projectcode == 'fr')))\n\n # On cache pour plus tard\n sums.cache()\n\n # on définit une windows := heure précédente\n window_spec = Window.partitionBy(sums.projectcode, sums.page) \\\n .orderBy(sums.hour.asc()).rowsBetween(-1, -1)\n\n # on calcule la différence entre views(h) - views(h-1)\n diffs = sums.withColumn('diff', sums.views - F.sum(sums.views) \\\n .over(window_spec))\n\n # on calcule les coefs à appliquer à chaque jour\n coefs = pd.DataFrame({'hour': range(24)})\n coefs['coef'] = 1. / (24. - coefs.hour)\n\n coefs = hc.createDataFrame(coefs)\n diffs = diffs.join(coefs, 'hour')\n\n # on calcul le score de chaque jour\n diffs = diffs.withColumn('sub_score', diffs.diff * diffs.coef)\n\n totals = diffs.groupby('projectcode', 'page').sum('views', 'sub_score')\n # on normalise par la racine de la somme des views \n totals = totals.withColumn('score',\n totals['SUM(sub_score)'] / F.sqrt(totals['SUM(views)'])) \\\n .orderBy(F.desc('score')) \\\n .withColumnRenamed('SUM(views)', 'total_views') \\\n .limit(10)\n\n views = sums.select('projectcode', 'page', 'hour', 'views') \\\n .join(totals.select('projectcode', 'page', 'total_views', 'score'), \n (totals.projectcode == sums.projectcode) & (totals.page == sums.page), 'right_outer')\n\n df = totals.select('projectcode', 'page', 'total_views', 'score').toPandas()\n df2 = views.toPandas()\n df2 = df2.iloc[:, 2:]\n df2 = df2.pivot_table(values='views', columns=['hour'], index=['projectcode', 'page'], fill_value=0)\n df = df.merge(df2, left_on=['projectcode', 'page'], right_index=True)\n df.to_csv(filename(day), index=False)\n \n # on vide le cache\n hc.clearCache()\n\n \n\n\n\nfor day in range(89, -1, -1):\n if os.path.exists(filename(day)):\n with open('/home/ubuntu/projetnosql/log_time', 'a') as f:\n f.write('\\nFile {} already exists, skip day {}' \\\n .format(filename(day), day))\n continue\n\n try:\n t0 = time.time()\n compute(day)\n # on calcule la différence entre views jour courant - views jour précédent\n t1 = time.time()\n d = t1-t0\n m = int(d // 60)\n s = int(d % 60)\n with open('/home/ubuntu/projetnosql/log_time', 'a') as f:\n f.write('\\nday {} written in {} min and {} sec'.format(day, m, s))\n except:\n with open('/home/ubuntu/projetnosql/log_errors', 'a') as f:\n f.write('\\nday {} has not been correctly computed!'.format(day)) \n\n","sub_path":"Req24h.py","file_name":"Req24h.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"488187199","text":"import pandas as pd\n\n# https://blog.csdn.net/wendaomudong_l2d4/article/details/83039724\n\ndf = pd.DataFrame({\n 'x1': [\"a\", \"b\", \"c\", \"b\"],\n \"x2\": [1, 2, 3, 4],\n \"x3\": [4, 3, 2, 1]\n})\nprint(df)\n\n\ndef count():\n # 统计个数\n print(df.x1.count())\n\n\ndef count_nunique():\n # ## 统计不重复的个数\n print(df.x1.nunique())\n\n\ndef count_unique():\n ## 得到不重复的值\n ## 返回结果是array\n print(df.x1.unique())\n\n\ndef count_freq():\n # 不同于列表,可以直接统计某个值出现的次数,DataFrame需要做一些转换。\n print(list(df.x1).count('b'))\n print(sum(df.x1.apply(lambda x: 1 if x=='b' else 0)))\n print(df.x1.apply(lambda x: 1 if x=='b' else 0).sum())\n\n\ndef groupby_count():\n # 分组统计\n x = pd.DataFrame({\n \"x1\": [\"a\", \"a\", \"b\", \"b\", 'c'],\n \"x2\": [1, 1, 1, 2, 2],\n \"x3\": [1, 2, 3, 4, 5]\n })\n print(x)\n print(x.groupby(by='x1').count())\n print(x.groupby(by=['x1', 'x2'], as_index=False).count())\n # 这里没有分各个列。\n print(x.groupby(by='x1').size())\n\n\ndef groupby_count_distinct_col1():\n x = pd.DataFrame({\n \"x1\": [\"a\", \"a\", \"b\", \"b\", 'c'],\n \"x2\": [1, 1, 1, 2, 2],\n \"x3\": [1, 2, 3, 4, 5]\n })\n # 类似于sql:select x1,count(distinct x1),count(distinct x2),count(distinct x3) from table group by x1\n print(x.groupby(by='x1').nunique())\n\n\ndef groupby_count_other():\n #\n x = pd.DataFrame({\n \"x1\": [\"a\", \"a\", \"b\", \"b\", 'c'],\n \"x2\": [1, 1, 1, 2, 2],\n \"x3\": [1, 2, 3, 4, 5]\n })\n print(x.groupby(by=[\"x1\",'x2']).mean())\n print(x.groupby(by=[\"x1\",'x2']).sum())\n print(x.groupby(by=[\"x1\",'x2'], as_index=False).aggregate(sum))\n\n\ndef groupby_describe():\n x = pd.DataFrame({\n \"x1\": [\"a\", \"a\", \"b\", \"b\", 'c'],\n \"x2\": [1, 1, 1, 2, 2],\n \"x3\": [1, 2, 3, 4, 5]\n })\n print(x.groupby(by=[\"x1\", 'x2'], as_index=True).describe())\n print(x.groupby(by=[\"x1\", 'x2'], as_index=False).describe())\n\n\ndef main():\n # count() # 统计个数\n # count_nunique() # 统计不重复值个数nunique\n # count_unique() # 筛选不重复值\n # count_freq() # 统计某一个值的���数\n # groupby_count() # 分组统计\n # groupby_count_distinct_col1() # 分组统计\n # groupby_count_other() # x.groupby(by=[\"x1\",'x2']).mean()\n groupby_describe() # 整体的描述统计\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"pandas_zhengli/pandas_count.py","file_name":"pandas_count.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"644389631","text":"import sys, os\nsys.path.append(os.path.abspath('../'))\n\nimport neonet\nimport netlog as logging\nimport filebase, remote_control\nimport storage, _thread\n\nif not os.path.isfile(\"cfg.txt\"):\n storage.saveDict(\"cfg.txt\", {\n 'adr':0xC7860010,\n 'key':'default-key',\n 'filebase-dir':'./filebase/',\n 'log_dir':'./logs/'\n })\ncfg = storage.loadDict(\"cfg.txt\")\nneonet.setup(cfg['adr'])\n\nlogging.add_log_file(os.path.join(cfg['log_dir'],'{}.txt'))\n\nlogging.log(\"Starting Filebase and Remote Control...\")\n_thread.start_new_thread(filebase.run, (cfg['key'],cfg['filebase-dir']))\n_thread.start_new_thread(remote_control.run, (cfg['key'],))\n","sub_path":"python3/Programs/speednode/speednode.py","file_name":"speednode.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"201224840","text":"\"\"\"empty message\n\nRevision ID: b05f938bde77\nRevises: ad34a1f59122\nCreate Date: 2019-01-19 11:36:08.309906\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b05f938bde77'\ndown_revision = 'ad34a1f59122'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('friends',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('focused_id', sa.Integer(), nullable=True),\n sa.Column('focuser_id', sa.Integer(), nullable=True),\n sa.Column('addtime', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_friends_addtime'), 'friends', ['addtime'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_friends_addtime'), table_name='friends')\n op.drop_table('friends')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/b05f938bde77_.py","file_name":"b05f938bde77_.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"120573155","text":"# Author: Thomas Vu\r\n# Email: thomas.vu@ucalgary.ca\r\n# Feel free to send any questions about this problem to the email above\r\n# or ask in the CPC discord. (discord.gg/MEXwfze)\r\n# ---------------------------------------------------------------------\r\n\r\nfor _ in range(int(input())):\r\n people = {}\r\n classes = {}\r\n\r\n for _ in range(int(input())):\r\n line = input().split()\r\n people[line[0][:-1]] = line[1].split(\"-\")\r\n\r\n for person in people:\r\n\r\n classNumber = \"\"\r\n for distinction in reversed(people[person]):\r\n if distinction == \"upper\": classNumber += \"1\"\r\n if distinction == \"middle\": classNumber += \"2\"\r\n if distinction == \"lower\": classNumber += \"3\"\r\n classNumber += \"2\" * (10-len(classNumber))\r\n\r\n if classNumber in classes:\r\n classes[classNumber].append(person)\r\n else:\r\n classes[classNumber] = [person]\r\n\r\n for key in sorted(classes.keys()):\r\n for person in sorted(classes[key]):\r\n print(person)\r\n\r\n print(\"==============================\")","sub_path":"solutions/classy.py","file_name":"classy.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"350912796","text":"import time\n\nfrom base.base_analyze import analyze_file\nfrom base.base_driver import init_driver\nfrom page.page import Page\nimport pytest\n\nclass TestUpdate:\n \"\"\"\n 更新版本\n \"\"\"\n def setup(self):\n self.driver=init_driver()\n self.page=Page(self.driver)\n def teardown(self):\n time.sleep(1)\n self.driver.quit()\n def test_update(self):\n #没有登录先登录\n self.page.home.login_if_not(self.page)\n #我 -点击设置\n self.page.me.click_setting()\n self.page.setting.click_about()\n self.page.about.click_uptdate()\n assert self.page.about.is_toast_exist(\"当前已是最新版本\")","sub_path":"script/test_update.py","file_name":"test_update.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"485958735","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 15 20:23:01 2021\n\n@author: Fred Hu\n\"\"\"\n\n#import libraries\nimport datetime\nimport json\nfrom requests import get\nimport logging\n\n#index of X for month\nmonthDict = {'January': 210,\n 'February':205,\n 'March':230,\n 'April':240,\n 'May':250,\n 'June':245,\n 'July':250,\n 'August':225,\n 'September':200,\n 'October':225,\n 'November':205,\n 'December':200,}\n\n#API Key\n#Replace with your own heWeatherKey\nheWeatherKey = \"*************************\"\n\n#return the index of X for month\ndef getMonthX(monthStr):\n return monthDict[monthStr]\n\n#return current time\ndef getCurrentTime():\n currentTime = datetime.datetime.now() \n date = currentTime.date()\n dateStr = date.strftime('%Y/%m/%d')\n weekStr = date.strftime('%A')\n dayStr = date.strftime('%d')\n monthStr = date.strftime('%B')\n return dateStr, weekStr, dayStr, monthStr\n\n#get the locationID and city name for current city\ndef getLocationID():\n try:\n response = get('https://api.myip.la/en?json\tjson')\n locationInfo = json.loads(response.text)['location']\n province = locationInfo['province']\n city = locationInfo['city']\n except Exception as e:\n logging.info(e)\n province = 'Jiangsu'\n city = 'Yangzhou'\n \n try:\n response = get(\"https://geoapi.qweather.com/v2/city/lookup?adm=\" \n + province + \"&location=\" + city + \"&key=\"\n + heWeatherKey)\n locationInfo = json.loads(response.text)['location']\n locationID = locationInfo[0]['id']\n city = locationInfo[0]['name']\n except Exception as e:\n logging.info(e)\n locationID = \"101190601\"\n city = \"扬州\"\n return locationID, city\n\n#get the information of weather\ndef getWeather():\n locationID, city = getLocationID()\n try:\n response = get(\"https://devapi.qweather.com/v7/weather/now?\" +\n \"location=\" + locationID + \"&key=\" + heWeatherKey)\n nowWeather = json.loads(response.text)['now']\n temp = nowWeather['temp']\n icon = nowWeather['icon']\n text = nowWeather['text']\n except Exception as e:\n temp = 'N/A'\n icon = '999'\n text = \"未知\"\n \n try:\n response = get(\"https://devapi.qweather.com/v7/weather/3d?\" +\n \"location=\" + locationID + \"&key=\" + heWeatherKey)\n dailyWeather = json.loads(response.text)['daily'][0]\n tempMin = dailyWeather['tempMin']\n tempMax = dailyWeather['tempMax']\n except Exception as e:\n logging.info(e)\n tempMin = \"N/A\"\n tempMax = \"N/A\"\n return city, temp, icon, text, tempMin, tempMax","sub_path":"RaspberryPi/E-PaperWeatherCalendar/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"436730574","text":"import numpy as np\nimport scipy.sparse.linalg\nimport numpy.linalg\n\n# Initialize Offensive & Defensive matrix\no_matrix = np.array(np.matrix('0. 7 21 7 0. ;52 0. 34 25 27 ; 24 16 0. 7 3 ;38 17 5 0. 14 ;45 7 30 52 0.'))\no_matrix_t = np.transpose(o_matrix)\n\n# Total numer of team\nN = o_matrix.shape[0]\n\n# Recursive function to produce the deserved result\ndef o_compute(M, k=50):\n if k==1:\n return np.ones(N)\n else:\n return np.dot(M,1/np.dot(np.transpose(M),1/o_compute(M,k-1)))\n\n# return offensive and Defensive rating\no_rating = o_compute(o_matrix)\nd_rating = o_compute(np.transpose(o_matrix))\n\n# OD rating\no_rating/d_rating\n","sub_path":"odrating.py","file_name":"odrating.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"351528622","text":"from random import randint\nimport re\n\n\ncont = True\n\nwhile cont == True:\n \n g = input(\"Guess a number between 1 and 10: \")\n \n while g == \"\":\n g = input(\"Enter a number between 1 and 10: \")\n \n \n # regex = re.search('[a-zA-Z]+',g)\n # amt = regex.group()\n #use = len(amt)\n \n \n \n # while use > 0 :\n # g = input(\"Please enter a number between 1 and 10: \")\n \n guessedNum = int(g)\n \n rnd = randint(1,10)\n \n while guessedNum > 10:\n guessedNum = int(input(\"Enter a number between 1 and 10: \"))\n \n while guessedNum < 0:\n guessedNum = int(input(\"Enter a number between 1 and 10: \"))\n \n if guessedNum == rnd:\n print(\"Congratulations you guessed the number\")\n else:\n print(\"Better luck next time\")\n print(\"The number was %d\" % rnd)\n \n cond = input(\"Do you wish to try again? Y/N: \")\n \n again = False\n \n while not again :\n if cond.upper() == \"N\":\n cont = False\n again = True\n elif cond.upper() == \"Y\":\n cont = True\n again = True\n else:\n cond = input(\"Please input Y/N: \")\n \n\n\n\n","sub_path":"Application.py","file_name":"Application.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"275079912","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 9 16:12:01 2019\n\n@author: NOTEBOOK\n\"\"\"\n\n\n\ndef main():\n purchase = float(input(\"Enter the total amount of purchase: \"))\n tax(purchase)\n \n \ndef tax(pur):\n sales_tax = pur * 0.04\n county_tax = pur * 0.02\n total_tax = sales_tax + county_tax\n total = pur + total_tax \n print(\"Purchase = \",format(pur,',.2f'))\n print(\"state tax = \",format(sales_tax,',.2f'))\n print(\"County tax = \",format(county_tax,',.2f'))\n print(\"Total tax = \",format(total_tax,',.2f'))\n print(\"Grand Total = \", format(total, ',.2f'))\n \n \nmain()\n\n \n \n","sub_path":"2.input, processing, output/sales_tax.py","file_name":"sales_tax.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"585700290","text":"print(\"\"\"\n21. Faça um programa que leia duas matrizes 2 x 2 com valores reais.\nOfereça ao usuário um menu de opções:\n (A) somar as duas matrizes\n (B) subtrair A primeira matriz da segunda\n (c) adicionar uma constante às duas matrizes\n (d) imprimir as matrizes\nNas duas primeiras opções uma terceira matriz 3 x 3 deve ser criada.\nNa terceira opção o valor da constante deve ser lido e o resultado da\nadição da constante deve ser armazenado na própria matriz.\n\"\"\")\n\nprint(\"\"\"\n [1] Somar as duas matrizes.\n [2] Subtrair A primeira matriz da segunda.\n [3] Adicionar uma constante às duas matrizes.\n [4] Imprimir as matrizes.\n\"\"\")\n\nmatriz1 = [[34, 10], [82, 60]]\nmatriz2 = [[51, 77], [53, 62]]\n\nprint('1º Matriz: ')\nfor linhas in matriz1:\n print(linhas)\nprint()\nprint('2º Matriz: ')\nfor linhas in matriz2:\n print(linhas)\n\nmatriz_soma = list()\nmatriz_dif = list()\nlinhas = list()\n\nescolha = None\n\nwhile escolha != 0:\n\n print()\n escolha = int(input('Escolha: '))\n\n if escolha == 1:\n matriz_soma = list()\n for i in range(len(matriz1)):\n for j in range(len(matriz1)):\n soma = matriz1[i][j] + matriz2[i][j]\n linhas.append(soma)\n matriz_soma.append(linhas)\n linhas = list()\n for linha in matriz_soma:\n print(linha)\n\n elif escolha == 2:\n matriz_dif = list()\n for i in range(len(matriz1)):\n for j in range(len(matriz1)):\n dif = matriz1[i][j] - matriz2[i][j] # dif = diferença\n linhas.append(dif)\n matriz_dif.append(linhas)\n linhas = list()\n\n for linha in matriz_dif:\n print(linha)\n\n elif escolha == 3:\n constante = int(input('Insira A constante: '))\n for i in range(len(matriz1)):\n for j in range(len(matriz1)):\n matriz1[i][j] = matriz1[i][j] + constante\n matriz2[i][j] = matriz2[i][j] + constante\n\n elif escolha == 4:\n print('1º Matriz: ')\n for linhas in matriz1:\n print(linhas)\n print()\n print('2º Matriz: ')\n for linhas in matriz2:\n print(linhas)\n","sub_path":"Seção_07/parte_2/Exercício_21.py","file_name":"Exercício_21.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"261006733","text":"#!/usr/bin/python3\n\"\"\"Unittest Rectangle class\"\"\"\nimport unittest\nimport unittest\nfrom models.base import Base\nfrom models.rectangle import Rectangle\nfrom models.square import Square\nimport pep8\nimport sys\nfrom io import StringIO\n\n\nclass TestRectangle(unittest.TestCase):\n\n def setUp(self):\n Base._Base__nb_objects = 0\n\n def test_id(self):\n r1 = Rectangle(10, 2)\n self.assertEqual((r1.id), 1)\n r2 = Rectangle(2, 10)\n self.assertEqual((r2.id), 2)\n r3 = Rectangle(10, 2, 0, 0, 12)\n self.assertEqual((r3.id), 12)\n r4 = Rectangle(10, 2, 0, 0)\n self.assertEqual((r4.id), 3)\n\n def test_validation(self):\n with self.assertRaises(TypeError):\n Rectangle(10, \"2\")\n self.assertTrue(\"height must be an integer\")\n with self.assertRaises(ValueError):\n r = Rectangle(10, 2)\n r.width = -10\n self.assertTrue(\"width must be > 0 \")\n with self.assertRaises(TypeError):\n Rectangle(\"10\", 2)\n self.assertTrue(\"width must be an integer\")\n with self.assertRaises(ValueError):\n r = Rectangle(10, 2)\n r.height = -10\n self.assertTrue(\"height must be > 0 \")\n with self.assertRaises(TypeError):\n r = Rectangle(10, 2)\n r.x = {}\n self.assertTrue(\"x must be an integer\")\n with self.assertRaises(ValueError):\n Rectangle(10, 2, 3, -1)\n self.assertTrue(\"y must be >= 0\")\n with self.assertRaises(TypeError):\n r = Rectangle(10, 2)\n r.y = {}\n self.assertTrue(\"y must be an integer\")\n with self.assertRaises(ValueError):\n Rectangle(10, 2, -1, 3)\n self.assertTrue(\"x must be >= 0\")\n\n def test_area_rectangle(self):\n r1 = Rectangle(3, 2)\n self.assertEqual(r1.area(), 6)\n r2 = Rectangle(2, 10)\n self.assertEqual(r2.area(), 20)\n r3 = Rectangle(8, 7, 0, 0, 12)\n self.assertEqual(r3.area(), 56)\n with self.assertRaises(TypeError):\n r4 = Rectangle(1.5, 5.6, 0, 0, 12)\n print(r4.area())\n self.assertTrue(\"width must be an integer\")\n\n def test_display_rectangle(self):\n disp = \"####\\n####\\n####\\n\"\n r1 = Rectangle(4, 3)\n tmp = StringIO()\n sys.stdout = tmp\n r1.display()\n self.assertEqual(tmp.getvalue(), disp)\n tmp.close()\n\n disp = \"\\n\\n ##\\n ##\\n ##\\n\"\n r2 = Rectangle(2, 3, 2, 2)\n tmp = StringIO()\n sys.stdout = tmp\n r2.display()\n self.assertEqual(tmp.getvalue(), disp)\n tmp.close()\n\n def test_str_rectangle(self):\n r1 = Rectangle(4, 6, 2, 1, 12)\n self.assertEqual(r1.__str__(), \"[Rectangle] (12) 2/1 - 4/6\")\n\n r2 = Rectangle(5, 5, 1)\n self.assertEqual(r2.__str__(), \"[Rectangle] (1) 1/0 - 5/5\")\n\n def test_update_rectangle(self):\n r1 = Rectangle(10, 10, 10, 10)\n r1.update(89)\n self.assertEqual(r1.__str__(), \"[Rectangle] (89) 10/10 - 10/10\")\n r1.update(89, 2)\n self.assertEqual(r1.__str__(), \"[Rectangle] (89) 10/10 - 2/10\")\n r1.update(89, 2, 3)\n self.assertEqual(r1.__str__(), \"[Rectangle] (89) 10/10 - 2/3\")\n r1.update(89, 2, 3, 4, 5)\n self.assertEqual(r1.__str__(), \"[Rectangle] (89) 4/5 - 2/3\") \n r1 = Rectangle(10, 10, 10, 10)\n r1.update(height=1)\n self.assertEqual(r1.__str__(), \"[Rectangle] (2) 10/10 - 10/1\")\n r1.update(y=1, width=2, x=3, id=89)\n self.assertEqual(r1.__str__(), \"[Rectangle] (89) 3/1 - 2/1\")\n r1.update(x=1, height=2, y=3, width=4)\n self.assertEqual(r1.__str__(), \"[Rectangle] (89) 1/3 - 4/2\")\n\n def test_instance_to_dict_rectangle(self):\n r1 = Rectangle(10, 2, 1, 9)\n r1_dictionary = r1.to_dictionary()\n self.assertEqual(r1_dictionary, {'x': 1, 'y': 9, 'id': 1,\n 'height': 2, 'width': 10})\n\n def test_rectangle_pep8(self):\n pep8style = pep8.StyleGuide(quiet=True)\n result = pep8style.check_files(['./models/rectangle.py'])\n self.assertEqual(result.total_errors, 0)\n","sub_path":"0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py","file_name":"test_rectangle.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"419802369","text":"import tensorflow as tf\nimport math\nimport numpy as np\n\n\n\n\n\ndef conv(inputs,filters,kernel_size,strides=(1, 1),padding='SAME',dilation_rate=(1, 1),activation=tf.nn.relu,use_bias=None,regularizer=None,name=None,reuse=None):\n out=tf.layers.conv2d(\n inputs,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n dilation_rate=dilation_rate,\n activation=activation,\n use_bias=use_bias,\n kernel_regularizer=regularizer,\n bias_initializer=tf.zeros_initializer(),\n kernel_initializer= tf.random_normal_initializer(stddev=0.1),\n name=name,\n reuse=reuse)\n return out\n\n\n# In[3]:\n\n\ndef batch(inputs,training=True,reuse=None,momentum=0.9,name='n'):\n out=tf.layers.batch_normalization(inputs,training=training,reuse=reuse,momentum=momentum,name=name)\n return out\n\n\n# In[4]:\n\n\ndef branch1(x,numOut,l2,stride=1,is_training=True,momentum=0.9,reuse=None):\n reg = None if l2 is None else tf.contrib.layers.l2_regularizer(scale=l2)\n with tf.variable_scope(\"conv1\"):\n y = conv(x, numOut, kernel_size=[3, 3],activation=None,strides=(stride,stride),name='conv',regularizer=reg,reuse=reuse)\n y = tf.nn.relu(batch(y,training=is_training,reuse=reuse,momentum=momentum,name='bn'))\n with tf.variable_scope(\"conv2\"):\n y = conv(y, numOut, kernel_size=[3, 3],activation=None,regularizer=reg,name='conv',reuse=reuse)\n y = batch(y,training=is_training,reuse=reuse,momentum=momentum,name='bn')\n return y\n\n\n# In[5]:\n\n\ndef branch2(x,numOut,l2,stride=1,is_training=True,momentum=0.9,reuse=None):\n reg = None if l2 is None else tf.contrib.layers.l2_regularizer(scale=l2)\n with tf.variable_scope(\"convshortcut\"):\n y = conv(x, numOut, kernel_size=[1, 1],activation=None,strides=(stride,stride),name='conv',regularizer=reg,reuse=reuse)\n y = batch(y,training=is_training,reuse=reuse,momentum=momentum,name='bn')\n return y\n\n\n# In[6]:\n\n\ndef residual(x,numOut,l2,stride=1,is_training=True,reuse=None,momentum=0.9,branch=False,name='res'):\n with tf.variable_scope(name):\n block = branch1(x,numOut,l2,stride=stride,is_training=is_training,momentum=momentum,reuse=reuse)\n if x.get_shape().as_list()[3] != numOut or branch:\n skip = branch2(x, numOut,l2,stride=stride,is_training=is_training,momentum=momentum,reuse=reuse)\n return tf.nn.relu(block+skip),block+skip\n else:\n return tf.nn.relu(x+block),x+block\n\n\n# In[7]:\n\n\ndef resnet18(x, is_training,l2=None,dropout=0.05,reuse=None,momentum=0.9,name='Resnet18'):\n feature=[]\n with tf.variable_scope(name):\n reg = None if l2 is None else tf.contrib.layers.l2_regularizer(scale=l2/4)\n y=conv(x, 64, kernel_size=[7, 7],activation=None,strides=2,name='conv0',regularizer=reg,reuse=reuse)\n y=tf.nn.relu(batch(y,training=is_training,reuse=reuse,momentum=momentum,name='conv0/bn'))\n y=tf.nn.max_pool(y,ksize=[1,3,3,1],strides=[1,2,2,1],padding='SAME',name='pool1')\n with tf.variable_scope('group0'):\n res2a,t=residual(y,64,l2,branch=True,reuse=reuse,is_training=is_training,name='block0')\n res2b,t=residual(res2a,64,l2,reuse=reuse,is_training=is_training,name='block1')\n feature.append(t)\n with tf.variable_scope('group1'):\n res3a,t=residual(res2b,128,l2,stride=2,reuse=reuse,is_training=is_training,name='block0')\n res3b,t=residual(res3a,128,l2,reuse=reuse,is_training=is_training,name='block1')\n feature.append(t)\n with tf.variable_scope('group2'):\n res4a,t=residual(res3b,256,l2,stride=2,reuse=reuse,is_training=is_training,name='block0')\n res4b,t=residual(res4a,256,l2,reuse=reuse,is_training=is_training,name='block1')\n feature.append(t)\n with tf.variable_scope('group3'):\n res5a,t=residual(res4b,512,l2,stride=2,reuse=reuse,is_training=is_training,name='block0')\n res5b,t=residual(res5a,512,l2,reuse=reuse,is_training=is_training,name='block1')\n feature.append(t)\n #pool5=tf.reduce_mean(res5b, [1, 2],keepdims=True)\n #dropout = tf.layers.dropout(pool5,rate=dropout,training=is_training)\n #y=conv(dropout, 1000, kernel_size=[1, 1],activation=None,name='class',use_bias=True,regularizer=reg,reuse=reuse)\n #y=conv(y, 512, kernel_size=[1, 1],activation=None,name='attention',use_bias=None,regularizer=reg,reuse=reuse)\n #y=tf.nn.sigmoid(batch(y,training=is_training,reuse=reuse,momentum=momentum,name='attentionbn'))\t\t\n #y=res5b*y+res5b\n #feature.append(y)\n return y,feature\n\ndef erfupsample(x,skip,is_training,shape=[512,512],kernal=3,stage=0,l2=None,reuse=None,momentum=0.9,name='up0'):\n height=int(shape[0]//math.pow(2,5-stage))\n weight=int(shape[1]//math.pow(2,5-stage))\n with tf.variable_scope(name):\n reg = None if l2 is None else tf.contrib.layers.l2_regularizer(scale=l2)\n skip=tf.nn.relu(batch(skip,training=is_training,reuse=reuse,momentum=momentum,name='skipbn'))\n skip = conv(skip,128,kernel_size=1,activation=None,name='changedemesion',regularizer=reg,reuse=reuse)\n x=tf.image.resize_images(x, [height,weight],method=0,align_corners=True)\n skip=x+skip\n skip=tf.nn.relu(batch(skip,training=is_training,reuse=reuse,momentum=momentum,name='blendbn0'))\n skip1=conv(skip,128,kernel_size=[kernal,1],activation=None,name='skipconv1a',regularizer=reg,reuse=reuse)\n skip1=conv(skip1,128,kernel_size=[1,kernal],activation=None,name='skipconv1b',regularizer=reg,reuse=reuse)\n skip2=conv(skip,128,kernel_size=[1,kernal],activation=None,name='skipconv2a',regularizer=reg,reuse=reuse)\n skip2=conv(skip2,128,kernel_size=[kernal,1],activation=None,name='skipconv2b',regularizer=reg,reuse=reuse)\n x=skip+skip1+skip2\n x=tf.nn.relu(batch(x,training=is_training,reuse=reuse,momentum=momentum,name='blendbn'))\n x=conv(x, 128, kernel_size=3,activation=None,name='blendconv',regularizer=reg,reuse=reuse)\n #pool5=tf.reduce_mean(x, [1, 2],keepdims=True)\n #y=conv(pool5, 128, kernel_size=[1, 1],activation=None,name='attention',use_bias=None,regularizer=reg,reuse=reuse)\n #y=tf.nn.sigmoid(batch(y,training=is_training,reuse=reuse,momentum=momentum,name='attentionbn'))\t\t\n #x=x*y+x\n return x\n\n\ndef SpatialPyramidPooling(x, is_training,shape=[512,512],grids=(8, 4, 2,1),l2=None,reuse=None,momentum=0.9,name='spp'):\n levels=[]\n height=shape[0]//32\n weight=shape[1]//32\n with tf.variable_scope(name):\n reg = None if l2 is None else tf.contrib.layers.l2_regularizer(scale=l2)\n x=tf.nn.relu(batch(x,training=is_training,reuse=reuse,momentum=momentum,name='bn0'))\n x=conv(x, 128, kernel_size=1,activation=None,name='conv0',regularizer=reg,reuse=reuse)\n levels.append(x)\n for i in range(len(grids)):\n h=math.floor(height/grids[i])\n w=math.floor(weight/grids[i])\n kh=height-(grids[i]-1) * h\n kw=weight-(grids[i]-1) * w\n y=tf.nn.avg_pool(x,[1,kh,kw,1],[1,h,w,1],padding='VALID')\n y=tf.nn.relu(batch(y,training=is_training,reuse=reuse,momentum=momentum,name='bn'+str(i+1)))\n y=conv(y, 32, kernel_size=1,activation=None,name='conv'+str(i+1),regularizer=reg,reuse=reuse)\n y=tf.image.resize_images(y, [height,weight],method=0,align_corners=True)\n levels.append(y)\n final=tf.concat(levels,-1)\n final=tf.nn.relu(batch(final,training=is_training,reuse=reuse,momentum=momentum,name='blendbn'))\n final=conv(final, 128, kernel_size=1,activation=None,name='blendconv',regularizer=reg,reuse=reuse)\n final=tf.nn.relu(batch(final,training=is_training,reuse=reuse,momentum=momentum,name='finalbn'))\n return final\n\n\n\n\n\n\ndef swiftnet(x, numclass,is_training,shape,l2=None,dropout=0.05,reuse=None,momentum=0.9):\n xclass,feature=resnet18(x, is_training,l2,dropout=dropout,reuse=reuse,momentum=momentum,name='Resnet18')\n x=SpatialPyramidPooling(feature[-1], is_training,shape=shape,grids=(8, 4, 2, 1),l2=l2,reuse=reuse,momentum=momentum,name='spp')\n x=erfupsample(x,feature[-2],is_training,shape=shape,kernal=3,stage=1,l2=l2,reuse=reuse,momentum=momentum,name='up1')\n x=erfupsample(x,feature[-3],is_training,shape=shape,kernal=5,stage=2,l2=l2,reuse=reuse,momentum=momentum,name='up2')\n x=erfupsample(x,feature[-4],is_training,shape=shape,kernal=7,stage=3,l2=l2,reuse=reuse,momentum=momentum,name='up3')\n with tf.variable_scope('class'):\n reg = None if l2 is None else tf.contrib.layers.l2_regularizer(scale=l2)\n x=tf.nn.relu(batch(x,training=is_training,reuse=reuse,momentum=momentum,name='classbn'))\n x=conv(x, numclass, kernel_size=3,activation=None,name='classconv',regularizer=reg,reuse=reuse)\n x=tf.image.resize_images(x, [shape[0],shape[1]],method=0,align_corners=True)\n final=tf.nn.softmax(x, name='logits_to_softmax')\n return x,final\n\n\n\n\ndef load_weight(sess,resnet50_path,varss):\n param = dict(np.load(resnet50_path))\n for v in varss:\n nameEnd = v.name.split('/')[-1]\n if nameEnd == \"moving_mean:0\":\n name = v.name[9:-13]+\"mean/EMA\"\n elif nameEnd == \"moving_variance:0\":\n name = v.name[9:-17]+\"variance/EMA\"\n elif nameEnd =='kernel:0':\n if v.name.split('/')[1]=='conv0':\n name='conv0/W'\n b=np.expand_dims(param[name][:,:,0,:],2)\n g=np.expand_dims(param[name][:,:,1,:],2)\n r=np.expand_dims(param[name][:,:,2,:],2)\n param[name]=np.concatenate([r,g,b],2)\n elif v.name.split('/')[1]=='class':\n name='linear/W'\n else:\n name=v.name[9:-13]+'W'\n elif nameEnd=='gamma:0':\n name=v.name[9:-2]\n elif nameEnd=='beta:0':\n name=v.name[9:-2]\n else:\n name='linear/b'\n sess.run(v.assign(param[name]))\n print(\"Copy weights: \" + name + \"---->\"+ v.name)\n\n\n","sub_path":"Swift_Factorized_Network(SFN)/sfn.py","file_name":"sfn.py","file_ext":"py","file_size_in_byte":10075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"41797089","text":"import sys\nimport os\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.units import cm\n\n\ndef chunker(seq, size):\n return (seq[pos:pos + size] for pos in range(0, len(seq), size))\n\n\nclass Generator:\n\tdef __init__(self, pdf_file, qr_code_dir, nb_columns, nb_rows):\n\t\tself.left_margin = 0.9 * cm\n\t\tself.right_margin = self.left_margin\n\t\tself.top_margin = self.left_margin\n\t\tself.bottom_margin = self.left_margin\n\t\tself.pdf_file = pdf_file\n\t\tself.qr_code_dir = qr_code_dir\n\t\tself.nb_columns = nb_columns\n\t\tself.nb_rows = nb_rows\n\t\tself.c = canvas.Canvas(self.pdf_file)\n\t\tself.page_x = self.c._pagesize[0] - self.left_margin - self.right_margin\n\t\tself.page_y = self.c._pagesize[1] - self.top_margin - self.bottom_margin\n\t\tself.font_size = 8\n\t\tself.c.setFontSize(self.font_size)\n\t\tself.width = self.page_x / self.nb_columns\n\t\tself.text_height = self.c._fontsize\n\t\tself.height = self.page_y / self.nb_rows\n\t\tself.page_height = self.page_y\n\t\tself.image_width = min([self.width, self.height])\n\t\tself.image_height = self.image_width\n\t\tself.character_width = self.c._fontsize * 0.25\n\t\tself.character_height = self.c._fontsize * 0.39\n\n\tdef generate(self):\n\t\timages = sorted(os.listdir(self.qr_code_dir))\n\t\tfor page in chunker(images, self.nb_columns * self.nb_rows):\n\t\t\tself.c.setFontSize(self.font_size)\n\t\t\tfor j, row in enumerate(chunker(page, self.nb_columns)):\n\t\t\t\tfor i, image in enumerate(row):\n\t\t\t\t\tself.c.drawImage(\"{}/{}\".format(self.qr_code_dir, image), self.left_margin + self.width * i + (self.width / 4 * 3) - self.image_width / 2, self.bottom_margin + self.page_height - (self.height * j + self.image_height), self.image_width, self.image_height)\n\t\t\t\t\timage_name = os.path.splitext(image)[0]\n\t\t\t\t\tself.c.drawString(self.left_margin + self.width * i + self.width / 4 - (len(image_name) * self.character_width), self.bottom_margin + self.page_height - (self.height * j + self.height / 2), image_name)\n\t\t\tself.c.showPage()\n\t\tself.c.save()\n\n\tdef drawRotatedString(self, rotation, x, y, text):\n\t\tself.c.rotate(rotation)\n\t\tself.c.drawString(-y, x, text)\n\t\tself.c.rotate(360 - rotation)\n\n\ndef main(pdf_file, qr_code_dir, nb_columns, nb_rows):\n\tgen = Generator(pdf_file, qr_code_dir, nb_columns, nb_rows)\n\tgen.generate()\n\n\nmain(sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]))","sub_path":"generate_qr_code_pdf.py","file_name":"generate_qr_code_pdf.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"369594920","text":"import io\nimport pandas as pd\nfrom flask import current_app, g\nfrom werkzeug.local import LocalProxy\nfrom pymongo import MongoClient\nfrom bson.errors import InvalidId\nfrom pymongo.write_concern import WriteConcern\nfrom pymongo.read_concern import ReadConcern\nfrom pymongo.errors import DuplicateKeyError, OperationFailure\nfrom datetime import datetime\n\ndef get_db():\n '''\n '''\n try:\n db = getattr(g, \"_database\", None)\n #DB_URI = current_app.config[\"DB_URI\"]\n #DB_NAME = current_app.config[\"DB_NAME\"]\n if db is None:\n #db = g._database = MongoClient(DB_URI)[DB_NAME]\n db = g._database = MongoClient('mongodb://root:example@192.168.99.100:27017').get_database('test')\n return db\n except Exception as _:\n raise\n\ndb = LocalProxy(get_db)\n\ndef get_users(name_pattern='',page=0,users_per_page=20):\n '''\n '''\n try:\n skip_count = page * users_per_page\n pipeline = [{\n '$match': {\n 'name': {\n '$regex': name_pattern, \n '$options': 'i'\n }\n }\n }, {\n '$sort': {\n 'user_id': -1\n }\n }, {\n '$skip': skip_count\n }, {\n '$limit': users_per_page\n }, {\n '$project': {\n '_id': 0, \n 'user_id': 1, \n 'name': 1\n }\n }]\n user_list = list(db.user.aggregate(pipeline))\n return user_list\n except Exception as _:\n return None\n\ndef get_projects(search_pattern='',page=0,projects_per_page=20):\n '''\n '''\n try:\n skip_count = page * projects_per_page\n pipeline = [{\n '$match': {\n 'project_igf_id': {\n '$regex': search_pattern, \n '$options': 'i'\n }\n }\n }, {\n '$sort': {\n 'Issued': -1\n }\n }, {\n '$skip': skip_count\n }, {\n '$limit': projects_per_page\n }, {\n '$project': {\n '_id': 0,\n 'project_id':1,\n 'project_igf_id':1,\n 'status':'$Status',\n 'Issued':1\n }\n }]\n projects_list = list(db.projects.aggregate(pipeline))\n return projects_list\n except Exception as _:\n return None\n\ndef get_quotes(search_pattern='',page=0,quotes_per_page=20):\n '''\n '''\n try:\n skip_count = page * quotes_per_page\n pipeline = [{\n '$match': {\n 'quotes_legacy_id': {\n '$regex': search_pattern, \n '$options': 'i'\n }\n }\n }, {\n '$sort': {\n 'Issued': -1\n }\n }, {\n '$skip': skip_count\n }, {\n '$limit': quotes_per_page\n }, {\n '$project': {\n '_id': 0,\n 'quote_id':1,\n 'quotes_legacy_id':1,\n 'status':'$Status',\n 'Issued':1\n }\n }]\n quotes_list = db.quotes.aggregate(pipeline)\n return quotes_list\n except Exception as e:\n print(e)\n return None\n\ndef get_total_pages(collection_name,search_pattern=''):\n try:\n lookup_key = ''\n if collection_name == 'quotes':\n lookup_key = 'quotes_legacy_id'\n elif collection_name == 'projects':\n lookup_key = 'project_igf_id'\n elif collection_name == 'user':\n lookup_key = 'name'\n else:\n raise ValueError('Collection {0} not supported'.\\\n format(collection_name))\n pipeline = [{\n '$match': {\n lookup_key: {\n '$regex': search_pattern, \n '$options': 'i'\n }\n }\n }, {\n '$count': 'total_rows'\n }]\n if collection_name == 'quotes':\n total_rows = db.quotes.aggregate(pipeline).next()\n elif collection_name == 'projects':\n total_rows = db.projects.aggregate(pipeline).next()\n elif collection_name == 'user':\n total_rows = db.user.aggregate(pipeline).next()\n else:\n raise ValueError('Collection {0} not supported'.\\\n format(collection_name))\n total_rows = total_rows.get('total_rows')\n return total_rows\n except (StopIteration,InvalidId) as _:\n return None\n except Exception as _:\n return {}\n\ndef get_user_by_user_id(user_id):\n '''\n '''\n try:\n user_record = db.user.find_one({'user_id':user_id},{'_id':0})\n return user_record\n except (StopIteration,InvalidId) as _:\n return None\n except Exception as _:\n return {}\n\ndef get_quote_by_quote_id(quote_id):\n '''\n '''\n try:\n pipeline = [{\n '$match': {\n 'quote_id': quote_id\n }\n }, {\n '$lookup': {\n 'from': 'user', \n 'let': {\n 'user_list': '$user_list'\n }, \n 'pipeline': [{\n '$match': {\n '$expr': {\n '$in': ['$user_id', '$$user_list']\n }\n }\n }, {\n '$project': {\n '_id': 0, \n 'email': 0\n }\n }], \n 'as': 'users'\n }\n }, {\n '$project': {\n '_id': 0, \n 'user_list': 0\n }\n }, {\n '$limit': 1\n }]\n quote_record = db.quotes.aggregate(pipeline).next()\n return quote_record\n except (StopIteration,InvalidId) as _:\n return None\n except Exception as _:\n return {}\n\ndef get_project_by_project_id(project_id):\n '''\n '''\n try:\n pipeline = [{\n '$match': {\n 'project_id': project_id\n }\n }, {\n '$lookup': {\n 'from': 'user', \n 'let': {\n 'user_list': '$user_list'\n }, \n 'pipeline': [{\n '$match': {\n '$expr': {\n '$in': ['$user_id', '$$user_list']\n }\n }\n }, {\n '$project': {\n '_id': 0, \n 'email': 0\n }\n }], \n 'as': 'users'\n }\n }, {\n '$project': {\n '_id': 0, \n 'user_list': 0\n }\n }, {\n '$limit': 1\n }]\n project_record = db.projects.aggregate(pipeline).next()\n return project_record\n except (StopIteration,InvalidId) as _:\n return None\n except Exception as _:\n return {}\n\ndef get_quotes_for_user_id(user_id,page=0,quotes_per_page=20):\n '''\n '''\n try:\n skip_count = page * quotes_per_page\n pipeline = [{\n '$match': {\n 'user_id': user_id\n }\n }, {\n '$lookup': {\n 'from': 'quotes', \n 'let': {\n 'user_id': '$user_id'\n }, \n 'pipeline': [{\n '$match': {\n '$expr': {\n '$in': ['$$user_id', '$user_list']\n }\n }\n }, {\n '$project': {\n '_id': 0, \n 'quote_id': 1,\n 'Status':1,\n 'Issued':1\n }\n }], \n 'as': 'quotes'\n }\n }, {\n '$project': {\n '_id': 0, \n 'quotes': 1\n }\n }, {\n '$unwind': {\n 'path': '$quotes'\n }\n }, {\n '$project': {\n 'quote_id': '$quotes.quote_id',\n 'status': '$quotes.Status',\n 'issued': '$quotes.Issued'\n }\n }, {\n '$sort': {\n 'issued': -1\n }\n }, {\n '$skip': skip_count\n }, {\n '$limit': quotes_per_page\n }]\n quote_ids = list(db.user.aggregate(pipeline))\n pipeline.append({'$count':'total_rows'})\n total_rows = db.user.aggregate(pipeline).next().get('total_rows')\n return quote_ids\n except (StopIteration,InvalidId) as _:\n return None\n except Exception as _:\n return {}\n\ndef get_projects_for_user_id(user_id,page=0,projects_per_page=20):\n '''\n '''\n try:\n skip_count = page * projects_per_page\n pipeline = [{\n '$match': {\n 'user_id': user_id\n }\n }, {\n '$lookup': {\n 'from': 'projects', \n 'let': {\n 'user_id': '$user_id'\n }, \n 'pipeline': [{\n '$match': {\n '$expr': {\n '$in': [ '$$user_id', '$user_list' ]\n }\n }\n }, {\n '$project': {\n '_id': 0, \n 'project_id': 1,\n 'project_igf_id':1,\n 'Status':1,\n 'Issued': 1\n }\n }], \n 'as': 'projects'\n }\n }, {\n '$project': {\n '_id': 0, \n 'projects': 1\n }\n }, {\n '$unwind': {\n 'path': '$projects'\n }\n }, {\n '$project': {\n 'project_id': '$projects.project_id',\n 'project_igf_id': '$projects.project_igf_id',\n 'status': '$projects.Status',\n 'issued': '$projects.Issued'\n }\n }, {\n '$sort': {\n 'issued': -1\n }\n }, {\n '$skip': skip_count\n }, {\n '$limit': projects_per_page\n }]\n quote_ids = list(db.user.aggregate(pipeline))\n return quote_ids\n except (StopIteration,InvalidId) as _:\n return None\n except Exception as _:\n return {}\n\ndef get_samples_for_project_id(project_id,page=0,samples_per_page=10):\n '''\n '''\n try:\n skip_count = page * samples_per_page\n pipeline = [{\n '$match': {\n 'project_id': project_id\n }\n }, {\n '$skip': skip_count\n }, {\n '$limit': samples_per_page\n },{\n '$project':{\n '_id':0,\n 'project_id':0,\n 'index':0,\n 'ID':0\n } \n }]\n sample_records = list(db.samples.aggregate(pipeline))\n return sample_records\n except (StopIteration,InvalidId) as _:\n return None\n except Exception as _:\n return {}\n\ndef get_libraries_for_project_id(project_id,page=0,libraries_per_page=10):\n '''\n '''\n try:\n skip_count = page * libraries_per_page\n pipeline = [{\n '$match': {\n 'project_id': project_id\n }\n }, {\n '$lookup': {\n 'from': 'library', \n 'let': {\n 'sample_id': '$sample_id'\n }, \n 'pipeline': [{\n '$match': {\n '$expr': {\n '$eq': [ '$sample_id', '$$sample_id' ]\n }\n }\n }, {\n '$project': {\n '_id': 0\n }\n }], \n 'as': 'libs'\n }\n }, {\n '$project': {\n '_id': 0, \n 'libs': 1\n }\n }, {\n '$unwind': {\n 'path': '$libs'\n }\n }, {\n '$replaceRoot': {\n 'newRoot': '$libs'\n }\n }, {\n '$skip': skip_count\n }, {\n '$limit': libraries_per_page\n }]\n library_records = list(db.samples.aggregate(pipeline))\n return library_records\n except (StopIteration,InvalidId) as _:\n return None\n except Exception as _:\n return {}\n\ndef get_active_projects_with_library():\n try:\n pipeline = [{\n '$match': {\n 'Status': {\n '$regex': 'open', \n '$options': 'i'\n }\n }\n }, {\n '$project': {\n '_id': 0,\n 'project_id':1,\n 'project_igf_id': 1\n }\n }, {\n '$lookup': {\n 'from': 'library', \n 'localField': 'project_id', \n 'foreignField': 'project_id', \n 'as': 'library'\n }\n }, {\n '$project': {\n 'project_igf_id': 1, \n 'lib_count': {\n '$size': '$library'\n }\n }\n }, {\n '$match': {\n 'lib_count': {\n '$gt': 0\n }\n }\n }, {\n '$group': {\n '_id': None, \n 'valid_project_list': {\n '$addToSet': '$project_igf_id'\n }\n }\n }, {\n '$project': {\n '_id': 0\n }\n }]\n valid_projects_list = db.projects.aggregate(pipeline)\n return valid_projects_list\n except (StopIteration,InvalidId) as e:\n print(e)\n return None\n except Exception as _:\n return {}\n\ndef list_planned_runs(run_pattern='',page=0,runs_per_page=20):\n '''\n '''\n try:\n skip_count = page * runs_per_page\n pipeline = [{\n '$match': {\n '$or': [{\n 'run_name': {\n '$regex': run_pattern, \n '$options': 'i'\n }\n }, {\n 'seqrun_id': {\n '$regex': run_pattern, \n '$options': 'i'\n }\n },{\n 'samplesheet_data':{\n '$elemMatch':{\n 'project_name':{\n '$regex':run_pattern,\n '$options':'i'\n }\n }\n }\n }]\n }\n }, {\n '$skip': skip_count\n }, {\n '$limit': runs_per_page\n },{\n '$sort': {\n 'datestamp': -1\n }\n },{\n '$project': {\n '_id': 0, \n 'run_name': 1,\n 'run_id': 1,\n 'seqrun_id': 1,\n 'run_type':1,\n 'status':1,\n 'datestamp': 1,\n 'projects':'$samplesheet_data.project_name'\n }\n }]\n run_list = \\\n db.planned_runs.\\\n aggregate(pipeline)\n run_list = list(run_list)\n pipeline= [{\n '$match': {\n '$or': [{\n 'run_name': {\n '$regex': run_pattern, \n '$options': 'i'\n }\n }, {\n 'seqrun_id': {\n '$regex': run_pattern, \n '$options': 'i'\n }\n },{\n 'samplesheet_data':{\n '$elemMatch':{\n 'project_name':{\n '$regex':run_pattern,\n '$options':'i'\n }\n }\n }\n }]\n }\n }, {\n '$count':'total_rows'}]\n total_rows = \\\n list(db.planned_runs.aggregate(pipeline))\n if len(total_rows) > 0:\n total_rows = total_rows[0].get('total_rows')\n else:\n total_rows = 0\n return run_list,total_rows\n except (StopIteration,InvalidId) as e:\n print(e)\n return None\n except Exception as _:\n return {}\n\ndef fetch_run_data_for_run_id(run_id):\n try:\n run = db.planned_runs.find_one({'run_id':run_id},{'_id':0})\n return run\n except (StopIteration,InvalidId) as e:\n print(e)\n return None\n except Exception as _:\n return {}\n\ndef create_or_update_run(run_name,run_type=None,status='ACTIVE',chemistry_info=None,\n r1_length=None,r2_length=None,assay_info=None,adapter2_seq=None,\n seqrun_id=None,samplesheet_data=None,adapter1_seq=None):\n try:\n rec = db.planned_runs.find_one({'run_name':run_name})\n\n if rec is None:\n records = \\\n list(db.planned_runs.aggregate([{\n \"$group\":{\n \"_id\":None,\n \"max_id\":{\"$max\":\"$_id\"}}\n },{\n \"$project\":{\"_id\":0}\n }]))\n if len(records) > 0 and \\\n 'max_id' in records[0]:\n max_id = records[0].get('max_id')\n if max_id == None:\n max_id = 0\n else:\n max_id = 0\n new_id = max_id + 1\n new_run = \\\n dict(\n _id=new_id,\n run_id='IGFSR{:0>5}'.format(new_id),\n run_name=run_name,\n run_type=run_type,\n status=status,\n r1_length=r1_length,\n r2_length=r2_length,\n assay_info=assay_info,\n chemistry_info=chemistry_info,\n adapter1_seq=adapter1_seq,\n adapter2_seq=adapter2_seq,\n seqrun_id=seqrun_id,\n samplesheet_data=samplesheet_data,\n datestamp=datetime.now()\n )\n db.planned_runs.insert_one(new_run)\n return None\n else:\n response = \\\n db.planned_runs.\\\n update_one({\n 'run_name':run_name\n },{\n '$set':{\n 'status':status,\n 'run_type':run_type,\n 'r1_length':r1_length,\n 'r2_length':r2_length,\n 'assay_info':assay_info,\n 'chemistry_info':chemistry_info,\n 'adapter1_seq':adapter1_seq,\n 'adapter2_seq':adapter2_seq,\n 'seqrun_id':seqrun_id,\n 'samplesheet_data':samplesheet_data,\n 'datestamp':datetime.now()\n }})\n return response\n except DuplicateKeyError as _:\n return {'error':'Duplicate run_name or run_id found'}\n except Exception as _:\n return None\n\ndef fetch_library_for_project_id_and_pool_id(project_igf_id,pool_id=1):\n try:\n pool_id = str(pool_id)\n pipeline = [{\n '$match': {\n 'project_igf_id': project_igf_id\n }\n }, {\n '$project': {\n '_id': 0, \n 'project_id': 1,\n 'project_igf_id':1\n }\n }, {\n '$lookup': {\n 'from': 'library',\n 'let': {\n 'project_id': '$project_id'\n }, \n 'pipeline': [{\n '$match': {\n '$expr': {\n '$and': [{\n '$eq': ['$project_id', '$$project_id']\n }, {\n '$eq': ['$Pool_No', pool_id]\n }]\n }\n }\n }], \n 'as': 'libraries'\n }\n }, {\n '$unwind': {\n 'path': '$libraries'\n }\n }, {\n '$project': {\n 'project_id': 1,\n 'project_igf_id':1,\n 'library_id': '$libraries.libs_id',\n 'sample_id': '$libraries.sample_id',\n 'sample_well': '$libraries.Well_Position',\n 'I7_Index_ID': '$libraries.Index_1_ID',\n 'index': '$libraries.Index1_Sequence',\n 'I5_Index_ID': '$libraries.Index_2_ID',\n 'index2': '$libraries.Index2_Sequence',\n 'pool_id': '$libraries.Pool_No'\n }\n }, {\n '$lookup': {\n 'from': 'samples',\n 'let': {\n 'sample_id': '$sample_id'\n }, \n 'pipeline': [{\n '$match': {\n '$expr': {\n '$eq': ['$sample_id', '$$sample_id']\n }\n }\n }, {\n '$project': {\n '_id': 0,\n 'sample_igf_id': 1,\n 'Sample Name': 1\n }\n }],\n 'as': 'samples'\n }\n }, {\n '$unwind': {\n 'path': '$samples'\n }\n }, {\n '$project': {\n 'Sample_Project':'$project_igf_id',\n 'Sample_ID': '$samples.sample_igf_id',\n 'Sample_Name': '$samples.Sample Name',\n 'Sample_ID':'$sample_id',\n 'Sample_Well':'$sample_well',\n 'Sample_Plate':None,\n 'I7_Index_ID': 1,\n 'index': 1,\n 'I5_Index_ID': 1,\n 'index2': 1,\n 'Description':None \n }\n }]\n records = db.projects.aggregate(pipeline)\n records = list(records)\n return records\n except (StopIteration,InvalidId) as e:\n print(e)\n return None\n except Exception as _:\n return {}\n\ndef get_samplesheet_data_for_planned_run_id(run_id,run_type=None,r1_length = 151,\n r2_length = 151,assay_info = 'UNKNOWN',\n chemistry_info = 'UNKNOWN',status='ACTIVE',\n adapter1_seq = 'AGATCGGAAGAGCACACGTCTGAACTCCAGTCA',\n adapter2_seq = 'AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGT'):\n try:\n pipeline = [{\n '$match': {\n 'run_id': run_id\n }\n }, {\n '$project': {\n '_id': 0,\n 'run_id':1,\n 'run_type':1,\n 'assay_info':1,\n 'status':1,\n 'chemistry_info':1,\n 'r1_length':1,\n 'r2_length':1,\n 'adapter1_seq':1,\n 'adapter2_seq':1,\n 'samplesheet_data': 1\n }\n }, {\n '$unwind': {\n 'path': '$samplesheet_data'\n }\n }, {\n '$project': {\n 'lane': '$samplesheet_data.lane',\n 'run_id':1,\n 'run_type':1,\n 'assay_info':1,\n 'status':1,\n 'chemistry_info':1,\n 'r1_length':1,\n 'r2_length':1,\n 'adapter1_seq':1,\n 'adapter2_seq':1,\n 'project_name': '$samplesheet_data.project_name', \n 'pool_id': '$samplesheet_data.pool_id'\n }\n }]\n records = db.planned_runs.aggregate(pipeline)\n records = list(records)\n \n if len(records) > 0:\n run_type = records[0].get('run_type') if 'run_type' in records[0] else run_type\n status = records[0].get('status') if 'status' in records[0] else status\n r1_length = records[0].get('r1_length') if 'r1_length' in records[0] else r1_length\n r2_length = records[0].get('r2_length') if 'r2_length' in records[0] else r2_length\n assay_info = records[0].get('assay_info') if 'assay_info' in records[0] else assay_info\n chemistry_info = records[0].get('chemistry_info') if 'chemistry_info' in records[0] else chemistry_info\n adapter1_seq = records[0].get('adapter1_seq') if 'adapter1_seq' in records[0] else adapter1_seq\n adapter2_seq = records[0].get('adapter2_seq') if 'adapter2_seq' in records[0] else adapter2_seq\n \n samplesheet_data = [\n '[Header],,,,,,,,,,',\n 'IEMFileVersion,4,,,,,,,,,',\n 'Investigator Name,IGF,,,,,,,,,',\n 'Experiment Name,{0},,,,,,,,,'.format(run_id),\n 'Date,{0},,,,,,,,,'.format(datetime.now().strftime('%d-%b-%Y')),\n 'Workflow,GenerateFASTQ,,,,,,,,,',\n 'Application,{0} FASTQ Only,,,,,,,,,'.format(run_type),\n 'Assay,{0},,,,,,,,,'.format(assay_info),\n 'Description,,,,,,,,,,',\n 'Chemistry,{0},,,,,,,,,'.format(chemistry_info),\n ',,,,,,,,,,',\n '[Reads],,,,,,,,,,',\n '{0},,,,,,,,,,'.format(int(r1_length)),\n '{0},,,,,,,,,,'.format(int(r2_length)),\n ',,,,,,,,,,',\n '[Settings],,,,,,,,,,',\n 'Adapter,{0},,,,,,,,,'.format(adapter1_seq),\n 'AdapterRead2,{0},,,,,,,,,'.format(adapter2_seq),\n ',,,,,,,,,,',\n '[Data],,,,,,,,,,'\n ]\n samplesheet_df = pd.DataFrame()\n columns = [\n 'Sample_ID',\n 'Sample_Name',\n 'Sample_Plate',\n 'Sample_Well',\n 'I7_Index_ID',\n 'index',\n 'I5_Index_ID',\n 'index2',\n 'Sample_Project',\n 'Description'\n ]\n if run_type in ('HISEQ4000','NOVASEQ'):\n columns.insert(0,'Lane')\n\n for entry in records:\n sr = \\\n fetch_library_for_project_id_and_pool_id(\n project_igf_id=entry.get('project_name'),\n pool_id=entry.get('pool_id'))\n data = pd.DataFrame(sr)\n lane = entry.get('lane')\n \n if len(data.index) > 0:\n if run_type in ('HISEQ4000','NOVASEQ'):\n data['Lane'] = int(lane)\n if len(samplesheet_df.index) > 0:\n samplesheet_df = pd.concat([samplesheet_df,data])\n else:\n samplesheet_df = data.copy()\n samplesheet_data = '\\n'.join(samplesheet_data)\n if len(samplesheet_df.index) > 0:\n csv_buf = io.StringIO()\n samplesheet_df[columns].\\\n to_csv(csv_buf,index=False)\n data = csv_buf.getvalue()\n samplesheet_data = samplesheet_data + '\\n' + data\n else:\n columns = ','.join(columns)\n samplesheet_data = samplesheet_data + '\\n' + columns\n return samplesheet_data\n except Exception as _:\n return {}","sub_path":"app/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":22487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"88268686","text":"import math\nimport random\nimport statistics\nimport pandas as pd\nimport plotly.figure_factory as ff\n\nprint(\"Running main.py\")\ndatalist = []\ncount = []\ncolname=\"Height(Inches)\"#Weight(Pounds) \nf = pd.read_csv(\"./data.csv\")\ndatalist= f[colname].to_list()\ndef precentagestdev(arr: list, mean, stddev):\n\n def isinrange(a): return (a > (mean - stddev)) and (a < (mean + stddev))\n i1 = filter(isinrange, arr)\n i1 = list(i1)\n p1 = (len(i1)/len(arr)) * 100\n return p1\n\nmymean = statistics.mean(datalist)\nmymode = statistics.mode(datalist)\nmymedian = statistics.median(datalist)\nmystdev = statistics.stdev(datalist)\nmyper = precentagestdev(datalist, mymean, mystdev)\nprint(f\"DataSet : {colname}\")\nprint(\"Mean : {} \\nMode: {} \\nMedian : {} \\nStandard Deveation : {} \\n% of Data between +Standard Deveation and -Standard Deveation : {}\".format(mymean, mymode, mymedian, mystdev, myper))\n\nexit()\n\nprint(\"Creating Figure...\")\nfig = ff.create_distplot([datalist], group_labels=[\"sums\"])\nprint(\"Displaying Figure...\")\nfig.show()\nprint(\"Done\")\nexit()\n","sub_path":"classwork/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"165700047","text":"PRIMES =[2, 3, 5, 7, 11 ,13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 107]\nA = ord('a')\n\ndef group(strs):\n ans = []\n map = {}\n for s in strs:\n hash = 1\n for e in s:\n hash *= PRIMES[ord(e) - A]\n if hash in map:\n map[hash].append(s)\n else:\n map[hash] = [s]\n \n for v in map.itervalues():\n ans.append(sorted(v))\n \n return ans\n","sub_path":"049 Group Anagrams.py","file_name":"049 Group Anagrams.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"42739355","text":"#!/usr/bin/env python\n\n__author__ = \"Patrick K. O'Brien \"\n__cvsid__ = \"$Id$\"\n__revision__ = \"$Revision$\"[11:-2]\n\nimport locale\ntry:\n locale.setlocale(locale.LC_ALL, '')\nexcept:\n pass\n\nimport sys\nimport zipfile\n\nfrom docutils import core\n\nimport OOdirectives\nimport OOtext\nimport OOwriter\n\n\ndef main():\n\n## pub = core.Publisher(writer=OOwriter.Writer())\n## pub.set_reader('standalone', None, 'restructuredtext')\n## settings = pub.get_settings()\n## pub.source = io.FileInput(settings, source_path=sys.argv[1])\n## pub.destination = io.StringOutput(settings)\n## content = pub.publish()\n\n source = file(sys.argv[1]).read()\n content = core.publish_string(source, writer=OOwriter.Writer())\n\n xml_manifest_list = [\n ('content.xml', content),\n ('styles.xml', OOtext.styles)\n ]\n\n xml_entries = []\n for docname, _ in xml_manifest_list:\n xml_entries.append(OOtext.m_xml_format % docname)\n\n image_manifest_list = OOtext.pictures\n\n image_entries = []\n for name, format in image_manifest_list:\n image_entries.append(format)\n\n manifest = OOtext.manifest % ('\\n '.join(image_entries),\n '\\n '.join(xml_entries))\n xml_manifest_list.append(('META-INF/manifest.xml', manifest))\n\n zip = zipfile.ZipFile(sys.argv[2], \"w\")\n for docname, contents in xml_manifest_list:\n zinfo = zipfile.ZipInfo(docname)\n zip.writestr(zinfo, contents)\n for name, format in image_manifest_list:\n zip.write(name, 'Pictures/' + name)\n zip.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"sandbox/pobrien/OpenOffice/rest2oo.py","file_name":"rest2oo.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"119615710","text":"import requests\nfrom bs4 import BeautifulSoup\n\nfrom . import classes\n\nbase_url = \"https://osu.ppy.sh/beatmapsets/events?user=&types%5B%5D=\"\n\ntypes = [\n \"nominate\",\n \"qualify\",\n \"rank\",\n \"love\",\n \"nomination_reset\",\n \"disqualify\"\n]\n\n\ndef get_events(types_val: list) -> str:\n additions = list()\n for i in range(6):\n additions.append(types_val[i] and types[i] or str())\n url = base_url + '&types%5B%5D='.join(additions)\n res = requests.get(url, cookies={\"locale\": \"en\"})\n res_soup = BeautifulSoup(res.text, features=\"html.parser\")\n events_html = res_soup.findAll(class_=\"beatmapset-event\")\n events = []\n event_cases = {\n \"Nominated\": classes.Nominated,\n \"Disqualified\": classes.Disqualified,\n \"New\": classes.Popped\n }\n for event in events_html:\n action = event.find(\n class_=\"beatmapset-event__content\").text.strip().split()[0]\n events.append(event_cases[action](event))\n return events\n","sub_path":"notAiess/event_helper.py","file_name":"event_helper.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"198795866","text":"__author__ = 'Andres Perez Dominguez'\n\nfrom whoosh.index import create_in, open_dir\nfrom whoosh.fields import *\nfrom whoosh.qparser import QueryParser\nfrom tkinter import messagebox\nimport os\nfrom tkinter import *\n# Crea un indice desde los documentos contenidos en dirdocs\n# El indice lo crea en un directorio (dirindex)\ndef create_index(dir_docs, dir_index):\n\n if not os.path.exists(dir_index):\n os.mkdir(dir_index)\n\n ix = create_in(dir_index, schema=get_schema())\n writer = ix.writer()\n for doc_name in os.listdir(dir_docs):\n if not os.path.isdir(dir_docs + doc_name):\n add_doc(writer, dir_docs, doc_name)\n writer.commit()\n\n messagebox.showinfo(\"Finished\",\"Index created succesfully\")\n\n\ndef add_doc(writer, path, doc_name):\n\n file_obj = open(path + '/' + doc_name, \"rb\")\n from_ = file_obj.readline().strip().decode()\n to_ = file_obj.readline().strip().decode()\n subject_ = file_obj.readline().strip().decode()\n body_ = file_obj.readline().strip().decode()\n file_obj.close()\n\n writer.add_document(from_who=from_, to_who=to_, subject=subject_, body=body_,\n id=doc_name)\n\n\ndef get_schema():\n return Schema(from_who=TEXT(stored=True), to_who=TEXT(stored=True), subject=TEXT(stored=True),\n body=TEXT(stored=True), id=ID(stored=True))\n\n\ndef search_by_recipient(dir_index, query):\n\n ix = open_dir(dir_index)\n\n with ix.searcher() as searcher:\n my_query = QueryParser(\"from_who\", ix.schema).parse(query)\n results = searcher.search(my_query, limit=6)\n res = []\n for r in results:\n mail = [r['to_who'], r['subject']]\n res.append(mail)\n\n return res\n\n\ndef main():\n root = Tk()\n\n root.title(\"Mails\")\n root.geometry(\"800x600\")\n\n def initialise():\n create_index(\"/home/andres/AII/Enunciados/Whoosh/Correos\",\"Index\")\n\n index_button = Button(root, text=\"Create index\", command=initialise)\n index_button.pack(side=\"top\")\n\n entry = Entry(root)\n entry.pack(side=\"top\")\n\n def search():\n show_list(search_by_recipient(\"Index\", entry.get()), frame)\n\n search_button = Button(root, text=\"Search\", command=search)\n search_button.pack(side=\"top\")\n\n frame = Frame(root)\n frame.pack(fill=BOTH, expand=1)\n\n root.mainloop()\n\n\ndef clear_window(tk):\n ls = tk.pack_slaves()\n for l in ls:\n l.destroy()\n\n\ndef show_list(elements, frame):\n clear_window(frame)\n # Scrollbar\n scrollbar = Scrollbar(frame)\n scrollbar.pack(side=RIGHT, fill=Y)\n # Listbox widget\n mylist = Listbox(frame, yscrollcommand=scrollbar.set)\n mylist.pack(fill=BOTH, expand=1)\n scrollbar.config(command=mylist.yview)\n # Add elements to listbox\n if elements is not None:\n for item in elements:\n mylist.insert(END, \"Recipient: \" + item[0])\n mylist.insert(END, \"Subject: \" + item[1])\n mylist.insert(END, \"\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Whoosh/p1/Whoosh_1.py","file_name":"Whoosh_1.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"453456387","text":"# Valle de México \n\nimport os\nimport pandas as pd\n\n#Abre bd\nentidades_s= pd.read_csv(\"https://raw.githubusercontent.com/fdealbam/censo2020/main/zm42020_2.csv\")#, encoding= \"Latin-1\")\nentidades_p= pd.read_csv(\"https://raw.githubusercontent.com/fdealbam/censo2020/main/zm42020percent_2.csv\")#, encoding=\"Latin-1\")\n\n#pormunicipio_fa.replace(to_replace =\"*\",\n# value =0, inplace=True)\n\n\n# Falta un identificador de la base 1) entidad 2)mpios\ndf = entidades_s[entidades_s.NOM_ZM == \"Valle de México\"]\ndf_p = entidades_p[entidades_p.NOM_ZM == \"Valle de México\"]\n\n\nnoment = df.iloc[0][\"NOM_ZM\"]\n\n#-------------------------------------Pob Total\nptotal_s = df.POBTOT.sum() # población total \npfemto_s = df.POBFEM.sum() # población femenina \npmascu_s = df.POBMAS.sum() # población masculina \n\n#-------------------------------------Derechohabiencia\nsinderechohabiencia_s = df.PSINDER.sum() # Población sin afiliación a servicios de salud \nderechoimss_s = df.PDER_IMSS.sum() # Población afiliada a servicios de salud en el IMSS \nderechosegp_s = df.PDER_SEGP.sum() # Población afiliada a servicios de salud en el Instituto de Salud para el Bienestar\nderechopriv_s = df.PAFIL_IPRIV.sum() # Población afiliada a servicios de salud en una institución privada \n\n\n#-------------------------------------Educación (Primaria completa cambió por analfabetismo)\npoblacion15ymasanalfabeta_s = df.P15YM_AN.sum() # Población de 15 años y más analfabeta \npoblacion15ymasconsecundaria_s = df.P15SEC_CO.sum() # Población de 15 años y más con secundaria completa\npoblacion15ymasconposbasica_s = df.P18YM_PB.sum() # Población de 18 años y más con educación posbásica\n\n\n\n\n#-------------------------------------Discapacidad|\ncondiscapacidad_s = df.PCON_DISC.sum() # Población con discapacidad\ncondiscapacidadparamoverse_s = df.PCDISC_MOT.sum() # Población con discapacidad caminar subir o bajar\ncondiscapacidadparaver_s = df.PCDISC_VIS.sum() # Población con discapacidad para ver aun con lentes\ncondiscapacidadparahablar_s = df.PCDISC_LENG.sum() # Población con discapacidad para hablar \ncondiscapacidadparaoir_s = df.PCDISC_AUD.sum() # Población con discapacidad para oir\n\n\n#Edad \nde60añosymas_s = df.P_60YMAS.sum() # población de 60 y más \nde15a64años_s = df.POB15_64.sum() # población de 15 a 64 años \nde15A17años_s = df.P_15A17.sum() # población de 15 a 17 años \nde12a14años_s = df.P_12A14.sum() # población de 12 a 14 años \nde6a11años_s = df.P_6A11.sum() # población de 6 a 11 años \nde3a5años_s = df.P_3A5.sum() # población de 3 a 5 años \nde0a2años_s = df.P_0A2.sum() # población de 0 a 2 años \n\n#Vivienda\n#------------------------------------- Variables de Vivienda\nconsanitario_s = df.VPH_EXCSA.sum() # Viviendas particulares habitadas que disponen de excusado o sanitario \nvivendashabitadas_s = df.VIVTOT.sum() # Total de viviendas \nconluzelectrica_s = df.VPH_C_ELEC.sum() # Viviendas particulares habitadas que disponen de energía eléctrica \nconaguaentubada_s = df.VPH_AGUADV.sum() # Viviendas particulares habitadas que disponen de agua entubada en el ámbito de la viviendas \nconundorm_s = df.VPH_1DOR.sum() # Viviendas particulares habitadas con un dormitorio \ncondrenaje_s = df.VPH_DRENAJ.sum() # Viviendas particulares habitadas que disponen de drenaje \ncontelevisor_s = df.VPH_TV.sum() # Viviendas particulares habitadas que disponen de televisor \nconrefrigerador_s = df.VPH_REFRI.sum() # Viviendas particulares habitadas que disponen de refrigerador \nconstreaming_s = df.VPH_SPMVPI.sum() # Viviendas particulares habitadas que disponen de servicio de películas, música o videos de paga por Internet \nconinternet_s = df.VPH_INTER.sum() # Viviendas particulares habitadas que disponen de Internet \nconcomputadora_s = df.VPH_PC.sum() # Viviendas particulares habitadas que disponen de computadora, laptop o tablet \nconcelular_s = df.VPH_CEL.sum() # Viviendas particulares habitadas que disponen de teléfono celular\ncontinaco_s = df.VPH_TINACO.sum() # Viviendas particulares habitadas que disponen de tinaco \nconcisterna = df.VPH_CISTER.sum() # Viviendas particulares habitadas que disponen de cisterna o aljibe\nconlavadora_s = df.VPH_LAVAD.sum() # Viviendas particulares habitadas que disponen de lavadora \nconbici_s = df.VPH_BICI.sum() # Viviendas particulares habitadas que disponen de bicicleta como medio de transporte \n\n\n#----------------------------------------------------Variables de Migración\npoblacionnacidaenotraentidad_s = df.PNACOE.sum() # Población nacida en otra entidad \npoblacionfemeninanacidaenotraentidad_s = df.PNACOE_F.sum() # Población femenina nacida en la entidad \npoblacionde15añosymasnacidaotraentidad_s = df.PRESOE15.sum() # Población de 5 años y más residente en otra entidad en marzo de 2015 \n\n\n#----------------------------------------------------Variables de economía\npoblacionOcupada_s = df.POCUPADA.sum() # población ocupada \npoblacionMasculinaOcupada_s = df.POCUPADA_M.sum() # Población femenina de 12 años y más desocupada \npoblacionFemeninaOcupada_s = df.POCUPADA_F.sum() # Población masculina de 12 años y más ocupada \npoblacion12ymasdesocupada_s = df.PDESOCUP.sum() # Población de 12 años y más desocupada \npoblacioninactiva_s = df.PE_INAC.sum() \n\n\n#----------------------------------------------------Variables de Religión \nreligioncatolica_s = df.PCATOLICA.sum() # Población con religión católica \nsinreligion_s = df.PSIN_RELIG.sum() # Población sin religión o sin adscripción religiosa \nevangelistasyprotestante_s = df.PRO_CRIEVA.sum() # Población con grupo religioso protestante/ cristiano evangélico \notrasreligioness_s = df.POTRAS_REL.sum() # Población con otras religiones diferentes a las anteriores \n\n#----------------------------------------------------Variables de Educación\npoblacion15ymasanalfabeta_s = df.P15YM_AN.sum() # Población de 15 años y más analfabeta \n\n#----------------------------------------------------Variables de Hogares censales\n \npoblacionenhogaresconjefaturafemenina_s = df.HOGJEF_F.sum() # Hogares censales con persona de referencia mujer \npoblacionenhogaresconjefaturamasculina_s = df.PHOGJEF_M.sum() # Hogares censales con persona de referencia hombre\npoblaciontotalenhogares_s = df.POBHOG.sum() # Población en hogares censales\n#agregados:jef masc y total de hogares\n\npromediodeocupantesporvivienda = df[\"PROM_OCUP.1\"].sum() #Promedio de ocupantes en viviendas particulares habitadas\n\n\n\n\n\n############################################################################### PORCEnTAJES\n\n\n\n# PORCEnTAJES\n#---------------------------------Pob Total\n#ptotal_p = df_p['POBTOT_%'].sum()\npfemto_p = (df_p['POBFEM_%'].sum()).round(1)\npmascu_p = df_p['POBMAS_%'].sum()\n\n#---------------------------------Derechohabiencia\nsinderechohabiencia_p = df_p['PSINDER_%'].sum()\nderechoimss_p = df_p['PDER_IMSS_%'].sum()\nderechosegp_p = df_p['PDER_SEGP_%'].sum()\nderechopriv_p = df_p['PAFIL_IPRIV_%'].sum()\n\n\n#---------------------------------Educación (Primaria completa cambió por analfabetismo)\n#poblacion15ymasanalfabeta_p = df_p['P15YM_AN_%'].sum()\n\n#---------------------------------Discapacidad\ncondiscapacidad_p = df_p['PCON_DISC_%'].sum()\ncondiscapacidadparamoverse_p = (df_p['PCDISC_MOT_%'].sum()).round(1) # Población con discapacidad caminar subir o bajar\ncondiscapacidadparaver_p = (df_p['PCDISC_VIS_%'].sum()).round(1) # Población con discapacidad para ver aun con lentes\ncondiscapacidadparahablar_p = (df_p['PCDISC_LENG_%'].sum()).round(1) # Población con discapacidad para hablar \ncondiscapacidadparaoir_p = (df_p['PCDISC_AUD_%'].sum()).round(1) # Población con discapacidad para oir\n\n\n#Edad \nde60añosymas_p = df_p['P_60YMAS_%'].sum() \nde15a64años_p = df_p['POB15_64_%'].sum() \nde15A17años_p = df_p['P_15A17_%'].sum() \nde12a14años_p = df_p['P_12A14_%'].sum() \nde6a11años_p = df_p['P_6A11_%'].sum() \nde3a5años_p = df_p['P_3A5_%'].sum() \nde0a2años_p = df_p['P_0A2_%'].sum() \n\n#Vivienda\n#---------------------------------Variables de Vivienda\nconsanitario_p = df_p['VPH_EXCSA_%'].sum() \nvivendashabitadas_p = df_p['TVIVHAB_%'].sum() \nconluzelectrica_p = df_p['VPH_C_ELEC_%'].sum() \nconaguaentubada_p = df_p['VPH_AGUADV_%'].sum() \nconundorm_p = df_p['VPH_1DOR_%'].sum() \ncondrenaje_p = df_p['VPH_DRENAJ_%'].sum() \ncontelevisor_p = df_p['VPH_TV_%'].sum() \nconrefrigerador_p = df_p['VPH_REFRI_%'].sum() \nconstreaming_p = df_p['VPH_SPMVPI_%'].sum() \nconinternet_p = df_p['VPH_INTER_%'].sum() \nconcomputadora_p = df_p['VPH_PC_%'].sum() \nconcelular_p = df_p['VPH_CEL_%'].sum() \ncontinaco_p = df_p['VPH_TINACO_%'].sum() \nconcisterna = df_p['VPH_CISTER_%'].sum()\nconlavadora_p = df_p['VPH_LAVAD_%'].sum() \nconbici_p = df_p['VPH_BICI_%'].sum()\n\n\n#---------------------------------Variables de Migración\npoblacionnacidaenotraentidad_p = df_p['PNACOE_%'].sum() \npoblacionfemeninanacidaenotraentidad_p = df_p['PNACOE_F_%'].sum() \npoblacionde15añosymasnacidaotraentidad_p = df_p['PRESOE15_%'].sum() \n\n\n#---------------------------------Variables de economía\npoblacionOcupada_p = (df_p['POCUPADA_%'].sum()).round(1) \npoblacionMasculinaOcupada_p = (df_p['POCUPADA_M_%'].sum()).round(1) \npoblacionFemeninaOcupada_p = (df_p['POCUPADA_F_%'].sum()).round(1) \npoblacioninactiva_p = (df_p['PE_INAC_%'].sum()).round(1) \npoblacion12ymasdesocupada_p = (df_p['PDESOCUP_%'].sum()).round(1) \n\n\n#---------------------------------Variables de Religión \nreligioncatolica_p = df_p['PCATOLICA_%'].sum() \nsinreligion_p = df_p['PSIN_RELIG_%'].sum() \nevangelistasyprotestante_p = df_p['PRO_CRIEVA_%'].sum() \notrasreligioness_p = df_p['POTRAS_REL_%'].sum() \n\n#---------------------------------Variables de Educación\npoblacion15ymasanalfabeta_p = df_p['P15YM_AN_%'].sum() \npoblacion15ymasconsecundaria_p = df_p['P15SEC_CO_%'].sum()\npoblacion15ymasconposbasica_p = df_p['P18YM_PB_%'].sum()\n\n#---------------------------------Variables de Hogares censales\n \npoblacionenhogaresconjefaturafemenina_p = (df_p['PHOGJEF_F_%'].sum()).round(1) \npoblacionenhogaresconjefaturamasculina_p = (df_p['PHOGJEF_M_%'].sum()).round(1)\npoblaciontotalenhogares_p = df_p['POBHOG_%'].sum()\n\n\n\n\n\nimport dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport pandas as pd\nimport plotly.graph_objs as go\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\nimport plotly.io as pio\nimport numpy as np\nimport dash_table\nimport sidetable as stb\nimport datetime\nfrom datetime import datetime, timedelta\nfrom datetime import date\n#import geopandas as gpd\nimport flask\nimport os\nyesterday = datetime.now() - timedelta(1)\nyea = datetime.strftime(yesterday, '%Y%m%d')\n\ntoday = date.today()\nd2 = today.strftime(\"Fecha de actualización : %d-%m-%Y\")\n\n#pobsindh = 7804407\n\n\n\n\n##########################################################################\n#Seccion 1. Variables de POBLACION\n##########################################################################\n\n\n\n################################## Card\n\ncard = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Variables\", \n className=\"card-title\",\n style={'textAlign': 'left',\"color\": \"gray\"}),\n html.H2(\"de población\", \n className=\"card-subtitle\",\n style={'textAlign': 'left',\"color\": \"black\", \"font-weight\": 'bold'}),\n html.Br(),\n html.Br(),\n html.Br(),\n \n html.P(\n \"Sin derechohabiencia \"\n f\"{int(sinderechohabiencia_s):,}\",\n className=\"card-text\",\n style={'textAlign': 'left',\"color\": \"black\",\n #'FontColor': 120\n }\n ),\n\n \n \n dbc.Button(\n html.Span([\"\", html.H1(className=\"fas fa-male\", style={\"color\": \"#FFD180\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"#FFD180\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"#FFD180\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"#FFD180\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"#E0E0E0\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"#E0E0E0\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"#E0E0E0\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"#E0E0E0\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"#E0E0E0\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"#E0E0E0\"}),]),),\n html.Br(),\n \n \n \n #Porcentaje derechohabiencia \n \n html.P([(sinderechohabiencia_p),\"%\"] , \n className=\"card-text\",\n style={'textAlign': 'right',\n \"color\": \"black\", \n \"font-size\": \"48px\",\n \"font-weight\": 'bold',\n \"color\": \"dark\",}),\n \n dbc.Button(\n html.Span([html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n\n ],style={\"align\" :\"center\",\n 'margin-left': '-30px',\n #'margin-right': '120px',\n }),),\n \n \n \n \n \n # 15 años y más analfabeta\n html.P(\n \"Población de 15 años y más analfabeta \" #verificar este campo (alfabeta* o analfabeta)\n f\"{int(poblacion15ymasanalfabeta_s):,}\", \n className=\"card-text\",\n style={'textAlign': 'left',\"color\": \"black\",\n 'FontColor': 120}\n ),\n dbc.Button(\n html.Span([\"\", html.H1(className=\"fas fa-user-graduate\", style={\"color\": \"#FFD180\"}),\n html.H1(className=\"fas fa-user-graduate\", style={\"color\": \"#FFD180\"}),\n html.H1(className=\"fas fa-user-graduate\", style={\"color\": \"#E0E0E0\"}),\n html.H1(className=\"fas fa-user-graduate\", style={\"color\": \"#E0E0E0\"}),\n html.H1(className=\"fas fa-user-graduate\", style={\"color\": \"#E0E0E0\"}),\n ]),),\n \n # % 15 años y más analfabeta\n html.P([(poblacion15ymasanalfabeta_p),\"%\"] ,\n className=\"card-text\",\n style={'textAlign': 'right',\n \"color\": \"black\", \n \"font-size\": \"48px\",\n \"font-weight\": 'bold',}),\n \n\n dbc.Button(\n html.Span([html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n html.H6(className=\"fas fa-window-minimize\", style={\"color\": \"#CFD8DC\"}),\n\n ],style={\"align\" :\"center\",\n 'margin-left': '-30px',\n }),),\n \n html.P(\n \"Con discapacidad \" \n f\"{int(condiscapacidad_s):,}\", \n className=\"card-text\",\n style={'textAlign': 'left',\"color\": \"black\",\n 'FontColor': 120}\n ),\n dbc.Button(\n html.Span([\"\", html.H1(className=\"fas fa-wheelchair\", style={\"color\": \"#FFD180\"}),\n html.H1(className=\"fas fa-wheelchair\", style={\"color\": \"#E0E0E0\"}),\n html.H1(className=\"fas fa-wheelchair\", style={\"color\": \"#E0E0E0\"}),\n html.H1(className=\"fas fa-wheelchair\", style={\"color\": \"#E0E0E0\"}),\n html.H1(className=\"fas fa-wheelchair\", style={\"color\": \"#E0E0E0\"}),]),),\n html.P([(condiscapacidad_p),\"%\"] , \n className=\"card-text\",\n style={'textAlign': 'right',\n \"color\": \"black\", \n \"font-size\": \"48px\",\n \"font-weight\": 'bold',}),\n\n ]\n ),\n \n style={\"width\": \"22.5rem\", \n \"border\": \"0\",\n \"card-border\": \"0\"},\n)\n\n\n\n\n\n##########################################################################\n#Seccion 2. Variables de vivienda\n##########################################################################\n\n#################################### Card2 HAY QUE AJUSTARLA CON....\n\n\ncard2 = dbc.Card(\n dbc.CardBody(\n [ \n #Falta Poblacion total\n html.H6(\"Población total\", \n style={#'textAlign': 'left',\n \"color\": \"white\",\n \"background-color\": \"orange\"}),\n html.H3(f\"{int(ptotal_s):,}\",\n style={#'textAlign': 'left',\n \"color\": \"white\",\n \"background-color\": \"orange\"}),\n dbc.Button(\n html.Span([html.H1(className=\"fas fa-male\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-female\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-female\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-female\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-female\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-female\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-female\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-female\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-female\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-male\", style={\"color\": \"white\"}),\n html.H1(className=\"fas fa-female\", style={\"color\": \"white\"}),\n ],style={#\"background-color\": \"orange\"\n }),style={\"background-color\": \"orange\"}),\n\n \n #Falta Poblacion masculina y femenina\n# html.Span([\n# html.H6([pfemto_p, \"% \"], style={\"color\": \"white\", \"background-color\": \"orange\"}), \n# html.H1(className=\"fas fa-female\", \n# style={\"color\": \"white\", \"background-color\": \"orange\"}),\n#\n# html.H6([pmascu_p, \"% \"], style={\"color\": \"white\", \"background-color\": \"orange\"}), \n# html.H1(className=\"fas fa-male\", \n# style={\"color\": \"white\", \"background-color\": \"orange\"}),\n# \n# ]),\n \n ]), \n style={\"width\": \"25rem\", \n \"border\": \"0\",\n \"margin-left\": \"-10px\",\n #\"height\": \"10px\",\n \"background-color\": \"orange\",\n },) \n\n \n\ncard21 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"De 0 a 2 años \", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5( f\"{int(de0a2años_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n \n \n html.P([(de0a2años_p),\"%\"] , #\"64%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"25.5rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n\ncard22 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"De 3 a 5 años\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(de3a5años_s ):,}\",\n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n html.P([(de3a5años_p),\"%\"] , \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"25.5rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n \n },),\n \ncard23 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"De 6 a 11 años\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(de6a11años_s):,}\",\n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n \n html.P([(de6a11años_p),\"%\"] , \n \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"25.5rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },),\n\ncard24 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"De 12 a 14 años\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(de12a14años_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n \n html.P([(de12a14años_p),\"%\"] ,\n \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n })]), \n style={\"width\": \"25.5rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n \n \n \n\ncard25 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"De 15 a 17 años\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(de15A17años_s):,}\",\n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n \n html.P([(de15A17años_p),\"%\"] ,\n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n })]), \n style={\"width\": \"25.5rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n\ncard26 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"De 15 a 64 años\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(de15a64años_s):,}\",\n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n \n html.P([(de15a64años_p),\"%\"] ,\n \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"25.5rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n\ncard27 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"De 60 años y más\", #Aqui cambio antes: \"De 18 años y más\"\n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(de60añosymas_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n \n html.P([(de60añosymas_p),\"%\"] ,\n \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"25.5rem\", \n \"border\": \"0\",\n \"background-color\": \"#0097A7\",\n },)\n\n\n##########################################################################\n#Seccion 3. Variables de vivienda\n##########################################################################\n \n \n\n\n\n## Tabla de variablesvar\nrow1 = html.Tr([\n html.Td([dbc.Button([html.H6(className=\"fas fa-home\",\n style={'textAlign': 'left',\n \"color\":\"#FBC02D\",\n \"font-size\": \"40px\",\n \"margin-right\": \"-120px\",\n \"margin-top\": \"-20px\",\n \"widht\": \"10px\"})])]), \n dbc.Alert(\"Con sanitario\", color=\"#E0E0E0\",\n style={\"text-align\": \"right\",\n \"margin-left\": \"-120px\",\n \"height\": \"50px\" }),\n html.Td(f\"{int(consanitario_s):,}\",\n style={\"height\": \"50px\",\n \"text-align\": \"top\"}),\n \n dbc.Alert( [(consanitario_p),\"%\"] ,#\"94%\", \n color=\"light\",\n style={\"font-size\": \"35px\",\n \"height\": \"40px\",\n \"margin-left\": \"-40px\",\n \n \"font-weight\": 'bold',\n \"color\": \"#FBC02D\", \n })])\n\n\nrow2 = html.Tr([\n html.Td([dbc.Button([html.H6(className=\"fas fa-home\",\n style={'textAlign': 'left',\n \"color\":\"#FBC02D\",\n \"font-size\": \"40px\",\n \"margin-right\": \"-120px\",\n \"margin-top\": \"-20px\",\n \"widht\": \"10px\"})])]), \n dbc.Alert(\"Viviendas habitadas\", color=\"#E0E0E0\",\n style={\"text-align\": \"right\",\n \"margin-left\": \"-120px\",\n \"height\": \"50px\" }),\n html.Td(f\"{int(vivendashabitadas_s):,}\", \n style={\"height\": \"50px\",\n \"text-align\": \"top\"}),\n \n dbc.Alert([(vivendashabitadas_p),\"%\"],#\"94%\",\n color=\"light\",\n style={\"font-size\": \"35px\",\n \"height\": \"40px\",\n \"margin-left\": \"-40px\",\n \"font-weight\": 'bold',\n \"color\": \"#FBC02D\",\n })])\n \n\n\nrow3 = html.Tr([\n html.Td([dbc.Button([html.H6(className=\"fas fa-home\",\n style={'textAlign': 'left',\n \"color\":\"#FBC02D\",\n \"font-size\": \"40px\",\n \"margin-right\": \"-120px\",\n \"margin-top\": \"-20px\",\n \"widht\": \"10px\"})])]), \n dbc.Alert(\"Con luz eléctrica\", color=\"#E0E0E0\",\n style={\"text-align\": \"right\",\n \"margin-left\": \"-120px\",\n \"height\": \"50px\" }),\n html.Td(f\"{int(conluzelectrica_s):,}\", \n style={\"height\": \"50px\",\n \"text-align\": \"top\"}),\n \n dbc.Alert([(conluzelectrica_p),\"%\"],#\"94%\",\n color=\"light\",\n style={\"font-size\": \"35px\",\n \"height\": \"40px\",\n \"margin-left\": \"-40px\",\n \"font-weight\": 'bold',\n \"color\": \"#FBC02D\",\n })])\n\n\nrow4 = html.Tr([\n html.Td([dbc.Button([html.H6(className=\"fas fa-home\",\n style={'textAlign': 'left',\n \"color\":\"#FBC02D\",\n \"font-size\": \"40px\",\n \"margin-right\": \"-120px\",\n \"margin-top\": \"-20px\",\n \"widht\": \"10px\"})])]), \n dbc.Alert(\"Con agua entubada\", color=\"#E0E0E0\",\n style={\"text-align\": \"right\",\n \"margin-left\": \"-120px\",\n \"height\": \"50px\" }),\n html.Td(f\"{int(conaguaentubada_s):,}\", \n style={\"height\": \"50px\",\n \"text-align\": \"top\"}),\n dbc.Alert([(conaguaentubada_p),\"%\"],#\"94%\",\n color=\"light\",\n style={\"font-size\": \"35px\",\n \"height\": \"40px\",\n \"margin-left\": \"-40px\",\n \n \"font-weight\": 'bold',\n \"color\": \"#FBC02D\", \n })])\n\n\nrow5 = html.Tr([\n html.Td([dbc.Button([html.H6(className=\"fas fa-home\",\n style={'textAlign': 'left',\n \"color\":\"#FBC02D\",\n \"font-size\": \"40px\",\n \"margin-right\": \"-120px\",\n \"margin-top\": \"-20px\",\n \"widht\": \"10px\"})])]), \n dbc.Alert(\"Con drenaje\", color=\"#E0E0E0\",\n style={\"text-align\": \"right\",\n \"margin-left\": \"-120px\",\n \"height\": \"50px\" }),\n html.Td(f\"{int(condrenaje_s):,}\",\n style={\"height\": \"50px\",\n \"text-align\": \"top\"}),\n dbc.Alert([(condrenaje_p),\"%\"],#\"94%\",\n color=\"light\",\n style={\"font-size\": \"35px\",\n \"height\": \"40px\",\n \"margin-left\": \"-40px\",\n \n \"font-weight\": 'bold',\n \"color\": \"#FBC02D\", \n })])\n\n\ntable_body = [html.Tbody([row2, row1, row3, row4,row5])]\n\n\n\n\n#################################### Card3\ncard3 = dbc.Card(\n dbc.CardBody(\n [\n \n html.P([dbc.Button([html.H1(className=\"fas fa-home\",\n style={'textAlign': 'left',\n \"color\":\"#FBC02D\",\n \"font-size\": \"80px\"}),\n \" Variables de Vivienda\"], \n style={'textAlign': 'left',\"color\":\"#FBC02D\",\n \"font-size\": \"30px\",\n 'margin-bottom':'-30px'\n })]),\n \n dbc.Table( table_body, bordered=False)]),\n \n \n style={\"width\": \"50rem\", \n \"border\": \"0\",\n \"fill\" : \"orange\"},\n)\n\n\n\n##########################################################################\n#Seccion 4 Variables de INTERNET\n##########################################################################\n \n#Falta por acomodar nuevas variables: \n#f\"{int(conundorm_s):,}\", \n# \n#f\"{int(conrefrigerador_s):,}\", \n#f\"{int(constreaming_s):,}\", \n#f\"{int(continaco_s):,}\", \n#f\"{int(concisterna):,}\", \n#f\"{int(conlavadora_s):,}\", \n#f\"{int(conbici_s):,}\", \n#################################### Card2p3\ncard2p3 = dbc.Card(\n dbc.CardBody(\n [\n dbc.Button(([\"\", html.H3(className=\"fas fa-wifi\", style={\"color\": \"black\",\n \"background-color\": \"light\"}),\n html.H6(\" Con internet \",\n style={\"color\":\"black\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(coninternet_p),\"%\"],#\"97%\",\n style={\"color\":\"#FBC02D\",\n \"background-color\": \"light\"}),\n html.P(f\"{int(coninternet_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\"}),\n\n \n dbc.Button(([\"\", html.H3(className=\"fas fa-tv\", \n style={\"color\": \"lightgray\",\n \"background-color\": \"light\"}),\n html.H6(\" Con televisor \", \n style={\"color\":\"lightgray\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(contelevisor_p),\"%\"],#\"97%\", \n style={\"color\":\"#FBC02D\",\n \"background-color\": \"light\"}),\n html.P(f\"{int(contelevisor_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\"}),\n\n dbc.Button(([\"\", html.H3(className=\"fas fa-laptop\", style={\"color\": \"lightgray\",\n \"background-color\": \"light\"}),\n html.H6(\" Con computadora \",\n style={\"color\":\"lightgray\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(concomputadora_p),\"%\"],#\"97%\",\n style={\"color\":\"#FBC02D\",\n \"background-color\": \"light\"}),# \n html.P(f\"{int(concomputadora_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\"}),\n \n\n dbc.Button(([\"\", html.H3(className=\"fas fa-mobile-alt\", style={\"color\": \"black\",\n \"background-color\": \"light\"}),\n html.H6(\" Con celular \",\n style={\"color\":\"black\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(concelular_p),\"%\"],#\"97%\",\n style={\"color\":\"#FBC02D\",\n \"background-color\": \"light\"}),\n html.P(f\"{int(concelular_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\"}),\n \n#poner aqui refrigerador \n dbc.Button(([\"\", html.H3(dbc.CardImg(src= \"https://raw.githubusercontent.com/fdealbam/nvoleon/main/application/static/refrigerator-light.svg?raw=true\", \n style={\"color\": \"black\",\n \"height\" :\"25px\",\n \"background-clor\": \"light\"})), \n\n \n #dbc.Button(([\"\", html.H3(className=\"fal fa-refrigerator\", style={\"color\": \"black\",\n # \"background-color\": \"light\"}),\n html.H6(\" Con refrigerador \",\n style={\"color\":\"black\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(conrefrigerador_p),\"%\"],#\"97%\",\n style={\"color\":\"#FBC02D\",\n \"background-color\": \"light\"}),\n html.P(f\"{int(conrefrigerador_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\"}),\n \n\n#poner aqui lavadora \n dbc.Button(([\"\", html.H3(dbc.CardImg(src= \"https://raw.githubusercontent.com/fdealbam/nvoleon/main/application/static/laundry.svg?raw=true\", \n style={\"color\": \"black\",\n \"height\" :\"25px\",\n \"background-clor\": \"light\"})), \n \n # dbc.Button(([\"\", html.H3(className=\"fal fa-washer\", style={\"color\": \"black\",\n # \"background-color\": \"light\"}),\n html.H6(\" Con lavadora \",\n style={\"color\":\"black\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(conlavadora_p),\"%\"],#\"97%\",\n style={\"color\":\"#FBC02D\",\n \"background-color\": \"light\"}),\n html.P(f\"{int(conlavadora_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\"}),\n\n\n#poner aqui bicicleta \n dbc.Button(([\"\", html.H2(className=\"fas fa-bicycle\", style={\"color\": \"black\",\n \"background-color\": \"light\"}),\n html.H6(\" Con bicicleta\",\n style={\"color\":\"black\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(conbici_p),\"%\"],#\"97%\",\n style={\"color\":\"#FBC02D\",\n \"background-color\": \"light\"}),\n html.P(f\"{int(conbici_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\"}),\n \n \n ]), style={\"width\": \"45rem\",\n \"margin-left\": \"46.5px\",\n \"margin-right\": \"46.5px\",\n \"border\": \"0\",\n \"background-color\": \"light\",\n \"outline\": \"white\"\n # \"border-width\": \"1px\"\n })\n\n\n \n\n\n\n\n##########################################################################\n#Seccion 7. Variables de MIGRACION\n##########################################################################\n \n \n\ncard_migra1 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Población nacida en otra entidad\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(poblacionnacidaenotraentidad_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n html.H2([(poblacionnacidaenotraentidad_p),\"%\"],#\"64%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"48rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n\ncard_migra2 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Población femenina nacida en otra entidad\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(poblacionfemeninanacidaenotraentidad_s):,}\",\n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n html.H2([(poblacionfemeninanacidaenotraentidad_p),\"%\"],#\"64%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"48rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n\ncard_migra3 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Población de 5 años y más residente en otra entidad en marzo de 2015\", # cambio: Población de 5 años y mas nacida en otra entidad otranota: VERIFICAR \"en marzo de 2015\"\n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(poblacionde15añosymasnacidaotraentidad_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n html.H2([(poblacionde15añosymasnacidaotraentidad_p),\"%\"],#\"64%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"48rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n\n\n#################################### card_v_migracion\n#\"fas fa-hospital-user\"\n#\"fas fa-procedures\"\ncard_v_migracion = dbc.Card(\n dbc.CardBody([\n html.P([dbc.Button([html.H1(className=\"fas fa-plane-departure\",\n style={'textAlign': 'left',\n \"color\":\"#0097A7\",\n \"font-size\": \"80px\"}),\n \" Variables de migración\"], \n style={'textAlign': 'left',\"color\":\"#0097A7\",\n \"font-size\": \"30px\",\n })]),\n \n dbc.Card(card_migra1),\n html.Br(),\n dbc.Card(card_migra2),\n html.Br(),\n dbc.Card(card_migra3),\n \n ], style={\"width\": \"50rem\", \n \"border\": \"0\",\n \"fill\" : \"orange\"},))\n\n\n \n##########################################################################\n#Seccion 8. Variables de HOGARES CENSALES\n##########################################################################\n\nrow1 = html.Tr([dbc.Alert(\"Población en hogares\" , color=\"E0E0E0\",), \n html.Td(f\"{int(poblaciontotalenhogares_s):,}\"),\n dbc.Alert([(poblaciontotalenhogares_p),\"%\"], color=\"light\",\n style={\"font-size\": \"35px\",\n \"font-weight\": 'bold',\n \"color\": \"#F48FB1\", \n })])\n\n\nrow2 = html.Tr([dbc.Alert(\"Población en hogares con jefatura masculina\", color=\"#E0E0E0\",), \n html.Td(f\"{int(poblacionenhogaresconjefaturamasculina_s):,}\"),\n dbc.Alert([(poblacionenhogaresconjefaturamasculina_p),\"%\"], color=\"light\",\n style={\"font-size\": \"35px\",\n \"font-weight\": 'bold',\n \"color\": \"#F48FB1\", \n })])\n\nrow3 = html.Tr([dbc.Alert(\"Población en hogares con jefatura femenina\", color=\"#E0E0E0\",), \n html.Td(f\"{int(poblacionenhogaresconjefaturafemenina_s):,}\"),\n dbc.Alert([(poblacionenhogaresconjefaturafemenina_p),\"%\"],\n color=\"light\",\n style={\"font-size\": \"35px\",\n \"font-weight\": 'bold',\n \"color\": \"#F48FB1\", \n })])\n\nrow4 = html.Tr([dbc.Alert(\"Promedio de ocupantes en viviendas particulares\", color=\"#E0E0E0\",), \n html.Td(\" \"),\n dbc.Alert(promediodeocupantesporvivienda, color=\"light\",\n style={\"font-size\": \"35px\",\n \"font-weight\": 'bold',\n \"color\": \"#F48FB1\", \n })])\n\ntable_body = [html.Tbody([row1, row2, row3, row4])]\n\n\n\n#################################### card_v_hog_cens\n\n \ncard_v_hog_cens = dbc.Card(\n dbc.CardBody(\n [\n\n html.P([dbc.Button([html.H1(className= \"fas fa-users\",\n #\"fas fa-house\",\n style={'textAlign': 'left',\n \"color\":\"#F48FB1\",\n \"font-size\": \"80px\"}),\n \" Variables de hogares censales\"], \n style={'textAlign': 'left',\"color\":\"#F48FB1\",\n \"font-size\": \"30px\",\n 'margin-bottom':'-30px'\n })]), \n \n \n dbc.Table( table_body, bordered=False)\n ]),\n \n \n style={\"width\": \"50rem\", \n \"border\": \"0\",\n \"fill\" : \"orange\"},\n)\n\n \n##########################################################################\n#Seccion 9. Variables de DISCAPACIDAD\n##########################################################################\n\n\nrow1 = html.Tr([dbc.Alert(\"Población con discapacidad\", color=\"#E0E0E0\",), \n html.Td(f\"{int(condiscapacidad_s):,}\"),\n dbc.Alert([(condiscapacidad_p),\"%\"],# \"4%\",\n color=\"light\",\n style={\"font-size\": \"35px\",\n \"font-weight\": 'bold',\n \"color\": \"#BA68C8\", \n })])\n\n\ntable_body = [html.Tbody([row1 ])]\n\n\ncard_v_discapacidad = dbc.Card(\n dbc.CardBody(\n [\n \n html.P([dbc.Button([html.H1(className=\"fa fa-wheelchair\",\n style={'textAlign': 'left',\n \"color\":\"#BA68C8\",\n \"font-size\": \"80px\"}),\n \" Variables de Discapacidad\"], \n style={'textAlign': 'left',\"color\":\"#BA68C8\",\n \"font-size\": \"30px\",\n 'margin-bottom':'-30px'\n })]),\n \n dbc.Table( table_body, bordered=False)\n ]),\n style={\"width\": \"50rem\", \n \"border\": \"0\",\n \"fill\" : \"orange\"},\n )\n\n\n###################Recuadro de discapacidad\n\nrecuadrodiscapacidad = dbc.Card(\n dbc.CardBody(\n [\n # discapacidad para caminar \n #dbc.Button(([\"\", html.H3(className=\"fab fa-accesible-icon\", style={\"color\": \"black\",\n # \"background-color\": \"light\"}),\n\n dbc.Button(([\"\", html.H3(dbc.CardImg(src= \"https://raw.githubusercontent.com/fdealbam/nuevoleon/main/application/static/accessible-icon-brands.svg?raw=true\", \n style={\"color\": \"purple\",\n \"height\" :\"25px\",\n \"weight\" :\"15px\",\n \"background-clor\": \"light\"})), \n \n html.H6(\"Caminar\",\n style={\"color\":\"black\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(condiscapacidadparamoverse_p),\"%\"],#\"97%\",\n style={\"color\":\"#BA68C8\",\n \"background-color\": \"light\"}),\n html.P(f\"{int(condiscapacidadparamoverse_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\",\n \"weight\" :\"15px\",}),\n\n\n # discapacidad para ver \n dbc.Button(([\"\", html.H3(dbc.CardImg(src= \"https://raw.githubusercontent.com/fdealbam/nuevoleon/main/application/static/blind-duotone.svg?raw=true\",\n style={\"color\": \"black\",\n \"height\" :\"25px\",\n \n \"background-clor\": \"light\"})), \n html.H6(\"Ver\", \n style={\"color\":\"black\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(condiscapacidadparaver_p),\"%\"],#\"97%\", \n style={\"color\":\"#BA68C8\",\n \"background-color\": \"light\"}),\n html.P(f\"{int(condiscapacidadparaver_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\",\n \"weight\" :\"20px\",}),\n\n # discapacidad para hablar \n dbc.Button(([\"\", html.H3(dbc.CardImg(src= \"https://raw.githubusercontent.com/fdealbam/nuevoleon/main/application/static/comment-slash-duotone.svg?raw=true\",\n style={\"color\": \"black\",\n \"height\" :\"25px\",\n \n \"background-clor\": \"light\"})), \n\n html.H6(\"Hablar\",\n style={\"color\":\"black\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(condiscapacidadparahablar_p),\"%\"],#\"97%\",\n style={\"color\":\"#BA68C8\",\n \"background-color\": \"light\"}),# \n html.P(f\"{int(condiscapacidadparahablar_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\",\n \"weight\" :\"20px\",}),\n \n # discapacidad para oir \n dbc.Button(([\"\", html.H3(dbc.CardImg(src= \"https://raw.githubusercontent.com/fdealbam/nuevoleon/main/application/static/deaf-duotone.svg?raw=true\",\n style={\"color\": \"black\",\n \"height\" :\"25px\",\n \n \"background-clor\": \"light\"})), \n html.H6(\"Oir\",\n style={\"color\":\"black\",\n \"font-size\":10,\n \"background-color\": \"light\"}),\n html.H4([(condiscapacidadparaoir_p),\"%\"],#\"97%\",\n style={\"color\":\"#BA68C8\",\n \"background-color\": \"light\"}),\n html.P(f\"{int(condiscapacidadparaoir_s):,}\", style={\"font-size\":10}), \n ]),style={ \"background-color\": \"light\",\n \"weight\" :\"20px\",}),\n \n \n ]), style={\"width\": \"51rem\",\n \"margin-top\": \"-40.5px\",\n \"margin-left\": \"-25px\",\n \"margin-right\": \"-25px\",\n \n \"border\": \"0\",\n \"background-color\": \"light\",\n \"outline\": \"white\"\n # \"border-width\": \"1px\"\n })\n\n\n \n\n\n\n\n##########################################################################\n#Seccion 10. Variables de ECONOMIA\n##########################################################################\n\n\ncard_econom1 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Población ocupada\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#9cd9e0\"}),\n html.H5(f\"{int(poblacionOcupada_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#9cd9e0\"}),\n html.H2([(poblacionOcupada_p),\"%\"],# \"95%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]),style={\"width\": \"36rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#9cd9e0\",\n },)\n\n\n\n\ncard_econom2 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Población masculina ocupada\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(poblacionMasculinaOcupada_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n html.H2([(poblacionMasculinaOcupada_p),\"%\"],#\"95%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]),style={\"width\": \"36rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n\n\ncard_econom3 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Población femenina ocupada\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#9cd9e0\"}),\n html.H5(f\"{int(poblacionFemeninaOcupada_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#9cd9e0\"}),\n html.H2([(poblacionFemeninaOcupada_p),\"%\"],# \"95%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]),style={\"width\": \"36rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#9cd9e0\",\n },)\n\n\ncard_econom4 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"12 años y más, no activa y estudiante\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(poblacioninactiva_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n html.H2([(poblacioninactiva_p),\"%\"],#\"95%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]),style={\"width\": \"36rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n\ncard_economia = dbc.Card(\n dbc.CardBody(\n [\n html.P([dbc.Button([html.H1(className=\"fas fa-hand-holding-usd\",\n style={'textAlign': 'left',\n \"color\":\"#0097A7\",\n \"font-size\": \"80px\"}),\n \" Variables de economía\"], \n style={'textAlign': 'left',\"color\":\"#0097A7\",\n \"font-size\": \"30px\",\n })],),\n dbc.Card(card_econom1),\n html.Br(),\n dbc.Card(card_econom2),\n html.Br(),\n dbc.Card(card_econom3),\n html.Br(),\n dbc.Card(card_econom4),\n ],style={\"width\": \"38rem\", }))\n \n\n \n \n \n \n \n \ncard_economia_discap = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Población de 12 años y más desocupada\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"background-color\": \"#6A1B9A\"}),\n html.H3(f\"{int(poblacion12ymasdesocupada_s):,}\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"background-color\": \"#6A1B9A\"}),\n html.Br(),\n html.Br(),\n\n\n dbc.ButtonGroup(([\n \"\", html.H3(dbc.CardImg(src= \"https://raw.githubusercontent.com/fdealbam/nuevoleon/main/application/static/user-unlock-solid.svg?raw=true\", #className=\"info\",\n style={\"color\": \"light\",\n #\"height\" :\"25px\",\n \"font-size\": \"110px\", \n \"background-clor\": \"#6A1B9A\"}))])),\n html.Br(),\n html.Br(),\n \n html.H2([(poblacion12ymasdesocupada_p),\"%\"], \n style={'textAlign': 'center',\n \"color\": \"white\",\n #\"height\": \"7px\",\n \"font-size\": \"40px\",\n #'margin-top': '-32px',\n #'margin-bottom': '30px',\n \"background-color\": \"#6A1B9A\"}),]),\n style={\"width\": \"13rem\", \n \"border\": \"0\",\n #\"margin-left\": \"40px\",\n \"background-color\": \"#6A1B9A\",\n 'color':'#BA68C8',\n \"height\": \"550px\",\n })\n\n\n##########################################################################\n#Seccion 5 Variables de RELIGION\n##########################################################################\ncard_religion1 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Religión católica\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#9cd9e0\"}),\n html.H5(f\"{int(religioncatolica_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#9cd9e0\"}),\n html.H2([(religioncatolica_p),\"%\"],#\"64%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"48rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#9cd9e0\",\n },)\n\ncard_religion2 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Protestantes, Evangélicas y diferentes de Evangélicas\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(evangelistasyprotestante_s):,}\",\n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n html.H2([(evangelistasyprotestante_p),\"%\"],#\"64%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"48rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n\n\ncard_religion3 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Sin religión\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#9cd9e0\"}),\n html.H5(f\"{int(sinreligion_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#9cd9e0\"}),\n html.H2([(sinreligion_p),\"%\"],#\"64%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"48rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#9cd9e0\",\n },)\ncard_religion4 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Otras religiones\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(otrasreligioness_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n html.H2([(otrasreligioness_p),\"%\"],#\"64%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"48rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n\n#########\ncard_v_religionAA = dbc.Card(\n dbc.CardBody(\n [\n html.P([dbc.Button([html.H1(className=\"fas fa-church\",\n style={'textAlign': 'left',\n \"color\":\"#0097A7\",\n \"font-size\": \"80px\"}),\n \" Variables de Religion\"], \n style={'textAlign': 'left',\"color\":\"#0097A7\",\n \"font-size\": \"30px\",\n })]),\n \n dbc.Card(card_religion1),\n html.Br(),\n dbc.Card(card_religion2),\n html.Br(),\n dbc.Card(card_religion3),\n html.Br(),\n dbc.Card(card_religion4),\n \n ]),\n style={\"width\": \"50rem\", \n \"border\": \"0\",\n \"fill\" : \"orange\"},\n)\n\n\n\n\n\n\n\n\n\n\n##########################################################################\n#Seccion 6 Variables de EDUCACION\n##########################################################################\n\n\nrow1edu = html.Tr([dbc.Alert(\"De 15 años y más analfabeta\", color=\"#E0E0E0\",), \n html.Td(f\"{int(poblacion15ymasanalfabeta_s):,}\"),\n dbc.Alert([(poblacion15ymasanalfabeta_p),\"%\"], color=\"light\",\n style={\"font-size\": \"35px\",\n \"font-weight\": 'bold',\n \"color\": \"#81C784\", \n })])\n\n\nrow2edu = html.Tr([dbc.Alert(\"De 15 años y más con secundaria completa\", color=\"#E0E0E0\",), \n html.Td(f\"{int(poblacion15ymasconsecundaria_s):,}\"),\n dbc.Alert([(poblacion15ymasconsecundaria_p),\"%\"], color=\"light\",\n style={\"font-size\": \"35px\",\n \"font-weight\": 'bold',\n \"color\": \"#81C784\", \n })])\n\nrow3edu = html.Tr([dbc.Alert(\"De 18 años y más con educación posbásica\", color=\"#E0E0E0\",), \n html.Td(f\"{int(poblacion15ymasconposbasica_s):,}\"),\n dbc.Alert([(poblacion15ymasconposbasica_p),\"%\"],color=\"light\",\n style={\"font-size\": \"35px\",\n \"font-weight\": 'bold',\n \"color\": \"#81C784\", \n })])\n\ntable_body = [html.Tbody([row1edu, row2edu, row3edu])]\n\n\n\n#################################### card_v_edu\n\n \ncard_v_edu = dbc.Card(\n dbc.CardBody(\n [\n html.P([dbc.Button([html.H1(className=\"fas fa-book-reader\",\n style={'textAlign': 'left',\n \"color\":\"#81C784\",\n \"font-size\": \"80px\"}),\n \" Variables de educación\"], \n style={'textAlign': 'left',\"color\":\"#81C784\",\n \"font-size\": \"30px\",\n 'margin-bottom':'-30px'\n })]),\n \n dbc.Table( table_body, bordered=False)\n ]),\n \n \n style={\"width\": \"50rem\", \n # \"border\":\"none\",\n # \"border-color\": \"transparent\",\n #\"background-color\": \"transparent\",\n # \" border-bottom\":\" 1px solid rgba(0,0,0,.8)\",\n # \"border\": \"0\",\n # \"border-top\":\"0\",\n # \"border-right\":\"0\",\n # \"border-bottom\":\"0\",\n # \"border-left\":\"0\",\n # \"padding\": \"0\",\n # \"card-border\": 0,\n \"border-color\": \"white\",\n \n },\n)\n \n\n \n\n##########################################################################\n#Seccion 7. Variables de DERECHOHABIENCIA\n##########################################################################\n\n\ncard_derechohab1 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Derechohabiente del IMSS\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#9cd9e0\"}),\n html.H5(f\"{int(derechoimss_s):,}\",\n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#9cd9e0\"}),\n html.H2([(derechoimss_p),\"%\"],#\"%\"\n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"48rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#9cd9e0\",\n },)\n\ncard_derechohab2 = dbc.Card(\n dbc.CardBody(\n [\n html.H6(\"Derechohabiente del Instituto de Salud para el Bienestar\", \n style={'textAlign': 'left',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"background-color\": \"#0097A7\"}),\n html.H5(f\"{int(derechosegp_s):,}\", \n style={'textAlign': 'left',\n \"height\": \"7px\",\n \"color\": \"white\",\n \"background-color\": \"#0097A7\"}),\n html.H2([(derechosegp_p),\"%\"],#\"64%\", \n style={'textAlign': 'right',\n \"color\": \"white\",\n \"height\": \"7px\",\n \"font-size\": \"38px\",\n 'margin-top': '-32px',\n 'margin-bottom': '30px',\n\n })]), \n style={\"width\": \"48rem\", \n \"border\": \"0\",\n #\"height\": \"10px\",\n \"background-color\": \"#0097A7\",\n },)\n \n#################################### card_v_derechohab\n#\"fas fa-hospital-user\"\n#\"fas fa-procedures\"\ncard_v_derechohab = dbc.Card(\n dbc.CardBody([\n html.P([dbc.Button([html.H1(className=\"fas fa-procedures\",\n style={'textAlign': 'left',\n \"color\":\"#0097A7\",\n \"font-size\": \"80px\"}),\n \" Variables de derechohabiencia\"], \n style={'textAlign': 'left',\"color\":\"#0097A7\",\n \"font-size\": \"30px\",\n })]),\n \n dbc.Card(card_derechohab1),\n html.Br(),\n dbc.Card(card_derechohab2),]),\n style={\"width\": \"50rem\", \n \"border\": \"0\",\n \"fill\" : \"orange\"},)\n \n \n \n \n \n########################################################################\n# A P P \n########################################################################\n\n\n\n# identificadores\nFONT_AWESOMEpro1 = \"{% static 'fontawesome_pro/js/all.min.js' %}\"\nFONT_AWESOMEpro = \"{% static 'fontawesome_pro/css/all.min.css' %}\"\nFONT_AWESOME = \"https://use.fontawesome.com/releases/v5.7.2/css/all.css\"\nserver = flask.Flask(__name__) \napp = dash.Dash(__name__, external_stylesheets=[dbc.themes. \n LUX, \n FONT_AWESOMEpro1,\n FONT_AWESOME, \n FONT_AWESOMEpro], server=server)\n\n\n# make a reuseable navitem for the different examples\nnav_item1 = dbc.NavItem(dbc.NavLink(\"Inicio\", href=\"https://plataformacenso2020.herokuapp.com/\"))\nnav_item2 = dbc.NavItem(dbc.NavLink(\"Entidades\", href=\"#\"))\nnav_item3 = dbc.NavItem(dbc.NavLink(\"Metrópolis\", href=\"#\"))\n\n\n\ndefault = dbc.NavbarSimple(\n children=[nav_item1,nav_item2,nav_item3],\n brand=\"MENU\", style={\"font-size\": \"12px\"},\n brand_href=\"#\",\n sticky=\"top\",\n className=\"mb-12\",\n)\n\nbody = html.Div([\n \n html.Br(),\n \n dbc.Row(\n [ #mapa de la entidad \n \n dbc.Col(dbc.Button(dbc.CardImg(src=\"https://github.com/fdealbam/0entrada/blob/main/application/static/mapas/map_Valle%20de%20M%C3%A9xico.png?raw=true\"),\n style={\"background-color\": \"transparent\"}),\n md={\"size\": 3,},\n style= {\n \n \"margin-top\": \"-32px\", \n \"display\": \"block\", \"position\": \"relative\",\n \"inline\": \"block\",\n \"column-break-inside\": \"avoid\",\n \"margin-left\": \"480px\",\n \"margin-top\": \"-40px\",\n \"margin-bottom\": \"-200px\"\n }),\n\n ], justify= \"start\"), \n \n \n# dbc.Col(dbc.CardImg(src=\"https://github.com/fdealbam/0entrada/blob/main/application/static/logo%20cesopycamara1.PNG?raw=true\"),\n# width=5, md={'size': 3, \"offset\": 6,\n# \"height\": \"5px\"}),\n dbc.Col(html.H4(\"Reporte estadístico de la zona metropolitana\",\n style={'offset' : 0, \"size\": 5,\n \n \"margin-left\": \"140px\",\n \"font-size\": \"12px\",\n \"color\": \"grey\",\n \"height\": \"5px\",\n #'textAlign': 'center',\n #\"font-weight\": 'bold',\n \"font-family\": \"Montserrat\"\n })),\n \n \n dbc.Row(\n [\n dbc.Col(html.H1(noment,\n style={ \"offset\":2, \"size\": 5, \n \"margin-left\": \"162px\",\n \"font-size\": \"35px\",\n \"height\": \"40px\",\n \"color\": \"dark\",\n #'textAlign': 'center',\n #\"font-weight\": 'bold',\n \"font-family\": \"Montserrat\",\n },)),\n ], justify= \"start\"), \n \n #Cintillo 00 \n dbc.Row(\n [\n dbc.Col(html.H6(\" \"), #Fecha de actualización\n width={'size' : \"auto\",\n 'offset' : 1,\n #'textAlign': 'center',\n }), \n ], justify= \"center\"),\n dbc.Row(\n [\n dbc.Col(html.H6(\"Fuente: Censo 2020, INEGI\",\n style={ \"offset\":2, \"size\": 5, \n \"margin-left\": \"162px\",\n \"font-size\": \"10px\",\n \"height\": \"40px\",\n \"color\": \"dark\",\n #'textAlign': 'center',\n #\"font-weight\": 'bold',\n \"font-family\": \"Montserrat\",\n },)),\n ], justify= \"start\"), \n \n html.Br(),\n \n\n \n\n \n ################## VARIABLES DE POBLACION\n dbc.Row([\n dbc.Col(dbc.Card(card), sm={ \"offset\": 1, }),#Variables Vivienda\n dbc.Col(dbc.Card(card2), #población total\n style={#'margin-top': '-540px', #arriba\n 'margin-left': '40px', \n # 'width': '479px',\n # 'height': '100%',\n }, sm={ \"offset\": 1, })\n ], className=\"blockquote\"),\n \n dbc.Row([\n dbc.Col(dbc.Card(card21), #cuadros azules\n style={'margin-top': '-678px', #arriba\n 'margin-left': '467px', \n 'width': '382px',\n 'height': '379px',})\n ]),\n \n dbc.Row([\n dbc.Col(dbc.Card(card22),#cuadros azules\n style={'margin-top': '-593px', #arriba\n 'margin-left': '467px', \n 'width': '382px',\n 'height': '379px',\n })\n ]),\n\n dbc.Row([\n dbc.Col(dbc.Card(card23),#cuadros azules\n style={'margin-top': '-508px', #arriba\n 'margin-left': '467px', \n 'width': '382px',\n 'height': '379px',})\n ]),\n\n dbc.Row([\n dbc.Col(dbc.Card(card24),#cuadros azules\n style={'margin-top': '-423px', #arriba\n 'margin-left': '467px', \n 'width': '382px',\n 'height': '379px',\n })\n ]),\n dbc.Row([\n dbc.Col(dbc.Card(card25),#cuadros azules\n style={'margin-top': '-338px', #arriba\n 'margin-left': '467px', \n 'width': '382px',\n 'height': '379px',\n })\n ]),\n dbc.Row([\n dbc.Col(dbc.Card(card26, outline=False),#cuadros azules\n style={'margin-top': '-293px', #arriba\n 'margin-left': '467px', \n 'width': '382px',\n 'height': '279px',\n })\n ]),\n dbc.Row([\n dbc.Col(dbc.Card(card27),#cuadros azules\n style={'margin-top': '-208px', #arriba\n 'margin-left': '467px', \n 'width': '382px',\n 'height': '19px',\n })\n ]),\n \n ################## VARIABLES DE VIVIENDA\n dbc.Row([\n \n \n \n dbc.Col(dbc.Card(card3, color=\"white\", inverse=True, outline =False ),sm={ \"offset\": 1, }),\n \n ], no_gutters= True, justify= \"start\",\n className=\"blockquote\",\n ),\n\n\n \n ################## VARIABLES DE INTERNET\n\n dbc.Row([\n dbc.Col(dbc.Card(card2p3, color=\"green\"),\n sm={ \"offset\": 1, }),\n \n ], no_gutters= True, justify= \"start\",\n className=\"blockquote\",\n ),\n html.Br(),\n \n\n \n ################## VARIABLES DE MIGRACION\n \n dbc.Row([\n dbc.Col(dbc.Card(card_v_migracion), #cuadros azules\n sm={ 'size': 9.5,\n \"offset\": 1, }),\n ], style={\"border\": \"0px\",\n \"border-color\": \"red\",\n \"border-width\": \"0px\"}, \n no_gutters= True, justify= \"start\",\n className=\"blockquote\"),\n\n \n \n #############################>>>>>>> II <<<<<<<<<#############################\n \n \n \n dbc.Row([\n dbc.Col(dbc.Card(card_economia), sm={ \"offset\": 1, }),#Variables Vivienda\n dbc.Col(dbc.Card(card_economia_discap), #población total\n style={#'margin-top': '-540px', #arriba\n 'margin-left': '15px',\n \"color\":\"#BA68C8\"\n # 'width': '479px',\n # 'height': '100%',\n }, sm={ \"offset\": 1, })\n ], no_gutters= True, justify= \"start\",\n className=\"blockquote\"),\n \n \n\n ################## VARIABLES DE RELIGION \n\n dbc.Row([\n dbc.Col(dbc.Card(card_v_religionAA),\n sm={ \"offset\": 1, }),\n ], no_gutters= True, justify= \"start\",\n className=\"blockquote\",\n ),\n \n \n \n ################## VARIABLES DE EDUCACION \n dbc.Row([\n dbc.Col(dbc.Card(card_v_edu, #color=\"#FBFBFB\", outline=True,\n #inverse=False\n ),\n sm={ \"offset\": 1, }),\n ], no_gutters= True, justify= \"start\",\n className=\"blockquote\",\n ),\n \n \n ################## VARIABLES DE DISCAPACIDAD\n dbc.Row([\n dbc.Col(dbc.Card(card_v_discapacidad, #color=\"#FBFBFB\", outline=True,\n #inverse=False\n ),\n sm={\"offset\": 1, }),\n \n ], no_gutters= True, justify= \"start\",\n className=\"blockquote\",\n ),\n\n ################## VARIABLES DE discapacidad en recuadro\n\n dbc.Row([\n dbc.Col(dbc.Card(recuadrodiscapacidad, color=\"aqua\"),\n sm={ \"offset\": 1, }),\n \n ], no_gutters= True, justify= \"start\",\n className=\"blockquote\",\n ),\n\n html.Br(),\n \n \n\n \n ################## VARIABLES DE DERECHOHABIENCIA\n dbc.Row([\n dbc.Col(dbc.Card(card_v_derechohab, #color=\"#FBFBFB\", outline=True,\n #inverse=False\n ),\n sm={ \"offset\": 1, }),\n ], no_gutters= True, justify= \"start\",\n className=\"blockquote\",),\n \n ################## SECCION 3 (3a pag)__VARIABLES DE HOGARES CENSALES \n dbc.Row([\n dbc.Col(dbc.Card(card_v_hog_cens, #color=\"#FBFBFB\", outline=True,\n #inverse=False\n ),\n sm={ \"offset\": 1, }),\n ], no_gutters= True, justify= \"start\",\n className=\"blockquote\",),\n\n html.Br(),\n html.Br(),\n html.Br(),\n html.Br(),\n html.Br(),\n html.Br(),\n \n# dbc.Row([\n# #https://github.com/fdealbam/CamaraDiputados/blob/b11ef31e8e0f73e1a4a06ce60402563e1bd0122e/application/static/logocamara.jfif\n# dbc.Col(dbc.CardImg(src=\"https://github.com/fdealbam/0entrada/blob/main/application/static/logo%20cesopycamara1.PNG?raw=true\"),\n# width=5, md={'size': 3, \"offset\": 6, }),\n# \n# dbc.Col(html.H6(\" S e c r e t a r í a G e n e r a l,\" \n# \" Secretaría de Servicios Parlamentarios, \"\n# \" México, 2021 \"),\n# width={'size': 5, 'offset': 0}),\n# ], justify=\"start\",),\n# dbc.Row([ \n# dbc.Col(html.H5([dbc.Badge(\"Equipo responsable\", \n# href=\"https://innovation-learning.herokuapp.com/\",\n# )]),\n# width={'size': 3, \"offset\": 4}),\n# ], justify=\"start\",),\n html.Br(),\n html.Br(),\n html.Br(),\n\n \n\n \n html.Br(),\n \n ])\n \n\napp.layout = html.Div(\n [default, body])\n#app.layout = html.Div(children=[html.Img(className='icon')])\n\nif __name__ == '__main__':\n app.run_server(use_reloader = False)\n \n","sub_path":"application/dash.py","file_name":"dash.py","file_ext":"py","file_size_in_byte":95623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"252171501","text":"import globus_sdk\n\nCLIENT_ID = '19ca51f3-41fd-4cd6-90c2-61118d0bafa2'\n\nclient = globus_sdk.NativeAppAuthClient(CLIENT_ID)\nclient.oauth2_start_flow()\n\nauthorize_url = client.oauth2_get_authorize_url()\nprint('Please go to this URL and login: {0}'.format(authorize_url))\n\n# this is to work on Python2 and Python3 -- you can just use raw_input() or\n# input() for your specific version\nget_input = getattr(__builtins__, 'raw_input', input)\nauth_code = get_input(\n 'Please enter the code you get after login here: ').strip()\ntoken_response = client.oauth2_exchange_code_for_tokens(auth_code)\n\nglobus_auth_data = token_response.by_resource_server['auth.globus.org']\nglobus_transfer_data = token_response.by_resource_server['transfer.api.globus.org']\n\n# most specifically, you want these tokens as strings\nAUTH_TOKEN = globus_auth_data['access_token']\nTRANSFER_TOKEN = globus_transfer_data['access_token']\n\n# a GlobusAuthorizer is an auxiliary object we use to wrap the token. In\n# more advanced scenarios, other types of GlobusAuthorizers give us\n# expressive power\nauthorizer = globus_sdk.AccessTokenAuthorizer(TRANSFER_TOKEN)\ntc = globus_sdk.TransferClient(authorizer=authorizer)\n\n# high level interface; provides iterators for list responses\nprint(\"My Endpoints:\")\nfor ep in tc.endpoint_search(filter_scope=\"my-endpoints\"):\n print(\"[{}] {}\".format(ep[\"id\"], ep[\"display_name\"]))\n","sub_path":"roles/ansible-role-file-transfer/files/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"231518336","text":"import inspect\r\nimport sys\r\nimport traceback\r\n\r\n\r\n\r\ndef checkStack():\r\n if len(traceback.format_stack()) > 15:\r\n print(\"STACK TOO BIG\")\r\n sys.exit(0)\r\n\r\n\r\n\r\ndef log(self_, location, message = \"\"):\r\n checkStack()\r\n indent = \" \" * len(traceback.format_stack())\r\n print(\"[{self_.__class__.__name__} / {location}()] {indent}{message}\".format(**locals()))\r\n\r\n\r\n\r\nclass MyObject(object):\r\n @classmethod\r\n def wrapMemberFunctionsWithSuper(class_):\r\n for memberName in class_.__dict__:\r\n member = class_.__dict__[memberName]\r\n\r\n if callable(member):\r\n memberArgs = inspect.getargspec(member).args\r\n \r\n if (len(memberArgs) >= 2) and (memberArgs[0] == 'self') and (memberArgs[1] == 'super'):\r\n class_.wrapMemberFunctionWithSuper(memberName)\r\n\r\n @classmethod\r\n def wrapMemberFunctionWithSuper(class_, funcNameToWrap):\r\n classFuncToWrap = getattr(class_, funcNameToWrap)\r\n setattr(class_, funcNameToWrap, lambda self, *args: classFuncToWrap(self, lambda: super(class_, self), *args))\r\n\r\n\r\n\r\ndef wrapMemberFunctionsWithSuper(class_):\r\n class_.wrapMemberFunctionsWithSuper()\r\n return class_\r\n\r\n\r\n\r\n@wrapMemberFunctionsWithSuper\r\nclass C1(MyObject):\r\n def __init__(self):\r\n log(self, \"C1.__init__\")\r\n\r\n def func(self, x):\r\n log(self, \"C1.func\", x)\r\n\r\n def func2(self, x):\r\n log(self, \"C1.func2\", x)\r\n\r\n\r\n\r\n@wrapMemberFunctionsWithSuper\r\nclass C2(C1):\r\n superClass = C1\r\n\r\n def __init__(self, super):\r\n log(self, \"C2.__init__\")\r\n super().__init__()\r\n\r\n def func(self, super, x):\r\n log(self, \"C2.func\", x)\r\n super().func(x)\r\n\r\n def func2(self, super, x):\r\n log(self, \"C2.func2\", x)\r\n super().func2(x * 10)\r\n\r\n\r\n\r\n@wrapMemberFunctionsWithSuper\r\nclass C3(C2):\r\n def __init__(self, super):\r\n log(self, \"C3.__init__\")\r\n super().__init__()\r\n\r\n def func(self, super, x):\r\n log(self, \"C3.func\", x)\r\n super().func(x)\r\n\r\n def func2(self, super, x):\r\n log(self, \"C3.func2\", x)\r\n super().func2(x * 10)\r\n\r\n\r\n\r\nlog(None, \"Create c1\")\r\nc1 = C1()\r\nlog(None, \"Create c2\")\r\nc2 = C2()\r\nlog(None, \"Create c3\")\r\nc3 = C3()\r\n\r\nlog(None, \"Call c1.func(1)\")\r\nc1.func(1)\r\nlog(None, \"Call c2.func(2)\")\r\nc2.func(2)\r\nlog(None, \"Call c3.func(3)\")\r\nc3.func(3)\r\n\r\n\r\nlog(None, \"Call c1.func2(11)\")\r\nc1.func2(11)\r\nlog(None, \"Call c2.func2(12)\")\r\nc2.func2(12)\r\nlog(None, \"Call c3.func2(13)\")\r\nc3.func2(13)\r\n","sub_path":"superProxy/superProxy.potential-solution-1.py","file_name":"superProxy.potential-solution-1.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"592489224","text":"# -*- coding: utf-8 -*-\n\"\"\"\n PUSH API for scrapi prototype\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport json\nimport logging\nfrom base64 import b64encode\n\nfrom scrapi import tasks\nfrom scrapi import events\nfrom scrapi import settings\nfrom scrapi.util import timestamp\nfrom scrapi.linter.document import RawDocument, NormalizedDocument\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\nTUTORIAL = {\n \"title\": \"string representing title of the resource\",\n \"contributors\": \"a list of dictionaries containing prefix, middle, family, suffix, and ORCID of contributors.\",\n \"id\": \"a dictionary of unique IDs given to the resource based on the particular publication we’re accessing. Should include an entry for a URL that links right to the original resource, a DOI, and a service specific ID\",\n \"url\": \"A url pointing to the resources\\' real location\",\n \"doi\": \"The digital object identifier of the resource, if it has one\",\n \"serviceID\": \"A service specific identifier for the resource\",\n \"description\": \"an abstract or general description of the resource\",\n \"tags\": \"a list of tags or keywords identified in the resource itself, normalized to be all lower case\",\n \"source\": \"string identifying where the resource came from\",\n \"timestamp\": \"string indicating when the resource was accessed by scrAPI using the format YYYY-MM-DD h : m : s in iso format\",\n \"dateCreated\": \"string indicating when the resource was first created or published using the format YYYY-MM-DD in iso format\",\n \"dateUpdated\": \"string indicating when the resource was last updated in the home repository using the format YYYY-MM-DD in iso format\",\n}\n\n\ndef process_api_input(events):\n ''' Takes a list of documents as raw input from API route\n returns a list of linted normalzied documents\n '''\n\n # this is a list of scrapi rawDocuments\n raw_documents = harvest(events)\n\n harvested_docs, timestamps = task_harvest(raw_documents)\n\n storage = {'is_push': True}\n\n for raw in harvested_docs:\n raw['timestamps'] = timestamps\n tasks.process_raw.delay(raw, storage=storage)\n normalized = task_normalize(raw)\n\n tasks.process_normalized.delay(normalized, raw, storage=storage)\n\n\ndef harvest(event_list):\n ''' takes a list of input from the api route,\n returns a list of raw documents\n '''\n\n return [\n RawDocument({\n 'filetype': 'json',\n 'doc': json.dumps(event),\n 'source': event['source'],\n 'docID': event['id']['serviceID']\n })\n for event in event_list\n ]\n\n\ndef task_harvest(raw_documents):\n ''' takes in the raw_doc_list and emulates the\n normal scrapi harvest task, adding appropriate\n timestamps and returning a tuple consisting\n of the raw doc list and the dict of timestamps\n '''\n\n source = raw_documents[0]['source']\n\n timestamps = {\n 'harvestTaskCreated': timestamp(),\n 'harvestStarted': timestamp(),\n 'harvestFinished': timestamp()\n }\n\n # TODO - handle harvester_name\n logger.info('API Input from \"{}\" has finished harvesting'.format(source))\n events.dispatch(events.HARVESTER_RUN, events.COMPLETED,\n harvester=source, number=len(raw_documents))\n\n return raw_documents, timestamps\n\n\ndef task_normalize(raw_doc):\n ''' emulates the normalize function in the celery\n tasks, adds timestamps to the raw doc and returns\n a single normalized document with the correct\n timestamps and raw field with link to archive\n '''\n\n raw_doc['timestamps']['normalizeStarted'] = timestamp()\n\n normalized = normalize(raw_doc)\n\n normalized['timestamps'] = raw_doc['timestamps']\n normalized['timestamps']['normalizeFinished'] = timestamp()\n\n normalized['dateCollected'] = normalized['timestamps']['harvestFinished']\n\n normalized['raw'] = '{url}/{archive}{source}/{doc_id}/{harvestFinished}/raw.json'.format(\n url=settings.SCRAPI_URL,\n archive=settings.ARCHIVE_DIRECTORY,\n source=normalized['source'],\n doc_id=b64encode(raw_doc['docID']),\n harvestFinished=normalized['timestamps']['harvestFinished']\n )\n\n return normalized\n\n\ndef normalize(raw_doc):\n normalized_dict = json.loads(raw_doc['doc'])\n source = normalized_dict['source']\n events.dispatch(events.PROCESSING, events.CREATED,\n harvester=source, docID=raw_doc['docID'])\n\n return NormalizedDocument(normalized_dict)\n","sub_path":"website/process_metadata.py","file_name":"process_metadata.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"412816346","text":"from shutil import copyfile\nimport os\n\ni = 400\npath = '/home/stian/Documents/remote/2019-06-12/'\ndataSet = '2019-06-12'\ndataRound = 'r2'\n\nsourceDir = os.path.join(path,dataRound)\ndestDir = os.path.join(path,dataRound,'annotations')\n# destDir = '/home/stian/Desktop/testVid'\n\nif not os.path.isdir(destDir):\n os.mkdir(destDir)\n\nwhile i <=6000:\n if i < 1000:\n imgFile = dataRound + '_0' + str(i) + '.tif'\n else:\n imgFile = dataRound + '_' + str(i) + '.tif' \n sourcePath = os.path.join(sourceDir,imgFile)\n destPath = os.path.join(destDir,dataSet + '_' +imgFile)\n if os.path.isfile(sourcePath):\n copyfile(sourcePath,destPath)\n i = i + 300\n\n","sub_path":"ImageAnnotation/copyImages.py","file_name":"copyImages.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"490215543","text":"import scrapy\r\n\r\nclass IntroSpider(scrapy.Spider):\r\n name = 'introduccion_spider'\r\n\r\n urls = [\r\n 'http://books.toscrape.com/catalogue/category/books/travel_2/index.html'\r\n ]\r\n\r\n def start_requests(self):\r\n for url in self.urls:\r\n yield scrapy.Request(url=url)\r\n \r\n def parse(self, response):\r\n etiqueta_contenedora = response.css(\r\n 'article.product_pod'\r\n )\r\n titulos = etiqueta_contenedora.css(\r\n 'h3 > a::text'\r\n ).extract()\r\n imagenes = etiqueta_contenedora.css(\r\n 'div.image_container > a > img::attr(src)'\r\n ).extract()\r\n precio = etiqueta_contenedora.css(\r\n 'div.product_price > p.price_color::text'\r\n ).extract()\r\n stock = etiqueta_contenedora.css(\r\n 'div.product_price > p.instock.availability::text'\r\n ).extract()\r\n lista_precios=[]\r\n for p in precio:\r\n p = p[1:]\r\n lista_precios.append(p)\r\n [float(i) for i in lista_precios]\r\n\r\n stock_final = [b.replace('\\n', '').replace(' ', '') for b in stock]\r\n\r\n stars = etiqueta_contenedora.css('.star-rating').xpath(\"@class\").extract()\r\n stars_final= [b.replace('star-rating ', '') for b in stars] \r\n print(titulos)\r\n print(imagenes)\r\n print(lista_precios)\r\n print(stock_final)\r\n print(stars_final)\r\n\r\n# scrapy crawl nombre_arania\r\n","sub_path":"04-Scrapy/03-intro-spider/arania_basica/arania_basica/spiders/arania-ejemplo.py","file_name":"arania-ejemplo.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"519414506","text":"from math import*\nimport numpy as np\nfrom Vector3 import Vector3\n\nclass vortexRing:\n\t\"\"\"docstring for panel\"\"\"\n\tdef __init__(self, p1,p2,p3,p4):\n\t\tself.p1 = p1\n\t\tself.p2 = p2\n\t\tself.p3 = p3\n\t\tself.p4 = p4\n\t\tself.gamma = []\n\t\tself.gammaij = []\n\n\t\tself.area = self.Area()\n\t\tself.normal = self.Normal()\n\t\tself.center = self.collocation()\n\n\tdef dl(self):\n\t\treturn self.p4 - self.p1\n\n\tdef forceActingPoint(self):\n\t\treturn (self.p1 + self.p4) * 0.5\n\n\tdef dy(self):\n\t\treturn (self.p4.y - self.p1.y)\n\n\tdef Normal(self):\n\t\treturn ((self.p2-self.p4).crossProduct(self.p3-self.p1)).Normalized()\n\n\tdef collocation(self):\n\t\treturn (self.p1 + self.p2 + self.p3 +self.p4)*0.25\n\n\tdef Area(self):\n\t\tb = self.p3-self.p1\n\t\tf = self.p2-self.p1\n\t\te = self.p4-self.p1\n\t\ts1 = f.crossProduct(b)\n\t\ts2 = b.crossProduct(e)\n\t\treturn 0.5 * (s1.Magnitude() + s2.Magnitude())\n\n\tdef influence(self,collocationPoint,Sym=True,boundInfluence=True):\n\t\tSYM = 0\n\t\tu = Vector3(0.0,0.0,0.0)\n\t\trcut = 1.0e-12\n\t\t\n\t\tif (Sym): SYM=1\n\t\tfor sym in range(0,SYM+1):\n\t\t\tx = collocationPoint.x\n\t\t\ty = collocationPoint.y\n\t\t\tif (sym): y *= -1.0\n\t\t\tz = collocationPoint.z\n\n\t\t\tif (boundInfluence):\n\t\t\t\tedges = [0,1,2,3]\n\t\t\telse:\n\t\t\t\tedges = [1,3]\n\n\t\t\tfor i in edges:\n\t\t\t\tif (i == 0):\n\t\t\t\t\tx1 = self.p1.x\n\t\t\t\t\ty1 = self.p1.y\n\t\t\t\t\tz1 = self.p1.z\n\t\t\t\t\tx2 = self.p4.x\n\t\t\t\t\ty2 = self.p4.y\n\t\t\t\t\tz2 = self.p4.z\n\t\t\t\telif (i == 1):\n\t\t\t\t\tx1 = self.p4.x \n\t\t\t\t\tx2 = self.p3.x\n\t\t\t\t\ty1 = self.p4.y \n\t\t\t\t\ty2 = self.p3.y\n\t\t\t\t\tz1 = self.p4.z \n\t\t\t\t\tz2 = self.p3.z\n\t\t\t\telif (i == 2):\n\t\t\t\t\tx1 = self.p3.x \n\t\t\t\t\tx2 = self.p2.x\n\t\t\t\t\ty1 = self.p3.y \n\t\t\t\t\ty2 = self.p2.y\n\t\t\t\t\tz1 = self.p3.z \n\t\t\t\t\tz2 = self.p2.z\n\t\t\t\telif (i == 3):\n\t\t\t\t\tx1 = self.p2.x \n\t\t\t\t\tx2 = self.p1.x\n\t\t\t\t\ty1 = self.p2.y \n\t\t\t\t\ty2 = self.p1.y\n\t\t\t\t\tz1 = self.p2.z \n\t\t\t\t\tz2 = self.p1.z\n\t\t\t\tr1r2x = (y-y1)*(z-z2) - (z-z1)*(y-y2)\n\t\t\t\tr1r2y = -((x-x1)*(z-z2) - (z-z1)*(x-x2))\n\t\t\t\tr1r2z = (x-x1)*(y-y2) - (y-y1)*(x-x2)\n\n\t\t\t\tr1 = sqrt((x-x1)**2+(y-y1)**2+(z-z1)**2)\n\t\t\t\tr2 = sqrt((x-x2)**2+(y-y2)**2+(z-z2)**2)\n\t\t\t\tr0 = Vector3(x2-x1,y2-y1,z2-z1)\n\n\t\t\t\tr1 = sqrt((x-x1)**2+(y-y1)**2+(z-z1)**2)\n\t\t\t\tr2 = sqrt((x-x2)**2+(y-y2)**2+(z-z2)**2)\n\t\t\t\tr0 = Vector3(x2-x1,y2-y1,z2-z1)\n\n\t\t # //calculation of (r1 x r2)^2\n\t\t\t\tsquare = ((r1r2x)**2+(r1r2y)**2+(r1r2z)**2)\n\n\t\t\t\tif ((r1 15 :\n\t#\t\tprint \"circle\"\n\t#\t\tcv2.drawContours(img, [cnt], 0, (0, 255, 255), -1)\n\t#(_, cnts, _) = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) \n\n\t# Makes the first contour the largest\n\t#contours = sorted(cnts, key = cv2.contourArea, reverse = True)\n\n\t# If no contours are detected, then don't try to process them or you'll get an error:\n\t#if len(contours) > 0:\n\t#\tcnt1 = contours[0]\n\t#\tarea = cv2.contourArea(cnt1)\n\t\t\n\t\t# Draw a minimum area rectangle around the contour\n\t#\trect1 = np.int32(cv2.boxPoints(cv2.minAreaRect(cnt1)))\n\t\t\n\t\t# Draw the contour over image\n\t#\tcv2.drawContours(img, [rect1], -1, (255, 0, 0), 2)\n\t#\tM1 = cv2.moments(cnt1)\n\t#\tcx1 = int(M1['m10']/M1['m00'])\n\t#\tcy1 = int(M1['m01']/M1['m00'])\n\t\t\n\t\t#draw center of cube on image in red\n\t#\tcv2.circle(img,(cx1,cy1), 50, (0,0,255))\n\n\t\t#display center of image on img in white\n\t#\tcentX = int(width/2)\n\t#\tcentY = int(height/2)\n\n\t\t#error to be sent over network tables\n#\t\terror = centX - cx1\n#\t\tif area < 200:\n# error = 0 \n#\t\tcv2.circle(img, (centX, centY),30, (255,255,255))\n\n\tcv2.imshow('frame', img)\n\tcv2.imshow('original', default)\n\tcv2.imshow('image', res)\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"593159078","text":"#!/usr/bin/env python\nimport rospy\n\n# Data structure here: http://docs.ros.org/api/sensor_msgs/html/msg/LaserScan.html\nfrom sensor_msgs.msg import LaserScan\nfrom geometry_msgs.msg import Twist\n\n\nclass ReadScan:\n\n range_value = 1 # anything to start with\n\n def query_range(self):\n return self.range_value\n\n def scan_callback(self, msg):\n import math\n self.range_value = min(msg.ranges)\n # If the object is not within the sensor's working range, range_value will be NaN; so let's set it to 0\n if math.isnan(self.range_value):\n self.range_value =1\n rospy.loginfo(self.range_value)\n \nrs = ReadScan()\n# The queue_size=1 argument tells rospy to only buffer a single outbound message. In case the node sending the messages is transmitting at a higher rate than the receiving node(s) can receive them, rospy will simply drop any messages beyond the queue_size.\ncmd_vel_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\nscan_sub=rospy.Subscriber('scan',LaserScan, rs.scan_callback)\n\nrospy.init_node('wander')\n\n# you now subscribe to the topic, this is similar to 'rostopic echo /scan' but now the messages are channelled to 'scan_callback' rather than the screen\n# The message constructors set all fields to zero. Therefore, the stop_twist message tells a robot to stop, since all of its velocity subcomponents are zero.\nstop_twist = Twist()\ngo_twist = Twist()\n\n\n# The x component of the linear velocity in a Twist message is, by convention, aligned in the direction the robot is facing, so this line means drive straight ahead at 0.5 meters per second.\ngo_twist.linear.x = 0.5\n\nstop_twist.angular.z=5\nstop_twist.linear.x=0\n\ndriving_forward = False\n\n# Checkout how time works in ROS -- http://wiki.ros.org/rospy/Overview/Time\nchange_time = rospy.Time.now()\nrate = rospy.Rate(5)\n\nwhile not rospy.is_shutdown():\n \n if driving_forward:\n \n cmd_vel_pub.publish(go_twist)\n# We need to continually publish a stream of velocity command messages, since most mobile base drivers will time out and stop the robot if they do not receive at least several messages per second.\n if rs.query_range() < 0.8:\n print(\"Hello\")\n cmd_vel_pub.publish(stop_twist)\n driving_forward=False\n\n \n# This branch checks the system time and toggles it periodically.\n if change_time < rospy.Time.now():\n if not driving_forward:\n cmd_vel_pub.publish(stop_twist)\n \n rospy.loginfo(\"Toggling Behaviour\")\n driving_forward=not driving_forward\n change_time = rospy.Time.now() + rospy.Duration(5)\n \n# Without this call to rospy.sleep() the code would still run, but it would send far too many messages, and take up an entire CPU core!\n rate.sleep()\n \n # spin() keeps your node from exiting until the node is shut down. This is thread independent and does not affect the execution of the callbacks\n","sub_path":"robot_ws/src/myturtlebot/src/wander.py","file_name":"wander.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"166142623","text":"# -*- coding: utf-8 -*-\n\nfrom osv import fields, osv\nimport pdb\n\n# class tipo_maquina(osv.osv):\n# _name = 'maquipal.tipo.maquina'\n# _description = 'Tipos de maquinas'\n# _columns = {\n# 'name': fields.char('Nombre', size=64),\n# }\n\n# tipo_maquina()\n\nclass product_product(osv.osv):\n def onchange_cliente_id(self, cr, uid, ids, c_id):\n \"\"\"This function returns value of default_code based on cliente_id\n @param self: the object pointer\n @param cr: the current row, from the database cursor\n @param uid: the current user's ID for security checks\n @param ids: list of case IDs\n @param c_id Id of cliente\n \"\"\"\n if not c_id:\n return {'value': {}}\n\n cliente = self.pool.get('res.partner').browse(cr, uid, c_id)\n #pdb.set_trace()\n return {'value': {'default_code': cliente.name}}\n\n _name = 'product.product'\n _description = 'Maquina'\n _inherit = 'product.product'\n _columns = {\n 'marca': fields.char('Marca', size=64, select=True),\n 'modelo': fields.char('Modelo', size=64, required=True, select=True),\n 'serie': fields.char('Serie', size=64, required=True, select=True),\n 'cliente_id': fields.many2one('res.partner', 'Cliente', required=True, select=True),\n 'mod_motor': fields.char('Mod. Motor', size=64),\n 'serie_motor': fields.char('Serie Motor', size=64),\n 'mod_convertidor': fields.char('Mod. Convertidor', size=64),\n 'serie_convertidor': fields.char('Serie Convertidor', size=64),\n 'f_combustible': fields.char('F. Combustible', size=64),\n 'f_aceite': fields.char('F. Aceite', size=64),\n 'f_aire_ext': fields.char('F. Aire Ext', size=64),\n 'f_aire_int': fields.char('F. Aire Int', size=64),\n 'f_hidraulico': fields.char('F. Hidraulico', size=64),\n 'f_convertidor': fields.char('F. Convertidor', size=64),\n 't_dientes': fields.char('T. Dientes', size=64),\n 'correa_alter': fields.char('Correa Alternador', size=64),\n 'correa_venti': fields.char('Correa Ventilador', size=64),\n 'alternador': fields.char('Alternador', size=64),\n 'm_arranque': fields.char('M. Arranque', size=64),\n 'ruedas': fields.char('Ruedas', size=64),\n 'mastil': fields.char('Mastil', size=64),\n 'bateria': fields.char('Bateria', size=64),\n 'comentarios': fields.text('Comentarios'),\n #'tipo': fields.many2one('maquipal.tipo.maquina', 'Tipo', select=True),\n }\n\n def crear_nota_desde_maquina(self, cr, uid, ids, context=None):\n \"\"\"\n @param self: The object pointer\n @param cr: the current row, from the database cursor,\n @param uid: the current user’s ID for security checks,\n @param context: A standard dictionary for contextual values\n \"\"\"\n value = {}\n data = context and context.get('active_ids', []) or []\n nota_obj = self.pool.get('maquipal.nota')\n maquina_obj = self.pool.get('product.product')\n\n data_obj = self.pool.get('ir.model.data')\n \n #select the view\n id2 = data_obj._get_id(cr, uid, 'maquipal', 'view_nota_form')\n id3 = data_obj._get_id(cr, uid, 'maquipal', 'view_nota_tree') \n if id2:\n id2 = data_obj.browse(cr, uid, id2, context=context).res_id\n if id3:\n id3 = data_obj.browse(cr, uid, id3, context=context).res_id \n\n #pdb.set_trace()\n\n for this in self.browse(cr, uid, ids, context=context):\n #pdb.set_trace()\n \n if this.cliente_id.riesgo == False:\n campo_riesgo = ''\n else:\n campo_riesgo = this.cliente_id.riesgo\n if this.cliente_id.comment == False:\n campo_comment = ''\n else:\n campo_comment = this.cliente_id.comment\n\n campo_comentarios = 'Riesgo: '+campo_riesgo+'\\n\\n'+campo_comment\n \n new_nota = nota_obj.create(cr, uid, {\n 'cliente_id': this.cliente_id.id,\n 'phone': this.cliente_id.phone,\n 'mobile': this.cliente_id.mobile,\n 'contacto': this.cliente_id.address[0].name,\n 'comentarios': campo_comentarios,\n 'maquina': this.id,\n 'modelo': this.modelo,\n 'serie': this.serie,\n }, context=context)\n\n\n value = {\n 'name': 'Nueva Nota',\n 'view_type': 'form',\n 'view_mode': 'form,tree',\n 'res_model': 'maquipal.nota',\n 'res_id' : new_nota,\n 'views': [(id2, 'form'), (id3, 'tree'), (False, 'calendar')],\n 'target': 'current',\n 'type': 'ir.actions.act_window',\n }\n\n return value\n\n # def default_get(self, cr, uid, fields, context=None):\n # \"\"\"\n # This function gets default values\n # @param self: The object pointer\n # @param cr: the current row, from the database cursor\n # @param uid: the current user's ID for security checks\n # @param fields: List of fields for default value\n # @param context: A standard dictionary for contextual values\n\n # @return: default values of fields\n # \"\"\"\n # maquina_obj = self.pool.get('product.product')\n # data = context and context.get('active_ids', []) or []\n # res = super(maquipal_nota_desde_maquina, self).default_get(cr, uid, fields, context=context)\n # for maquina in maquina_obj.browse(cr, uid, data, context=context):\n # if 'cliente_id' in fields:\n # res.update({'cliente_id': maquina.cliente_id.name})\n # if 'phone' in fields:\n # res.update({'phone': maquina.cliente_id.phone})\n # if 'contacto' in fields:\n # res.update({'contacto': maquina.cliente_id.address[0].name})\n # if 'maquina' in fields:\n # res.update({'maquina': maquina.name})\n # if 'modelo' in fields:\n # res.update({'modelo': maquina.modelo})\n # if 'serie' in fields:\n # res.update({'serie': maquina.serie})\n \n # return res\n\nproduct_product()\n\n","sub_path":"maquipal_maquina.py","file_name":"maquipal_maquina.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"12579092","text":"\nimport glob\nimport pandas as pd\nimport numpy as np\n\nimport os\nos.chdir('/Users/evanbiederstedt/Downloads/annoOld_files')\n\n# set glob subdirectory via cell batch\nnormalB_cellbatch = glob.glob(\"RRBS_NormalBCD19pCD27pcell67_88*.anno\")\n\n\nnewdf1 = pd.DataFrame()\nfor filename in normalB_cellbatch:\n df = pd.read_table(filename)\n df['filename'] = str(filename)\n df = df.drop(['chr', 'start', 'strand', 'thisMeth', 'thisUnmeth', 'avgWeightedEnt', 'CpGEntropy',\n 'avgReadCpGs', 'tss', 'tssDistance', 'genes', 'exons', 'introns', 'promoter', 'cgi',\n 'geneDensity', 'ctcfUpstream', 'ctcfDownstream','ctcfDensity', 'geneDistalRegulatoryModules',\n 'vistaEnhancers', '3PrimeUTR', 'ctcfUpDistance', 'ctcfDownDistance','3PrimeUTRDistance',\n '5PrimeUTR', '5PrimeUTRDistance', 'firstExon','geneDistalRegulatoryModulesK562',\n 'geneDistalRegulatoryModulesK562Distance', 'hypoInHues64','hypoInHues64Distance'], axis=1)\n\n df['total_reads'] = df[[\"methReadCount\", \"unmethReadCount\", \"mixedReadCount\"]].sum(axis=1)\n \n df['totreads_genesDistance'] = df[[\"methReadCount\", \"unmethReadCount\", \"mixedReadCount\"]].sum(axis=1).where(df['genesDistance']<0, 0)\n df['totreads_exonsDistance'] = df[[\"methReadCount\", \"unmethReadCount\", \"mixedReadCount\"]].sum(axis=1).where(df['exonsDistance']<0, 0)\n df['totreads_intronsDistance'] = df[[\"methReadCount\", \"unmethReadCount\", \"mixedReadCount\"]].sum(axis=1).where(df['intronsDistance']<0, 0)\n df['totreads_promoterDistance'] = df[[\"methReadCount\", \"unmethReadCount\", \"mixedReadCount\"]].sum(axis=1).where(df['promoterDistance']<0, 0)\n df['totreads_cgiDistance'] = df[[\"methReadCount\", \"unmethReadCount\", \"mixedReadCount\"]].sum(axis=1).where(df['cgiDistance']<0, 0)\n df['totreads_ctcfDistance'] = df[[\"methReadCount\", \"unmethReadCount\", \"mixedReadCount\"]].sum(axis=1).where(df['ctcfDistance']<0, 0)\n df['totreads_geneDistalRegulatoryModulesDistance'] = df[[\"methReadCount\", \"unmethReadCount\", \"mixedReadCount\"]].sum(axis=1).where(df['geneDistalRegulatoryModulesDistance']<0, 0)\n df['totreads_firstExonDistance'] = df[[\"methReadCount\", \"unmethReadCount\", \"mixedReadCount\"]].sum(axis=1).where(df['firstExonDistance']<0, 0)\n \n \n df['mixedReads_genesDistance'] = np.where(df['genesDistance']<0, df['mixedReadCount'], 0)\n df['mixedReads_exonsDistance'] = np.where(df['exonsDistance']<0, df['mixedReadCount'], 0)\n df['mixedReads_intronsDistance'] = np.where(df['intronsDistance']<0, df['mixedReadCount'], 0)\n df['mixedReads_promoterDistance'] = np.where(df['promoterDistance']<0, df['mixedReadCount'], 0)\n df['mixedReads_cgiDistance'] = np.where(df['cgiDistance']<0, df['mixedReadCount'], 0)\n df['mixedReads_ctcfDistance'] = np.where(df['ctcfDistance']<0, df['mixedReadCount'], 0)\n df['mixedReads_geneDistalRegulatoryModulesDistance'] = np.where(df['geneDistalRegulatoryModulesDistance'] <0, df['mixedReadCount'], 0)\n df['mixedReads_vistaEnhancersDistance'] = np.where(df['vistaEnhancersDistance'] <0, df['mixedReadCount'], 0)\n df['mixedReads_firstExonDistance'] = np.where(df['firstExonDistance'] <0, df['mixedReadCount'], 0)\n \n \n df['fullMethReads_genesDistance'] = np.where(df['genesDistance']<0, df['methReadCount'], 0)\n df['fullMethReads_exonsDistance'] = np.where(df['exonsDistance']<0, df['methReadCount'], 0)\n df['fullMethReads_intronsDistance'] = np.where(df['intronsDistance']<0, df['methReadCount'], 0)\n df['fullMethReads_promoterDistance'] = np.where(df['promoterDistance']<0, df['methReadCount'], 0)\n df['fullMethReads_cgiDistance'] = np.where(df['cgiDistance']<0, df['methReadCount'], 0)\n df['fullMethReads_ctcfDistance'] = np.where(df['ctcfDistance']<0, df['methReadCount'], 0)\n df['fullMethReads_geneDistalRegulatoryModulesDistance'] = np.where(df['geneDistalRegulatoryModulesDistance'] <0, df['methReadCount'], 0)\n df['fullMethReads_vistaEnhancersDistance'] = np.where(df['vistaEnhancersDistance'] <0, df['methReadCount'], 0)\n df['fullMethReads_firstExonDistance'] = np.where(df['firstExonDistance'] <0, df['methReadCount'], 0)\n \n df = df.sum()\n df['filename'] = str(filename)\n \n df['PDR_total'] = df['mixedReadCount']/df['total_reads']\n df['PDR_GenesBody'] = df['mixedReads_genesDistance']/df['totreads_genesDistance']\n df['PDR_Exons'] = df['mixedReads_exonsDistance']/df['totreads_exonsDistance']\n df['PDR_Introns'] = df['mixedReads_intronsDistance']/df['totreads_intronsDistance']\n df['PDR_Promoters'] = df['mixedReads_promoterDistance']/df['totreads_promoterDistance']\n df['PDR_CGIslands'] = df['mixedReads_cgiDistance']/df['totreads_cgiDistance']\n df['PDR_CTCF'] = df['mixedReads_ctcfDistance']/df['totreads_ctcfDistance']\n df['PDR_Enhancer'] = df['mixedReads_geneDistalRegulatoryModulesDistance']/df['totreads_geneDistalRegulatoryModulesDistance']\n \n df['percent_totalMeth'] = df['methReadCount']/df['total_reads']\n df['totalMeth_GenesBody'] = df['fullMethReads_genesDistance']/df['totreads_genesDistance']\n df['totalMeth_Exons'] = df['fullMethReads_exonsDistance']/df['totreads_exonsDistance']\n df['totalMeth_Introns'] = df['fullMethReads_intronsDistance']/df['totreads_intronsDistance']\n df['totalMeth_Promoters'] = df['fullMethReads_promoterDistance']/df['totreads_promoterDistance']\n df['totalMeth_CGIslands'] = df['fullMethReads_cgiDistance']/df['totreads_cgiDistance']\n df['totalMeth_CTCF'] = df['fullMethReads_ctcfDistance']/df['totreads_ctcfDistance']\n df['totalMeth_Enhancer'] = df['fullMethReads_geneDistalRegulatoryModulesDistance']/df['totreads_geneDistalRegulatoryModulesDistance']\n newdf1 = newdf1.append(df, ignore_index=True)\n\n\n\n# export as .csv\nnewdf1.to_csv('PDR_genomicRegions_RRBS_NormalBCD19pCD27pcell67_88.csv')\n\n################################################\n################################################\n#\n# NOTE: We need to recalculate for annotations\n#\n# Dataframe headers versus labels in Landau et al (2014)\n#\n# 'tssDistance' // always seems to be a zero value---why?\n# 'genesDistance' = 'Genes Body'\n# 'exonsDistance' = 'Exons'\n# 'intronsDistance' = 'Introns'\n# 'promoterDistance' = 'Promoters'\n# 'cgiDistance' = 'CG Islands'\n# 'ctcfDistance' = 'CTCF binding site density'\n# 'ctcfUpDistance'\n# 'ctcfDownDistance'\n# 'geneDistalRegulatoryModulesDistance' = 'Enhancer'\n# 'vistaEnhancersDistance' = // ignore\n# 'firstExonDistance'\n#\n###############\n# QUESTIONS\n###############\n#\n# Question (1) Calculating GCI shores and shelves is very tricky, as one must know the exact GCI boundaries\n# e.g.\n# if GCI distance is -1, this is included in GCIshore up [0 to 2000]\n# if GCI distance is -2001, this is included in GCIshelf up [2000 to 4000]\n#\n# One cannot do this:\n# df['GCIshoreUp'] = df['cgiDistance'] + 2000\n# df['GCIshoreDown'] = df['cgiDistance'] - 2000\n# df['GCIshelfUp'] = df['cgiDistance'] + 4000\n# df['GCIshelfDown'] = df['cgiDistance'] - 4000\n# as you are using 'cgiDistance' to be both the left boundary and the right boundary\n#\n# Question (2) How to calculate \"Intergenic\"?\n#\n# Question (3) What's up with 'tssDistance'?\n#\n\n","sub_path":"scripts/PDR_GenomicRegions_pcell67_88.py","file_name":"PDR_GenomicRegions_pcell67_88.py","file_ext":"py","file_size_in_byte":7701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"530775843","text":"from django.urls import path\nfrom users.api import (\n register_user,\n users,\n user,\n update_user,\n delete_user,\n)\n\napp_name = \"users\"\n\nurlpatterns = [\n path('register/', register_user, name=\"register\"),\n path('', users, name=\"users\"),\n path('/', user, name=\"user\"),\n path('update//', update_user, name=\"update\"),\n path('delete//', delete_user, name=\"delete\"),\n]","sub_path":"queue_system/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"652246164","text":"import random\n\ndef GetTaunt():\n TauntList = ['I\\'m Mario and I\\'m a going to win!', 'Now We are playing with power',\n 'up up down down left right left right B A ... hmmmm, that did nothing?',\n 'All Your Base Are Belong To Us', 'YOU SPOONY BARD!!!','Hey! Listen!', 'Do a barrel roll',\n 'You have died of dysentery', 'I am Error', 'The President has been kidnapped by ninjas',\n 'Snake? Snake?! Snaaaaake!!', 'Stop Poking me!', 'Sorry, I am dead',\n 'Don\\'t you have a kingdom to run?', 'Hit the any key, which one is the any key?!?!','My life for Auir']\n return random.choice(TauntList)","sub_path":"app/Stephen.py","file_name":"Stephen.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"152089400","text":"from .gameMode import GameMode\nfrom .env import *\nfrom .coin import Coin\nimport pygame\nimport random\nimport time\n\n\nclass CoinPlayingMode(GameMode):\n def __init__(self, user_num):\n super(CoinPlayingMode, self).__init__(user_num)\n\n def create_coins(self):\n if time.time() - self.creat_coin_time > 1.6:\n coin = Coin(random.choice(self.coin_lanes), 0)\n self.coin_lanes.remove(coin.rect.centerx)\n self.all_sprites.add(coin)\n self.coins.add(coin)\n self.creat_coin_time = time.time()\n if len(self.coin_lanes) == 0:\n self.coin_lanes = [35, 105, 175, 245, 315, 385, 455, 525, 595]\n else:\n pass\n\n def collide_coins(self, car):\n hits = pygame.sprite.spritecollide(car, self.coins, True)\n for hit in hits:\n car.coin_num += 1\n\n def is_create_coin(self):\n if self.maxVel >= 12:\n self.is_crear_coin = True\n return self.is_crear_coin\n\n def is_car_arrive_end(self, car):\n if car.distance > end_line:\n user_coins = []\n for user in self.user_cars:\n user_coins.append(user.coin_num)\n for user in self.user_cars:\n if user.coin_num == min(user_coins):\n user_coins.remove(user.coin_num)\n user.state = False\n self.detect_car_state(user)\n\n def draw_user_imformation(self):\n for car in self.user_cars:\n self.__draw_information(self.screen, \"Player\" + str(car.car_no + 1) +\n \"(\" + USER_COLOR[car.car_no] +\")\", 17, 715, (car.car_no) * 120 + 10)\n self.__draw_information(self.screen, \"vel : \" + str(round(car.velocity, 2)), 17, 715,\n (car.car_no) * 120 + 40)\n self.__draw_information(self.screen, \"distance : \" + str(abs(round(car.distance, 2))), 17, 715,\n (car.car_no) * 120 + 70)\n self.__draw_information(self.screen, \"coins : \" + str(car.coin_num), 17, 715,\n (car.car_no) * 120 + 100)\n","sub_path":"game/coinMode.py","file_name":"coinMode.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"632285218","text":"\n#Source : https://leetcode.com/problems/ransom-note/\n#Author : Yuan Wang\n#Date : 2018-06-23\n'''\n********************************************************************************** \n*Given an arbitrary ransom note string and another string containing letters from \n*all the magazines, write a function that will return true if the ransom note can \n*be constructed from the magazines ; otherwise, it will return false.\n*\n*Each letter in the magazine string can only be used once in your ransom note.\n*\n*Note:\n*You may assume that both strings contain only lowercase letters.\n*\n*canConstruct(\"a\", \"b\") -> false\n*canConstruct(\"aa\", \"ab\") -> false\n*canConstruct(\"aa\", \"aab\") -> true\n**********************************************************************************/\n'''\n#Self solution A,Time complexity:O(n), Space Complexity:O(n)\ndef canConstructA(ransomNote, magazine):\n\t\"\"\"\n\t:type ransomNote: str\n\t:type magazine: str\n\t:rtype: bool\n\t\"\"\"\n\tmagazine=dict(collections.Counter(magazine))\n\transomNote=dict(collections.Counter(ransomNote))\n\tfor i in ransomNote:\n\t\ttry:\n\t\t\tif ransomNote[i] > magazine[i]:\n\t\t\t\treturn False\n\t\texcept:\n\t\t\treturn False\n\treturn True\n\n#Self solution B,Time complexity:O(n), Space Complexity:O(n)\ndef canConstructB(ransomNote, magazine):\n\t\"\"\"\n\t:type ransomNote: str\n\t:type magazine: str\n\t:rtype: bool\n\t\"\"\"\n\tmagazine=dict(collections.Counter(magazine))\n\tfor i in ransomNote:\n\t\tif i in magazine:\n\t\t\tif magazine[i] > 0:\n\t\t\t\tmagazine[i]-=1\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse:\n\t \t\treturn False\n\treturn True\n\n#Other suliton using set\ndef canConstruct(ransomNote, magazine):\n\t\"\"\"\n\t:type ransomNote: str\n\t:type magazine: str\n\t:rtype: bool\n\t\"\"\"\n\tfor i in set(ransomNote):\n\t\tif ransomNote.count(i) > magazine.count(i):\n\t\t\treturn False\n\treturn True\n\nransomNote=\"aa\"\nmagazine=\"aab\"\nprint(canConstruct(ransomNote,magazine))\n\n\n","sub_path":"String/canConstruct.py","file_name":"canConstruct.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"187097267","text":"import sys\nimport os\nimport random\n\n#Fonctions\n##########\n\ndef effaceEcran():\n \"\"\"\n Efface l'écran de la console\n \"\"\"\n if sys.platform.startswith(\"win\"):\n #Si le systéme est Windows\n os.system(\"cls\")\n else:\n #Si le systéme est Linux ou OS X\n os.system(\"clear\")\n\ndef afficheLabyrinthe(lab, perso, posPerso, tresor):\n \"\"\"\n Affichage d'un labyrinthe\n \n lab : Variable contenant le labyrinthe\n perso : caractère représentant le personnage\n posPerso : liste contenant la position du personnage [ligne, colonne]\n tresor: Caractère représantant le trésort.\n\n pas de valeur de retour\n \"\"\"\n nLigne = 0\n for ligne in lab:\n for i in range(1, 4):\n ligne = ligne.replace(str(i), tresor)\n if posPerso[1] == nLigne:\n print(ligne[0:posPerso[0]] + perso + ligne[posPerso[0] + 1:])\n else:\n print(ligne)\n nLigne += 1\n\ndef verifDeplacement(lab, posCol, posLigne, data):\n \"\"\"\n Indique si le déplacement est autorisé ou pas.\n \n lab: labyrinthe\n posCol: position du personnage sur les colonnes.\n posLigne: position du personnage sur les lignes.\n\n Valeurs de retour:\n None: déplacement interdit.\n [col, ligne]: déplacement autorisé sur la case indiquée par la liste.\n \"\"\"\n #Calcul de la taille du labyrinthe\n nCols = len(lab[0])\n nLignes = len(lab)\n #Teste si le déplacement conduit le personnage en dehors de l'aire de jeu.\n if posLigne < 0 or posCol < 0 or \\\n posLigne > (nLignes - 1) or posCol > (nCols - 1):\n return None\n elif lab[posLigne][posCol] == \"1\" or lab[posLigne][posCol] == \"2\" or lab[posLigne][posCol] == \"3\":\n #Découverte d'un trésor\n decouverteTresor(lab[posLigne][posCol], data)\n #On recrée la ligne sans le coffre\n lab[posLigne] = lab[posLigne][:posCol] + \" \" + lab[posLigne][posCol + 1 :] \n return [posCol, posLigne]\n elif lab[posLigne][posCol] == \"$\":\n #Combat avec un ennemi\n combat(data)\n #On recrée la ligne l'ennemi\n lab[posLigne] = lab[posLigne][:posCol] + \" \" + lab[posLigne][posCol + 1 :] \n return [posCol, posLigne]\n elif lab[posLigne][posCol] == \"0\":\n return [-1, -1]\n elif lab[posLigne][posCol] != \" \":\n return None\n else:\n return [posCol, posLigne]\n\ndef choixJoueur(lab, posPerso, data):\n \"\"\"\n Demande au joueur de saisir son déplacement et vérifie s'il est possible.\n Si ce n'est pas le cas on affiche un message, sinon modife la position\n du personnage dans la liste posPerso.\n\n lab: labyrinthe\n posPerso: liste contenant la position du personnage [colonne, ligne]\n\n Pas de valeur de retour\n \"\"\"\n choix = input(\"Votre déplacement : [(h)aut/(b)as/(d)roite/(g)auche/(q)uitter]? \")\n while choix != \"h\" and choix != \"b\" and choix != \"g\" and choix != \"d\" and choix != \"q\":\n print(\"Vueillez rentrer une valeur correct! (h, b, g, d, q)\")\n choix = input(\"Votre déplacement : [(h)aut/(b)as/(d)roite/(g)auche/(q)uitter]? \")\n if choix == \"h\":\n dep = verifDeplacement(lab, posPerso[0], posPerso[1] -1, data)\n elif choix == \"b\":\n dep = verifDeplacement(lab, posPerso[0], posPerso[1] +1, data)\n elif choix == \"d\":\n dep = verifDeplacement(lab, posPerso[0] +1, posPerso[1], data)\n elif choix == \"g\":\n dep = verifDeplacement(lab, posPerso[0] -1, posPerso[1], data)\n elif choix == \"q\":\n exit(0)\n\n if dep == None:\n print(\"Impossible de se déplacer!\")\n input(\"Appuyer sur une touche pour continuer.\")\n else:\n posPerso[0] = dep[0]\n posPerso[1] = dep[1]\n\ndef jeu(level, data, perso, posPerso, tresor):\n \"\"\"\n Boucle principale du jeu. Affiche le labyrinthe dans ses différents états\n après les déplacements du joueur.\n\n level: labyrinthe\n data: dictionnaire contenant\n -level : le numéro du niveau\n -po : le nombre de pièce d'or\n -pc : le nombre de points de vie\n perso: caractère représentant le personnage\n posPerso: position du personnage dans le labyrinthe\n \"\"\"\n while True:\n effaceEcran()\n afficheLabyrinthe(level, perso, posPerso, tresor)\n barreScore(data)\n if data[\"pv\"] <= 0:\n effacerEcran()\n print(\"GAME OVER\")\n input()\n exit(0)\n choixJoueur(level, posPerso, data)\n if posPerso == [-1,-1]:\n print(\"Vous avez passé le niveaux!\")\n input(\"Appuyer sur une touche pour continuer.\")\n break\n\ndef chargeLabyrinthe(nom):\n \"\"\"\n Charge le labyrinthe à partir d'un fichier nom.txt\n\n nom : nom du fichier contenant le labyrinthe (sans l'extention)\n\n Valeur de retour : une liste contenant les données du labyrinthe.\n \"\"\"\n try:\n fich = open(\"levels/\" + nom + \".txt\", \"r\")\n data = fich.readlines()\n fich.close()\n except IOError:\n print(\"Impossible d'ouvrir le fichier \" + nom + \"!\")\n input(\"Vueillez appuyer sur une touche.\")\n exit(1)\n\n for i in range(len(data)): ##Suprime les caractère invisible\n data[i] = data[i].strip()\n\n return data\n\ndef barreScore(data):\n \"\"\"\n Barre de score affichant les données du jeu\n\n data: dictionnaire de données de la barre score\n\n Pas de valeur de retour\n \"\"\"\n print(\"Level : {:3d} PO: {:4d} PV: {:3d} \"\\\n .format(data[\"level\"], data[\"or\"], data[\"pv\"]))\n\ndef decouverteTresor(categorie, data):\n \"\"\"\n Incrémente le nombre de pièces d'or du joueur en fonction du trésor\n\n catégorie: type de trésor\n -1 : entre 1 et 5 po\n -2 : entre 5 et 10 po\n -3 : entre 0 et 25 po\n\n data : contient les données du joueur (pv, or, lvl)\n \"\"\"\n if categorie == \"1\":\n data[\"or\"] = data[\"or\"] + random.randint(1, 5)\n elif categorie == \"2\":\n data[\"or\"] = data[\"or\"] + random.randint(5, 10)\n else:\n data[\"or\"] = data[\"or\"] + random.randint(0, 25)\ndef combat(data):\n \"\"\"\n Determine le nombre de pv perdus lors d'un combat\n\n data : données du joueur (pv, or, lvl)\n \"\"\"\n de = random.randint(1, 10)\n if de == 1:\n data[\"pv\"] = data[\"pv\"] - random.randint(5, 10)\n elif de >= 2 and de <= 4:\n data[\"pv\"] = data[\"pv\"] - random.randint(1, 5)\n","sub_path":"lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":6587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"496443025","text":"# Copyright 2014 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\nclass ChangeType(object):\n ADD = 'add'\n DELETE = 'delete'\n MODIFY = 'modify'\n COPY = 'copy'\n RENAME = 'rename'\n\n\ndef IsKnownChangeType(change_type):\n return change_type in [\n ChangeType.ADD, ChangeType.DELETE, ChangeType.MODIFY, ChangeType.COPY,\n ChangeType.RENAME\n ]\n","sub_path":"appengine/findit/libs/gitiles/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"343132666","text":"# exports each selected object into its own file\n# -*- coding: utf-8 -*-\n\nimport math\nimport mathutils\nimport bpy\nimport os\nimport json\n\nprint(os.getcwd())\n\nimport debug\n#debug.start_debug()\n\nXZ_Y = \"XZ_Y\"\nX_ZY = \"X_ZY\"\nXYZ = \"XYZ\"\n_XY_Z = \"_XY_Z\"\n\ndef flip_axes (a, dir=XYZ):\n \"\"\"\n :function to swap vectors:\n \"\"\"\n\n if dir == XZ_Y:\n a = (a[0], a[2], -a[1])\n elif dir == X_ZY:\n a = (a[0], -a[2], a[1])\n elif dir == _XY_Z:\n a = (-a[0], -a[1], a[2])\n\n return (a[0], a[1], a[2])\n\n# export to blend file location\nbasedir = os.path.dirname(bpy.data.filepath)\n\nif not basedir:\n raise Exception(\"Blend file is not saved\")\n\nobj = bpy.context.scene.objects.active\n\nbpy.ops.object.mode_set(mode='OBJECT')\nmesh = obj.to_mesh(bpy.context.scene, True, 'RENDER')\n\n# 三角形化\n\nbackup = obj.data\nhide = obj.hide \nobj.data = mesh\nobj.select = True\nbpy.context.scene.objects.active = obj\nbpy.ops.object.modifier_add(type='TRIANGULATE')\nbpy.ops.object.modifier_apply(apply_as='DATA',modifier='Triangulate')\n\nbpy.ops.object.modifier_add(type='EDGE_SPLIT')\nbpy.context.object.modifiers['EdgeSplit'].use_edge_angle = False\nbpy.context.object.modifiers['EdgeSplit'].use_edge_sharp = True\nbpy.ops.object.modifier_apply(apply_as='DATA', modifier='EdgeSplit')\n\nbpy.ops.object.mode_set(mode='EDIT')\nbpy.ops.mesh.select_all(action='SELECT')\nbpy.ops.mesh.normals_make_consistent()\n#bpy.ops.mesh.set_normals_from_faces()\nbpy.ops.object.editmode_toggle()\n\nobj.data = backup\n# obj.select = False\n\nrot = mathutils.Matrix.Rotation(-math.pi, 4, 'Z')\nmesh.transform(rot * obj.matrix_world)\n\nmesh.update(calc_tessface=True)\n#mesh.calc_normals()\n#bpy.ops.mesh.set_normals_from_faces()\n\nmesh.calc_tessface()\nscale_ = 1.0\nmesh.transform(mathutils.Matrix.Scale(scale_, 4))\n\n#print(len(mesh.vertices)*3,len(mesh.uv_layers[0].data),len(mesh.tessfaces)*3)\n\n\n# mesh.update(calc_tessface=True)\n\n# debug.start_debug()\n\nobjects = {}\n\ndata = []\n\nfloat_size = 4\nobjects['position_size'] = 3\nobjects['texcoord_size'] = 2\nobjects['stride']= (objects['position_size'] + objects['texcoord_size']) * float_size\n\n\nfor (pos,uv) in zip(mesh.vertices,mesh.uv_layers[0].data):\n uv = uv.uv\n pos = pos.co\n data.extend(pos)\n data.extend(uv)\n\nprint(data)\n\nobjects['data'] = data\n\nindices = []\nindices_offset = 0\nobjects['indices'] = indices\ndrawinfos = []\nobjects['drawInfos'] = drawinfos\n\nfor i,material_ in enumerate(mesh.materials):\n drawinfo = {}\n material = {}\n drawinfo['material'] = material\n\n material['u_diffuse'] = list(material_.diffuse_color) + [1.0]\n material['u_specular'] = list(material_.specular_color) + [1.0]\n material['u_specularFactor'] = material_.specular_intensity\n material['u_shininess'] = material_.specular_hardness\n count = 0\n # 頂点\n for face in [f for f in mesh.tessfaces if f.material_index == i]:\n indices.extend(face.vertices)\n count += 3\n\n drawinfo['count'] = count\n drawinfo['offset'] = indices_offset\n indices_offset += count * 2\n drawinfos.append(drawinfo)\n\n\n\n \n\n# # 頂点情報を保存\n# for i,material in enumerate(mesh.materials):\n# arrays = {}\n# position = []\n# indices = []\n# vertex_indexes = {}\n# texcoord = []\n# normals = []\n# object_ = {}\n# uniforms = {}\n\n# # uniform\n# uniforms['u_diffuse'] = material.diffuse_color + [1.0]\n# uniforms['u_specular'] = material.specular_color + [1.0]\n# uniforms['u_specularFactor'] = material.specular_intensity\n# uniforms['u_shininess'] = material.specular_hardness\n# object_['uniforms'] = uniforms\n# count = 0\n \n# # 頂点\n# for fi,face in [(fi,f) for fi,f in enumerate(mesh.tessfaces) if f.material_index == i]:\n\n# # vert_count = len(face.vertices)\n# print(i,face.material_index,fi)\n\n# #if vert_count is not 3:\n# # print(vert_count)\n# #msg = \"Non-triangulated face detected\"\n# #raise Exception(msg)\n# for vidx,vertex_index in enumerate(face.vertices):\n# if vertex_index in vertex_indexes:\n# idx = vertex_indexes[vertex_index]\n# indices.append(vertex_indexes[vertex_index])\n# # 点法線の計算\n# normal = face.normal\n# normal2 = (normals[idx * 3:(idx * 3 + 3)])\n# normal = [normal[0] + normals[idx * 3],normal[1] + normals[idx * 3 + 1],normal[2] + normals[idx * 3 + 2]]\n# # 正規化\n# norm = math.sqrt(normal[0]**2 + normal[1]**2 + normal[2]**2)\n# normal = [n/norm for n in normal]\n# normals[idx * 3] = normal[0]\n# normals[idx * 3 + 1] = normal[1]\n# normals[idx * 3 + 2] = normal[2]\n# else:\n# vertex = mesh.vertices[vertex_index]\n# vector = flip_axes(vertex.co)\n# position.extend(vector)\n# indices.append(count)\n# vertex_indexes[vertex_index] = count\n# count = count + 1\n# normal = face.normal # mesh.vertices[vertex_index].normal\n# # vector = flip_axes(normal) if face.use_smooth else flip_axes(face.normal)\n# vector = flip_axes(normal)\n# normals.extend(vector)\n# # テクスチャーUV \n# uv = mesh.uv_layers[0].data[fi * 3 + vidx].uv\n# texcoord.extend((uv[0],uv[1]))\n# #for uv in uvs[fi * 3 : (fi + 3) * 3] :\n# # texcoord.extend((uv.uv[0],uv.uv[1]))\n\n \n# '''\n# for uv_data in [ u for u in ranmesh.uv_layers[0].data if u.material_index == i] :\n# uv_tuple = (uv_data.uv[0], uv_data.uv[1])\n# texcoord.extend(uv_tuple)\n# '''\n# arrays['position'] = position\n# arrays['normal'] = normals\n# arrays['texcoord'] = texcoord\n# arrays['indices'] = indices\n\n# object_['arrays'] = arrays\n# objects.append(object_)\n\n# JSONファイルとして保存\nname = bpy.path.clean_name(obj.name)\npath = os.path.join(basedir,name)\n\nwith open(path + '.json','w') as f:\n json.dump(objects,f,ensure_ascii=False, indent=2, sort_keys=True, separators=(',', ': '));\n #json.dump(objects,f);\n\nprint(\"written:\", path + \".json\")\n\n\n","sub_path":"contents/test/twgl/blender/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":6304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"259200256","text":"''''\nThis program was developed by Dr. Mi Zhang and Konglin Zhu at MSU, Spring 2018, aiming to recognize human activities by\nubiquitous wireless signals, such as Wi-fi, Cellular Radios, etc..\n\nCross validation, filter number reduction and feature map plotting was implemented in this program.\n'''\n\n\nfrom __future__ import print_function\nfrom sklearn.model_selection import KFold\nfrom matplotlib.font_manager import FontProperties\nfrom sklearn.externals import joblib\n# from sklearn.preprocessing import StandardScaler\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pylab as plt\n\n\ndef load_data(load_dir):\n # Load data\n tra_labels = joblib.load(load_dir+'tra_labels.pkl')\n tra_features = joblib.load(load_dir+'tra_features.pkl')\n test_labels = joblib.load(load_dir+'test_labels.pkl')\n test_features = joblib.load(load_dir+'test_features.pkl')\n\n tra_features = tra_features - np.mean(tra_features, axis=0)\n test_features = test_features - np.mean(test_features, axis=0)\n\n n_tra, n_test = get_num_ratio(tra_labels, test_labels)\n return tra_labels, tra_features, test_labels, test_features,n_tra, n_test\n\n# return the sizes of split sets\ndef get_num_ratio(tra_labels, val_labels):\n shape = np.shape(tra_labels)\n n_tra = list(shape)\n n_tra = n_tra[0]\n print('n_tra= %d' % n_tra)\n\n shape = np.shape(val_labels)\n n_val = list(shape)\n n_val = n_val[0]\n print('n_val= %d' % n_val)\n return n_tra, n_val\n\n\n# yield one batch and wait for the next iteration in the loop\ndef gen_data(features, labels,batch_size,data_size) :\n batch_num = data_size/batch_size\n batch_num = np.int64(batch_num)\n for i in range(batch_num):\n x = features[i*batch_size:i*batch_size+batch_size,:,:]\n # reduce 3D dimensions to 2D, so we do not need y = y.reshape(500,3)\n y = labels[i*batch_size:i*batch_size+batch_size]\n y = np.reshape(y,(batch_size))\n yield (x, y)\n\n\ndef save_plot(save_dir,epoch_train_loss, epoch_train_acc, epoch_val_loss, epoch_val_acc, epoch_test_loss,\n epoch_test_acc,fold):\n lists = sorted(epoch_train_loss.items())\n x, lyt = zip(*lists) # unpack a list of pairs into two tuples\n # type(lyt) = tuple\n # (len,) array was dumped\n joblib.dump(np.asarray(lyt), save_dir+'train_loss_KF'+str(fold)+'.pkl')\n\n lists = sorted(epoch_train_acc.items())\n x, ayt = zip(*lists)\n joblib.dump(np.asarray(ayt), save_dir+'train_acc_KF'+str(fold)+'.pkl')\n\n lists = sorted(epoch_val_loss.items())\n x, lyv = zip(*lists)\n joblib.dump(np.asarray(lyv), save_dir+'val_loss_KF'+str(fold)+'.pkl')\n\n lists = sorted(epoch_val_acc.items())\n x, ayv = zip(*lists)\n joblib.dump(np.asarray(ayv), save_dir+'val_acc_KF'+str(fold)+'.pkl')\n\n lists = sorted(epoch_test_acc.items())\n x, ays = zip(*lists)\n joblib.dump(np.asarray(ays), save_dir+'test_acc_KF' + str(fold) + '.pkl')\n # joblib.dump(y1, 'cnn2_train.pkl')\n\n lists = sorted(epoch_test_loss.items())\n x, lys = zip(*lists)\n joblib.dump(np.asarray(lys), save_dir+'test_loss_KF' + str(fold) + '.pkl')\n\n plt.figure()\n fontP = FontProperties()\n fontP.set_size('small')\n plt.plot(x, lyt, label='train')\n plt.plot(x, lyv, label='evaluate')\n plt.plot(x, lys, label='test')\n # plt.plot(x1, y1, label='evaluate ')\n plt.title('loss_KF'+str(fold))\n # plt.legend(prop=fontP, loc='upper right')\n plt.xlabel('step')\n plt.ylabel('loss')\n plt.grid()\n plt.legend(prop=fontP, loc='upper right')\n plt.savefig(save_dir+'loss_KF'+str(fold)+'.png')\n plt.close()\n\n plt.figure()\n fontP = FontProperties()\n fontP.set_size('small')\n plt.plot(x, ayt, label='train')\n plt.plot(x, ayv, label='evaluate')\n plt.plot(x, ays, label='test')\n plt.title('acc_KF'+str(fold))\n plt.legend(prop=fontP, loc='lower right')\n plt.xlabel('step')\n plt.ylabel('acc')\n plt.grid()\n plt.savefig(save_dir+'acc_KF'+str(fold)+'.png')\n plt.close()\n\n\ndef create_network(batch_size, height, width):\n #with tf.name_scope('input'):\n x = tf.placeholder(tf.float32, shape = (batch_size,height,width),name='x-imput') #feed in 90X500 tensor\n y = tf.placeholder(tf.int64, shape=(batch_size), name='y-input') #feed in 500x3 tensor\n is_training = tf.placeholder(tf.bool)\n \"\"\"Model function for CNN.\"\"\"\n # Input Layer\n input_layer = tf.reshape(x, [-1, height, width, 1]) # [batch_size=500, image_width, image_height, channels]\n #with tf.name_scope('conv1'):\n # Convolutional Layer #1\n conv1 = tf.layers.conv2d(\n inputs=input_layer,\n filters=16,\n kernel_size=[5, 5],\n padding=\"same\",\n activation=tf.nn.relu)\n #with tf.name_scope('pool1'):\n #Pooling Layer #1\n pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=[3,2],strides=(3,2))\n\n\n #with tf.name_scope('pool2_flat'):\n # Output Layer:Dense Layer\n pool2_flat = tf.layers.flatten(pool1)\n dense1 = tf.layers.dense(inputs=pool2_flat, units=128, activation=tf.nn.relu)\n dropout = tf.layers.dropout(inputs=dense1, rate=0.5, training=is_training)\n\n\n logits = tf.layers.dense(inputs=dropout, units=2)\n softmax_linear = tf.nn.softmax(logits, name='softmax_linear')\n onehot_labels = tf.one_hot(indices=tf.cast(y, tf.int32), depth=2)\n\n\n # logits = tf.layers.dense(inputs=dropout, units=1)\n # prediction = tf.nn.sigmoid(logits)\n # y_reshape = tf.reshape(y,[-1,1])\n # loss = tf.losses.sigmoid_cross_entropy(y_reshape, prediction)\n\n\n # Define loss and optimizer\n loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=softmax_linear)\n # loss = tf.reduce_mean(tf.sqrt(tf.reduce_sum(tf.squared_difference(predicts,y), axis=1)))\n\n\n # # Loss function with L2 Regularization with beta=0.01\n reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n reg_constant = 0.01 # Choose an appropriate one.\n loss = loss + reg_constant * sum(reg_losses)\n\n train_op = tf.train.RMSPropOptimizer(learning_rate=0.0001).minimize(loss)\n acc = evaluation(softmax_linear, y)\n # acc = tf.reduce_mean( tf.cast(tf.equal( tf.to_int64(tf.round(prediction)), y), tf.int64))\n\n\n # feature_maps,label= feature_maps_plot(pool1,y, height=30, width=250)\n # create a summary for our cost and accuracy\n tf.summary.scalar(\"loss\", loss)\n tf.summary.scalar(\"accuracy\", acc)\n\n # merge all summaries into a single \"operation\" which we can execute in a session\n summary_op = tf.summary.merge_all()\n return {'x':x,'y':y,'loss':loss,'train_op':train_op,'is_training':is_training,\n 'acc':acc, 'summary_op':summary_op, 'softmax_linear':softmax_linear} #, 'prediction':prediction, , 'feature_maps':feature_maps, 'label':label\n\n\ndef evaluation(logits, labels):\n with tf.variable_scope('accuracy') as scope:\n correct = tf.nn.in_top_k(logits, labels, 1)\n correct = tf.cast(correct, tf.float16)\n accuracy = tf.reduce_mean(correct)\n #tf.summary.scalar(scope.name + '/accuracy', accuracy)\n return accuracy\n\n\ndef feature_maps_plot(feature_maps,y,height, width,channels=2,cy=2,cx=1):\n feature_maps = tf.slice(feature_maps, (0, 0, 0, 0), (1, -1, -1, -1)) # V[0,...]\n feature_maps = tf.reshape(feature_maps, (height, width, channels))\n\n # add a couple of pixels of zero padding around the image\n height += 4\n width += 4\n feature_maps = tf.image.resize_image_with_crop_or_pad(feature_maps, height, width)\n\n # reshape so that instead of 32 channels you have 4x8 channels, lets call them cy=4 and cx=8\n feature_maps = tf.reshape(feature_maps, (height, width, cy, cx))\n\n # To rearrange the order\n feature_maps = tf.transpose(feature_maps, (2, 0, 3, 1))\n\n # image_summary needs 4d input\n # feature_maps = tf.reshape(1, feature_maps, (cy * height, cx * width, 1))\n feature_maps = tf.reshape(feature_maps, (cy * height, cx * width))\n\n #tf.summary.image()\n return feature_maps,y[0]\n\n\ndef run_train(session, save_dir,tra_x,tra_y,val_x,val_y, test_labels,test_features, max_step, batch_size,\n n_tra,n_val, n_test,logs_train_dir,fold,height, width):\n # temprary containers for results\n train_loss = {}\n train_acc = {}\n epoch_train_loss = {}\n epoch_train_acc = {}\n\n val_loss = {}\n val_acc = {}\n epoch_val_loss = {}\n epoch_val_acc = {}\n\n test_loss = {}\n test_acc = {}\n epoch_test_loss = {}\n epoch_test_acc = {}\n\n ops = create_network(batch_size, height, width)\n # session = tf.Session()\n # Initializing the variables\n init = tf.global_variables_initializer()\n session.run(init)\n # writer = tf.summary.FileWriter(logs_train_dir, graph=tf.get_default_graph())\n # Launch the graph\n for epoch in range(max_step):\n # training until reach max steps\n i = 0 # Batch Step Reset\n ii=np.random.randint(np.int64(n_tra/batch_size), size=1)\n for batch_x, batch_y in gen_data(tra_x, tra_y, batch_size, n_tra):\n _, loss, prediction, acc = session.run([ops['train_op'], ops['loss'],\n ops['softmax_linear'], ops['acc']],\n feed_dict={ops['x']: batch_x, ops['y']: batch_y,\n ops['is_training']: True})\n # to plot feature map\n # if i == ii:\n # print(\"Batch ID\")\n # print(i)\n # plt.figure()\n # plt.imshow(feature_maps, cmap='gray')\n # # plt.show()\n # plt.imsave('feature_maps_epoch' + str(epoch) +'_label'+str(label)+ '.png',feature_maps,cmap='gray')\n # plt.close()\n\n # if i % 50 == 0:\n # print(\"\\nfold= %d epoch= #%d step=%d loss=%f acc=%f\" % (fold,epoch, i, loss, acc))\n\n # acc = np.mean(np.round(prediction)==batch_y)\n # loss returns scaler\n # print(np.round(prediction).flatten())\n # np.set_printoptions(precision=3)\n # print(prediction.flatten())\n train_loss.update({i: loss}) # to store for batch step\n train_acc.update({i: acc})\n i += 1\n # summary_str = session.run(ops['summary_op'],\n # feed_dict={ops['x']: batch_x, ops['y']: batch_y, ops['is_training']: True})\n # writer.add_summary(summary_str, epoch)\n # average acc for batches across one global step\n a = []\n b = []\n for batch_step, loss in train_loss.items():\n a.append(loss)\n for batch_step, acc in train_acc.items():\n b.append(acc)\n epoch_loss = np.mean(a)\n epoch_acc = np.mean(b)\n epoch_train_loss.update({epoch: epoch_loss})\n epoch_train_acc.update({epoch: epoch_acc})\n print(\"fold=\"+str(fold)+\" epoch: \" + str(epoch+1) + \", train loss = \" + str(\n epoch_loss) + \", train acc = \" + str(epoch_acc))\n\n # evaluating\n if epoch % 1 == 0 or (epoch + 1) == max_step:\n j = 0\n for batch_x, batch_y in gen_data(val_x, val_y, batch_size, n_val):\n # sess.run(ops['train_op'], feed_dict={ops['x']: batch_x, ops['y']: batch_y, ops['kp']: 0.8})\n # Calculate batch loss and accuracy\n loss, acc = session.run([ops['loss'], ops['acc']],\n feed_dict={ops['x']: batch_x, ops['y']: batch_y, ops['is_training']: True})\n val_loss.update({j: loss})\n val_acc.update({j: acc})\n j += 1\n # average acc for batches across one global step\n a = []\n b = []\n for batch_step, loss in val_loss.items():\n a.append(loss)\n for batch_step, acc in val_acc.items():\n b.append(acc)\n epoch_loss = np.mean(a)\n epoch_acc = np.mean(b)\n epoch_val_loss.update({epoch: epoch_loss})\n epoch_val_acc.update({epoch: epoch_acc})\n print(\"fold=\"+str(fold)+\" epoch: \" + str(epoch+1) + \", val loss = \" + str(\n epoch_loss) + \", val acc = \" + str(epoch_acc))\n\n # testing...\n if epoch % 1 == 0 or (epoch + 1) == max_step:\n j = 0\n for batch_x, batch_y in gen_data(test_features, test_labels, batch_size, n_test):\n loss, acc = session.run([ops['loss'], ops['acc']],\n feed_dict={ops['x']: batch_x, ops['y']: batch_y, ops['is_training']: True})\n test_loss.update({j: loss})\n test_acc.update({j: acc})\n j += 1\n a = []\n b = []\n for batch_step, loss in test_loss.items():\n a.append(loss)\n for batch_step, acc in test_acc.items():\n b.append(acc)\n epoch_loss = np.mean(a)\n epoch_acc = np.mean(b)\n epoch_test_loss.update({epoch: epoch_loss})\n epoch_test_acc.update({epoch: epoch_acc})\n print(\"fold=\"+str(fold)+\" epoch: \" + str(epoch+1) + \", test loss = \" + str(\n epoch_loss) + \", test acc = \" + str(epoch_acc))\n print('#################################################################')\n '''\n temp ={'epoch_loss':epoch_loss,'epoch_acc':epoch_acc}\n f = 'test_kf_results'+str(i)+'.txt'\n joblib.dump(temp,f)\n print(\"\\nepoch: \" + str(epoch) + \", test loss = \" + str(\n epoch_loss) + \", test acc = \" + str(epoch_acc))\n '''\n # session.close()\n save_plot(save_dir,epoch_train_loss, epoch_train_acc, epoch_val_loss, epoch_val_acc, epoch_test_loss,epoch_test_acc, fold)\n\ndef cross_validate(session, load_dir, save_dir,max_step, batch_size, logs_train_dir,height, width,split_size=5 ):\n print('loading data')\n tra_labels, tra_features, test_labels, test_features, n_train, n_test = load_data(load_dir)\n print(\"\\nStart training\")\n\n results = []\n kf = KFold(n_splits=split_size,shuffle=False)\n fold=1\n for train_idx, val_idx in kf.split(tra_features, tra_labels):\n print(type(train_idx))\n tra_x = tra_features[train_idx]\n tra_y = tra_labels[train_idx]\n print(tra_x.shape)\n val_x = tra_features[val_idx]\n val_y = tra_labels[val_idx]\n n_tra, n_val = get_num_ratio(tra_y, val_y)\n print('#'+str(fold)+' fold is training...')\n run_train(session, save_dir, tra_x,tra_y,val_x,val_y,\n test_labels,test_features, max_step, batch_size,\n n_tra,n_val, n_test,logs_train_dir,fold,height, width)\n # results.append(session.run(accuracy, feed_dict={x: val_x, y: val_y}))\n fold+=1\n return results\n\n\ndef main():\n max_step = 3200\n batch_size = 50\n\n split_size = 5\n height = 90\n width = 500\n logs_train_dir = '/home/eb1228lab/Documents/DNN_Projects/Contactless_Sensing/logs'\n load_dir = '/home/eb1228lab/Documents/DNN_Projects/Contactless_Sensing/data/data_split_pkl/'\n save_dir = '/home/eb1228lab/Documents/DNN_Projects/Contactless_Sensing/results/cnn1layers/11655/3200/'\n\n with tf.Session() as session:\n cross_validate(session,load_dir,save_dir,max_step, batch_size, logs_train_dir,height, width,split_size=split_size)\n # print(\"Cross-validation result: %s\" % result)\n # print(\"Test accuracy: %f\" % session.run(accuracy, feed_dict={x: test_x, y: test_y}))\n # # run_train(session, init, train_x, train_y, batch_size, logs_train_dir)\n print('cross validation with 5 folds is done!')\n\n\nif __name__ == '__main__':\n main()","sub_path":"Code/CNN/cnn_1layer.py","file_name":"cnn_1layer.py","file_ext":"py","file_size_in_byte":16286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"299493485","text":"from django.conf.urls import url\n\nfrom server.views import Info, Status, Setpwd, Ssl, Cipher, Hub, Tcp\n\nurlpatterns = [\n url('^info$', Info),\n url('^status$', Status),\n url('^setpwd$', Setpwd),\n url('^ssl$', Ssl),\n url('^cipher$', Cipher),\n url('^hub$', Hub),\n url('^tcp$', Tcp),\n]\n","sub_path":"apps/server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"544309191","text":"\"\"\"ProtoTorch loss functions.\"\"\"\n\nimport torch\n\n\ndef _get_dp_dm(distances, targets, plabels):\n matcher = torch.eq(targets.unsqueeze(dim=1), plabels)\n if plabels.ndim == 2:\n # if the labels are one-hot vectors\n nclasses = targets.size()[1]\n matcher = torch.eq(torch.sum(matcher, dim=-1), nclasses)\n not_matcher = torch.bitwise_not(matcher)\n\n inf = torch.full_like(distances, fill_value=float('inf'))\n d_matching = torch.where(matcher, distances, inf)\n d_unmatching = torch.where(not_matcher, distances, inf)\n dp = torch.min(d_matching, dim=1, keepdim=True).values\n dm = torch.min(d_unmatching, dim=1, keepdim=True).values\n return dp, dm\n\n\ndef glvq_loss(distances, target_labels, prototype_labels):\n \"\"\"GLVQ loss function with support for one-hot labels.\"\"\"\n dp, dm = _get_dp_dm(distances, target_labels, prototype_labels)\n mu = (dp - dm) / (dp + dm)\n return mu\n","sub_path":"prototorch/functions/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"412885781","text":"import os, sys, json\nimport subprocess\nimport logging\nimport logging.handlers\nimport requests\nfrom chump import Application as Pushover\nfrom pymongo import MongoClient\n\n\nGA_TRACKING_ID = os.getenv('GA_TRACKING_ID', False)\n\n\ndef josiendotnet_db():\n c = MongoClient(connect=False)\n db = c[os.getenv('DB')]\n return db\n\n\ndef db():\n c = MongoClient(connect=False)\n db = c[os.getenv('DB_NAME')]\n return db\n\n\ndef track_event(category, action, label=None, value=0):\n data = {\n 'v': '1',\n 'tid': GA_TRACKING_ID,\n 'cid': '555',\n 't': 'event',\n 'ec': category,\n 'ea': action,\n 'el': label,\n 'ev': value }\n response = requests.post( 'https://www.google-analytics.com/collect', data=data)\n response.raise_for_status()\n\n\ndef jlog(feil=False, stdout=False):\n jlog = logging.getLogger(__name__)\n jlog.setLevel(logging.DEBUG)\n formatter = logging.Formatter('jlog [%(asctime)s] %(filename)s %(module)s %(funcName)s %(levelname)s %(message)s')\n\n syslog = logging.handlers.SysLogHandler(address = '/dev/log')\n syslog.setFormatter(formatter)\n jlog.addHandler(syslog)\n\n if feil:\n feil = logging.FileHandler(feil)\n feil.setFormatter(formatter)\n jlog.addHandler(feil)\n\n if stdout:\n stdout = logging.StreamHandler(sys.stdout)\n stdout.setFormatter(formatter)\n jlog.addHandler(stdout)\n\n return jlog\n\n\ndef cmd_run(cmd):\n process = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE)\n #process.wait()\n data, err = process.communicate()\n if process.returncode is 0:\n return data.decode('utf-8')\n else:\n print(\"Error:\", err)\n return \"\"\n\n\ndef listvoters():\n o = cmd_run('/usr/bin/remcli system listvoters --json -l 1000')\n j = False\n if o:\n try:\n j = json.loads(o)\n except:\n print(sys.exc_info())\n\n return j\n\n\ndef listproducers():\n o = cmd_run('/usr/bin/remcli system listproducers --json -l 100')\n j = False\n if o:\n try:\n j = json.loads(o)\n except:\n print(sys.exc_info())\n\n return j\n\ndef get_remswap():\n o = cmd_run('/usr/bin/remcli get actions rem.swap --json')\n j = False\n if o:\n try:\n j = json.loads(o)\n except:\n print(sys.exc_info())\n\n return j\n\ndef get_block(block):\n o = cmd_run('/usr/bin/remcli get block {}'.format(block))\n j = False\n if o:\n try:\n j = json.loads(o)\n except:\n print(sys.exc_info())\n\n return j\n\n\ndef get_account(account):\n o = cmd_run('/usr/bin/remcli get account {0} --json'.format(account))\n j = False\n if o:\n try:\n j = json.loads(o)\n except:\n print(sys.exc_info())\n\n return j\n\n\ndef remcli_get_info():\n o = cmd_run('/usr/bin/remcli get info')\n j = False\n if o:\n try:\n j = json.loads(o)\n except:\n print(sys.exc_info())\n\n return j\n\n\ndef remcli_get_action_swap():\n o = cmd_run('/usr/bin/remcli get table rem.swap rem.swap swaps -r -l 4')\n j = False\n if o:\n try:\n j = json.loads(o)\n except:\n print(sys.exc_info())\n\n return j\n\n\ndef po(msg):\n app = Pushover(os.getenv('PUSHOVER_APP', False))\n if app.is_authenticated == True:\n user = app.get_user(os.getenv('PUSHOVER_USER', False))\n if user.is_authenticated == True:\n message = user.send_message(msg)\n return True\n\n return False\n\n\n\ndef human_readable(v):\n try:\n v = '{:0,.0f}'.format(float(v)).split(',')\n if len(v) == 2:\n return('{} k'.format(v[0]))\n if len(v) == 3:\n return('{} M'.format(v[0]))\n if len(v) == 4:\n return('{} G'.format(v[0]))\n if len(v) == 5:\n return('{} T'.format(v[0]))\n if len(v) == 6:\n return('{} P'.format(v[0]))\n if len(v) == 7:\n return('{} E'.format(v[0]))\n except:\n print(sys.exc_info())\n\n return False\n","sub_path":"app/lib/josien.py","file_name":"josien.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"429655530","text":"# coding=utf-8\n\nfrom setuptools import setup\nimport re\n\nwith open('vcloudair/__init__.py') as f:\n v = re.search(\"^__version__ = '(.+?)'$\", f.read(), re.MULTILINE)\n v = v.group(1)\n\nif not v:\n raise RuntimeError('Cannot find version number')\n\nwith open('README.rst', 'r', encoding='utf-8') as f:\n readme = f.read()\nwith open('CHANGELOG.rst', 'r', encoding='utf-8') as f:\n changelog = f.read()\n\nsetup(name='vcloudair',\n version=v,\n description='Python SDK for vCloud Air',\n long_description=readme+'\\n\\n'+changelog,\n author='Scott Schaefer',\n author_email='sschaefer@vmware.com',\n url='https://gitlab.com/scottjs/vcloudair',\n packages=['vcloudair'],\n install_requires=['requests>=2.10'],\n license='MIT',\n zip_safe=False,\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: MacOS',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: Implementation :: CPython',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: System :: Systems Administration'\n ]\n )\n","sub_path":"pypi_install_script/vcloudair-0.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"142305367","text":"import re\n\nfrom orderedset import OrderedSet\nfrom flask import Markup\n\nfrom notifications_utils.columns import Columns\nfrom notifications_utils.formatters import (\n unescaped_formatted_list,\n strip_html,\n escape_html,\n strip_dvla_markup,\n)\n\n\nclass Field():\n\n placeholder_pattern = re.compile(\n '\\(\\(' # opening ((\n '([^\\(\\)\\?]+)' # 1. name of placeholder, eg ‘registration number’\n '(\\?\\?)?' # 2. optional ??\n '([^\\)\\(]*)' # 3. optional text to display if the placeholder’s value is True\n '\\)\\)' # closing ))\n )\n placeholder_tag = \"(({}{}))\"\n optional_placeholder_tag = \"(({}??{}))\"\n placeholder_tag_no_brackets = \"{}{}\"\n\n def __init__(self, content, values=None, with_brackets=True, html='strip', markdown_lists=False):\n self.content = content\n self.values = values\n self.markdown_lists = markdown_lists\n if not with_brackets:\n self.placeholder_tag = self.placeholder_tag_no_brackets\n self.sanitizer = {\n 'strip': strip_html,\n 'escape': escape_html,\n 'passthrough': str,\n 'strip_dvla_markup': strip_dvla_markup,\n }[html]\n\n def __str__(self):\n if self.values:\n return self.replaced\n return self.formatted\n\n def __repr__(self):\n return \"{}(\\\"{}\\\", {})\".format(self.__class__.__name__, self.content, self.values) # TODO: more real\n\n @property\n def values(self):\n return self._values\n\n @values.setter\n def values(self, value):\n self._values = Columns(value) if value else {}\n\n def get_match(self, match):\n if match[1] and match[2]:\n return match[0]\n return match[0] + match[2]\n\n def format_match(self, match):\n if match.group(2) and match.group(3):\n return self.optional_placeholder_tag.format(\n self.sanitizer(match.group(1)),\n self.sanitizer(match.group(3))\n )\n return self.placeholder_tag.format(\n self.sanitizer(match.group(1)), self.sanitizer(match.group(3))\n )\n\n def replace_match(self, match):\n if match.group(2) and match.group(3) and self.values.get(match.group(1)) is not None:\n return match.group(3) if str2bool(self.values.get(match.group(1))) else ''\n if self.get_replacement(match) is not None:\n return self.get_replacement(match)\n return self.format_match(match)\n\n def get_replacement(self, match):\n\n replacement = self.values.get(match.group(1) + match.group(3))\n\n if isinstance(replacement, list):\n return self.get_replacement_as_list(list(filter(None, replacement)))\n\n if (\n isinstance(replacement, bool) or\n replacement == 0 or\n replacement == ''\n ):\n return str(replacement)\n\n if replacement:\n return self.sanitizer(str(replacement)) or ''\n\n return None\n\n def get_replacement_as_list(self, replacement):\n if not replacement:\n return None\n if self.markdown_lists:\n return self.sanitizer('\\n\\n' + '\\n'.join(\n '* {}'.format(item) for item in replacement\n ))\n return self.sanitizer(unescaped_formatted_list(replacement, before_each='', after_each=''))\n\n @property\n def _raw_formatted(self):\n return re.sub(\n self.placeholder_pattern, self.format_match, self.sanitizer(self.content)\n )\n\n @property\n def formatted(self):\n return Markup(self._raw_formatted)\n\n @property\n def placeholders(self):\n return OrderedSet(\n self.get_match(match) for match in re.findall(\n self.placeholder_pattern, self.content\n )\n )\n\n @property\n def replaced(self):\n return re.sub(\n self.placeholder_pattern, self.replace_match, self.sanitizer(self.content)\n )\n\n\ndef str2bool(value):\n if not value:\n return False\n return str(value).lower() in (\"yes\", \"y\", \"true\", \"t\", \"1\", \"include\", \"show\")\n","sub_path":"notifications_utils/field.py","file_name":"field.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"28531899","text":"from configparser import ConfigParser\nimport numpy as np\nimport nibabel as nib\nimport random\nimport ast\nparser = ConfigParser()\nparser.read('/Users/robmcc/mnt/droplet/home/k1201869/DOPA_symptoms/src/project_details.txt')\n\nall_nodes_nib = nib.load('/Users/robmcc/Documents/academic/DOPA_symptoms/results/figures/methods_diagram/nodes/Gordon_MNI_222.nii', mmap=False)\nall_nodes = np.squeeze(np.array((all_nodes_nib).get_data()))\nall_nodes = all_nodes.astype(int)\n\n# Node id dictionary\napriori_communities = parser._sections['datadriven_node_ids']\n\ndict1 = {}\nfor k, v in apriori_communities.items():\n val_ints = ast.literal_eval(v) # convert string to list\n dict1[k] = [x for x in val_ints] # dont subtract 1 frome ach node_id\n\nswitched_dict = {str(val): key for (key, val) in dict1.items()} # switch keys and value (convert back to string)\n\nreplacement_values = {'default': 1, 'smhand': 2, 'smmouth': 3, 'visual': 4, 'frontoparietal': 5, 'cinguloparietal': 6,\n 'retrosplenialtemporal': 7, 'cinguloperc': 8, 'dorsalattn': 9, 'auditory': 10, 'ventralattn': 11,\n 'salience': 12, 'none': 13}\nreplaced_dict = {k: replacement_values.get(v, v) for k, v in switched_dict.items()}\n\nnode_details = {}\nfor k, v in replaced_dict.items():\n key_ints = ast.literal_eval(k)\n for i in key_ints:\n node_details[i] = v\n\n#Comment out the below 3 lines if wanting true rather than shuffled image\n# values = list(node_details.values())\n# random.shuffle(values)\n# node_details = dict(zip(node_details, values))\n\nnodes_coded = np.vectorize(node_details.get)(all_nodes)\nnodes_coded[nodes_coded == None] = 0\nnodes_coded = nodes_coded.astype(float)\n\n#this saves just the blobs in the requested nodes, comment out otherwise\nselect_nodes = np.zeros([91,109,91])\nselect_nodes[all_nodes==245] = 1\nselect_nodes[all_nodes==111] = 1\nnodes_coded = select_nodes\n\nselect_nodes = all_nodes\nselect_nodes[all_nodes==245] = 0\nselect_nodes[all_nodes==111] = 0\nnodes_coded2 = select_nodes\n\n#salience network without nodes of interest (deleted 111 and 245)\nselect_nodes = np.zeros([91,109,91])\nsalience_nodes = [29,83,183,24,7, 21,22,27,28,34,40,63,71,72,76,81,82,84,101,103,105,112,147,153,180,181,185,187,188,192,196,198,219,223,234,235,238,246,248,249,274,317,318]\nsalience_locations = np.isin(all_nodes, salience_nodes)\nselect_nodes[salience_locations]=1\nselect_nodes=select_nodes*all_nodes\n\n\nnodes_coded_nii = nib.Nifti1Image(select_nodes, all_nodes_nib.affine)\nnib.save(nodes_coded_nii, '/Users/robmcc/Documents/academic/DOPA_symptoms/results/figures/methods_diagram/nodes/overlap_nodes2.nii')\n","sub_path":"diagrams/color_node_diagram.py","file_name":"color_node_diagram.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"216226184","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # 共享单车数据分析\n# \n# ## 数据描述性分析\n# \n# ### 数据导入\n# 使用pandas导入数据\n\n# In[1]:\n\n\nimport pandas as pd\ndata=pd.read_excel(r'C:\\Users\\路魂\\Desktop\\study\\运输经济学\\运输经济学数据\\bike.xlsx')\ndata.head()\n\n\n# In[348]:\n\n\ndata_all_cell_use=data.groupby(by=[\"CELL_ID\"])[\"MOVE\"].sum().to_frame()\ndata_all_cell_use=data_all_cell_use.sort_values('MOVE',ascending=False)\n#print(np.array(data_all_cell_use.index))\nx_train_num=np.array(data_all_cell_use.index[0:300])#取训练集\nx_train_num.sort()\nprint(x_train_num)\nprint(data_all_cell_use.iloc[300][\"MOVE\"])\n\n\n# In[512]:\n\n\ndata_all_cell_use.describe()\n\n\n# In[397]:\n\n\ndata_all_cell_use.to_csv(path_or_buf=\"cell_useall.csv\",index=True)\ndata_all_cell_total=data.groupby(by=[\"CELL_ID\"])[\"TOTAL\"].mean().to_frame()\ndata_all_cell_total.to_csv(path_or_buf=\"cell_totalall.csv\",index=True)\n\n\n# 先简单看看数据类型和含义\n# * ID:数据库中的主键值(不用管)\n# * CELL_ID:土地块ID,对应shp文件中“id” \n# * DAYS:日期 \n# * HOURS:小时 \n# * SEQ:以2017.04.26 0:00为0,每小时+1 \n# * MOVE:土地块在这一小时内被使用的单车数 \n# * TOTAL:土地块在这一小时内的单车总数\n# * HDB:土地块公有住宅建筑的容积率 \n# * PRIVATE:土地块私有住宅建筑的容积率 \n# * COMM:土地块商业建筑的容积率 \n# * INDU:土地块工业建筑的容积率 \n# * CYCLPATH:土地块内自行车道总长(米) \n# * BUS_STOP:土地块内公交站点总数 \n# * ROADINT:土地块内交叉口总数 \n# * ROAD_LIN:土地块内路段总数\n# * ENTROPY:熵(计算方法见论文) \n# * MRTDIST:距离最近的地铁站距离(米) \n# + DISTCEN:距离市中心的距离(米) \n# + RAIN:土地块在这一小时内的降雨量(厘米) \n# + TEMPO:土地块在这一小时内的温度(℃) \n# + LABORFREE:五一节免费骑活动(01变量) \n# + WENDFREE:周末免费骑活动(01变量\n# \n# >由于ID是数据主键,无其他作用,在此处删去\n\n# ### 对数据进行描述性统计分析\n# * 先展示数据的基本特性\n\n# In[2]:\n\n\nimport pandas_profiling\ndata=data.drop('ID',axis=1)\npandas_profiling.ProfileReport(data)\n#data_an.to_file(\"REPORT.html\")\n\n\n# 从上表可以简单看出数据的各类数据的分布,同时,上表还给出了一些提示,例如:CELL_ID和ID具有高度相关性,Road_LIN和ROADINT具有高度相关性\n# * 下面对数据的相关性先做简单的分析\n\n# In[3]:\n\n\ndata_corr=data.corr()\nimport seaborn as sn\nimport matplotlib as mpl\nimport matplotlib as mpl\nmpl.rcParams['font.sans-serif'] = ['Times New Roman']\nmpl.rcParams['font.serif'] = ['Times New Roman']\nsn.heatmap(data_corr,cmap=\"Set1\")\n\n\n# * 接下来展示一日之内和一周之内的使用规律\n# * 一日之内\n\n# In[498]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nmpl.rcParams['font.sans-serif'] = ['KaiTi']\nmpl.rcParams['font.serif'] = ['KaiTi']\nplt.figure(figsize=(10,7), dpi=200)\ncount=1\nfor i in [26,27,28,29,30,1,2,3,4]:\n daily_data= data[(data[u'DAYS']==i)]\n use_sumBy_hour = daily_data.groupby(by=['HOURS'])['MOVE'].sum()\n use_sumBy_hour = use_sumBy_hour.to_frame()\n use_sumBy_hour['HOURS'] =use_sumBy_hour.index\n use_sumBy_hour =use_sumBy_hour.reset_index(drop=True)\n plt.subplot(3,3,count)\n plt.title(str(i)+\"号使用量时变图像\")\n plt.xticks([0,3,6,9,12,15,18,21])\n plt.ylim((0,1500))\n plt.xlabel('小时',fontsize=14)\n plt.ylabel('共享单车使用量',fontsize=14)\n plt.plot(use_sumBy_hour['HOURS'].tolist(),use_sumBy_hour['MOVE'].tolist(),'b.-')\n count=count+1\nplt.tight_layout()\n \n \n\n\n# * 一周之内\n# \n\n# In[497]:\n\n\nuse_sumBy_day = data.groupby(by=['DAYS'])['MOVE'].sum()\nX=[]\nY=[]\nfor i in [26,27,28,29,30,1,2]:\n X.append(str(i))\n Y.append(use_sumBy_day[i])\nplt.figure( dpi=400)\nplt.title(\"使用量日变化图像(26���为周三,1日为劳动节假期)\")\nplt.xlabel('日期',fontsize=14)\nplt.ylim((0,17000))\nplt.ylabel('共享单车使用量',fontsize=14) \nplt.plot(X,Y)\n\n\n# ## 探究使用量与投放量的关系\n\n# In[6]:\n\n\n#找停车最多的一个区域\ndata.sort_values('CELL_ID')\nplace_data=data.groupby(by=[\"CELL_ID\"])[\"ROADINT\"].sum()\nprint(place_data.idxmax())\n\n\n# In[487]:\n\n\nm=[11972,12334]\nplt.figure(figsize=(15,4),dpi=200)\nfor k in [1,2]:\n Y1=[]\n data_9402=data[(data[\"CELL_ID\"]==m[k-1])]\n data_9402_dM=data_9402.groupby(by=['DAYS'])['MOVE'].sum()\n for i in [26,27,28,29,30,1,2,3,4]:\n day_data=data_9402[(data_9402[\"DAYS\"]==i)]\n data_9402_dt=day_data.groupby(by=[\"HOURS\"])[\"TOTAL\"].sum()\n Y1.append(data_9402_dt.quantile(0.5))\n Y2=data_9402_dM.tolist()\n plt.subplot(1,2,k)\n plt.xlabel('中位数投放量')\n plt.ylabel('使用量')\n plt.scatter(Y1,Y2)\n\n\n# > 可以看出,用一个地块的数据去做相应的分析并没有什么意义\n\n# In[496]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nmpl.rcParams['font.sans-serif'] = ['KaiTi']\nmpl.rcParams['font.serif'] = ['KaiTi']\nplt.figure(figsize=(10,7), dpi=200)\ncount=1\nfor i in [26,27,28,29,30,1,2,3,4]:\n daily_data= data[(data[u'DAYS']==i)]\n t_sumBy_hour = daily_data.groupby(by=['HOURS'])['TOTAL'].sum()\n t_sumBy_hour = t_sumBy_hour.to_frame()\n t_sumBy_hour['HOURS'] =t_sumBy_hour.index\n t_sumBy_hour =t_sumBy_hour.reset_index(drop=True)\n plt.subplot(3,3,count)\n plt.title(str(i)+\"号投放量时变图像\")\n plt.xticks([0,3,6,9,12,15,18,21])\n plt.xlabel('小时',fontsize=14)\n plt.ylabel('共享单车投放量',fontsize=14)\n plt.plot(t_sumBy_hour['HOURS'].tolist(),t_sumBy_hour['TOTAL'].tolist(),'r.-')\n count=count+1\nplt.tight_layout()\n\nplt.figure( dpi=100)\nplt.title(\"投放量小时变化图像\")\nplt.ylim((5000,10000))\nt_sumBy_seq = data.groupby(by=['SEQ'])['TOTAL'].sum()\nt_sumBy_seq.plot()\n \n \n\n\n# In[495]:\n\n\nmpl.rcParams['font.sans-serif'] = ['KaiTi']\nmpl.rcParams['font.serif'] = ['KaiTi']\nX=[]\nY1=[]\nY3=[]\nY2=[]\nY4=[]\nuse_sumBy_day = data.groupby(by=['DAYS'])['MOVE'].sum()\npro_sumBy_day = data.groupby(by=['DAYS'])['TOTAL'].sum()\nplt.figure(figsize=(10,4), dpi=300)\nfor i in [26,27,28,29,30,1,2,3,4]:\n X.append(str(i))\n daily_data= data[(data[u'DAYS']==i)]\n use_sumBy_hour = daily_data.groupby(by=['HOURS'])['MOVE'].sum()\n pro_sumBy_hour= daily_data.groupby(by=['HOURS'])['TOTAL'].sum()\n Y1.append(use_sumBy_hour[18])#当天18点的使用量\n Y2.append(pro_sumBy_hour[18])#当天18点的投放量\n Y3.append(use_sumBy_day[i])#当天全部使用量\n Y4.append(pro_sumBy_hour.quantile(0.5))#当天小时投放量的中位数\nplt.subplot(1,2,1)\nplt.plot(X,Y1,'g.-',label='使用量')\nplt.plot(X,Y2,'r.-',label='投放量')\nplt.xlabel('日期',fontsize=14)\nplt.ylabel('数量',fontsize=14)\nplt.legend()\nplt.title('各日18:00-19:00共享单车投放量与使用量关系')\nplt.subplot(1,2,2)\nplt.plot(X,Y3,'g.-',label='使用量')\nplt.plot(X,Y4,'r.-',label='投放量')\nplt.xlabel('日期',fontsize=14)\nplt.ylabel('数量',fontsize=14)\nplt.legend()\nplt.title('各日共享单车投放量与总使用量关系')\nplt.tight_layout()\nplt.show()\n \n\n\n# In[447]:\n\n\nmpl.style.use('ggplot')\n\n\n# #### 先比较所有地块的投放量和需求量变化\n\n# In[506]:\n\n\n\nsn.set(style='ticks', context='paper')\nmpl.rcParams['font.sans-serif'] = ['KaiTi']\nmpl.rcParams['font.serif'] = ['KaiTi']\n#接下来是二次拟合\nimport numpy as np\nz_all = np.polyfit(Y4,Y3, 2) \np_all = np.poly1d(z_all)\nprint(p_all)\nResidual= sum((Y3 - p_all(Y4))**2) # 残差平方和\ntotal = sum((Y3-np.mean(Y3))**2) #总体平方和\nR_square1 = 1-Residual / total # 相关性系数R^2\nprint(\"二次多项式拟合--全天使用量与投放量拟合的优度为\",R_square1)\n\n\n\n\n\nz_h = np.polyfit(Y2,Y1, 2) \np_h = np.poly1d(z_h)\nprint(p_h)\nResidual= sum((Y1 - p_h(Y2))**2) # 残差平方和\ntotal = sum((Y1-np.mean(Y1))**2) #总体平方和\nR_square2 = 1-Residual / total # 相关性系数R^2\nprint(\"二次多项式拟合--18时使用量与投放量拟合的优度为\",R_square2)\n\n\nplt.figure(figsize=(10,8),dpi=300)\nplt.subplot(2,2,1)\nplt.scatter(Y4,Y3,c=\"b\")\nplt.xlabel('投放量',fontsize=14)\nplt.ylabel('使用量',fontsize=14)\nplt.title(\"全天总使用量与投放量关系\")\nplt.plot(np.arange(7500,10000,10),p_all(np.arange(7500,10000,10)),'r--',label=\"$0.002496x^2-40.02x+166200$\")\nplt.legend()\n\nplt.subplot(2,2,2)\nplt.scatter(Y2,Y1)\nplt.xlabel('投放量',fontsize=14)\nplt.ylabel('使用量',fontsize=14)\nplt.title(\"18时的总使用量与投放量关系\")\nplt.plot(np.arange(7500,10000,10),p_h(np.arange(7500,10000,10)),'r--',label=\"$0.00032x^2-5.404x+23350$\")\nplt.legend()\n\nplt.subplot(2,2,3)\nplt.xlabel('投放量',fontsize=14)\nplt.ylabel('车均使用量',fontsize=14)\nY43=np.array(Y3)/np.array(Y4)\nplt.scatter(Y4,Y43)\nz_all = np.polyfit(Y3,Y43, 1) \np_all = np.poly1d(z_all)\nprint(\"每天车均使用量的线性回归\",p_all)\nplt.title(\"全天车均使用量与投放量关系\")\nplt.plot(np.arange(7500,10000,10),p_all(np.arange(7500,10000,10)),'r--',label=\"$8.7*10^-5x+0.208$\")\nplt.legend()\n\nplt.subplot(2,2,4)\nplt.xlabel('投放量',fontsize=14)\nplt.ylabel('车均使用量',fontsize=14)\nY21=np.array(Y1)/np.array(Y2)\nplt.scatter(Y2,Y21)\nz_all = np.polyfit(Y2,Y21, 1) \np_all = np.poly1d(z_all)\nprint(\"18时车均使用量的线性回归\",p_all)\nplt.title(\"18时车均使用量与投放量关系\")\nplt.plot(np.arange(7500,10000,10),p_all(np.arange(7500,10000,10)),'r--',label=\"$2.37*10^-5x-0.124$\")\n\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n# In[484]:\n\n\nfrom scipy.optimize import curve_fit\ndef func(x, a, b, c):\n return a * np.exp(0.000001*b * x) + c\n\nplt.figure(figsize=(10,5),dpi=300)\npopt, pcov = curve_fit(func, Y4, Y3,maxfev = 800000)\n#popt数组中,三个值分别是待求参数a,b,c\nY3_ = [func(i, popt[0],popt[1],popt[2]) for i in np.arange(7500,10000,100)]\nY3__=[func(i, popt[0],popt[1],popt[2]) for i in Y4]\nplt.subplot(1,2,1)\nplt.scatter(Y4,Y3)\nplt.xlabel('投放量',fontsize=14)\nplt.ylabel('使用量',fontsize=14)\nplt.plot(np.arange(7500,10000,100),Y3_,'r--')\nprint(popt)\nResidual= sum((Y3 - np.array(Y3__))**2)\ntotal = sum((Y3-np.mean(Y3))**2) #总体平方和\nR_square1 = 1-Residual / total # 相关性系数R^2\nprint(R_square1)\n\npopt, pcov = curve_fit(func, Y2, Y1,maxfev = 800000)\nY1_ = [func(i, popt[0],popt[1],popt[2]) for i in np.arange(7500,10000,100)]\nY1__=[func(i, popt[0],popt[1],popt[2]) for i in Y2]\nplt.subplot(1,2,2)\nplt.scatter(Y2,Y1)\nplt.xlabel('投放量',fontsize=14)\nplt.ylabel('使用量',fontsize=14)\nplt.plot(np.arange(7500,10000,100),Y1_,'r--')\nprint(popt)\nResidual= sum((Y1 - np.array(Y1__))**2)\ntotal = sum((Y1-np.mean(Y1))**2) #总体平方和\nR_square1 = 1-Residual / total # 相关性系数R^2\nprint(R_square1)\n\n\n# >the next part i will try to scatter every cell in 18 o'clock\n# \n\n# In[502]:\n\n\nplt.figure(dpi=300)\nmpl.rcParams['font.sans-serif'] = ['KaiTi']\nmpl.rcParams['font.serif'] = ['KaiTi']\ndata_cell=data.groupby(by=[\"DAYS\",\"CELL_ID\"])[\"MOVE\",\"TOTAL\"].sum()\ndata_cell[u\"全天投放量\"]=data_cell[\"TOTAL\"]/24#data_cell是每个地块每天的总使用量和投放量的关系(投放量取全天投放量的平均值)\ndata_cell.plot(kind=\"scatter\",x=u\"全天投放量\",y=\"MOVE\",figsize=(8,6),fontsize=18)\n\n\ndata.plot(kind=\"scatter\",x=\"TOTAL\",y=\"MOVE\",figsize=(8,6),title=\"在全部小时内各个地块的使用量与投放量的关系\")\n\n#接下来定义一个datapure\ndatapure=data[(data[\"HOURS\"]>=6)]\n#datapure.plot(kind=\"scatter\",x=\"TOTAL\",y=\"MOVE\",figsize=(8,6),fontsize=18,title=\"在各高频小时内各个地块的使用量与投放量的关系\")\ndatapure[u\"投放量的log值\"]=np.log(datapure[\"TOTAL\"])\nx1=datapure[\"TOTAL\"]\nx2=datapure[u\"投放量的log值\"]\ny=datapure[\"MOVE\"]\nz_1 = np.polyfit(x1,y, 1) \nz_2=np.polyfit(x2,y,1)\np_1=np.poly1d(z_1)\np_2=np.poly1d(z_2)\n\n\nplt.figure(figsize=(10,6),dpi=200)\nplt.subplot(1,1,1)\nplt.scatter(datapure[\"TOTAL\"],datapure[\"MOVE\"])\nplt.plot(np.arange(0,80,1),p_1(np.arange(0,80,1)),'r--')#优度是0.1195\nplt.plot(np.arange(0,80,1),p_2(np.log(np.arange(0,80,1))),'g--')#0.1262\n\n# Residual= sum((y - p_2(x2))**2) # 残差平方和\n# total = sum((y-np.mean(y))**2) #总体平方和\n# R2 = 1-Residual / total # 相关性系数R^2\n# print(\"二次多项式拟合--18时使用量与投放量拟合的优度为\",R2)\n\n\n# In[501]:\n\n\ndata_seq_all=datapure.groupby(by=[\"SEQ\"])[\"MOVE\",\"TOTAL\"].sum().reset_index()\ndata_seq_all=data_seq_all[(data_seq_all[\"SEQ\"]<213)]\nz_seq_all=np.polyfit(data_seq_all[\"TOTAL\"],data_seq_all[\"MOVE\"],2)\np_seq_all=np.poly1d(z_seq_all)\nprint(p_seq_all)\nplt.figure(figsize=(7,4),dpi=100)\nplt.subplot(1,1,1)\nplt.plot(np.arange(7000,10000,10),p_seq_all(np.arange(7000,10000,10)),'r--',label='$0.0000784x^2-1.154x+4476$')#0.1262\nplt.title(\"move and total around city during all distinct hours from 26th to 4th\")\nplt.scatter(data_seq_all[\"TOTAL\"],data_seq_all[\"MOVE\"])\nplt.legend()\nplt.show()\n\n\n# *上面的图充分显示了每辆车做统计的不现实性,上图难以说明每个地块的使用量和投放量的任何关系,他们太乱了*\n\n# ## 需求预测模型的建立\n\n# In[55]:\n\n\ndatapure=data[(data[\"HOURS\"]>=6)] #style控制默认样式,context控制着默认的画幅大小\ndatapure_scatter=datapure[[\"MOVE\",\"HDB\",\"PRIVATE\",\"COMM\",\"INDU\"]]\nsn.pairplot(datapure_scatter)\n#plt.savefig('x.png')\n\n\n# In[406]:\n\n\n#datapure=datapure.drop('ROADINT',axis=1)\ndata_corr=data.corr()\nmpl.rcParams['font.sans-serif'] = ['Times New Roman']\nmpl.rcParams['font.serif'] = ['Times New Roman']\nplt.figure(figsize=(12,5),dpi=200)\nplt.subplot(1,2,1)\nplt.title(\"all data's pearson Correlation coefficient\")\nsn.heatmap(data_corr,cmap=\"Set3\")\nplt.subplot(1,2,2)\ndata_corr=datapure.corr()\nplt.title(\"data after 6:00's pearson Correlation coefficient\")\nsn.heatmap(data_corr,cmap=\"Set3\")\nplt.tight_layout()\n\n\n# In[162]:\n\n\n#数据处理---data_cell is a dataframe which contain the useful variables in this lineregress model\ndata_cell=data.groupby(by=[\"CELL_ID\",\"DAYS\",\"HDB\",\"PRIVATE\",\"COMM\",\"INDU\",\"CYCLPATH\",\"BUS_STOP\",\"ROAD_LIN\",\"ENTROPY\",\"MRTDIST\",\"DISTCEN\",\"LABORFREE\",\"WENDFREE\"])[\"MOVE\"].sum()\ndata_fuzhu=data.groupby(by=[\"CELL_ID\",\"DAYS\",\"HDB\",\"PRIVATE\",\"COMM\",\"INDU\",\"CYCLPATH\",\"BUS_STOP\",\"ROAD_LIN\",\"ENTROPY\",\"MRTDIST\",\"DISTCEN\",\"LABORFREE\",\"WENDFREE\"])[\"TOTAL\",\"TEMPO\",\"RAIN\"].mean()\n# data_cell.head()\n# data_fuzhu.head()\ndata_cell=data_cell.to_frame()\ndata_cell=pd.merge(data_cell,data_fuzhu, left_index=True, right_index=True, how='inner')\ndata_cell=data_cell.reset_index()\ndata_cell.head()\n\n\n# In[415]:\n\n\n#datapure=datapure.drop('ROADINT',axis=1)\ndata_cell=data_cell.drop(\"SPATIAL\",axis=1)\ndata_corr=data_cell.corr()\nmpl.rcParams['font.sans-serif'] = ['Times New Roman']\nmpl.rcParams['font.serif'] = ['Times New Roman']\nplt.figure(figsize=(14,6),dpi=200)\nplt.subplot(1,2,1)\nplt.title(\"data groupby days and cell's correlation coefficient\")\nsn.heatmap(data_corr,cmap=\"Set3\")\nplt.subplot(1,2,2)\ndata_corr=data_cell_2.corr()\nplt.title(\"data of mostly used cells groupby days and cell's correlation coefficient\")\nsn.heatmap(data_corr,cmap=\"Set3\")\nplt.tight_layout()\n\n\n# In[363]:\n\n\n#datapure=datapure.drop('ROADINT',axis=1)\ndata_corr=data_cell_2.corr()\nmpl.rcParams['font.sans-serif'] = ['Times New Roman']\nmpl.rcParams['font.serif'] = ['Times New Roman']\nplt.figure(figsize=(12,5),dpi=200)\nplt.subplot(1,2,1)\nplt.title(\"pearson\")\nsn.heatmap(data_corr,cmap=\"Set1\")\nplt.subplot(1,2,2)\ndata_corr=data_cell_2.corr(\"spearman\")\nplt.title(\"spearman\")\nsn.heatmap(data_corr,cmap=\"Set1\")\nplt.tight_layout()\n\n\n# In[169]:\n\n\ndata_cell.plot(kind=\"scatter\",x=\"TOTAL\",y=\"MOVE\")\n\n\n# In[199]:\n\n\n#以下代码用来生成GIS的信息矩阵\n#print(data.groupby(by=[\"CELL_ID\"])[\"MOVE\"].sum())\nfrom dbfread import DBF\nsp_dep_M = DBF(r\"C:\\Users\\路魂\\Desktop\\study\\运输经济学\\运输经济学数据\\singapore_grids\\singapore_grids\\sg_grid_300_Select.dbf\")\nCELL_ID_gis=[]\nx_long=[]\ny_lati=[]\n\nfor record in sp_dep_M:\n CELL_ID_gis.append(record[\"id\"])\n x_long.append(record[\"xmin\"]+150)\n y_lati.append(record[\"ymin\"]+150)\n#print(x_long,y_lati)\n\nGIS_data = pd.DataFrame({'CELL_GIS_ID':CELL_ID_gis,'x_long':x_long,'y_lati':y_lati})\n\nGIS_data.set_index('CELL_GIS_ID',inplace=True)\nprint(GIS_data)\n\n\n# In[219]:\n\n\n#print(80 in GIS_data[\"x_long\"])\nGIS_data[\"num\"]=np.arange(9481)\nprint(GIS_data)\n\n\n# In[225]:\n\n\n#以下代码用来生成使用量矩阵BIT\n# BIT=np.zeros([3298,31])#用来存储所有的使用量数据\n# for i in range(0, len(data_cell)):\n# #print data.iloc[i]['c1'], df.iloc[i]['c2']\n# hang=GIS_data.loc[data_cell.iloc[i][\"CELL_ID\"]][\"num\"]\n# #print(hang,int(data_cell.iloc[i][\"DAYS\"]))\n# BIT[int(hang),int(data_cell.iloc[i][\"DAYS\"])]=int(data_cell.iloc[i][\"MOVE\"])\n# print(BIT)\ndata_cell.describe()\n\n\n# \n# ID:数据库中的主键值(不用管)\n# CELL_ID:土地块ID,对应shp文件中“id”\n# DAYS:日期\n# HOURS:小时\n# SEQ:以2017.04.26 0:00为0,每小时+1\n# MOVE:土地块在这一小时内被使用的单车数\n# TOTAL:土地块在这一小时内的单车总数\n# HDB:土地块公有住宅建筑的容积率\n# PRIVATE:土地块私有住宅建筑的容积率\n# COMM:土地块商业建筑的容积率\n# INDU:土地块工业建筑的容积率\n# CYCLPATH:土地块内自行车道总长(米)\n# BUS_STOP:土地块内公交站点总数\n# ROADINT:土地块内交叉口总数\n# ROAD_LIN:土地块内路段总数\n# ENTROPY:熵(计算方法见论文)\n# MRTDIST:距离最近的地铁站距离(米)\n# DISTCEN:距离市中心的距离(米)\n# RAIN:土地块在这一小时内的降雨量(厘米)\n# TEMPO:土地块在这一小时内的温度(℃)\n# LABORFREE:五一节免费骑活动(01变量)\n# WENDFREE:周末免费骑活动(01变量\n# \n\n# In[248]:\n\n\n\n\n\n# In[349]:\n\n\n#用来生成空间权重矩阵\ndef spatial_de_M(i,j):\n if(i in GIS_data[\"x_long\"] and j in GIS_data[\"x_long\"] and (i!=j)):\n x1=GIS_data.loc[i][\"x_long\"]\n y1=GIS_data.loc[i][\"y_lati\"]\n x2=GIS_data.loc[j][\"x_long\"]\n y2=GIS_data.loc[j][\"y_lati\"]\n dis= abs(x1-x2) + abs(y1-y2)\n dis=1.0/dis\n return dis\n\n else:\n return 0 \n \n\n#print(spatial_de_M(78,82))\ndata_cnum=data_cell_2.groupby(by=[\"CELL_ID\"])[\"MOVE\"].sum().to_frame()#这个dataframe用来找cell_id和id\ndata_cnum=data_cnum.reset_index()\ndata_cnum=data_cnum.drop(\"MOVE\",axis=1)\nprint(data_cnum.shape)\ndepend_M=np.zeros([300,300])#只求测试集的150x150的距离矩阵\nfor i in range(0,300):\n print(i)\n for j in range(i+1,300):\n #print(x_train_num[i],x_train_num[j])\n depend_M[i][j]=depend_M[j][i]=spatial_de_M(x_train_num[i],x_train_num[j])\nprint(depend_M) \n\n\n# In[350]:\n\n\ndata_cnum[\"num\"]=np.arange(300)\ndata_cnum=data_cnum.set_index(\"CELL_ID\")\nprint(data_cnum)\n\n\n# In[302]:\n\n\ndata_cnum2=data_cnum.reset_index()#这个索引是为了方便根据区间的序号查找区间的ID\nprint(data_cnum2)\n\n\n# In[351]:\n\n\ndata_cell_2=data_cell[(data_cell[\"CELL_ID\"].isin(x_train_num))]\ndata_cell_2=data_cell_2.reset_index()\ndata_cell_2.head()\n\n\n# In[352]:\n\n\n#这里计算空间滞后值,并添加到data_cell的一列---注意:只计算影响能力前300位的\ndata_cell_2[\"SPATIAL\"]=0\nSPATIAL=[]\nfor i in range(len(data_cell_2)):\n print(i)\n tempol=data_cell_2[(data_cell_2[\"DAYS\"]==data_cell_2.loc[i][\"DAYS\"])&data_cell_2[\"MOVE\"]>0]\n spatial=0\n for items in range(len(tempol)):\n #print(tempol2.iloc[items][\"MOVE\"])\n spatial+=depend_M[data_cnum.loc[data_cell_2.loc[i][\"CELL_ID\"]][\"num\"],data_cnum.loc[tempol.iloc[items][\"CELL_ID\"]][\"num\"]]*tempol.iloc[items][\"MOVE\"]\n #print(spatial)\n #print(spatial)\n SPATIAL.append(spatial)\nprint(SPATIAL)\n \n# for i in range(0,300):\n# print(i)\n# CELL_id=x_train_num[i]\n# tempal=data_cell_2[(data_cell_2[\"CELL_ID\"]==CELL_id)]\n# #print(tempal)\n# for days in range(len(tempal)):\n# spatial=0\n# #print(tempal.iloc[days][\"DAYS\"]) \n# tempol2=data_cell_2[(data_cell_2[\"DAYS\"]==tempal.iloc[days][\"DAYS\"])&data_cell_2[\"MOVE\"]>0]\n# #print(tempol2)\n# for items in range(len(tempol2)):\n# #print(tempol2.iloc[items][\"MOVE\"])\n# spatial+=depend_M[data_cnum.loc[x_train_num[i]][\"num\"],data_cnum.loc[tempol2.iloc[items][\"CELL_ID\"]][\"num\"]]*tempol2.iloc[items][\"MOVE\"]\n# #print(spatial)\n \n# data_cell_2[(data_cell_2[\"CELL_ID\"]==CELL_id)&(data_cell_2[\"DAYS\"]==tempal.iloc[days][\"DAYS\"])][\"SPATIAL\"].value=spatial\n# print(spatial)\n# print(data_cell_2[(data_cell_2[\"CELL_ID\"]==CELL_id)&(data_cell_2[\"DAYS\"]==tempal.iloc[days][\"DAYS\"])][\"SPATIAL\"])\n #print(spatial)\n# 筛选出这个时间有使用量的地区,他们才会对空间滞后量产生影响\n# for items in tempal[\"CELL_ID\"]:\n# spatial=0\n \n# disj=data_cnum.loc[items]\n# print(disi,disj)\n #spatial+=depend_M[disi][disj]*tempal[(tempal[\"CELL_ID\"]==items)][\"MOVE\"]\n \n \n\n\n# In[353]:\n\n\nprint(data_cell_2.shape)\ndata_cell_2['SPATIAL'] = pd.Series(SPATIAL, index=range(2699))\ndata_cell_2.head()\n\n\n# In[372]:\n\n\ndata_cell_2[\"TOTAL_log\"]=data_cell_2[\"TOTAL\"].apply(lambda x: np.log(x))\ndata_cell_2.head()\n\n\n# In[547]:\n\n\n#接下来就来回归啦!! 空间自回归模型的建立\n\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import explained_variance_score, mean_absolute_error, mean_squared_error, r2_score \nfrom sklearn.model_selection import train_test_split\n\nfor total_style in [16,20,21,22]:\n X_re=data_cell_2.iloc[:,[3,4,5,6,7,8,9,10,11,12,13,14,total_style,17,18,19]]\n y_re=data_cell_2.iloc[:,15]\n X_train,X_test,Y_train,Y_test = train_test_split(X_re,y_re,train_size=0.80,test_size=0.2)\n\n # print(\"训练数据特征:\",X_train.shape,\n # \"测试数据特征:\",X_test.shape)\n\n # print(\"训练数据标签:\",Y_train.shape,\n # \"测试数据标签:\",Y_test.shape)\n\n import statsmodels.api as sm\n X_Re=sm.add_constant(X_re)\n est = sm.OLS(y_re, X_Re).fit()\n print(data_cell_2.columns[total_style],\"拟合报告\")\n print(est.summary())\n\n model_lr = LinearRegression()\n\n model_lr.fit(X_re,y_re)\n\n a = model_lr.intercept_#截距\n\n b = model_lr.coef_#回归系数\n\n print(\"最佳拟合线:截距\",a,\",回归系数:\",b)\n\n score = model_lr.score(X_test,Y_test)\n\n print(score,\"\\n\\n\\n\\n\")\n\n\n# In[518]:\n\n\n\nX_re=data_cell_2.iloc[:,[3,4,5,6,7,8,9,10,11,12,13,14,16,17]]\ny_re=data_cell_2.iloc[:,15]\n\n \n# print(\"训练数据特征:\",X_train.shape,\n# \"测试数据特征:\",X_test.shape)\n \n# print(\"训练数据标签:\",Y_train.shape,\n# \"测试数据标签:\",Y_test.shape)\n\nimport statsmodels.api as sm\nX_Re=sm.add_constant(X_re)\nest = sm.OLS(y_re, X_Re).fit()\n\nprint(est.summary())\n\n\n# In[377]:\n\n\n\n\n\n# In[398]:\n\n\n\n\n\n# In[410]:\n\n\nprint(SPATIAL)\n\n\n# In[511]:\n\n\ndata[\"TOTAL\"].sum()\n\n\n# In[548]:\n\n\n#切分数据\nX_re=data_cell_2.iloc[:,[3,4,5,6,7,8,9,10,11,12,13,14,total_style,17,18,19]]\ny_re=data_cell_2.iloc[:,15]\nX_train,X_test,Y_train,Y_test = train_test_split(X_re,y_re,train_size=0.2,test_size=0.8)\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import svm\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.linear_model import Ridge\nmodel1 = RandomForestClassifier(n_estimators=200,oob_score=True)\nmodel1.fit(X_train,Y_train)\nprint(\"随机森林:\")\nprint(\"训练集:%f\"%model1.score(X_train,Y_train))\nprint(\"测试集:%f\"%model1.score(X_test,Y_test))\nprint(\"支持向量机:\")\nmodel2=svm.SVC(C=2,kernel='rbf',gamma=10,decision_function_shape='ovr') \nmodel2.fit(X_train, Y_train) \nprint(\"训练集:\",model2.score(X_train,Y_train))\nprint(\"测试集:\",model2.score(X_test,Y_test))\nprint(\"k最近邻算法\")\nmodel3 = KNeighborsRegressor(n_neighbors=50)\nmodel3.fit(X_train,Y_train)\nprint(\"训练集:\",model3.score(X_train,Y_train))\nprint(\"测试集:\",model3.score(X_test,Y_test))\nprint(\"岭回归\")\nmodel4= Ridge(alpha=.5)\nmodel4.fit(X_train,Y_train)\nprint(\"训练集:\",model4.score(X_train,Y_train))\nprint(\"测试集:\",model4.score(X_test,Y_test))\nprint(model4.coef_)\n\n\n# In[552]:\n\n\npandas_profiling.ProfileReport(data_cell_2)\n\n\n# In[553]:\n\n\ndata_cell_2.describe()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"dockless sharing bike.py","file_name":"dockless sharing bike.py","file_ext":"py","file_size_in_byte":24446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"346871840","text":"\n\ndef part_one(vals):\n i = 1\n for v in vals:\n while(v + vals[-i] > 2020):\n i += 1\n\n if v + vals[-i] == 2020:\n print(\"{}\".format(v*vals[-i]))\n return\n\ndef part_two(vals):\n i = 0\n j = 0\n first_j = 0\n for v in vals:\n first_j += 1\n j = first_j\n while(v + vals[j] + vals[-i] > 2020):\n i += 1\n\n while(v + vals[j] + vals[-i] < 2020):\n j += 1\n\n if v + vals[j] + vals[-i] == 2020:\n print(\"{}\".format(v*vals[j]*vals[-i]))\n return\n\n\nif __name__ == \"__main__\":\n vals = []\n with open(\"input\", 'r') as f:\n for line in f:\n vals.append(int(line))\n vals.sort()\n part_one(vals)\n part_two(vals)\n","sub_path":"2020/1/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"464977119","text":"# -*- coding:utf-8 -*-\r\n\"\"\"\r\n@Time : 2019/6/18 16:54\r\n@Author : zhaoguoqing600689\r\n\"\"\"\r\nimport numpy as np\r\nfrom operator import *\r\nfrom collections import defaultdict\r\nfrom sklearn.datasets import load_iris\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndataset = load_iris()\r\nx = dataset.data\r\ny = dataset.target\r\n\r\nn_samples, n_features = x.shape\r\n\r\nprint(n_samples, n_features)\r\n## 分割训练集和测试集\r\n\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=20)\r\n\r\n\r\ndef knn(k, testdata, traindata, labels):\r\n \"\"\"\r\n testdata: 一维数组[0, 0, 1, ...]\r\n traindata: 二维数组\r\n labels: 一维数组,和traindata一一对应\r\n \"\"\"\r\n traindata_size = traindata.shape[0]\r\n\r\n ## 计算欧式距离\r\n dif = np.tile(testdata, (traindata_size, 1)) - traindata\r\n sqdif = dif ** 2\r\n sum_sqdif = sqdif.sum(axis=1) ###行向量分别相加,从而得到新的一个行向量\r\n distance = sum_sqdif ** 0.5\r\n\r\n ## 根据元素的值从大到小对元素进行排序,返回下标\r\n sorted_distance = distance.argsort()\r\n count = defaultdict(int)\r\n for i in range(0, k):\r\n vote = labels[sorted_distance[i]]\r\n count[vote] += 1\r\n\r\n sorted_count = sorted(count.items(), key=itemgetter(1), reverse=True)\r\n return sorted_count[0][0]\r\n\r\n\r\nif __name__ == '__main__':\r\n test_one = [4.8, 3.4, 1.6, 0.2]\r\n predict_one = knn(3, test_one, x_train, y_train)\r\n print(predict_one)\r\n","sub_path":"knn_core.py","file_name":"knn_core.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"564575666","text":"from typing import List\n\n\nclass Solution:\n \"\"\"\n Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.\n\n Example 1:\n\n Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]\n Output: 8\n Explanation: There are 8 negatives number in the matrix.\n Example 2:\n\n Input: grid = [[3,2],[1,0]]\n Output: 0\n \"\"\"\n def countNegatives(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n cnt = 0\n row, col = rows - 1, 0\n while row >= 0 and col < cols:\n if grid[row][col] < 0:\n cnt += cols - col\n row -= 1\n else:\n col += 1\n return cnt","sub_path":"python_module/examples/1351_Count_Negative_Numbers_in_a_Sorted_Matrix.py","file_name":"1351_Count_Negative_Numbers_in_a_Sorted_Matrix.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"334813189","text":"class LinkedList:\n class __Node:\n def __init__(self,item,next=None):\n self.item=item\n self.next=next\n def getItem(self):\n return self.item\n def getNext(self):\n return self.next\n def setItem(self,item):\n self.item = item\n def setNext(self,next):\n self.next = next\n\n def __init__(self,contents=[]):\n self.first = LinkedList.__Node(None,None)\n self.numItems = 0\n self.first.setNext(self.first)\n self.last = self.first\n for e in contents:\n self.append(e)\n\n def printList(self):\n tmp = self.first.next\n nodes = []\n for i in range(self.numItems):\n nodes.append(str(tmp.item))\n tmp = tmp.next\n print(' -> '.join(nodes))\n\n def append(self,item):\n lastNode = self.last\n newNode = LinkedList.__Node(item,self.first)\n lastNode.setNext(newNode)\n self.last = newNode\n self.numItems += 1\n def palindrome(self):\n A=[]\n B=[]\n stack=Stack()\n queue=Fifo()\n curs=self.first.next\n for i in range(self.numItems):\n stack.push(str(curs.item))\n queue.pushback(str(curs.item))\n curs=curs.next\n curs=self.first.next\n for i in range(self.numItems):\n A.append(stack.pop())\n B.append(queue.popfront())\n curs=curs.next\n for i in range(self.numItems):\n if(A[i]!=B[i]):\n return False\n return True\n#list=LinkedList([1,2,2,2,2,3,4,5,5])\n#list.printList()\n#list.duplicates()\n#list.printList()\nclass Fifo:\n def __init__(self,size=20):\n self.items = [None] * size\n self.first = 0\n self.last = -1\n self.size = size\n self.length = 0\n def isEmpty(self):\n if self.length != 0:\n return False\n return True\n def front(self):\n if self.length != 0:\n return self.items[self.first]\n raise ValueError(\"Queue is empty\")\n def back(self):\n if self.length != 0:\n return self.items[self.last]\n raise ValueError(\"Queue is empty\")\n def pushback(self,item):\n if self.length == self.size:\n self.allocate()\n self.last = (self.last + 1) % self.size\n self.items[self.last] = item\n self.length += 1\n def popfront(self):\n if self.size > 20 and self.length == self.size / 4:\n self.deallocate()\n if self.length != 0:\n frontelement = self.items[self.first]\n self.first = (self.first + 1) % self.size\n self.length -= 1\n return frontelement\n raise ValueError(\"Queue is empty\")\n def allocate(self):\n newlength = 2 * self.size\n length = self.length\n newQueue = [None] * newlength\n for i in range(self.size):\n pos = (i + self.first) % self.size\n newQueue[i] = self.items[pos]\n self.items = newQueue\n self.first = 0\n self.last = self.size - 1\n self.size = newlength\n self.length = length\n def deallocate(self):\n newlength = self.size // 2\n length = self.length\n newQueue = [None] * newlength\n length = self.length\n for i in range(length):\n pos = (i + self.first) % self.size\n newQueue[i] = self.items[pos]\n self.items = newQueue\n self.first = 0\n self.last = length - 1\n self.size = newlength\n self.length = length\n def __iter__(self):\n rlast = self.first + self.length\n for i in range(self.first,rlast):\n yield self.items[i % self.size]\nclass Stack:\n def __init__(self,size=20):\n self.items = [None] * size\n self.numItems = 0\n self.size = size\n\n def top(self):\n if self.numItems != 0:\n return self.items[self.numItems-1]\n raise Error(\"Stack is empty\")\n\n def push(self,item):\n if self.numItems == self.size:\n self.allocate()\n self.items[self.numItems] = item\n self.numItems += 1\n\n def allocate(self):\n newlength = 2 * self.size\n newStack = [None] * newlength\n for i in range(self.numItems):\n newStack[i] = self.items[i]\n self.items = newStack\n self.size = newlength\n\n def pop(self):\n if self.numItems == self.size / 4:\n self.deallocate()\n if self.numItems != 0:\n topelement = self.items[self.numItems-1]\n self.numItems -= 1\n return topelement\n raise Error(\"Stack is empty\")\n\n def deallocate(self):\n newlength = self.size // 2\n newStack = [None] * newlength\n for i in range(self.numItems):\n newStack[i] = self.items[i]\n self.items = newStack\n self.size = newlength\n\n def isEmpty(self):\n if self.numItems != 0:\n return False\n return True\n\n\nlist=LinkedList([])\nlist.printList()\nprint(list.palindrome())\n","sub_path":"Linked_List_Problems/palindrome_check/palindrome_check.py","file_name":"palindrome_check.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"125092441","text":"from tkinter import *\r\nfrom tkinter.messagebox import showinfo\r\n\r\ny=\"\"\r\nx=2\r\nplayer_1=[]\r\nplayer_2=[]\r\ndef define_sign(number):\r\n\r\n global x,y\r\n global player_1, player_2\r\n from itertools import permutations\r\n set1 = permutations([1, 2, 3])\r\n set2 = permutations([4, 5, 6])\r\n set3 = permutations([7, 8, 9])\r\n set4 = permutations([3, 5, 7])\r\n set5 = permutations([1, 5, 9])\r\n set6 = permutations([1, 4, 7])\r\n set7 = permutations([2, 5, 8])\r\n set8 = permutations([3, 6, 9])\r\n\r\n for i in set1, set2, set3, set4, set5, set6, set7, set8:\r\n for j in list(i):\r\n plyr_1 = all(elem in player_1 for elem in j)\r\n plyr_2 = all(elem in player_2 for elem in j)\r\n if plyr_1 == True:\r\n print(\"player 1 wins\")\r\n showinfo(\"game result \", \"Player 1 has won\")\r\n break\r\n elif plyr_2 == True:\r\n print(\"player 2 wins\")\r\n showinfo(\"game result \", \"Player 2 has won\")\r\n break\r\n else:\r\n pass\r\n\r\n\r\n\r\n if number == 1:\r\n if x%2 == 0:\r\n y='X'\r\n player_1.append(number)\r\n print(player_1)\r\n elif x%2 != 0:\r\n y='O'\r\n player_2.append(number)\r\n print(player_2)\r\n btn1.config(text=y)\r\n x = x + 1\r\n\r\n if number == 2:\r\n if x%2 == 0:\r\n y='X'\r\n player_1.append(number)\r\n print(player_1)\r\n elif x%2 != 0:\r\n y='O'\r\n player_2.append(number)\r\n print(player_2)\r\n btn2.config(text=y)\r\n x = x + 1\r\n\r\n if number == 3:\r\n if x%2 == 0:\r\n y='X'\r\n player_1.append(number)\r\n print(player_1)\r\n elif x%2 != 0:\r\n y='O'\r\n player_2.append(number)\r\n print(player_2)\r\n btn3.config(text=y)\r\n x = x + 1\r\n\r\n if number == 4:\r\n if x%2 == 0:\r\n y='X'\r\n player_1.append(number)\r\n print(player_1)\r\n elif x%2 != 0:\r\n y='O'\r\n player_2.append(number)\r\n print(player_2)\r\n btn4.config(text=y)\r\n x = x + 1\r\n\r\n if number == 5:\r\n if x%2 == 0:\r\n y='X'\r\n player_1.append(number)\r\n print(player_1)\r\n elif x%2 != 0:\r\n y='O'\r\n player_2.append(number)\r\n print(player_2)\r\n btn5.config(text=y)\r\n x = x + 1\r\n\r\n if number == 6:\r\n if x%2 == 0:\r\n y='X'\r\n player_1.append(number)\r\n print(player_1)\r\n elif x%2 != 0:\r\n y='O'\r\n player_2.append(number)\r\n print(player_2)\r\n btn6.config(text=y)\r\n x = x + 1\r\n\r\n if number == 7:\r\n if x%2 == 0:\r\n y='X'\r\n player_1.append(number)\r\n print(player_1)\r\n elif x%2 != 0:\r\n y='O'\r\n player_2.append(number)\r\n print(player_2)\r\n btn7.config(text=y)\r\n x = x + 1\r\n\r\n if number == 8:\r\n if x%2 == 0:\r\n y='X'\r\n player_1.append(number)\r\n print(player_1)\r\n elif x%2 != 0:\r\n y='O'\r\n player_2.append(number)\r\n print(player_2)\r\n btn8.config(text=y)\r\n x = x + 1\r\n\r\n if number == 9:\r\n if x%2 == 0:\r\n y='X'\r\n player_1.append(number)\r\n print(player_1)\r\n elif x%2 != 0:\r\n y='O'\r\n player_2.append(number)\r\n print(player_2)\r\n btn9.config(text=y)\r\n x = x + 1\r\n\r\nroot = Tk()\r\nroot.title(\"Tic Tac Toe\")\r\nroot.wm_iconbitmap(r'C:\\Users\\User\\Downloads\\5067718-xo-png-3-png-image-xo-png-530_366_preview.ico')\r\n#root.geometry('400x700')\r\nlabel1 = Label(root, text=\"player 1 = X\", font=('times 15'))\r\nlabel1.grid(row=0, column=1)\r\nlabel2 = Label(root, text=\"player 2 = O\", font=('times 15'))\r\nlabel2.grid(row=0, column=2)\r\n\r\nbtn1 = Button(root, width=20, height=10, command=lambda: define_sign(1))\r\nbtn1.grid(row=1, column=1)\r\n\r\nbtn2 = Button(root, width=20, height=10, command=lambda: define_sign(2))\r\nbtn2.grid(row=1, column=2)\r\n\r\nbtn3 = Button(root, width=20, height=10, command=lambda: define_sign(3))\r\nbtn3.grid(row=1, column=3)\r\n\r\nbtn4 = Button(root, width=20, height=10, command=lambda: define_sign(4))\r\nbtn4.grid(row=2, column=1)\r\n\r\nbtn5 = Button(root, width=20, height=10, command=lambda: define_sign(5))\r\nbtn5.grid(row=2, column=2)\r\n\r\nbtn6 = Button(root, width=20, height=10, command=lambda: define_sign(6))\r\nbtn6.grid(row=2, column=3)\r\n\r\nbtn7 = Button(root, width=20, height=10, command=lambda: define_sign(7))\r\nbtn7.grid(row=3, column=1)\r\n\r\nbtn8 = Button(root, width=20, height=10, command=lambda: define_sign(8))\r\nbtn8.grid(row=3, column=2)\r\n\r\nbtn9 = Button(root, width=20, height=10, command=lambda: define_sign(9))\r\nbtn9.grid(row=3, column=3)\r\n\r\n\r\n\r\nroot.mainloop()\r\n","sub_path":"XO_spelletje.py","file_name":"XO_spelletje.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"465034082","text":"from simple3D import Mesh, DisplayObject, Window, ViewPort, Transform\nfrom simple3D.components.mouseRotate import MouseRotate\nfrom simple3D.components.keyboardMover import KeyboardMover\nfrom simple3D.mats.lineMeterial import LineMeterial\nimport numpy as np\n\nvertices = [0.0, 0.0, 0.0,\n 1, 0, 0.0,\n 0, 0, 0,\n 0, 1, 0,\n 0, 0, 0,\n 0, 0, 1]\n\nvertices_color = [1, 0, 0,\n 1, 0, 0,\n 0, 1, 0,\n 0, 1, 0,\n 0, 0, 1,\n 0, 0, 1]\n\n# rod_vertices = [0.0, 0.0, 0.0,\n# 0.0, 1, 0.0]\n\n# rod_color = [1, 1, 1,\n# 1, 1, 1]\n\nindices = [0, 1, 2, 3, 4, 5]\n\n# rod_indices = [0, 1]\n\nclass SE3Scene:\n def __init__(self):\n self.axis1 = self.get_axis()\n self.axis2 = self.get_axis()\n\n window = Window()\n viewports = ViewPort.get_aranged_viewports(window.width, window.height, 1, 2)\n viewports[0].add(self.axis1)\n viewports[1].add(self.axis2)\n mouseRotate = MouseRotate(window)\n mouseRotate.add(self.axis1)\n keyMover = KeyboardMover(window)\n keyMover.add(self.axis1)\n\n window.add(*viewports, mouseRotate, keyMover)\n self.scene = window\n\n def set_convert_func(self, func):\n self.scene.add(func)\n\n def start(self):\n self.scene.render()\n\n def get_axis(self):\n mesh = Mesh(vertices, indices, vectices_color=vertices_color)\n material = LineMeterial()\n axis = DisplayObject(mesh, material)\n return axis\n\n # def get_rod(self):\n # mesh = Mesh(rod_vertices, rod_indices, vectices_color=rod_color)\n # meterial = LineMeterial()\n # rod = DisplayObject(mesh, meterial)\n # return rod\n\n\nif __name__ == \"__main__\":\n rotateScene = SE3Scene()\n\n\n def func():\n rm = rotateScene.axis1.transform.rotation\n rotateScene.axis2.transform.rotation = np.array(rm)\n translate = rotateScene.axis1.transform.pos\n rotateScene.axis2.transform.pos = translate\n\n\n rotateScene.set_convert_func(func)\n rotateScene.start()\n","sub_path":"rotateExample/scenes/SE3Scene.py","file_name":"SE3Scene.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"259433170","text":"import io\nfrom contextlib import redirect_stdout\n\nimport pytest\nfrom pytest import approx\n\n\nfrom easymunk import CircleBody, PolyBody, SegmentBody, Body\n\n\n@pytest.fixture()\ndef space(phys):\n phys.moment_multiplier(5)\n return phys.space()\n\n\n@pytest.fixture()\ndef no_space(phys):\n phys.moment_multiplier(5)\n return phys.space()\n\n\n@pytest.fixture(scope=\"module\")\ndef pyxel():\n try:\n import pyxel\n\n pyxel.is_real = True\n except ImportError:\n import sys\n from unittest.mock import Mock\n\n sys.modules[\"pyxel\"] = pyxel = Mock()\n pyxel.is_real = False\n\n def skip_mock():\n if not pyxel.is_real:\n pytest.skip(\"Skipping test on fake Pyxel module\")\n\n pyxel.skip_mock = skip_mock\n return pyxel\n\n\n@pytest.fixture(scope=\"module\")\ndef phys():\n try:\n from easymunk import pyxel\n\n return pyxel\n except ImportError:\n pytest.skip(\"pyxel is not available\")\n\n\nclass TestPyxelModule:\n def test_circ(self, space, phys):\n circ = phys.circ(1, 2, 3)\n assert isinstance(circ, CircleBody)\n assert circ.radius == 3\n assert circ.space == space\n assert circ.position == (1, 2)\n\n def test_rect(self, space, phys):\n rect = phys.rect(1, 2, 3, 4)\n assert isinstance(rect, PolyBody)\n assert len(rect.vertices) == 4\n assert rect.cache_bb().shape == (3, 4)\n assert rect.bb.left == 1\n assert rect.bb.bottom == 2\n assert rect.position == (2.5, 4)\n assert rect.space == space\n\n def test_tri(self, space, phys):\n tri = phys.tri(0, 1, 1, 0, 1, 1)\n assert isinstance(tri, PolyBody)\n assert len(tri.vertices) == 3\n assert tri.vertices_world == [(0, 1), (1, 0), (1, 1)]\n assert tri.cache_bb().shape == (1, 1)\n assert tuple(tri.bb) == (0, 0, 1, 1)\n assert tri.position == approx((0.6666, 0.6666), abs=1e-3)\n assert tri.space == space\n\n def test_line(self, space, phys):\n line = phys.line(1, 2, 3, 4, radius=0)\n assert isinstance(line, SegmentBody)\n assert line.endpoints_world == ((1, 2), (3, 4))\n assert tuple(line.cache_bb()) == (1, 2, 3, 4)\n assert line.position == (2.0, 3.0)\n assert line.space == space\n\n def test_margin(self, space, phys):\n margin = phys.margin(0, 0, 10, 10, radius=0)\n assert isinstance(margin, Body)\n assert tuple(margin.cache_bb()) == (0, 0, 10, 10)\n assert len(margin.shapes) == 4\n assert margin.space == space\n\n def test_draw_functions(self, space, phys):\n opts = phys.DrawOptions(phys.echo_pyxel)\n\n phys.circ(0, 0, 1)\n phys.tri(0, 0, 0, 1, 1, 1)\n phys.line(0, 0, 1, 1)\n\n stdout = io.StringIO()\n with redirect_stdout(stdout):\n space.debug_draw(opts)\n\n assert stdout.getvalue() == (\n \"circ(x=0.0, y=0.0, r=1.0, col=7)\\n\"\n \"tri(x1=0.0, y1=0.0, x2=1.0, y2=1.0, x3=0.0, y3=1.0, col=7)\\n\"\n \"line(x1=0.0, y1=0.0, x2=1.0, y2=1.0, col=7)\\n\"\n )\n\n opts = phys.DrawOptions(phys.echo_pyxel, wireframe=True)\n stdout = io.StringIO()\n with redirect_stdout(stdout):\n space.debug_draw(opts)\n\n assert stdout.getvalue() == (\n \"circb(x=0.0, y=0.0, r=1.0, col=13)\\n\"\n \"line(x1=0.0, y1=0.0, x2=1.0, y2=0.0, col=13)\\n\"\n \"line(x1=0.0, y1=0.0, x2=0.0, y2=0.0, col=13)\\n\"\n \"line(x1=0.0, y1=0.0, x2=1.0, y2=1.0, col=13)\\n\"\n \"line(x1=1.0, y1=1.0, x2=0.0, y2=1.0, col=13)\\n\"\n \"line(x1=0.0, y1=0.0, x2=0.0, y2=1.0, col=13)\\n\"\n \"line(x1=0.0, y1=0.0, x2=1.0, y2=1.0, col=13)\\n\"\n )\n","sub_path":"tests/test_pyxel.py","file_name":"test_pyxel.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"143010294","text":"#!/usr/bin/env python\n\nimport os\nfrom distutils.core import setup\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(name = 'python-gorun',\n version = '1.6',\n description = 'Wrapper on pyinotify for running commands (often tests)',\n long_description = read('README.md'),\n author='Peter Bengtsson',\n author_email='peter@fry-it.com',\n url = 'http://github.com/peterbe/python-gorun',\n classifiers = [\n 'Programming Language :: Python :: 2',\n 'Intended Audience :: Developers',\n 'Operating System :: POSIX :: Linux',\n 'Topic :: Software Development :: Testing'\n 'Topic :: Software Development :: Build Tools'\n ],\n scripts = ['gorun.py']\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"28481175","text":"\n\ndef is_prime(number):\n if number<0 : number*=-1\n if number<2 : return False\n \n for x in range(2,number):\n if number%x==0:\n return False\n\n return True\n\ndef prime_range(min,max=None):\n result=[]\n if max==None:\n min,max=0,min\n\n for value in range(min,max):\n if is_prime(value):\n result.append(value)\n\n return result","sub_path":"module-demo-01/primes.py","file_name":"primes.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"350542990","text":"import tensorflow as tf\nimport numpy as np\nfrom PIL import Image\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\n# import tensorflow.contrib.eager as tfe\n# tfe.enable_eager_execution\n\nLABEL_IN_COLOR = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],\n [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],\n [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],\n [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],\n [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],\n [0, 64, 128]]\n\n\n\ndef paser_pascolvoc_instance_segmentation(segmentationObject_filename, segmentationClass_filename, NUM_CLASS = 21, NUM_OBJECT = 21 ):\n segmentationClass_data = tf.gfile.FastGFile(segmentationClass_filename,'rb').read()\n segmentationObject_data = tf.gfile.FastGFile(segmentationObject_filename,'rb').read()\n\n segmentationClass_img = tf.image.decode_png(segmentationClass_data,channels=3,dtype=tf.uint8)\n segmentationObject_img = tf.image.decode_png(segmentationObject_data,channels=3,dtype=tf.uint8)\n # print(segmentationObject_img.mode)\n\n\n # init instance vector\n # img_shape = tf.shape(segmentationObject_img)\n # num_class_tensor = tf.constant(NUM_CLASS)\n # img_shape_two_dim = tf.slice(img_shape,begin=0,size=2)\n # instance_shape = tf.concat([img_shape_two_dim, num_class_tensor], axis=0)\n\n # instance_vector = tf.constant(0,dtype=tf.uint8,shape=instance_shape)\n instance_vector = []\n instance_class = []\n\n instance_labels = tf.constant([],tf.int64)\n for i in range(NUM_OBJECT):\n # print(i, '/', NUM_OBJECT)\n compare_with_dim = tf.equal(segmentationObject_img,LABEL_IN_COLOR[i])\n mask_boolen = tf.reduce_all(input_tensor=compare_with_dim,axis=-1)\n mask_int = tf.cast(mask_boolen,dtype=tf.uint8)\n instance_vector.append(mask_int)\n\n instance_class_mask = tf.multiply(segmentationClass_img, mask_int)\n for j in range(NUM_CLASS):\n compare_label_dim = tf.equal(instance_class_mask,LABEL_IN_COLOR[j])\n compare_label = tf.reduce_all(compare_with_dim, axis=-1)\n compare_label_final = tf.reduce_any(compare_label)\n\n instance_labels = tf.cond(compare_label_final, lambda:tf.concat([instance_labels,[j]],axis=0), lambda:instance_labels)\n\n instance_tensor = tf.convert_to_tensor(instance_vector)\n\n return instance_tensor, instance_labels\n\n\n\n\ndef paser_pascolvoc_instance_segmentation_np_version(segmentationObject_filename, segmentationClass_filename, NUM_CLASS = 21, NUM_OBJECT = 21 ):\n\n segmentationClass_img = Image.open(segmentationClass_filename)\n segmentationObject_img = Image.open(segmentationObject_filename)\n\n # print(segmentationClass_img.mode) #P模式,需转化为RGB模式\n\n segmentationClass_img = segmentationClass_img.convert('RGB')\n segmentationObject_img = segmentationObject_img.convert('RGB')\n\n segmentationClass_img = np.array(segmentationClass_img,dtype=np.uint8)\n segmentationObject_img = np.array(segmentationObject_img,dtype=np.uint8)\n\n instance_vector = []\n instance_labels = []\n\n for i in range(0,NUM_OBJECT):\n # print(i, '/', NUM_OBJECT)\n compare_with_dim = np.equal(segmentationObject_img,LABEL_IN_COLOR[i])\n mask_boolen = np.all(compare_with_dim,axis=-1)\n mask_int = mask_boolen.astype(np.uint8)\n mask_int_dim_expand = np.expand_dims(mask_int,axis=2)\n instance_vector.append(mask_int_dim_expand)\n\n mask_int = np.expand_dims(mask_int,axis=2)\n instance_class_mask = np.multiply(segmentationClass_img, mask_int)\n for j in range(1,NUM_CLASS):\n compare_label_dim = np.equal(instance_class_mask,LABEL_IN_COLOR[j])\n compare_label = np.all(compare_label_dim, axis=-1)\n compare_label_final = np.any(compare_label)\n\n if compare_label_final:\n instance_labels.append((i,j))\n # im=Image.fromarray(instance_vector[2]*255)\n # im.save('./fig.png')\n\n # instance_vector = np.expand_dims(instance_vector,axis=3)\n instance_np_array = np.concatenate(instance_vector,axis=2)\n\n return instance_np_array, np.array(instance_labels) # instance_tensor 中0是背景\n\n\n\n\ndef test(dataset_dir, name= '000032'):\n import os\n DIRECTORY_ANNOTATIONS = 'Annotations/'\n RANDOM_SEED = 4240\n SAMPLES_PER_FILES = 20000\n DIRECTORY_IMAGES = 'JPEGImages/'\n DIRECTORY_SEGMENTATIONCLASS = 'SegmentationClass/'\n DIRECTORY_SEGMENTATIONOBJECT = 'SegmentationObject/'\n\n IMAGE_TYPE = 'jpg'\n SEGMENTATION_TYPE = 'png'\n\n image_filename = os.path.join(dataset_dir, DIRECTORY_IMAGES, name + '.' + IMAGE_TYPE)\n segmentationClass_filename = os.path.join(dataset_dir, DIRECTORY_SEGMENTATIONCLASS, name + '.' + SEGMENTATION_TYPE)\n segmentationObject_filename = os.path.join(dataset_dir, DIRECTORY_SEGMENTATIONOBJECT,\n name + '.' + SEGMENTATION_TYPE)\n\n if os.path.exists(image_filename) and os.path.exists(segmentationObject_filename) and os.path.exists(\n segmentationClass_filename):\n instance_tensor, instance_labels = paser_pascolvoc_instance_segmentation_np_version(segmentationObject_filename,\n segmentationClass_filename)\n\n\nif __name__ == '__main__':\n dataset_dir = '/Volumes/TOSHIBA/Deep_Learning/All_Data/VOC2007/VOCtrainval_06-Nov-2007/VOCdevkit/VOC2007/'\n test(dataset_dir)\n pass\n","sub_path":"vgg/utils/paser_pascolvoc.py","file_name":"paser_pascolvoc.py","file_ext":"py","file_size_in_byte":5566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"278315100","text":"\"\"\"\nProject Euler 60\n\nThe primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.\n\nFind the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.\n\"\"\"\n\nimport math\n\ndef isPrime(number):\n for x in range(2, int(number / 2) + 1):\n if number % x == 0:\n return False\n return True\n\ndef isConcatPrime(a,b):\n return isPrime(int(str(a) + str(b))) and isPrime(int(str(a) + str(b)))\n\ndef getPrimesUpto(limit):\n \"\"\"\n Uses Sieve of Eratosthenes\n \"\"\"\n allNumbers = [True for x in range(2, limit)]\n \n for x in range(2, int(math.sqrt(limit))):\n if allNumbers[x - 2] == True:\n for y in range(x**2, limit, x):\n allNumbers[y - 2] = False\n\n for i in range(len(allNumbers)):\n if allNumbers[i]:\n yield i + 2\n \nprint(list(getPrimesUpto(10000)))\n \n\n","sub_path":"project_euler_60.py","file_name":"project_euler_60.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"424328033","text":"# Each command has its own type\r\n# Value order: type, size, needs_linking, byte(s)\r\ntype_dictionary = {\r\n # RAM ops\r\n 'read' : 3,\r\n 'save' : 3,\r\n # Arithmetic\r\n 'add' : 1,\r\n 'sub' : 1,\r\n 'mul' : 1,\r\n 'ssl' : 1,\r\n 'ssr' : 1,\r\n 'inca' : 1,\r\n 'incb' : 1,\r\n 'deca' : 1,\r\n 'decb' : 1,\r\n 'and' : 1,\r\n # Jump, need linking\r\n 'breq' : 2,\r\n 'brab' : 2,\r\n 'brba' : 2,\r\n 'goto' : 2,\r\n 'call' : 2,\r\n # Simple ops\r\n 'idle' : 0,\r\n 'return' : 0,\r\n 'deref' : 0\r\n}\r\n\r\n'''\r\nCLASSES\r\n'''\r\n# Static class that returns the proper type of command\r\nclass CMD_Builder:\r\n @staticmethod\r\n def getCMD(line):\r\n name = 'idle'\r\n args = ''\r\n line_list = line.split()\r\n if len(line_list) > 0:\r\n name = line_list[0]\r\n args = line_list[1:]\r\n\r\n # Get command type and return correct object\r\n cmd_type = type_dictionary.get(name)\r\n if cmd_type == 0: return CMD_0(name, args)\r\n elif cmd_type == 1: return CMD_1(name, args)\r\n elif cmd_type == 2: return CMD_2(name, args)\r\n elif cmd_type == 3: return CMD_3(name, args)\r\n\r\n\r\n# Basic CMD\r\nclass CMD:\r\n def __init__(self, name, args):\r\n self.size = 1\r\n self.needs_linking = False\r\n self.name = name\r\n self.args = args\r\n self.bytes = []\r\n\r\n ## Returns (size, needs_linking, bytes)\r\n def getInfo(self):\r\n return self.size, self.needs_linking, self.bytes\r\n\r\n def debug(self):\r\n p = '['+self.__class__.__name__+']:'\r\n print(p, 'Bytes for:', self.name, \" \".join(self.args), ' are:',self.bytes)\r\n\r\n'''\r\nSUBCLASSES\r\n'''\r\n# Simple op class ####################################################\r\nclass CMD_0(CMD):\r\n def __init__(self, name, args):\r\n super().__init__(name, args)\r\n # Set bytes\r\n if self.name == 'idle': self.bytes.append('08')\r\n elif self.name == 'return': self.bytes.append('0a')\r\n elif self.name == 'deref':\r\n if self.args[1] == 'a': self.bytes.append('0b')\r\n elif self.args[1] == 'b': self.bytes.append('0c')\r\n else: print('CMD_0: there was something wrong with the command')\r\n else: print('CMD_0: there was something wrong with the command')\r\n\r\n self.debug()\r\n\r\n\r\n# Arithmetic op class ################################################\r\nclass CMD_1(CMD):\r\n def __init__(self, name, args):\r\n super().__init__(name, args)\r\n\r\n # Set default values for reg target and op_code\r\n op_code = '0' # default is add\r\n target = '4' # default is A\r\n\r\n # Check that argument is valid and correct target if needed\r\n if len(args) > 0:\r\n if args[0] == 'b': target = '5'\r\n\r\n # Set op_code if needed\r\n if self.name == 'sub': op_code = '1'\r\n elif self.name == 'mul': op_code = '2'\r\n elif self.name == 'ssl': op_code = '3'\r\n elif self.name == 'ssr': op_code = '4'\r\n elif self.name == 'inca': op_code = '5'\r\n elif self.name == 'incb': op_code = '6'\r\n elif self.name == 'deca': op_code = '7'\r\n elif self.name == 'decb': op_code = '8'\r\n elif self.name =='and' : op_code = 'c'\r\n\r\n # Construct byte\r\n self.bytes.append(op_code+target)\r\n\r\n self.debug()\r\n\r\n\r\n# Jump op class ######################################################\r\nclass CMD_2(CMD):\r\n def __init__(self, name, args):\r\n super().__init__(name, args)\r\n self.size = 2\r\n self.needs_linking = True\r\n\r\n # Set default values for reg target and op_code\r\n op_code_1 = '0' # default is goto/call\r\n op_code_2 = '7' # default is goto\r\n target_address = '00'\r\n\r\n # Check that argument is valid\r\n if len(args) > 0:\r\n target_address = args[0]\r\n if self.name=='breq':\r\n op_code_1 = '9'\r\n op_code_2 = '6'\r\n if self.name=='brab':\r\n op_code_1 = 'a'\r\n op_code_2 = '6'\r\n if self.name=='brba':\r\n op_code_1 = 'b'\r\n op_code_2 = '6'\r\n if self.name=='call':\r\n op_code_2 = '9'\r\n\r\n # Construct byte and leave address empty for linking\r\n self.bytes.append(op_code_1+op_code_2)\r\n self.bytes.append(target_address) # FOR NOW LEAVE IT FOR TESTING\r\n\r\n self.debug()\r\n\r\n\r\n# Ram op class #######################################################\r\nclass CMD_3(CMD):\r\n def __init__(self, name, args):\r\n super().__init__(name, args)\r\n self.size = 2\r\n\r\n # Set default values for reg target and op_code\r\n op_code_1 = '0' # Always 0 for type 3\r\n op_code_2 = '0' # Default is read A\r\n target_address = '00'\r\n\r\n # Check that argument is valid\r\n if len(args) > 1:\r\n arg = args[0]\r\n target_address = args[1]\r\n if self.name=='read' and arg=='b': op_code_2 = '1'\r\n if self.name=='save' and arg=='a': op_code_2 = '2'\r\n if self.name=='save' and arg=='b': op_code_2 = '3'\r\n\r\n # Construct byte and address\r\n self.bytes.append(op_code_1+op_code_2)\r\n self.bytes.append(target_address)\r\n\r\n self.debug()\r\n\r\n\r\n'''\r\nInput: cmd _ _\r\nOutput: size, needs_linking, bytes\r\n'''\r\n## Returns triple (size,needs_linking,bytes)\r\ndef decode(line):\r\n cmd = CMD_Builder.getCMD(line.lower())\r\n return cmd.getInfo()\r\n","sub_path":"van_assembler/assembler/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":5585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"486847405","text":"\"\"\"\n Laplace方程式をSOR法で解く.\n https://qiita.com/sci_Haru/items/6b80c7eb8d4754fb5c2d\n https://qiita.com/sci_Haru/items/b98791f232b93690a6c3\n\"\"\"\n\n#パッケージの導入\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import ArtistAnimation #アニメーション作成のためのメソッド\n\n#定数設定\ndelta_Lx = 0.03 #グリッド幅\ndelta_Ly = 0.03 #グリッド幅\nLLx = 10 #領域の幅(x方向)\nLLy = 10 #領域の幅(y方向)\nLx = int(LLx/delta_Lx) #x方向の分割数\nLy = int(LLy/delta_Ly) #x方向の分割数\n\nV = 5.0 #一辺のDirichlet境界条件\nconv_criterion = 10**-3 #収束判定条件\n\n#計算用配列の準備\nphi = np.zeros([Lx+1,Ly+1]) #2次元物理量の配列\nphi_Bound = np.zeros([Lx+1,Ly+1])\nphi_Bound[0,:] = V #この辺にDirichlet境界条件を導入\n\n#SOR法\naa_recta = 0.5*(np.cos(np.pi/Lx) + np.cos(np.pi/Ly)) #???\nomega_SOR = 2/(1+np.sqrt(1-aa_recta**2)) #加速パラメータ\nprint(\"omega_SOR = \", omega_SOR)\n\n#main\ndelta = 1.0\nn_itr = 0\nconv_check = [] #???\nwhile delta > conv_criterion: #収束するまで\n phi_in = phi.copy()\n if n_itr % 100 == 0: #100回ごとに残差を表示\n print(\"Iteration No =\", n_itr, \"delta =\", delta)\n conv_check.append([n_itr, delta])\n for i in range(Lx+1): #領域\n for j in range(Ly+1):\n if i == 0 or i == Lx or j == 0 or j == Ly: #各辺はそのまま\n phi[i,j] = phi_Bound[i,j] #境界条件を格納している配列\n else: #SOR法により更新\n phi[i,j] = phi[i,j] + omega_SOR * ((phi[i+1,j] + phi[i-1,j] + phi[i,j+1] + phi[i,j-1])/4-phi[i,j])\n\n delta = np.max(abs(phi-phi_in)) #1ステップで最も変化した値をdeltaとする\n n_itr += 1\n\nprint(\"Total iteration =\", n_itr)\nprint(\"Data points =\", Lx*Ly)\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.imshow(phi, cmap='hsv')\nplt.show()\n","sub_path":"numerical/2d_laplace_SOR.py","file_name":"2d_laplace_SOR.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"349366699","text":"import zmq\nimport time\n\nhost = \"127.0.0.1\"\nport = \"5001\"\n\n# Creates a socket instance\ncontext = zmq.Context()\nsocket = context.socket(zmq.PUB)\n\n# Binds the socket to a predefined port on localhost\nsocket.bind(\"tcp://{}:{}\".format(host, port))\n\ntime.sleep(1)\n\n# Sends a string message\nsocket.send_string(\"hello\")","sub_path":"pc/configurator_using_zmq/pub.py","file_name":"pub.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"597140524","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('fb360', '0053_auto_20151016_1117'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='respondent',\n name='respondent_type',\n field=models.CharField(default=b'P', max_length=2, verbose_name=b'Respondent Type', choices=[(b'P', b'Peer'), (b'E', b'Reportee'), (b'M', b'Manager'), (b'AM', b'Additional Manager')]),\n preserve_default=True,\n ),\n ]\n","sub_path":"fb360/migrations/0054_auto_20151016_1253.py","file_name":"0054_auto_20151016_1253.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"641039699","text":"def install_package(module, device):\n junos = SW(device)\n package = module.params['src']\n no_copy = module.params['no_copy']\n progress_log = (lambda x, y: module.log(y))\n module.log('installing package')\n result = junos.install(package, progress=progress_log, no_copy=no_copy)\n if (not result):\n module.fail_json(msg='Unable to install package on device')\n if module.params['reboot']:\n module.log('rebooting system')\n junos.reboot()","sub_path":"Data Set/bug-fixing-5/33624fe96faaff2169d2ff1252c32f26a62826bc--fix.py","file_name":"33624fe96faaff2169d2ff1252c32f26a62826bc--fix.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"169628341","text":"import random\n\n\ndef random_book():\n books = [['Umberto Eco', 'Numele trandafirului'], ['Fyodor Dostoevsky', 'Crime and Punishment'],\n ['Erich Maria Remarque', 'Soroc de viata si soroc de moarte'], ['Boualem Sansal', 'Satul Neamtului'],\n ['Fyodor Dostoevsky', 'Idiotul'], ['Nicolas Bouvier', 'Cronica Japoneza'],\n ['André Gide', 'Les Faux-monnayeurs'],\n ['Hermann Hesse', 'Narcis si Gura-de-Aur'], ['André Gide', 'Les Faux-monnayeurs'],\n ['Marin Preda', 'Cel mai iubit dintre pamanteni'],\n ['J. D. Salinger', 'Franny and Zooey'], ['Tom Hanks', 'Caractere atipice'],\n ['Pisica Cara', 'Miau Miau'], ['Crabul Clachi', 'Clac Clac'], ['Cezar Petrescu', 'Fram, ursul polar'],\n ['Marin Sorescu', 'Trei diniti din fata'], ['A.E. Baconsky', 'Biserica Neagra'],\n ['Hermann Hesse', 'Jocul cu margele de sticla']]\n\n book = random.choice(books)\n return random.randint(10, 99), book[1], book[0]\n\n\ndef random_client():\n clients = ['Alex', 'Alexandra', 'Adriana', 'Adrian', 'Maria', 'Marian', 'Bianca', 'Mihai', 'Mihaela', 'Andrei',\n 'Andreea', 'Miruna', 'Liliana', 'Diana', 'Daniel', 'Daniela', 'George', 'Georgiana', 'Ionut']\n id_client = random.randint(10, 99)\n client_name = random.choice(clients)\n return id_client, client_name\n\n\ndef random_rental():\n id_rental = random.randint(10, 99)\n id_book = random.randint(10, 99)\n id_client = random.randint(0, 20)\n rented_date = '{0}.{1}.{2}'.format(random.randint(1, 31), random.randint(1, 12), random.randint(2015, 2017))\n returned_date = '{0}.{1}.{2}'.format(random.randint(1, 31), random.randint(1, 12), random.randint(2018, 2020))\n return id_rental, id_book, id_client, rented_date, returned_date\n\n\n","sub_path":"HW10 - Library Update + Iterable data sturcture/Service/myrandom.py","file_name":"myrandom.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"284037268","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom skimage.feature import hog\n#HOG SUBSAMPLE\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nimport cv2\nfrom sklearn.preprocessing import StandardScaler\nfrom window import *\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import LinearSVC\nfrom sklearn.preprocessing import StandardScaler\nfrom skimage.feature import hog\nfrom scipy.ndimage.measurements import label\nfrom settings import *\nfrom feature import *\nfrom load_data import *\nfrom train import *\n\n\ndef add_heat(heatmap, bbox_list):\n # Iterate through list of bboxes\n for box in bbox_list:\n # Add += 1 for all pixels inside each bbox\n # Assuming each \"box\" takes the form ((x1, y1), (x2, y2))\n heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1\n\n # Return updated heatmap\n return heatmap# Iterate through list of bboxes\n \ndef apply_threshold(heatmap, threshold):\n # Zero out pixels below the threshold\n heatmap[heatmap <= threshold] = 0\n # Return thresholded map\n return heatmap\n\n# Draw bounding boxes based on labels\ndef draw_labeled_bboxes(img, labels):\n\t# Iterate through all detected cars\n\tfor car_number in range(1, labels[1]+1):\n\t\t# Find pixels with each car_number label value\n\t\tnonzero = (labels[0] == car_number).nonzero()\n\n\t\t# Identify x and y values of those pixels\n\t\tnonzeroy = np.array(nonzero[0])\n\t\tnonzerox = np.array(nonzero[1])\n\n\t\t# Define a bounding box based on min/max x and y\n\t\tbbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))\n\t\tbbox_w = (bbox[1][0] - bbox[0][0])\n\t\tbbox_h = (bbox[1][1] - bbox[0][1])\n\n\t\t# Filter final detections for aspect ratios, e.g. thin vertical box is likely not a car\n\t\taspect_ratio = bbox_w / bbox_h # width / height\n\t\t#print('ar: %s' % (aspect_ratio,))\n\n\t\t# Also if small box \"close\" to the car (i.e. bounding box y location is high),\n\t\t# then probaby not a car\n\t\tbbox_area = bbox_w * bbox_h\n\n\t\tif bbox_area < small_bbox_area and bbox[0][1] > close_y_thresh:\n\t\t\tsmall_box_close = True\n\t\telse:\n\t\t\tsmall_box_close = False\n\n\t\t# Combine above filters with minimum bbox area filter\n\t\tif aspect_ratio > min_ar and aspect_ratio < max_ar and not small_box_close and bbox_area > min_bbox_area:\n\t\t\t# Draw the box on the image\n\t\t\tcv2.rectangle(img, bbox[0], bbox[1], (0,0,255), 6)\n\n\t# Return the image\n\treturn img\n\n\nif __name__ == '__main__':\n\tsvc = LinearSVC()\n\tX_scaler = StandardScaler()\n\n\tif use_pretrained:\n\t\twith open('model.p', 'rb') as f:\n\t\t\tsave_dict = pickle.load(f)\n\t\tsvc = save_dict['svc']\n\t\tX_scaler = save_dict['X_scaler']\n\n\t\tprint('Loaded pre-trained model from model.p')\n\telse:\n\t\tprint('Reading training data and training classifier from scratch')\n\n\t\t# with open('data.p', 'rb') as f:\n\t\t# \tdata = pickle.load(f)\n\t\t# cars = data['vehicles']\n\t\t# notcars = data['non_vehicles']\n\t\tcars, notcars = load_data()\n\t\ttrain(cars, notcars, svc, X_scaler)\n\n\t\tprint('Training complete, saving trained model to model.p')\n\n\t\twith open('model.p', 'wb') as f:\n\t\t\tpickle.dump({'svc': svc, 'X_scaler': X_scaler}, f)\n\n\t# Display predictions on all test_images\n\timdir = 'test_images'\n\tfor image_file in os.listdir(imdir):\n\t\timage = mpimg.imread(os.path.join(imdir, image_file))\n\t\tdraw_image = np.copy(image)\n\n\t\twindows = slide_window(image, x_start_stop=(0, 1280), y_start_stop=(400, 656),\n\t\t\t\t\t\txy_window=(96, 96), xy_overlap=(pct_overlap, pct_overlap))\n\t\t# windows = slide_window(image, x_start_stop=(0, 1280), y_start_stop=(400, 500),\n\t\t# \t\t\t\txy_window=(96, 96), xy_overlap=(pct_overlap, pct_overlap))\n\n\t\thot_windows = search_windows(image, windows, svc, X_scaler, color_space=color_space,\n\t\t\t\t\t\t\t\tspatial_size=spatial_size, hist_bins=hist_bins,\n\t\t\t\t\t\t\t\torient=orient, pix_per_cell=pix_per_cell,\n\t\t\t\t\t\t\t\tcell_per_block=cell_per_block,\n\t\t\t\t\t\t\t\thog_channel=hog_channel, spatial_feat=spatial_feat,\n\t\t\t\t\t\t\t\thist_feat=hist_feat, hog_feat=hog_feat)\n\n\t\twindow_img = draw_boxes(draw_image, hot_windows, color=(0, 0, 255), thick=6)\n\n\t\tplt.imshow(window_img)\n\t\tplt.show()\n\n\t\t# Calculate and draw heat map\n\t\theatmap = np.zeros((720, 1280)) # NOTE: Image dimensions hard-coded\n\t\theatmap = add_heat(heatmap, hot_windows)\n\t\theatmap = apply_threshold(heatmap, heatmap_thresh)\n\t\tlabels = label(heatmap)\n\t\tprint(labels[1], 'cars found')\n\t\tplt.imshow(labels[0], cmap='gray')\n\t\tplt.show()\n\t\tplt.savefig('cars_found')\n\n\t\t# Draw final bounding boxes\n\t\tdraw_img = draw_labeled_bboxes(np.copy(image), labels)\n\t\tplt.imshow(draw_img)\n\t\tplt.show()\n\t\tplt.savefig('bounding_boxes')\n","sub_path":"heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":4602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"137726094","text":"import random\nimport itertools\ndef make_deck():\n suit = 'HSDC'\n rank = 'A23456789XJQK'\n deck = [''.join(card) for card in itertools.product(rank, suit)]\n return deck\ndeck = make_deck()\nrandom.shuffle(deck)\ndef deal_cards(deck, players):\n hands = []\n for m in range(players):\n playercards = []\n for n in range(4):\n cards = deck.pop(0)\n playercards.append(cards)\n hands.append(playercards)\n return hands\nprint(deal_cards(deck, 13))\n\n\n\n","sub_path":"Lab6.py","file_name":"Lab6.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"488537306","text":"# GENOCIDE OTP-CR-117/19\n# -*- coding: utf-8 -*-\n#\n\n\n\"Prosecutor. Court. Reconsider OTP-CR-117/19.\"\n\n\n__name__ = \"president\"\n__version__ = \"111\"\n\n\nimport doctest\nimport os\nimport sys\nimport unittest\n\n\nsys.setrecursionlimit(1500)\n\n\ncurdir = os.getcwd()\n\n\nsys.path.insert(0, os.path.join(curdir))\nsys.path.insert(0, os.path.join(curdir, \"..\"))\nsys.path.insert(0, os.path.join(curdir, \"..\", \"..\"))\n\n\n# -- Options for GENERIC output ---------------------------------------------\n\n\nproject = __name__\nmaster_doc = 'index'\nversion = '%s' % __version__\nrelease = '%s' % __version__\nlanguage = 'utf-8'\ntoday = ''\ntoday_fmt = '%B %d, %Y'\nneeds_sphinx='1.7'\nexclude_patterns = ['_build', '_templates', '_source', 'Thumbs.db', '.DS_Store']\nsource_suffix = '.rst'\nsource_encoding = 'utf-8-sig'\nmodindex_common_prefix = [\"\"]\nkeep_warnings = True\ntemplates_path=['_templates']\nadd_function_parentheses = False\nadd_module_names = False\nshow_authors = False\npygments_style = 'colorful'\nextensions=[\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.doctest',\n 'sphinx.ext.viewcode',\n 'sphinx.ext.todo',\n 'sphinx.ext.githubpages'\n]\n\n\n# -- Options for HTML output -------------------------------------------------\n\n\nhtml_title = \"Prosecutor. Court. Reconsider OTP-CR-117/19.\"\nhtml_style = 'president.css'\nhtml_static_path = [\"_static\"]\nhtml_css_files = [\"president.css\",]\nhtml_short_title = \"PRESIDENT %s\" % __version__\nhtml_sidebars = {\n '**': [\n 'about.html',\n 'searchbox.html',\n 'navigation.html',\n 'relations.html',\n ]\n}\nhtml_theme = \"alabaster\"\nhtml_theme_options = {\n 'github_user': 'bthate',\n 'github_repo': __name__,\n 'github_button': False,\n 'github_banner': False,\n 'logo': 'aes.ico',\n 'link': '#000',\n 'link_hover': '#000',\n 'nosidebar': True,\n 'show_powered_by': False,\n 'show_relbar_top': False,\n 'sidebar_width': 0,\n}\nhtml_favicon = \"aes.ico\"\nhtml_extra_path = [\"robots.txt\"]\nhtml_last_updated_fmt = '%Y-%b-%d'\nhtml_additional_pages = {}\nhtml_domain_indices = False\nhtml_use_index = False\nhtml_split_index = False\nhtml_show_sourcelink = False\nhtml_show_sphinx = False\nhtml_show_copyright = False\nhtml_copy_source = False\nhtml_use_opensearch = 'http://%s.rtfd.io/' % __name__\nhtml_file_suffix = '.html'\nhtmlhelp_basename = 'testdoc'\n\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3', 'objects.inv'),\n 'sphinx': ('http://sphinx.pocoo.org/', None),\n }\nintersphinx_cache_limit=1\n\n\nrst_prolog = '''.. image:: bewijsgif4.jpg\n :width: 100%\n :height: 2.6cm\n :target: index.html\n\n\n.. raw:: html\n\n
\n\n'''\n\n\nrst_epilog = '''.. raw:: html\n\n
\n
\n \n\n:ref:`home ` - :ref:`manual ` - :ref:`source ` - :ref:`about `\n\n.. raw:: html\n\n \n
\n'''\n\n\nautosummary_generate=True\nautodoc_default_flags=['members', 'undoc-members', 'private-members', \"imported-members\"]\nautodoc_member_order='groupwise'\nautodoc_docstring_signature=True\nautoclass_content=\"class\"\ndoctest_global_setup=\"\"\ndoctest_global_cleanup=\"\"\ndoctest_test_doctest_blocks=\"default\"\ntrim_doctest_flags=True\ndoctest_flags=doctest.REPORT_UDIFF\nnitpick_ignore=[\n ('py:class', 'builtins.BaseException'),\n ]\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"619867886","text":"import collections\nimport copy\nimport csv\nimport gc\nimport io\nimport json\nfrom typing import List, Tuple\n\nimport flask\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numba as nb\nimport numpy as np\nimport qrcode\nimport requests_cache\nfrom spectrum_utils import plot as sup, spectrum as sus\n\nimport parsing\n\nmatplotlib.use('Agg')\n\nrequests_cache.install_cache('demo_cache', expire_after=300)\n\nUSI_SERVER = 'https://metabolomics-usi.ucsd.edu/'\n\ndefault_plotting_args = {\n 'width': 10,\n 'height': 6,\n 'max_intensity_unlabeled': 1.05,\n 'max_intensity_labeled': 1.25,\n 'max_intensity_mirror_labeled': 1.50,\n 'grid': True,\n # List of peaks to annotate in the top/bottom\n # spectrum.\n 'annotate_peaks': [True, True],\n 'annotate_threshold': 0.1,\n 'annotate_precision': 4,\n 'annotation_rotation': 90,\n 'cosine': 'standard',\n 'fragment_mz_tolerance': 0.02\n}\n\nblueprint = flask.Blueprint('ui', __name__)\n\n\nSpectrumTuple = collections.namedtuple(\n 'SpectrumTuple', ['precursor_mz', 'precursor_charge', 'mz', 'intensity'])\n\n\n@blueprint.route('/', methods=['GET'])\ndef render_homepage():\n return flask.render_template('homepage.html')\n\n\n@blueprint.route('/contributors', methods=['GET'])\ndef render_contributors():\n return flask.render_template('contributors.html')\n\n\n@blueprint.route('/heartbeat', methods=['GET'])\ndef render_heartbeat():\n return json.dumps({'status': 'success'})\n\n\n@blueprint.route('/spectrum/', methods=['GET'])\ndef render_spectrum():\n spectrum, source_link = parsing.parse_usi(flask.request.args.get('usi'))\n spectrum = copy.deepcopy(spectrum)\n spectrum.scale_intensity(max_intensity=1)\n return flask.render_template(\n 'spectrum.html',\n usi=flask.request.args.get('usi'),\n source_link=source_link,\n peaks=[\n _get_peaks(spectrum),\n ],\n annotations=[\n _generate_labels(spectrum),\n ],\n )\n\n\n@blueprint.route('/mirror/', methods=['GET'])\ndef render_mirror_spectrum():\n spectrum1, source1 = parsing.parse_usi(flask.request.args.get('usi1'))\n spectrum1 = copy.deepcopy(spectrum1)\n spectrum1.scale_intensity(max_intensity=1)\n spectrum2, source2 = parsing.parse_usi(flask.request.args.get('usi2'))\n spectrum2 = copy.deepcopy(spectrum2)\n spectrum2.scale_intensity(max_intensity=1)\n return flask.render_template(\n 'mirror.html',\n usi1=flask.request.args.get('usi1'),\n usi2=flask.request.args.get('usi2'),\n source_link1=source1,\n source_link2=source2,\n peaks=[\n _get_peaks(spectrum1),\n _get_peaks(spectrum2),\n ],\n annotations=[\n _generate_labels(spectrum1),\n _generate_labels(spectrum2),\n ],\n )\n\n\n@blueprint.route('/png/')\ndef generate_png():\n usi = flask.request.args.get('usi')\n plotting_args = _get_plotting_args(flask.request)\n buf = _generate_figure(usi, 'png', **plotting_args)\n return flask.send_file(buf, mimetype='image/png')\n\n\n@blueprint.route('/png/mirror/')\ndef generate_mirror_png():\n usi1 = flask.request.args.get('usi1')\n usi2 = flask.request.args.get('usi2')\n plot_pars = _get_plotting_args(flask.request, mirror=True)\n buf = _generate_mirror_figure(usi1, usi2, 'png', **plot_pars)\n return flask.send_file(buf, mimetype='image/png')\n\n\n@blueprint.route('/svg/')\ndef generate_svg():\n usi = flask.request.args.get('usi')\n plot_pars = _get_plotting_args(flask.request)\n buf = _generate_figure(usi, 'svg', **plot_pars)\n return flask.send_file(buf, mimetype='image/svg+xml')\n\n\n@blueprint.route('/svg/mirror/')\ndef generate_mirror_svg():\n usi1 = flask.request.args.get('usi1')\n usi2 = flask.request.args.get('usi2')\n plot_pars = _get_plotting_args(flask.request, mirror=True)\n buf = _generate_mirror_figure(usi1, usi2, 'svg', **plot_pars)\n return flask.send_file(buf, mimetype='image/svg+xml')\n\n\ndef _generate_figure(usi: str, extension: str, **kwargs) -> io.BytesIO:\n fig, ax = plt.subplots(figsize=(kwargs['width'], kwargs['height']))\n\n kwargs['annotate_peaks'] = kwargs['annotate_peaks'][0]\n spectrum = _prepare_spectrum(usi, **kwargs)\n sup.spectrum(\n spectrum,\n annotate_ions=kwargs['annotate_peaks'],\n annot_kws={'rotation': kwargs['annotation_rotation'], 'clip_on': True},\n grid=kwargs['grid'], ax=ax,\n )\n\n ax.set_xlim(kwargs['mz_min'], kwargs['mz_max'])\n ax.set_ylim(0, kwargs['max_intensity'])\n\n if not kwargs['grid']:\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\n title = ax.text(0.5, 1.06, usi, horizontalalignment='center',\n verticalalignment='bottom', fontsize='x-large',\n fontweight='bold', transform=ax.transAxes)\n title.set_url(f'{USI_SERVER}spectrum/?usi={usi}')\n subtitle = (f'Precursor m/z: '\n f'{spectrum.precursor_mz:.{kwargs[\"annotate_precision\"]}f} '\n if spectrum.precursor_mz > 0 else '')\n subtitle += f'Charge: {spectrum.precursor_charge}'\n subtitle = ax.text(0.5, 1.02, subtitle, horizontalalignment='center',\n verticalalignment='bottom', fontsize='large',\n transform=ax.transAxes)\n subtitle.set_url(f'{USI_SERVER}spectrum/?usi={usi}')\n\n buf = io.BytesIO()\n plt.savefig(buf, bbox_inches='tight', format=extension)\n buf.seek(0)\n fig.clear()\n plt.close(fig)\n gc.collect()\n\n return buf\n\n\ndef _generate_mirror_figure(usi1: str, usi2: str, extension: str, **kwargs) \\\n -> io.BytesIO:\n fig, ax = plt.subplots(figsize=(kwargs['width'], kwargs['height']))\n\n annotate_peaks = kwargs['annotate_peaks']\n kwargs['annotate_peaks'] = annotate_peaks[0]\n spectrum_top = _prepare_spectrum(usi1, **kwargs)\n kwargs['annotate_peaks'] = annotate_peaks[1]\n spectrum_bottom = _prepare_spectrum(usi2, **kwargs)\n\n fragment_mz_tolerance = kwargs['fragment_mz_tolerance']\n\n if kwargs['cosine']:\n # Initialize the annotations as unmatched.\n if spectrum_top.annotation is None:\n spectrum_top.annotation = np.full_like(\n spectrum_top.mz, None, object)\n if spectrum_bottom.annotation is None:\n spectrum_bottom.annotation = np.full_like(\n spectrum_bottom.mz, None, object)\n for annotation in spectrum_top.annotation:\n if annotation is not None:\n annotation.ion_type = 'unmatched'\n for annotation in spectrum_bottom.annotation:\n if annotation is not None:\n annotation.ion_type = 'unmatched'\n # Assign the matching peak annotations.\n similarity, peak_matches = cosine(\n spectrum_top, spectrum_bottom, fragment_mz_tolerance,\n kwargs['cosine'] == 'shifted')\n for top_i, bottom_i in peak_matches:\n if spectrum_top.annotation[top_i] is None:\n spectrum_top.annotation[top_i] = sus.FragmentAnnotation(\n 0, spectrum_top.mz[top_i], '')\n spectrum_top.annotation[top_i].ion_type = 'top'\n if spectrum_bottom.annotation[bottom_i] is None:\n spectrum_bottom.annotation[bottom_i] = sus.FragmentAnnotation(\n 0, spectrum_bottom.mz[bottom_i], '')\n spectrum_bottom.annotation[bottom_i].ion_type = 'bottom'\n else:\n similarity = 0\n\n # Colors for mirror plot peaks, subject to change.\n sup.colors['top'] = '#212121'\n sup.colors['bottom'] = '#388E3C'\n sup.colors['unmatched'] = 'darkgray'\n\n sup.mirror(spectrum_top, spectrum_bottom,\n {'annotate_ions': kwargs['annotate_peaks'],\n 'annot_kws': {'rotation': kwargs['annotation_rotation'],\n 'clip_on': True},\n 'grid': kwargs['grid']}, ax=ax)\n\n ax.set_xlim(kwargs['mz_min'], kwargs['mz_max'])\n ax.set_ylim(-kwargs['max_intensity'], kwargs['max_intensity'])\n\n if not kwargs['grid']:\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\n text_y = 1.2 if kwargs['cosine'] else 1.15\n for usi, spec, loc in zip([usi1, usi2], [spectrum_top, spectrum_bottom],\n ['Top', 'Bottom']):\n title = ax.text(0.5, text_y, f'{loc}: {usi}',\n horizontalalignment='center',\n verticalalignment='bottom',\n fontsize='x-large',\n fontweight='bold',\n transform=ax.transAxes)\n title.set_url(f'{USI_SERVER}mirror/?usi1={usi1}&usi2={usi2}')\n text_y -= 0.04\n subtitle = (\n f'Precursor $m$/$z$: '\n f'{spec.precursor_mz:.{kwargs[\"annotate_precision\"]}f} '\n if spec.precursor_mz > 0 else '')\n subtitle += f'Charge: {spec.precursor_charge}'\n subtitle = ax.text(0.5, text_y, subtitle, horizontalalignment='center',\n verticalalignment='bottom', fontsize='large',\n transform=ax.transAxes)\n subtitle.set_url(f'{USI_SERVER}mirror/?usi1={usi1}&usi2={usi2}')\n text_y -= 0.06\n\n if kwargs['cosine']:\n subtitle_score = f'Cosine similarity = {similarity:.4f}'\n ax.text(0.5, text_y, subtitle_score, horizontalalignment='center',\n verticalalignment='bottom', fontsize='x-large',\n fontweight='bold', transform=ax.transAxes)\n\n buf = io.BytesIO()\n plt.savefig(buf, bbox_inches='tight', format=extension)\n buf.seek(0)\n fig.clear()\n plt.close(fig)\n gc.collect()\n\n return buf\n\n\ndef cosine(spectrum1: sus.MsmsSpectrum, spectrum2: sus.MsmsSpectrum,\n fragment_mz_tolerance: float, allow_shift: bool) \\\n -> Tuple[float, List[Tuple[int, int]]]:\n \"\"\"\n Compute the cosine similarity between the given spectra.\n\n Parameters\n ----------\n spectrum1 : sus.MsmsSpectrum\n The first spectrum.\n spectrum2 : sus.MsmsSpectrum\n The second spectrum.\n fragment_mz_tolerance : float\n The fragment m/z tolerance used to match peaks.\n allow_shift : bool\n Boolean flag indicating whether to allow peak shifts or not.\n\n Returns\n -------\n Tuple[float, List[Tuple[int, int]]]\n A tuple consisting of (i) the cosine similarity between both spectra,\n and (ii) the indexes of matching peaks in both spectra.\n \"\"\"\n spec_tup1 = SpectrumTuple(\n spectrum1.precursor_mz, spectrum1.precursor_charge, spectrum1.mz,\n np.copy(spectrum1.intensity) / np.linalg.norm(spectrum1.intensity))\n spec_tup2 = SpectrumTuple(\n spectrum2.precursor_mz, spectrum2.precursor_charge, spectrum2.mz,\n np.copy(spectrum2.intensity) / np.linalg.norm(spectrum2.intensity))\n return _cosine(spec_tup1, spec_tup2, fragment_mz_tolerance, allow_shift)\n\n\n@nb.njit\ndef _cosine(spec: SpectrumTuple, spec_other: SpectrumTuple,\n fragment_mz_tolerance: float, allow_shift: bool) \\\n -> Tuple[float, List[Tuple[int, int]]]:\n \"\"\"\n Compute the cosine similarity between the given spectra.\n\n Parameters\n ----------\n spec : SpectrumTuple\n Numba-compatible tuple containing information from the first spectrum.\n spec_other : SpectrumTuple\n Numba-compatible tuple containing information from the second spectrum.\n fragment_mz_tolerance : float\n The fragment m/z tolerance used to match peaks in both spectra with\n each other.\n allow_shift : bool\n Boolean flag indicating whether to allow peak shifts or not.\n\n Returns\n -------\n Tuple[float, List[Tuple[int, int]]]\n A tuple consisting of (i) the cosine similarity between both spectra,\n and (ii) the indexes of matching peaks in both spectra.\n \"\"\"\n # Find the matching peaks between both spectra, optionally allowing for\n # shifted peaks.\n # Candidate peak indices depend on whether we allow shifts\n # (check all shifted peaks as well) or not.\n # Account for unknown precursor charge (default: 1).\n precursor_charge = max(spec.precursor_charge, 1)\n precursor_mass_diff = ((spec.precursor_mz - spec_other.precursor_mz)\n * precursor_charge)\n # Only take peak shifts into account if the mass difference is relevant.\n num_shifts = 1\n if allow_shift and abs(precursor_mass_diff) >= fragment_mz_tolerance:\n num_shifts += precursor_charge\n other_peak_index = np.zeros(num_shifts, np.uint16)\n mass_diff = np.zeros(num_shifts, np.float32)\n for charge in range(1, num_shifts):\n mass_diff[charge] = precursor_mass_diff / charge\n\n # Find the matching peaks between both spectra.\n peak_match_scores, peak_match_idx = [], []\n for peak_index, (peak_mz, peak_intensity) in enumerate(zip(\n spec.mz, spec.intensity)):\n # Advance while there is an excessive mass difference.\n for cpi in range(num_shifts):\n while (other_peak_index[cpi] < len(spec_other.mz) - 1 and\n (peak_mz - fragment_mz_tolerance >\n spec_other.mz[other_peak_index[cpi]] + mass_diff[cpi])):\n other_peak_index[cpi] += 1\n # Match the peaks within the fragment mass window if possible.\n for cpi in range(num_shifts):\n index = 0\n other_peak_i = other_peak_index[cpi] + index\n while (other_peak_i < len(spec_other.mz) and\n abs(peak_mz - (spec_other.mz[other_peak_i]\n + mass_diff[cpi])) <= fragment_mz_tolerance):\n peak_match_scores.append(\n peak_intensity * spec_other.intensity[other_peak_i])\n peak_match_idx.append((peak_index, other_peak_i))\n index += 1\n other_peak_i = other_peak_index[cpi] + index\n\n score, peak_matches = 0., []\n if len(peak_match_scores) > 0:\n # Use the most prominent peak matches to compute the score (sort in\n # descending order).\n peak_match_scores_arr = np.asarray(peak_match_scores)\n peak_match_order = np.argsort(peak_match_scores_arr)[::-1]\n peak_match_scores_arr = peak_match_scores_arr[peak_match_order]\n peak_match_idx_arr = np.asarray(peak_match_idx)[peak_match_order]\n peaks_used, other_peaks_used = set(), set()\n for peak_match_score, peak_i, other_peak_i in zip(\n peak_match_scores_arr, peak_match_idx_arr[:, 0],\n peak_match_idx_arr[:, 1]):\n if (peak_i not in peaks_used\n and other_peak_i not in other_peaks_used):\n score += peak_match_score\n # Save the matched peaks.\n peak_matches.append((peak_i, other_peak_i))\n # Make sure these peaks are not used anymore.\n peaks_used.add(peak_i)\n other_peaks_used.add(other_peak_i)\n\n return score, peak_matches\n\n\ndef _prepare_spectrum(usi: str, **kwargs) -> sus.MsmsSpectrum:\n spectrum, _ = parsing.parse_usi(usi)\n spectrum = copy.deepcopy(spectrum)\n spectrum.scale_intensity(max_intensity=1)\n\n if kwargs['annotate_peaks']:\n if kwargs['annotate_peaks'] is True:\n kwargs['annotate_peaks'] = spectrum.mz[_generate_labels(spectrum)]\n for mz in kwargs['annotate_peaks']:\n t = f'{mz:.{kwargs[\"annotate_precision\"]}f}'\n spectrum.annotate_mz_fragment(\n mz, 0, kwargs['fragment_mz_tolerance'], 'Da', text=t)\n\n spectrum.set_mz_range(kwargs['mz_min'], kwargs['mz_max'])\n spectrum.scale_intensity(max_intensity=1)\n\n return spectrum\n\n\ndef _get_peaks(spectrum: sus.MsmsSpectrum) -> List[Tuple[float, float]]:\n return [\n (float(mz), float(intensity))\n for mz, intensity in zip(spectrum.mz, spectrum.intensity)\n ]\n\n\ndef _generate_labels(spec, intensity_threshold=None):\n if intensity_threshold is None:\n intensity_threshold = default_plotting_args['annotate_threshold']\n mz_exclusion_window = (spec.mz[-1] - spec.mz[0]) / 20 # Max 20 labels.\n\n # Annotate peaks in decreasing intensity order.\n labeled_i, order = [], np.argsort(spec.intensity)[::-1]\n for i, mz, intensity in zip(order, spec.mz[order], spec.intensity[order]):\n if intensity < intensity_threshold:\n break\n if not any(\n abs(mz - spec.mz[already_labeled_i]) <= mz_exclusion_window\n for already_labeled_i in labeled_i\n ):\n labeled_i.append(i)\n\n return labeled_i\n\n\ndef _get_plotting_args(request, mirror=False):\n plotting_args = {}\n width = request.args.get('width')\n plotting_args['width'] = (default_plotting_args['width']\n if width is None else float(width))\n height = request.args.get('height')\n plotting_args['height'] = (default_plotting_args['height']\n if height is None else float(height))\n mz_min = request.args.get('mz_min')\n plotting_args['mz_min'] = float(mz_min) if mz_min else None\n mz_max = request.args.get('mz_max')\n plotting_args['mz_max'] = float(mz_max) if mz_max else None\n grid = request.args.get('grid')\n plotting_args['grid'] = (default_plotting_args['grid']\n if grid is None else grid == 'true')\n annotate_peaks_args = request.args.get('annotate_peaks')\n annotate_peaks = ([[mz for mz in peaks]\n for peaks in json.loads(annotate_peaks_args)]\n if annotate_peaks_args is not None else\n default_plotting_args['annotate_peaks'])\n plotting_args['annotate_peaks'] = annotate_peaks\n annotate_precision = request.args.get('annotate_precision')\n plotting_args['annotate_precision'] = (\n default_plotting_args['annotate_precision']\n if not annotate_precision else int(annotate_precision))\n annotation_rotation = request.args.get('annotation_rotation')\n plotting_args['annotation_rotation'] = (\n default_plotting_args['annotation_rotation']\n if not annotation_rotation else float(annotation_rotation))\n max_intensity = request.args.get('max_intensity')\n # Explicitly specified maximum intensity.\n if max_intensity:\n plotting_args['max_intensity'] = float(max_intensity) / 100\n # Default labeled maximum intensity.\n elif any(annotate_peaks):\n # Default mirror plot labeled maximum intensity.\n if mirror:\n plotting_args['max_intensity'] = \\\n default_plotting_args['max_intensity_mirror_labeled']\n # Default standard plot labeled maximum intensity.\n else:\n plotting_args['max_intensity'] = \\\n default_plotting_args['max_intensity_labeled']\n # Default unlabeled maximum intensity.\n else:\n plotting_args['max_intensity'] = \\\n default_plotting_args['max_intensity_unlabeled']\n cosine_type = request.args.get('cosine')\n plotting_args['cosine'] = (default_plotting_args['cosine']\n if cosine_type is None else cosine_type)\n if plotting_args['cosine'] == 'off':\n plotting_args['cosine'] = False\n fragment_mz_tolerance = request.args.get('fragment_mz_tolerance')\n plotting_args['fragment_mz_tolerance'] = (\n default_plotting_args['fragment_mz_tolerance']\n if fragment_mz_tolerance is None else float(fragment_mz_tolerance))\n\n return plotting_args\n\n\n@blueprint.route('/json/')\ndef peak_json():\n try:\n spectrum, _ = parsing.parse_usi(flask.request.args.get('usi'))\n # Return for JSON includes, peaks, n_peaks, and precursor_mz.\n result_dict = {\n 'peaks': _get_peaks(spectrum),\n 'n_peaks': len(spectrum.mz),\n 'precursor_mz': spectrum.precursor_mz}\n except ValueError as e:\n result_dict = {'error': {'code': 404,\n 'message': str(e)}}\n return flask.jsonify(result_dict)\n\n\n@blueprint.route('/api/proxi/v0.1/spectra')\ndef peak_proxi_json():\n try:\n spectrum, _ = parsing.parse_usi(flask.request.args.get('usi'))\n result_dict = {\n 'intensities': spectrum.intensity.tolist(),\n 'mzs': spectrum.mz.tolist(),\n 'attributes': [\n {\n 'accession': 'MS:1000744',\n 'name': 'selected ion m/z',\n 'value': float(spectrum.precursor_mz)\n },\n {\n 'accession': 'MS:1000041',\n 'name': 'charge state',\n 'value': int(spectrum.precursor_charge)\n }\n ]\n }\n except ValueError as e:\n result_dict = {'error': {'code': 404,\n 'message': str(e)}}\n\n return flask.jsonify([result_dict])\n\n\n@blueprint.route('/csv/')\ndef peak_csv():\n spectrum, _ = parsing.parse_usi(flask.request.args.get('usi'))\n csv_str = io.StringIO()\n writer = csv.writer(csv_str)\n writer.writerow(['mz', 'intensity'])\n for mz, intensity in zip(spectrum.mz, spectrum.intensity):\n writer.writerow([mz, intensity])\n csv_bytes = io.BytesIO()\n csv_bytes.write(csv_str.getvalue().encode('utf-8'))\n csv_bytes.seek(0)\n return flask.send_file(csv_bytes, mimetype='text/csv', as_attachment=True,\n attachment_filename=f'{spectrum.identifier}.csv')\n\n\n@blueprint.route('/qrcode/')\ndef generate_qr():\n # QR Code Rendering.\n if flask.request.args.get('mirror') != 'true':\n usi = flask.request.args.get('usi')\n url = f'{USI_SERVER}spectrum/?usi={usi}'\n else:\n usi1 = flask.request.args.get('usi1')\n usi2 = flask.request.args.get('usi2')\n url = f'{USI_SERVER}mirror/?usi1={usi1}&usi2={usi2}'\n qr_image = qrcode.make(url, box_size=2)\n qr_bytes = io.BytesIO()\n qr_image.save(qr_bytes, format='PNG')\n qr_bytes.seek(0)\n return flask.send_file(qr_bytes, 'image/png')\n\n\n@blueprint.errorhandler(Exception)\ndef internal_error(error):\n return flask.render_template('500.html', error=error), 500\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":22312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"474115220","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n# 需要更改的参数\ncurrent_season = '17t18'\n\nimport pymysql.cursors\nimport datetime\nimport json\nimport pdb\n\nnowadays = datetime.datetime.now().strftime('%Y_%m_%d')\nnowatime = datetime.datetime.now().strftime('%Y_%m_%d_%H%M')\n\nclass AutoTeamsAnalysisPipeline(object):\n def process_item(self, item, spider):\n if spider.name == 'auto_teams_analysis':\n # 这里写爬虫 odds_spider 的逻辑\n match_list = item['match_list']\n # 获取查询日期\n search_date = item['search_date']\n # Connect to the database\n db_name = 'auto_teams_analysis'\n config = {\n 'host': '127.0.0.1',\n 'user': 'root',\n 'password': '19940929',\n 'db': db_name,\n 'charset': 'utf8mb4',\n 'cursorclass': pymysql.cursors.DictCursor\n }\n connection = pymysql.connect(**config)\n print('连接至数据库' + db_name)\n try:\n with connection.cursor() as cursor:\n tableName = 'teams_' + search_date # 表名\n # 建立当前队伍表\n build_table = (\n \"CREATE TABLE IF NOT EXISTS \"' %s '\"\"\n \"(match_id VARCHAR(20) NOT NULL PRIMARY KEY,\"\n \"match_name VARCHAR(50) NOT NULL,\"\n \"home_name VARCHAR(50) NOT NULL,\"\n \"away_name VARCHAR(50) NOT NULL,\"\n \"time_score VARCHAR(50) NOT NULL,\"\n \"home_rate FLOAT(8) NOT NULL,\"\n \"away_rate FLOAT(8) NOT NULL,\"\n \"average_completed_match INT(8) NOT NULL,\"\n \"support_direction VARCHAR(50) NOT NULL)\"\n )\n cursor.execute(build_table % tableName)\n # 建表完成\n # pdb.set_trace()\n for single_match in match_list:\n cursor.execute('SELECT match_id FROM %s WHERE match_id=\"%s\"' % (tableName, single_match['match_id']))\n table_row_len = len(cursor.fetchall())\n print('analysis 表中存在查询数据的数目::', table_row_len)\n insert_sql = (\n \"INSERT INTO \" + tableName + \" VALUES \"\n \"('%s', '%s', '%s', '%s', '%s', '%f', '%f','%d', '%s')\"\n )\n try:\n if table_row_len < 1:\n print('insert数据库')\n cursor.execute(insert_sql % (\n single_match['match_id'], single_match['match_name'], single_match['home_name'], single_match['away_name'],\n single_match['time_score'],\n single_match['home_rate'], single_match['away_rate'],\n single_match['average_completed_match'],\n single_match['support_direction']))\n else:\n update_sql = (\n 'UPDATE %s SET time_score=\"%s\",support_direction=\"%s\" WHERE match_id=\"%s\"'\n )\n print('update信息')\n cursor.execute(update_sql % (\n tableName, single_match['time_score'], single_match['support_direction'], single_match['match_id']))\n except Exception as e:\n print(\"数据库执行失败 \", e)\n\n # connection is not autocommit by default. So you must commit to save your changes.\n cursor.close()\n if not connection.commit():\n connection.rollback()\n\n finally:\n connection.close()\n\n return item\n","sub_path":"auto_teams_analysis/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":4281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"428191795","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/coils/logic/workflow/actions/mail/send.py\n# Compiled at: 2012-10-12 07:02:39\nimport os\nfrom email import Encoders\nfrom email.Utils import COMMASPACE, formatdate\nfrom email.MIMEBase import MIMEBase\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom coils.core import *\nfrom coils.core.logic import ActionCommand\n\nclass SendMailAction(ActionCommand):\n __domain__ = 'action'\n __operation__ = 'send-mail'\n __aliases__ = ['sendMail', 'sendMailAction']\n\n def __init__(self):\n ActionCommand.__init__(self)\n\n def do_action(self):\n if self._attach == 'YES':\n message = MIMEMultipart()\n if self._body is not None:\n message.attach(MIMEText(self._body))\n else:\n message.attach(MIMEText(''))\n part = MIMEBase(self._mime.split('/')[0], self._mime.split('/')[1])\n part.set_payload(self.rfile.read())\n part.add_header('Content-Disposition', ('attachment; filename=\"{0}\"').format(self._partname))\n Encoders.encode_base64(part)\n message.attach(part)\n elif self._body is not None:\n message = MIMEText(self._body)\n else:\n message = MIMEText(self.rfile.read())\n message['Subject'] = self._subject\n message['From'] = self._from\n message['To'] = COMMASPACE.join(self._to)\n if len(self._cc):\n message['Cc'] = COMMASPACE.join(self._cc)\n message['Date'] = formatdate(localtime=True)\n if self.process.task_id:\n message['X-Opengroupware-Regarding'] = str(self.process.task_id)\n else:\n message['X-Opengroupware-Regarding'] = str(self.pid)\n message['X-Opengroupware-Process-Id'] = str(self.pid)\n message['X-Opengroupware-Context'] = ('{0}[{1}]').format(self._ctx.get_login(), self._ctx.account_id)\n addresses = []\n addresses.extend(self._to)\n addresses.extend(self._cc)\n addresses.extend(self._bcc)\n SMTP.send(self._from, addresses, message)\n return\n\n def parse_action_parameters(self):\n self._from = self.action_parameters.get('from', None)\n self._to = self.action_parameters.get('to', self._ctx.email)\n self._body = self.action_parameters.get('bodyText', None)\n self._cc = self.action_parameters.get('CC', '')\n self._bcc = self.action_parameters.get('BCC', '')\n self._attach = self.action_parameters.get('asAttachment', 'YES').upper()\n self._partname = self.action_parameters.get('filename', 'message.data')\n self._subject = self.action_parameters.get('subject', '')\n if self._to is None:\n raise CoilsException('Attempt to send e-mail with no destination!')\n self._from = self.process_label_substitutions(self._from)\n self._to = self.process_label_substitutions(self._to)\n self._to = self._to.split(',')\n self._cc = self.process_label_substitutions(self._cc)\n self._cc = self._cc.split(',')\n self._bcc = self.process_label_substitutions(self._bcc)\n self._bcc = self._bcc.split(',')\n if self._body is not None:\n self._body = self.process_label_substitutions(self._body)\n self._subject = self.process_label_substitutions(self._subject)\n self._partname = self.process_label_substitutions(self._partname)\n return\n\n def do_epilogue(self):\n pass","sub_path":"pycfiles/OpenGroupware-0.1.48-py2.6/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"196927759","text":"from textblob import Word, TextBlob, blob\r\nfrom application.artifacts.text_processing.variables import *\r\nimport nltk\r\nimport json\r\nimport datetime\r\n\r\ndef get_word(list):\r\n result = []\r\n for item in list:\r\n word = Word(item)\r\n result.append(word)\r\n return result\r\n\r\ndef get_string(list):\r\n keys = []\r\n for key in list:\r\n keys.append(key)\r\n return ' '.join(keys) \r\n\r\ndef get_blob(list):\r\n string = get_string(list)\r\n return TextBlob(string)\r\n\r\ndef combine_priorities(old_prio, new_prio):\r\n print(old_prio)\r\n print(new_prio)\r\n\r\ndef to_wordnet(tag=None):\r\n \"\"\"Converts a Penn corpus tag into a Wordnet tag.\"\"\"\r\n _wordnet = blob._wordnet\r\n if tag in (\"NN\", \"NNS\", \"NNP\", \"NNPS\"):\r\n return _wordnet.NOUN\r\n elif tag in (\"JJ\", \"JJR\", \"JJS\"):\r\n return _wordnet.ADJ\r\n elif tag in (\"VB\", \"VBD\", \"VBG\", \"VBN\", \"VBP\", \"VBZ\"):\r\n return _wordnet.VERB\r\n elif tag in (\"RB\", \"RBR\", \"RBS\"):\r\n return _wordnet.ADV\r\n else:\r\n return _wordnet.NOUN\r\n\r\nteams = {\r\n '8d1fbcfe-aae9-4f05-971e-da144b72f699': 'testSet1',\r\n 'ba2340a3-e798-4956-baf2-4ba6c76a074f': 'testSet2',\r\n}\r\n\r\ndef to_json(pipeline, output, input, team, vars):\r\n date = datetime.datetime.now().strftime('%m%d_%H%M')\r\n words = input[0].split()\r\n search_terms = ''\r\n for element in words:\r\n search_terms += '_' + element\r\n filename = 'results_' + date + search_terms\r\n path = FILE_PATH + '/' + teams[str(team)] + '/' + filename + '.json'\r\n\r\n stages = {}\r\n for item in pipeline:\r\n item = str(item)\r\n stage = item[item.find(\"(\")+1:item.find(\")\")]\r\n stages[stage] = vars[stage]\r\n\r\n data = {\r\n 'pipeline': stages,\r\n 'original': words,\r\n 'processed': output\r\n }\r\n\r\n try:\r\n with open(path, 'w') as outfile:\r\n json.dump(data, outfile)\r\n except FileNotFoundError:\r\n print('File could not be found.')\r\n except:\r\n print('An error occured. File was not created.')\r\n else:\r\n print('File was successfully created.')\r\n\r\ndef sort_dict(dict):\r\n return sorted(dict, key=lambda element: (-dict[element]['priority'], -dict[element]['amount']))","sub_path":"application/artifacts/text_processing/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"414490599","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom music21 import converter\r\nimport EncDec_music21_helper\r\nimport pickle\r\nimport os\r\n\r\ndirectory_name = '/Users/tzvikif/Documents/Msc/Deep Learning/Project/MID/Bach'\r\ndirectory = os.fsencode(directory_name)\r\n\r\ncounter = 0\r\ntotal_vec = []\r\nfor file in os.listdir(directory):\r\n filename = os.fsdecode(file)\r\n holder = converter.parse(directory_name+'/'+filename)\r\n total_vec.append(EncDec_music21_helper.organize_song_midi_length(holder))\r\n \r\n counter+= 1\r\n print(counter)\r\n \r\nwith open(directory_name + 'classical_notes2.pkl', 'wb') as handle:\r\n pickle.dump(total_vec, handle, protocol= pickle.HIGHEST_PROTOCOL )\r\n","sub_path":"EncDec_converting_midi2vector.py","file_name":"EncDec_converting_midi2vector.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"529691389","text":"import numpy as np\nimport datetime\nimport csv\nimport pandas as pd\nfrom filterpy.kalman import KalmanFilter\nfrom filterpy.common import Q_discrete_white_noise\nimport matplotlib.pyplot as plt\n\n\ndelay_dates = 5\n\n\ndef error_calculation(data, pred):\n avg_error = 0\n data_size = data.shape[0]\n for i in range(1, data_size):\n avg_error += (data[i] - pred[i]) ** 2\n avg_error /= (data_size - 1)\n return avg_error\n\n\ndef plot_curve(data1, data2, data3, label1, label2, label3, xlabel, ylabel,\n dataname):\n data_size = data1.shape[0]\n time = np.linspace(0, data_size, data_size)\n plt.plot(time, data1, label=label1, color='r')\n plt.plot(time, data2, label=label2, color='g')\n plt.plot(time, data3, label=label3, color='b')\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.legend()\n plt.savefig('./{}.png'.format(dataname))\n # plt.show()\n plt.close()\n\n\ndef plot_e(data1, data2, label1, xlabel, ylabel, dataName):\n data_size = data1.shape[0]\n e = np.abs(data1 - data2)\n time = np.linspace(0, data_size, data_size)\n plt.plot(time, e, label=label1)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.legend()\n plt.savefig('./{}.png'.format(dataName))\n # plt.show()\n plt.close()\n\n\ndef plot_curve_single(data):\n data_size = data.shape[0]\n time = np.linspace(0, data_size, data_size)\n plt.plot(time, data, label='Bias')\n plt.xlabel('Time')\n plt.ylabel('Bias')\n plt.legend()\n # plt.show()\n plt.close()\n\n\ndef plot_curve_two(data1, data2, label1, label2, xlabel, ylabel, data_name):\n data_size = data1.shape[0]\n time = np.linspace(0, data_size, data_size)\n plt.plot(time, data1, label=label1)\n plt.plot(time, data2, label=label2)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.legend()\n plt.savefig('./{}.png'.format(data_name))\n # plt.show()\n plt.close()\n\n\ndef kalman_filter(data):\n data_size = data.shape[0]\n h = 1.0 # the time step\n my_filter = KalmanFilter(dim_x=3, dim_z=1)\n my_filter.x = np.array([[50.],\n [0.01],\n [0.01]]) # initial state\n my_filter.F = np.array([[1., h, 0.5*h**2],\n [0., 1., h],\n [0., 0., 1.]]) # state transition matrix\n my_filter.H = np.array([[1., 0., 0.]]) # Measurement function\n my_filter.P *= 1000. # initial covariance matrix\n my_filter.R = 200000000 #0.48\n my_filter.Q = Q_discrete_white_noise(dim=3, dt=h, var=512) # uncertainty\n print(my_filter.Q)\n estimation = np.zeros(data_size)\n # estimation is based on the current state\n for i in range(data_size):\n z = data[i]\n my_filter.predict()\n my_filter.update(z)\n estimation[i] = my_filter.x[0][0]\n # curve plot\n # plot_curve(data, estimation)\n return estimation\n\n\ndef date_str2num(date):\n return datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S').toordinal()\n\n\ndef sum_by_date(data, col_num):\n if col_num == 2:\n data_frame = pd.DataFrame(data=data,\n columns=['date', 'twitter_numbers'])\n gp = data_frame.groupby(['date'])['twitter_numbers'].sum().reset_index()\n gp.rename(columns={'twitter_numbers': 'twitter_numbers_of_dates'},\n inplace=True)\n elif col_num == 3:\n data_frame = pd.DataFrame(data=data,\n columns=['date', 'remain', 'leave'])\n gp = data_frame.groupby(['date'])['remain', 'leave'].mean().reset_index()\n gp.rename(columns={'remain': 'remain_sum', 'leave': 'leave_sum'},\n inplace=True)\n gp_np = gp.to_numpy().astype(int)\n return gp_np\n\n\ndef data_extraction(address, usecols):\n if len(usecols) == 2:\n dateParse = lambda dates: pd.datetime.strptime(dates,\n '%Y-%m-%d %H:%M:%S')\n elif len(usecols) == 3:\n dateParse = lambda dates: pd.datetime.strptime(dates, '%Y-%m-%d')\n rawdata = pd.read_csv(address,\n parse_dates={'timeline': ['dates']},\n date_parser=dateParse,\n usecols=usecols)\n new_data = []\n for i in range(rawdata.shape[0]):\n # print('date:{}'.format(str(rawdata.iloc[i, 0])))\n date_convert = int(date_str2num(str(rawdata.iloc[i, 0])))\n # print('date_convert:{}'.format(date_convert))\n new_data.append(date_convert)\n if len(usecols) == 2:\n new_data.append(rawdata.iloc[i, 1].astype(np.int))\n elif len(usecols) == 3:\n new_data.append(rawdata.iloc[i, 1].astype(np.int))\n new_data.append(rawdata.iloc[i, 2].astype(np.int))\n new_data = np.array(new_data)\n new_data = new_data.reshape((-1, len(usecols)))\n sum_data = sum_by_date(new_data, len(usecols))\n return sum_data\n\n\ndef correlation_coefficient(data1, data2):\n coef = np.corrcoef(data1, data2) # data1 : before/after, data2: obers\n return coef\n\n\ndef MSE(data1, data2):\n data_size = data1.shape[0]\n mse = sum((data1 - data2)**2)/data_size\n return mse\n\n\ndef E34(before, after):\n data3 = before - after\n return np.linalg.norm(data3)/np.linalg.norm(before)\n\n\nif __name__ == '__main__':\n # read the csv files. The csv file provides the real data. The data will be\n # stored in a matrix.\n spt_leave_h = data_extraction('support_leave_hour.csv', [0, 2])\n spt_remain_h = data_extraction('support_remain_hour.csv', [0, 2])\n real_polling = data_extraction('real_polling.csv', [1, 5, 6])\n spt_leave = []\n spt_remain = []\n gt_polling = []\n for i in range(real_polling.shape[0]):\n pos_leave = -1\n pos_remain = -1\n for j in range(spt_leave_h.shape[0]):\n if real_polling[i][0] == spt_leave_h[j][0]:\n pos_leave = j\n break\n for j in range(spt_remain_h.shape[0]):\n if real_polling[i][0] == spt_remain_h[j][0]:\n pos_remain = j\n break\n if pos_leave != -1 and pos_remain != -1:\n gt_polling.append(real_polling[i][1]) # Remain\n gt_polling.append(real_polling[i][2]) # Leave\n spt_leave.append(spt_leave_h[pos_leave][1])\n spt_remain.append(spt_remain_h[pos_remain][1])\n spt_leave = np.array(spt_leave).reshape(-1, 1)\n spt_remain = np.array(spt_remain).reshape(-1, 1)\n gt_polling = np.array(gt_polling).reshape(-1, 2)\n # gt_polling = np.log(gt_polling)\n # before_kalman_remain = []\n # before_kalman_leave = []\n # for i in range(spt_remain.shape[0]):\n # remain = int(spt_remain[i] / (spt_leave[i] + spt_remain[i]) * 100)\n # before_kalman_remain.append(remain)\n # leave = int(spt_leave[i] / (spt_leave[i] + spt_remain[i]) * 100)\n # before_kalman_leave.append(leave)\n # before_kalman_remain = np.log(np.array(before_kalman_remain))\n # before_kalman_leave = np.log(np.array(before_kalman_leave))\n # before_kalman_remain = np.array(before_kalman_remain)\n # before_kalman_leave = np.array(before_kalman_leave)\n # after_kalman_remain = kalman_filter(before_kalman_remain)\n # after_kalman_leave = kalman_filter(before_kalman_leave)\n # plot_curve(before_kalman_remain, after_kalman_remain, gt_polling[:, 0],\n # 'Before Kalman, Remain', 'After Kalman, Remain', 'Observation',\n # 'Time', 'Log Percentage', 'log_remain')\n # print('Before Kalman:')\n # print(correlation_coefficient(gt_polling[:, 0], before_kalman_remain))\n # print('After Kalman:')\n # print(correlation_coefficient(gt_polling[:, 0], after_kalman_remain))\n kal_spt_leave = kalman_filter(spt_leave)\n kal_spt_remain = kalman_filter(spt_remain)\n kal_polling = []\n for i in range(spt_leave.shape[0]):\n remain = int(spt_remain[i] / (spt_leave[i] + spt_remain[i]) * 100)\n remain_kal = int(kal_spt_remain[i] /\n (kal_spt_leave[i] + kal_spt_remain[i]) * 100)\n leave = int(spt_leave[i] / (spt_leave[i] + spt_remain[i]) * 100)\n leave_kal = int(kal_spt_leave[i] /\n (kal_spt_leave[i] + kal_spt_remain[i]) * 100)\n kal_polling.append(remain)\n kal_polling.append(remain_kal)\n kal_polling.append(leave)\n kal_polling.append(leave_kal)\n kal_polling = np.array(kal_polling).reshape(-1, 4)\n # plot_curve(kal_polling[:, 0], kal_polling[:, 1], gt_polling[:, 0],\n # 'Before Kalman', 'After Kalman', 'Original', 'Time', 'Remain %',\n # 'Remain')\n plot_curve(kal_polling[:, 2], kal_polling[:, 3], gt_polling[:, 1],\n 'Before Kalman', 'After Kalman', 'Original', 'Time', 'Leave %',\n 'Leave')\n e1 = np.abs(gt_polling[:62-delay_dates, 0] - kal_polling[delay_dates:62, 0])\n e2 = np.abs(gt_polling[:62-delay_dates, 0] - kal_polling[delay_dates:62, 1])\n plot_curve_two(e1, e2, 'e1 (Before Kal.)', 'e2 (After Kal.)',\n 'time', 'e', 'e')\n print('Before Kalman, delay days:{}'.format(delay_dates))\n coef1 = correlation_coefficient(gt_polling[:62-delay_dates, 0],\n kal_polling[delay_dates:62, 0])\n print(coef1)\n print('After Kalman, delay days:{}'.format(delay_dates))\n coef2 = correlation_coefficient(gt_polling[:62-delay_dates, 0],\n kal_polling[delay_dates:62, 1])\n print(coef2)\n print('The performance correlation coefficient is improved by {}%'.format\n ((coef2[0][1]-coef1[0][1])*100/coef1[0][1]))\n mse_before_kal = MSE(gt_polling[:, 0], kal_polling[:, 0])\n mse_after_kal = MSE(gt_polling[:, 0], kal_polling[:, 1])\n print('The MSE improved from {} to {}'.format(mse_before_kal, mse_after_kal))\n e3 = E34(before=gt_polling[:62-delay_dates, 1], after=kal_polling[delay_dates:62, 2])\n e4 = E34(before=gt_polling[:62-delay_dates, 1], after=kal_polling[delay_dates:62, 3])\n print('e3 = {}, e4 = {}'.format(e3, e4))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"33158668","text":"\"\"\"\n Tim Coutinho\n Prof. Rhodes\n Implementation of the Kruskal and Dijkstra algorithms in Python.\n\"\"\"\n\nfrom sys import maxsize\n\n\nclass Graph():\n\n def __init__(self, nodes):\n self.graph = {vert: edge_list for vert, edge_list in nodes.items()}\n self.vset = {vert: maxsize for vert in nodes} # Dijkstra\n self.ranks = {vert: 0 for vert in self.graph} # Kruskal\n self.parents = {vert: vert for vert in self.graph} # Kruskal\n\n def Dijkstra(self, start='A'):\n \"\"\"Finds the shortest path from the starting node to every other.\"\"\"\n print('Dijkstra:')\n vert = prev = start\n visited = {} # Distance and path to each node, each only visited once\n visited[vert] = {'Distance': 0, 'Path': start}\n self.vset[vert] = 0\n\n while self.vset: # Break once every node has been reached\n # Use the smallest available edge\n vert, dist = sorted(self.vset.items(), key=lambda v: v[1])[0]\n for adj, weight in self.graph[vert].items():\n if adj in visited:\n prev = adj\n continue\n new_dist = dist + weight\n if new_dist < self.vset[adj]: # Found a shorter path to adj\n self.vset[adj] = new_dist\n\n del self.vset[vert] # Remove from set once seen\n if vert not in visited: # Add to visited list with final path\n visited[vert] = {'Distance': dist,\n 'Path': f'{visited[prev][\"Path\"]} -> {vert}'}\n\n print(f'Shortest path from {start} to each node:')\n for vert in sorted(visited):\n dist, path = visited[vert].values()\n print(f'Node {vert}: Value = {dist}, Path = {path}')\n return visited\n\n def Kruskal(self, start='A'):\n \"\"\"Finds the Minimum Spanning Tree of a graph.\"\"\"\n\n def ancestor(vert):\n \"\"\"Finds the root parent of a node\"\"\"\n if self.parents[vert] != vert:\n self.parents[vert] = ancestor(self.parents[vert])\n return self.parents[vert]\n\n def merge(vert, adj):\n \"\"\"Joins two sub trees into one tree\"\"\"\n if self.ranks[vert] > self.ranks[adj]:\n self.parents[adj] = vert\n elif self.ranks[vert] < self.ranks[adj]:\n self.parents[vert] = adj\n else:\n self.parents[adj] = vert\n self.ranks[vert] += 1\n\n print('Kruskal:')\n edge_set = set() # Final list of edges included\n node_set = set() # Final list of nodes reached\n total_weight = 0\n edges = () # List of edges in an easier format than the graph\n for vert in self.graph:\n for adj in self.graph[vert]:\n v = tuple(sorted([vert, adj]))\n edges += ((v, self.graph[vert][adj]),)\n edges = tuple(sorted(edges, key=lambda t: t[1]))\n\n for verts, weight in edges:\n vert, adj = verts\n vert_root, adj_root = ancestor(vert), ancestor(adj)\n if vert_root != adj_root:\n merge(vert_root, adj_root)\n total_weight += weight if verts not in edge_set else 0\n edge_set.add(f'{vert}-{adj}') # Display format\n node_set.add(vert)\n node_set.add(adj)\n\n print(f'MST has a total weight of {total_weight}')\n print(f'Node set = {sorted(node_set)}, Edge set = {sorted(edge_set)}')\n\n\ndef main():\n \"\"\"The graph in a (vertex: (neighbors: weight)) format.\"\"\"\n nodes = {'A': {'B': 22, 'C': 9, 'D': 12},\n 'B': {'A': 22, 'C': 35, 'F': 36, 'H': 34},\n 'C': {'A': 9, 'B': 35, 'D': 4, 'E': 65, 'F': 42},\n 'D': {'A': 12, 'C': 4, 'E': 33, 'I': 30},\n 'E': {'C': 65, 'D': 33, 'F': 18, 'G': 23},\n 'F': {'B': 36, 'C': 42, 'E': 18, 'G': 39, 'H': 24},\n 'G': {'E': 23, 'F': 39, 'H': 25, 'I': 21},\n 'H': {'B': 34, 'F': 24, 'G': 25, 'I': 19},\n 'I': {'D': 30, 'G': 21, 'H': 19}}\n # Went for an object oriented approach, why not\n graph = Graph(nodes)\n graph.Dijkstra()\n print()\n graph.Kruskal()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Math and Theory/kruskal_dijkstra.py","file_name":"kruskal_dijkstra.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"294518212","text":"import tensorflow as tf\n\ntraining_samples_file_path = tf.keras.utils.get_file(\"trainingSamples.csv\",\n \"file:///C:/Users/cj\\PycharmProjects/tensorflowstudy/sparrowrecsys/data/trainingSamples.csv\")\ntest_samples_file_path = tf.keras.utils.get_file(\"testSamples.csv\",\n \"file:///C:/Users/cj\\PycharmProjects/tensorflowstudy/sparrowrecsys/data/testSamples.csv\")\n\ndef get_dataset(file_path):\n dataset = tf.data.experimental.make_csv_dataset(\n file_path,\n batch_size=12,\n label_name='label',\n na_value=\"0\",\n num_epochs=1,\n ignore_errors=True\n )\n return dataset\n\ntrain_dataset = get_dataset(training_samples_file_path)\ntest_dataset = get_dataset(test_samples_file_path)\n\ngenre_vocab = ['Film-Noir', 'Action', 'Adventure', 'Horror', 'Romance', 'War', 'Comedy', 'Western', 'Documentary',\n 'Sci-Fi', 'Drama', 'Thriller',\n 'Crime', 'Fantasy', 'Animation', 'IMAX', 'Mystery', 'Children', 'Musical']\n\nGENRE_FEATURES = {\n 'userGenre1': genre_vocab,\n 'userGenre2': genre_vocab,\n 'userGenre3': genre_vocab,\n 'userGenre4': genre_vocab,\n 'userGenre5': genre_vocab,\n 'movieGenre1': genre_vocab,\n 'movieGenre2': genre_vocab,\n 'movieGenre3': genre_vocab\n}\n\ncategorical_columns = []\nfor feature, vocal in GENRE_FEATURES.items():\n cat_col = tf.feature_column.categorical_column_with_vocabulary_list(\n key=feature, vocabulary_list=vocal\n )\n emb_col = tf.feature_column.embedding_column(cat_col, 10)\n categorical_columns.append(emb_col)\n\nmovie_col = tf.feature_column.categorical_column_with_identity(key='movieId', num_buckets=1001)\nmovie_emb_col = tf.feature_column.embedding_column(movie_col, 10)\ncategorical_columns.append(movie_emb_col)\n\nuser_col = tf.feature_column.categorical_column_with_identity(key='userId', num_buckets=30001)\nuser_em_col = tf.feature_column.embedding_column(user_col, 10)\ncategorical_columns.append(user_em_col)\n\nnumerical_columns = [\n tf.feature_column.numeric_column('releaseYear'),\n tf.feature_column.numeric_column('movieRatingCount'),\n tf.feature_column.numeric_column('movieAvgRating'),\n tf.feature_column.numeric_column('movieRatingStddev'),\n tf.feature_column.numeric_column('userRatingCount'),\n tf.feature_column.numeric_column('userAvgRating'),\n tf.feature_column.numeric_column('userRatingStddev')\n]\n\nrated_movie = tf.feature_column.categorical_column_with_identity(key='userRatedMovie1', num_buckets=1001)\ncross_feature = tf.feature_column.indicator_column(tf.feature_column.crossed_column([movie_col, rated_movie], 10000))\n\ninputs = {\n \"movieAvgRating\": tf.keras.layers.Input(name=\"movieAvgRating\", shape=(), dtype='float32'),\n 'movieRatingStddev': tf.keras.layers.Input(name='movieRatingStddev', shape=(), dtype='float32'),\n 'movieRatingCount': tf.keras.layers.Input(name='movieRatingCount', shape=(), dtype='int32'),\n 'userAvgRating': tf.keras.layers.Input(name='userAvgRating', shape=(), dtype='float32'),\n 'userRatingStddev': tf.keras.layers.Input(name='userRatingStddev', shape=(), dtype='float32'),\n 'userRatingCount': tf.keras.layers.Input(name='userRatingCount', shape=(), dtype='int32'),\n 'releaseYear': tf.keras.layers.Input(name='releaseYear', shape=(), dtype='int32'),\n\n 'movieId': tf.keras.layers.Input(name='movieId', shape=(), dtype='int32'),\n 'userId': tf.keras.layers.Input(name='userId', shape=(), dtype='int32'),\n 'userRatedMovie1': tf.keras.layers.Input(name='userRatedMovie1', shape=(), dtype='int32'),\n\n 'userGenre1': tf.keras.layers.Input(name='userGenre1', shape=(), dtype='string'),\n 'userGenre2': tf.keras.layers.Input(name='userGenre2', shape=(), dtype='string'),\n 'userGenre3': tf.keras.layers.Input(name='userGenre3', shape=(), dtype='string'),\n 'userGenre4': tf.keras.layers.Input(name='userGenre4', shape=(), dtype='string'),\n 'userGenre5': tf.keras.layers.Input(name='userGenre5', shape=(), dtype='string'),\n 'movieGenre1': tf.keras.layers.Input(name='movieGenre1', shape=(), dtype='string'),\n 'movieGenre2': tf.keras.layers.Input(name='movieGenre2', shape=(), dtype='string'),\n 'movieGenre3': tf.keras.layers.Input(name='movieGenre3', shape=(), dtype='string'),\n}\n\n# wide and deep model architecture\n# deep part for all input features\ndeep = tf.keras.layers.DenseFeatures(numerical_columns + categorical_columns)(inputs)\ndeep = tf.keras.layers.Dense(128, activation='relu')(deep)\ndeep = tf.keras.layers.Dense(128, activation='relu')(deep)\n# wide part for cross feature\nwide = tf.keras.layers.DenseFeatures(cross_feature)(inputs)\nboth = tf.keras.layers.concatenate([wide, deep])\noutput_layer = tf.keras.layers.Dense(1, activation='sigmoid')(both)\nmodel = tf.keras.Model(inputs, output_layer)\n\n# compile the model, set loss function, optimizer and evaluation metrics\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy', tf.keras.metrics.AUC(curve='ROC'), tf.keras.metrics.AUC(curve='PR')])\nmodel.fit(train_dataset, epochs=5)\ntest_loss, test_accuracy, test_roc_auc, test_pr_auc = model.evaluate(test_dataset)\nprint('\\n\\nTest Loss {}, Test Accuracy {}, Test ROC AUC {}, Test PR AUC {}'.format(test_loss, test_accuracy,\n test_roc_auc, test_pr_auc))","sub_path":"recommend/model/WideNDeep.py","file_name":"WideNDeep.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"359058783","text":"import requests\n\n#GET Avaliacoes\n\n\n#headers = {'Authorization': 'Token a1cd3b565c85355dab17777ad9cadad4bfcb9b77'}\n\n#curso = requests.get(url='http://localhost:8000/api/v2/cursos/', headers=headers)\n#print(curso.json())\n\ndef calcularValorCorrida(ehBandeiraDois, distancia):\n if ehBandeiraDois:\n return distancia * 3.9\n else:\n return distancia * 2.1\n\nrec = calcularValorCorrida('890,00', 2)\nprint(rec)\n\n\n\n\n\n","sub_path":"test_requests.py","file_name":"test_requests.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"325662518","text":"from pylab import *\n\ndata = loadtxt('data.txt');\n\nN = 20; #Number of noisy patches in the data-set to be added\nlength = 100; #average length of each noisy patch\nchange = 20;\n\n'''Adding the noise'''\ndata_noisy = data;\nindices = array(rand(N)*(data.size-2*length),dtype = int);\nfor i in indices:\n\t# generate the data points and add noise\n\tscl = 1.5;\n\tn=randn(length,)*scl # generate k vectors\n\tdata_noisy[i:i+length] += n # add noise to signal\n\n#plot(data_noisy[indices[1]-100:indices[1]+220]);\n#show();\n\nsavetxt('data_noise.txt',data_noisy);\n\n\n\n\n\n\n","sub_path":"estimation/noise_error_intro.py","file_name":"noise_error_intro.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"257353866","text":"import os, sys, pickle, math, time, logging, itertools\nfrom collections import deque as Queue\nimport networkx as nx\n\nREPO_PATH = os.path.dirname(os.path.realpath(__file__))\nDATA_PATH = os.path.join(REPO_PATH, 'data/')\nPKL_PATH = os.path.join(REPO_PATH, 'pickles/')\n\nfrom collections.abc import Iterable\nfrom collections import defaultdict\nfrom typing import List, Dict, Set, Tuple\n\nLOGGING_LEVELS = { 0 : logging.CRITICAL,\n 1 : logging.ERROR,\n 2 : logging.WARNING,\n 3 : logging.INFO,\n 4 : logging.DEBUG}\n\nUTIL_LOG_LEVEL = LOGGING_LEVELS[3]\n\n\nlogger = logging.getLogger(\"Util\")\nlogger.setLevel(UTIL_LOG_LEVEL)\n\n\ndef toPicklePath(filename):\n if not filename.endswith(\".pickle\"):\n filename += \".pickle\"\n filepath = os.path.join(PKL_PATH, filename)\n return filepath\n\ndef pickleExists(filename):\n filepath = toPicklePath(filename)\n return os.path.isfile(filepath)\n\n\ndef fromPickle(filename, **kwargs):\n filepath = toPicklePath(filename)\n logger.info(\"Loading pickle file\", filepath)\n with open(filepath, 'rb') as fp:\n obj = pickle.load(fp, **kwargs)\n logger.info(\"Done loading\", filepath)\n return obj\n\n\ndef toPickle(obj, filename, **kwargs):\n filepath = toPicklePath(filename)\n logger.info(\"Writing to pickle file\", filepath)\n with open(filepath, 'wb') as fp:\n pickle.dump(obj, fp, **kwargs)\n logger.info(\"Done writing pickle\", filepath)\n\n\n\ndef extractSubmatrix(matrix, columns):\n submatrix = []\n for row in matrix:\n submatrix.append(row.intersection(columns))\n row.difference_update(columns)\n\n return submatrix\n\n\ndef matrixToGraph(matrix):\n \"\"\" Docstring\n \"\"\"\n G = nx.Graph()\n for row in matrix:\n for col1, col2 in itertools.combinations(row, 2):\n G.add_edge(col1, col2)\n return G\n\n\ndef copyMatrix(matrix):\n return [set(row) for row in matrix]\n\ndef longestLen(items):\n return max([len(item) for item in items])\n\n\n\ndef ternaryCompare(str1, str2):\n if len(str1) != len(str2):\n raise Exception(\"strings of unequal length compared: %s and %s (len %d and %d)\" %(str1, str2, len(str1), len(str2)))\n for (c,d) in zip(str1,str2):\n # compare every pair of bits. failure short-circuits\n if not ((c=='*') or (d=='*') or (c==d)):\n return False\n return True\n\ndef longestPrefixMatch(table, tag):\n matches = [prefix for prefix in table if ternaryCompare(prefix, tag)]\n if len(matches) == 0: return -1\n return table.index(max(matches, key=lambda s:s.index('*') if '*' in s else len(s)))\n\n\n\ndef recoverRow(tag, queryDict):\n recovered = set()\n for col, queries in queryDict.items():\n if type(queries) == str or not isinstance(queries, Iterable):\n queries = [queries]\n for query in queries:\n if ternaryCompare(tag, query):\n recovered.add(col)\n break\n return recovered\n\ndef verifyCompression(tagDict, queryDict, matrix=None):\n if matrix != None:\n for row in matrix:\n if frozenset(row) not in tagDict:\n raise Exception(\"A matrix row was not in the tag dictionary!\")\n for row, tag in tagDict.items():\n recovered = recoverRow(tag, queryDict)\n if set(recovered) != set(row):\n print(\"Original row is\", row)\n print(\"Recovered row is\", recovered)\n raise Exception(\"Compression failed to verify\")\n print(\"Compression verified successfully\")\n return True\n\n\n\n\ndef prettySet(s):\n return \"{%s}\" % ', '.join(str(i) for i in s)\n\n\ndef getShellWidth():\n return int(os.popen(\"tput cols\", 'r').read())\n\n\ndef printShellDivider(text=\"\", divChar=\"=\", width=None):\n if width == None:\n width = getShellWidth()\n\n if len(text) > 0:\n numDivChars = max(width - len(text) - 2, 0)\n lWidth = numDivChars // 2\n rWidth = numDivChars - lWidth\n print(divChar * lWidth, text, divChar * rWidth)\n else:\n print(divChar * width)\n\n\ndef printAsColumns(items, title='', delim=\", \"):\n shellWidth = getShellWidth()\n\n\n printShellDivider(title)\n\n items = [str(item) for item in items]\n items.sort(key=len, reverse=True)\n\n delimWidth = len(delim)\n\n i = 0\n while i < len(items):\n if len(items[i]) + delimWidth > shellWidth:\n print(items[i] + \",\")\n i += 1\n else:\n numCols = shellWidth // (len(items[i])+delimWidth)\n colWidth = shellWidth // numCols\n for item in items[i : i+numCols]:\n print(item + delim + \" \"*(colWidth-len(item)-delimWidth), end=\"\")\n print()\n i += numCols\n\n printShellDivider()\n\n\n\ndef shellHistogram(values, numBins=None, barChar='=', title=\"Histogram\", log=False):\n minVal = min(values)\n maxVal = max(values)\n if numBins == None:\n numBins = maxVal - minVal\n binWidth = (maxVal - minVal) / numBins\n\n binCounts = defaultdict(int)\n for val in values:\n dstBin = math.floor((val - minVal)/binWidth)\n binCounts[dstBin] += 1\n\n if log:\n binCounts = {binID : count.bit_length() for binID, count in binCounts.items()} \n\n binIDWidth = len(str(maxVal))\n binIDFormatString = \"%%%dd\" % binIDWidth\n\n shellWidth = getShellWidth()\n maxCount = max(binCounts.values())\n barScalingFactor = (shellWidth - (binIDWidth + 1)) / float(maxCount)\n\n binIndices = sorted(list(binCounts.keys()))\n\n if log:\n title += \" (log scale)\"\n printShellDivider(title)\n print(' '*binIDWidth + '0' +\\\n ('-'*(shellWidth - (binIDWidth+1 +len(str(maxCount))))) +\\\n str(maxCount))\n for binIndex in binIndices:\n trueBinID = math.floor(minVal + (binIndex * binWidth))\n barLength = math.ceil(barScalingFactor * binCounts[binIndex])\n print(binIDFormatString % (trueBinID), barChar * barLength)\n\n printShellDivider(\"End \" + title)\n\n\n\n\nUTIL_TIMER_CLOCK = None\ndef printTimer(init=False):\n global UTIL_TIMER_CLOCK\n currTime = time.time()\n if UTIL_TIMER_CLOCK == None or init:\n print(\"Timer initialized.\")\n else:\n elapsedTime = currTime - UTIL_TIMER_CLOCK\n elapsedDiscrete = int(math.floor(elapsedTime))\n print(\"%2d min %5.2f sec elapsed since last timer call.\" % (elapsedDiscrete // 60, elapsedTime % 60))\n UTIL_TIMER_CLOCK = currTime\n\n\ndef pointerBitsFor(numItems):\n \"\"\" Returns the number of bits needed to distinctly identify every element in a set of size 'count'.\n \"\"\"\n return (numItems-1).bit_length()\n\ndef kraftsInequality(lengths):\n kraftSum = sum([2**length for length in lengths])\n return (kraftSum-1).bit_length()\n\n\ndef generateIdentifiers(lengths : List[int]) -> Tuple[List[str], List[str]]:\n \"\"\" Given a list of lengths (of clusters or strings or whatever), return (1) a list of variable-length prefix-free identifiers\n for each length that minimizes the maximum tag length, and (2) a list of identifiers that were unused.\n \"\"\"\n\n minWidth = kraftsInequality(lengths)\n\n # indices of objects that have no assigned identifiers yet\n unassignedIndices = [i for i in range(len(lengths))]\n # sort it in descending order of available identifier widths\n unassignedIndices.sort(key = lambda index: minWidth - lengths[index], reverse = True)\n identifierLens = [minWidth - lengths[i] for i in unassignedIndices]\n\n freeIDs = Queue(['']) # right is head, left is tail\n assignments = [None]*len(lengths) # assignments[i] is the identifier assigned to the ith object\n\n while len(unassignedIndices) > 0:\n # If we have enough unused identifiers\n # OR if the current shortest identifier's length is the limit for the longest uncoded object\n if len(freeIDs) >= len(unassignedIndices) or len(freeIDs[-1]) == identifierLens[-1]:\n assignmentIndex = unassignedIndices.pop()\n identifierLens.pop()\n assignments[assignmentIndex] = freeIDs.pop()\n # else, we fork the shortest identifier\n else:\n idToSplit= freeIDs.pop()\n freeIDs.extendleft([idToSplit + c for c in ['0','1']])\n\n return (assignments, list(freeIDs))\n\n\n\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":8238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"25397916","text":"from collections import defaultdict\nN = int(input())\n\ncnt = defaultdict(int)\n\nfor a in range(1, N + 1):\n cnt[(str(a)[0], str(a)[-1])] += 1\n\nans = 0\nfor head in range(1, 10):\n for tail in range(1, 10):\n ans += cnt[(str(head), str(tail))] * cnt[(str(tail), str(head))]\n\nprint(ans)","sub_path":"AtCoder/abc/152d.py","file_name":"152d.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"278135976","text":"# Feel free to modifiy this file. \n# It will only be used to verify the settings are correct \n\nimport os\nimport argparse\n\nimport time\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import datasets, transforms, models\n\nfrom jigsaw_dataset import JigsawDataset\n\n\nnormalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\npre_jigsaw_transforms = transforms.Compose([\n transforms.ColorJitter(hue=.1, saturation=.1, contrast=.1),\n transforms.RandomRotation(25),\n])\n\npost_jigsaw_transforms = transforms.Compose([\n transforms.Resize(96),\n transforms.ToTensor(), # convert PIL to Pytorch Tensor\n normalize,\n])\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--checkpoint-dir', type=str)\nargs = parser.parse_args()\n\ntrainset = JigsawDataset(root='/dataset', split=\"unlabeled\", pre_jigsaw_transforms=pre_jigsaw_transforms, post_jigsaw_transforms=post_jigsaw_transforms)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=192, shuffle=True, num_workers=2)\n\nevalset = JigsawDataset(root='/dataset', split=\"val\", pre_jigsaw_transforms=pre_jigsaw_transforms, post_jigsaw_transforms=post_jigsaw_transforms)\nevalloader = torch.utils.data.DataLoader(evalset, batch_size=192, shuffle=False, num_workers=2)\n\nfeature_extractor = torchvision.models.alexnet(pretrained=False)\nfeature_extractor.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(256 * 6 * 6, 4096),\n)\nfeature_extractor = feature_extractor.cuda()\n\nprojector = nn.Linear(4096, 1024)\nprojector = projector.cuda()\n\npredictor = nn.Sequential(\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Linear(4096, 24),\n )\npredictor = predictor.cuda()\n\n\ncriterion = torch.nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD([\n {'params': feature_extractor.parameters()},\n {'params': projector.parameters()},\n {'params': predictor.parameters()}\n ],\n lr=0.01, momentum=0.9, weight_decay=5e-4)\n\nscheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[10, 20, 30], gamma=0.1)\n\nos.makedirs(args.checkpoint_dir, exist_ok=True)\n\ndef compute_accuracy(outputs, perm):\n predictions = torch.argmax(outputs, dim=1)\n correct = (predictions == perm)\n return sum(correct).item() / list(correct.size())[0]\n\n\nprint('Start Training')\ntic = time.perf_counter()\n\n\nfor epoch in range(100):\n feature_extractor.train()\n projector.train()\n predictor.train()\n\n if (epoch % 5 == 0) and (epoch != 0):\n torch.save(feature_extractor.state_dict(), os.path.join(args.checkpoint_dir, \"jigsaw_ep_%s\" % str(epoch)))\n print(\"Saved intermediate checkpoint to jigsaw_ep_%s\" % str(epoch))\n tac = time.perf_counter()\n print(\"Time elapsed: \" + str(tac - tic))\n\n running_loss = 0.0\n running_accuracy = 0.0\n for i, data in enumerate(trainloader):\n inputs, perm = data\n inputs = [i.cuda() for i in inputs]\n perm = perm.cuda()\n\n outputs = [projector(feature_extractor(i)) for i in inputs]\n outputs = torch.cat(outputs, dim=1)\n outputs = predictor(outputs)\n\n loss = criterion(outputs, perm)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n accuracy = compute_accuracy(outputs, perm)\n running_accuracy += accuracy\n if i % 10 == 9: # print every 10 mini-batches\n print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 10), flush=True)\n print('[%d, %5d] ACC: %.3f' % (epoch + 1, i + 1, running_accuracy / 10), flush=True)\n running_loss = 0.0\n running_accuracy =0.0\n \n feature_extractor.eval()\n projector.eval()\n predictor.eval()\n running_eval_loss = 0.0\n running_eval_accuracy = 0.0\n for i, data in enumerate(evalloader):\n inputs, perm = data\n inputs = [i.cuda() for i in inputs]\n perm = perm.cuda()\n\n outputs = [projector(feature_extractor(i)) for i in inputs]\n outputs = torch.cat(outputs, dim=1)\n outputs = predictor(outputs)\n\n loss = criterion(outputs, perm)\n running_eval_loss += loss.item()\n eval_accuracy = compute_accuracy(outputs, perm)\n running_eval_accuracy += eval_accuracy\n if i % 10 == 9:\n print('Eval loss: ' + str(running_eval_loss / 10))\n print('Eval ACC: ' + str(running_eval_accuracy / 10))\n running_eval_loss = 0.0\n running_eval_accuracy = 0.0\n\nprint('Finished Training')\ntoc = time.perf_counter()\nprint('Time elapsed: ' + str(toc - tic))\n\n","sub_path":"rotations/train_jigsaw.py","file_name":"train_jigsaw.py","file_ext":"py","file_size_in_byte":4997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"172618096","text":"from collections import defaultdict\n\ndef get_genomes_tested():\n genomes_tested_by = defaultdict(lambda: set())\n\n # col: 0: genome id, 1: genome_name, 2: taxon_id, 3: antibiotic, ect\n # we want a dictionary where key: antibiotic val: set(genome_ids that are tested agains the antibiotic key)\n tsf = open(\"./PATRIC_genomes_AMR.tsv\", \"r\")\n for line in tsf:\n temp = line.split('\\t')\n genome_id = temp[0]\n antibiotic = temp[3]\n genomes_tested_by[antibiotic].add(str(genome_id)) if str(genome_id).strip() != \"genome_id\" else lambda:None\n #print(\"Adding \", str(genome_id), \" to : \", antibiotic) if str(genome_id).strip() != \"genome_id\" else lambda:None\n\n return genomes_tested_by\n","sub_path":"get_genomes.py","file_name":"get_genomes.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"239925097","text":"import re\nimport os\nimport sys\nimport faker\nfrom faker import Faker\nfaker = Faker()\nimport PySimpleGUI as sg\nimport random\n\n\nclass Intro():\n\n def __init__(self, *args, **Kwargs):\n print(('\\n' * 10) \n + '+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+ +-+-+-+'\n +'\\n|T|a|b|l|e| |G|e|n|e|r|a|t|o|r| |1|.|0|'\n +'\\n+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+ +-+-+-+\\n'\n )\n \n\nclass FileProcessor():\n \"\"\"\n An object for processing files with name and path as inputs.\n \"\"\"\n def __init__(self, *args, **Kwargs):\n pass\n\n def find(self, name, path):\n \"\"\"Searches directories for file\"\"\"\n for root, dirs, files in os.walk(path):\n if name in files:\n return os.path.join(root, name)\n\n def file_getter(self, file_path):\n \"\"\"Returns iterable 'file-reader' for scanning\"\"\"\n find_file_name = file_path\n if find_file_name != None:\n # If file found return 'file-reader' object\n file_reader = open(find_file_name)\n file_reader = file_reader.readlines()\n return file_reader\n else:\n # If file not found, set finished_flag to 'False'\n return False\n\n\nclass FileScanner():\n \"\"\"\n Scans the SQL Document.\n Looks for Table Creation statements and creates table dictionaries.\n Stores column names as values in dictionaries.\n \"\"\"\n\n def __init__(self):\n self.table_builder\n \n\n def table_namer(self, line):\n # Search for everything after Create Table statement\n table_search = re.compile(r'CREATE TABLE (.*)')\n # Save with line passed from Scanner as argument\n table_name = table_search.search(line)\n return table_name.group(1)\n\n def table_builder(self, file_reader):\n # Initialization.\n table_flag = None\n self.my_tables = []\n table_info = {}\n columns = []\n foreign_keys = []\n primary_key_counter = 0\n for line in file_reader:\n # Set table flag to true if building table\n if 'CREATE TABLE' in line:\n table_flag = True\n # Name table once Statement begins\n table_title = self.table_namer(line)\n table_info['table name'] = table_title\n # Add table dictionary to list\n self.my_tables.append(table_info)\n # Once statement ends, build table dictionary, reset columns\n if ',CONSTRAINT' in line:\n table_flag = False\n # Key = columns, value = list of colums\n table_info['columns'] = columns\n # Set list of possible foreign keys\n table_info['foreign keys'] = foreign_keys\n # Reset sub-lists/dictionaries and counters for next table\n primary_key_counter = 0\n table_info = {}\n columns = []\n foreign_keys = []\n # Build Table Columns\n if table_flag == True:\n # Break line after Create into list\n column_list = line.split()\n for item in column_list:\n # Test each item to see if its a column name\n if 'str' in item or 'dtm' in item or 'mon' in item:\n # If column name, format and add to main list\n column_name = item.replace(',', '')\n columns.append(column_name)\n if 'int' in item:\n # If first int in list of columns, item=PK\n primary_key_counter += 1\n if primary_key_counter == 1:\n table_info['primary key'] = item\n else:\n # If not primary key\n item = item.replace(',', '')\n # Search for item in other tables' PKs\n for searched_table in self.my_tables:\n # If another Table's PK, is foreign key\n if item == searched_table['primary key']:\n foreign_keys.append(item)\n columns.append(item)\n # Else if not FK, integer column\n if item not in foreign_keys:\n columns.append(item)\n \n #self.deep_access()\n return self.my_tables\n\n\ndef key_doublecheck(tables):\n \"\"\"\n Double checks for out of order table keys.\n \"\"\"\n searched_tables1 = tables\n searched_tables2 = tables\n for table in searched_tables1:\n columns1 = table['columns'] \n foreign_keys1 = table['foreign keys']\n for table2 in searched_tables2:\n pk = table2['primary key']\n if pk in columns1:\n foreign_keys1.append(pk)\n\n\n\n\nclass Constraint():\n\n def __init__(self, my_tables, txt_output):\n self.txt_output = txt_output\n self.my_tables = my_tables\n self.constrainer()\n self.constaint_formatter()\n self.constraint_builder()\n\n def constrainer(self):\n \"\"\"\n For each table1, loop again through a second instance of tables, \n i.e table2. If table1's primary key in table2's foreign keys\n add to temporary list. Once tables2 exhausted, add temporary\n list to table1 newly created children dictionary. \n Reset temporary list for next table1.\n \"\"\"\n tables = self.my_tables\n \n for table in tables:\n children = []\n for table2 in tables:\n if table['primary key'] in table2['foreign keys']:\n children.append(table2['table name'])\n\n if children:\n table['children'] = children\n \n \n \n \n \n\n def constaint_formatter(self):\n file = open(self.txt_output, 'a')\n comment_break = '-'\n number = 0\n numbers = []\n child = []\n parent = []\n column = []\n headings = ['#', 'Child', 'Parent', 'Column']\n ref_title = '--Step #2 : Establish Referential Integrity'\n ref_title = ref_title.center(100)\n # Build headers for Ray's tables\n print(comment_break * 100)\n print('--' +ref_title)\n print(comment_break * 100)\n file.write('\\n' + (comment_break * 100))\n file.write('\\n' + ref_title)\n file.write('\\n'+ (comment_break * 100))\n # Build each row.\n for table in self.my_tables:\n try: \n # Check for children, if none, pass\n for key in table['children']:\n number += 1\n numbers.append(str(number))\n child.append(key)\n parent.append(table['table name'])\n column.append(table['primary key'])\n except KeyError:\n pass\n # zip rows together\n self.data = [headings] + list(zip(numbers, child, parent, column))\n # Format Ray's tables\n for i in range(len(self.data)):\n if i == 0:\n print(\"--{:<10s}{:>4s}{:>31s}{:>30s}\".format(self.data[i][0],\n self.data[i][1],self.data[i][2],self.data[i][3]))\n print(\n \"--{:<10s}{:>4s}{:>31s}{:>30s}\".format('-'*len(self.data[i][0]), \n '-'*len(self.data[i][1]),'-'*len(self.data[i][2]), \n '-'*len(self.data[i][3]))\n )\n file.write(\"\\n--{:<10s}{:>4s}{:>31s}{:>30s}\".format(self.data[i][0],\n self.data[i][1],self.data[i][2],self.data[i][3]))\n file.write(\n \"\\n--{:<10s}{:>4s}{:>31s}{:>30s}\".format('-'*len(self.data[i][0]), \n '-'*len(self.data[i][1]),'-'*len(self.data[i][2]), \n '-'*len(self.data[i][3]))\n )\n else:\n print(\"--{:<10s}{:<30s}{:<30s}{:<30s}\".format(self.data[i][0],\n self.data[i][1],self.data[i][2],self.data[i][3]))\n file.write(\"\\n--{:<10s}{:<30s}{:<30s}{:<30s}\".format(self.data[i][0],\n self.data[i][1],self.data[i][2],self.data[i][3]))\n\n\n def constraint_builder(self):\n file = open(self.txt_output, 'a')\n print('\\n')\n \"\"\"Builds constraint commands\"\"\"\n alter_table_template = (\n \"\\n\\n--{0}\"\n \"\\nALTER TABLE {1} ADD CONSTRAINT {1}_{2}_FK\" \n + \"\\nFOREIGN KEY ( {3} ) REFERENCES {2} ( {3} )\"\n )\n for i, row in enumerate(self.data):\n if i > 0:\n # For row in list of rows, make statement.\n alter_statement = alter_table_template.format(row[0], \n row[1], row[2], row[3])\n print(alter_statement)\n file.write(alter_statement)\n file.close()\n\n\"\"\"def multikeysort(tables):\n\n newtables = []\n for table in tables:\n try:\n if table['children']:\n newtables.append(table)\n except KeyError:\n pass\"\"\"\n\n \n\n \n #newtables = tables\n #return newtables\n\nclass Inserter():\n\n def __init__(self, my_tables, txt_output, faker):\n self.txt_output = txt_output\n self.tables = my_tables\n self.fake = faker\n self.insert_table()\n \n def insert_table(self):\n file = open(self.txt_output, 'a')\n comment_break = '-'\n insert_title = '--Step #3 : Insert Tables'\n insert_title = insert_title.center(100)\n # Build headers for Ray's tables\n print('\\n\\n')\n print(comment_break * 100)\n print(insert_title)\n print(comment_break * 100)\n file.write('\\n\\n\\n' + (comment_break * 100))\n file.write('\\n' + insert_title)\n file.write('\\n'+ (comment_break * 100))\n \n \n for table in self.tables:\n rows = []\n # gender counter\n g_counter = 0\n r_counter = 0\n # Write first line of insert.\n first_line_template = ('\\n\\nINSERT {0}( {1}, '.format(\n table['table name'], table['primary key'])\n + ', '.join('{}'.format(i) for i in table['columns']) + ' )'\n + '\\nVALUES'\n \n )\n print(first_line_template, end=\"\")\n file.write(first_line_template)\n table['header row'] = first_line_template\n \n for i in range(table['entries']):\n space = ' ' * (7 + len(table['table name']))\n if i == 0:\n space = ' '* (len(table['table name']) +1)\n if i > 0:\n line_temp = (space + ',( ')\n else:\n line_temp = (space + '( ')\n line = line_temp\n line += str(i + 1)\n gender_num = random.randint(1, 2)\n race_num = random.randint(1, 3)\n #line += ', '.join('{}'.format(x) for x in range(len(table['columns']) +1))\n attributes = []\n for x in range(len(table['columns'])):\n integer_flag = False\n column = table['columns'][x]\n fr = ', '\n attribute = 'TEMP'\n if 'int' in column[:3] and column in table['foreign keys']:\n if 'intstate' in column.lower():\n for table3 in tables:\n if 'intstate' in table3['primary key'].lower():\n state_counter = table3['entries']\n state_table = table3\n try:\n num = random.randint(1, state_counter)\n except IndexError:\n state_counter = state_table['entries']\n attribute = str(num)\n state_counter -= 1\n integer_flag = True\n if 'intrace' in column.lower():\n attribute = str(race_num)\n integer_flag = True\n else:\n for table4 in tables:\n if column in table4['primary key']:\n foreign_key_counter = table4['entries']\n num = random.randint(1, foreign_key_counter)\n attribute = str(num)\n integer_flag = True\n\n if 'firstname' in column.lower():\n if gender_num == 1:\n attribute = self.fake.first_name_male()\n name_g = 0\n elif gender_num == 2:\n attribute = self.fake.first_name_female()\n name_g = 1\n if 'lastname' in column.lower():\n attribute = self.fake.last_name()\n if 'strstate' in column.lower():\n attribute = self.fake.state()\n if 'strgender' in column.lower():\n genders = ['Male', 'Female']\n if 'gender' in table['table name'].lower():\n if table['entries'] > 2:\n for x in range(table['entries']- 2):\n genders.append(\"Other\")\n attribute = genders[g_counter]\n g_counter += 1\n else:\n attribute = genders[name_g ]\n if 'intgender' in column.lower():\n attribute = str(gender_num)\n integer_flag = True\n if 'strrace' in column.lower():\n races = [\n 'Afircan American', \n 'White', \n 'Hispanic',\n 'Asian',\n 'Pacific Islander'\n ]\n if 'race' in table['table name'].lower():\n if table['entries'] > 5:\n for x in range(table['entries']- 5):\n races.append(\"Other\")\n attribute = races[r_counter]\n r_counter += 1\n else:\n attribute = races[random.randint(0,4)]\n if 'address' in column.lower():\n attribute = self.fake.street_address()\n if 'strcity' in column.lower():\n attribute = self.fake.city()\n if 'zip' in column.lower():\n attribute = self.fake.zipcode()\n if 'phone' in column.lower():\n first_two = [random.randint(201, 999) for i in range(2)]\n last = random.randint(1000, 9999)\n my_phone = \"({:3d}){:3d}-{:4d}\".format(first_two[0],\n first_two[1], last)\n attribute = my_phone\n if 'year' in column.lower():\n if 'int' in column.lower():\n pass\n year1 = self.fake.date_this_decade()\n attribute = year1.year\n if 'email' in column.lower():\n attribute = self.fake.email()\n if 'ssn' in column.lower() or (\n 'socialsecurity' in column.lower()\n ):\n attribute = self.fake.ssn()\n \n if 'mon' in column[:3]:\n attribute = random.randint(100, 2000)\n attribute = float(attribute)\n if 'dtm' in column[:3]:\n year_form = '{:d}/{:d}/{:d}'\n if 'dob' in column.lower() or (\n 'birth' in column.lower()\n ):\n rand_year = random.randint(1960, 1991)\n rand_month = random.randint(1, 12)\n rand_day = random.randint(1, 28)\n birth_day = year_form.format(rand_day, \n rand_month, \n rand_year)\n attribute = birth_day\n if 'doh' in column.lower() or (\n 'hire' in column.lower()\n ):\n rand_year = random.randint(2005, 2016)\n rand_month = random.randint(1, 12)\n rand_day = random.randint(1, 28)\n hire_date = year_form.format(rand_day, \n rand_month,\n rand_year)\n attribute = hire_date\n else:\n rand_year = random.randint(2010, 2018)\n rand_month = random.randint(1, 12)\n rand_day = random.randint(1, 28)\n date = year_form.format(rand_day, \n rand_month,\n rand_year)\n attribute = date\n \n\n \n if integer_flag == False:\n attribute = \"'\" + str(attribute) + \"'\"\n line += (fr + str(attribute))\n attributes.append(attribute)\n \n line += ' )\\n'\n rows.append(attributes)\n print(line)\n file.write(line)\n name_g = 1\n table['rows'] = rows\n \n\n # For each column after pk, write column name\n #for column in enumerate(table['columns']):\n\n \n\nclass Tables():\n\n def __init__(self, my_tables):\n self.tables = my_tables\n\n def display_tables(self):\n d_tables = []\n for c, table in enumerate(self.tables):\n table_name = table['table name']\n d_tables.append('{:02d}'.format(c + 1) + ': ' + table_name)\n return d_tables\n \n\n \n\n\nclass Exiter():\n\n def __init__(self):\n self.input = input(\"\\n\\nRun another script? (y/n): \")\n \n def output(self):\n return self.input\n\n#def entity_counter(my_tables, option_1, option_2):\n choice = ''\n \n \n \n \n \n\ndef output(file_name, file_path, counter):\n\n txt_output = file_name.strip('.sql')\n cwd = os.getcwd()\n for file in os.listdir(cwd):\n file_tester = file.strip('.txt')\n if txt_output in file_tester:\n if 'Copy' in file_tester: \n for i in range(20):\n if 'Copy({0})'.format(i) in file_tester:\n counter = i - 1\n \n counter += 1\n numberer = '(' + str(counter) + ')'\n else:\n txt_output += ' - Copy'\n if counter > 0:\n txt_output += numberer\n txt_output += '.txt'\n return txt_output\n\n\n\n\n\nclass Dropper():\n\n def __init__(self, my_tables, txt_output):\n self.txt_output = txt_output\n self.re_tables = reversed(my_tables)\n self.build_drops()\n\n def build_drops(self):\n file = open(self.txt_output, 'a')\n print(\"\\n\\n\")\n \n \n for table in self.re_tables:\n null_id = \"IS NOT NULL DROP TABLE \" + table['table name']\n\n drop_format = (\n \"\\nIF OBJECT_ID ('{0}')\\t{1:>5}\".format(\n table['table name'], \n null_id)\n )\n print(drop_format)\n file.write(drop_format)\n print(\"\\n\\n\")\n file.write(\"\\n\\n\")\n\nsg.SetOptions(button_color=('black', 'light grey'), background_color='#afb5ad', element_background_color='#afb5ad',\n )\nlayout = [\n [sg.Text('Tables')],\n [sg.Listbox(values='', size=(30, 10), key='tables'), \n sg.Frame(layout=[\n [sg.Radio('Default: 5', 'Entries', default=True, size=(12, 4))],\n [sg.Radio('Set For all Tables', 'Entries')],\n [sg.Radio('Set Per Table', 'Entries')]], \n title='# of Table Rows', relief=sg.RELIEF_SUNKEN, \n tooltip='Sets the amount of entries (rows) per table.'\n )],\n [sg.Button('Display')],\n [sg.Text('SQL Filename')],\n [sg.Input(), sg.FileBrowse()],\n [sg.Button('Submit'), sg.Button('Close')]\n]\n\nwindow = sg.Window('SQL Table Generator 2.0', \n default_button_element_size=(40, 1), grab_anywhere=True).Layout(layout)\n\nwin2active = False\nwhile True:\n counter = 0 \n event, values = window.Read()\n try:\n file_path = values[3]\n if event == 'Close':\n break\n if event == 'Display':\n try:\n os.startfile(txt_name)\n except:\n pass\n except TypeError:\n sys.exit()\n\n \n # New instance of input class\n # Input methods return file name and path\n start_flag = False\n if event == 'Submit': \n start_flag = True\n while start_flag == True:\n if event == 'Close' or event is None:\n sys.exit()\n # New instance of processor class\n new_processor = FileProcessor()\n # Assign iterable file object from instance method.\n try:\n file_reader = new_processor.file_getter(file_path)\n except FileNotFoundError:\n break\n except UnicodeDecodeError:\n sg.Popup(\"Wrong File Type!\")\n break\n file_name = os.path.basename(file_path)\n new_scanner = FileScanner()\n tables = new_scanner.table_builder(file_reader)\n txt_name = output(file_name, file_path, counter)\n key_doublecheck(tables)\n t_displayer = Tables(tables)\n d_tables = t_displayer.display_tables()\n window.FindElement('tables').Update(d_tables)\n option_1 = values[0]\n option_2 = values[1]\n option_3 = values[2]\n \n if option_1 == True:\n for table in tables:\n table_name = table['table name']\n if 'gender' in table_name.lower():\n table['entries'] = 2\n else:\n table['entries'] = 5\n \n elif option_2 == True:\n entries = sg.PopupGetText(\"# of Entries for tables\")\n if entries:\n entries = int(entries)\n for table in tables:\n table_name = table['table name']\n if 'gender' in table_name.lower():\n table['entries'] = 2\n else:\n table['entries'] = entries\n else:\n start_flag = False\n break\n \n if not win2active and option_3 == True:\n num_inputs = len(tables)\n table_names = [x['table name'] for x in tables]\n win2active = True\n layout2 = [\n [sg.Text(\"Select per table.\")],\n *[[sg.Input(default_text=table_names[i]),] for i in range(num_inputs)],\n [sg.Button('OK'), sg.Button('Cancel')]]\n\n window2 = sg.Window('Entries per table', location=(950, 100), border_depth=2,\n no_titlebar=True, grab_anywhere=True).Layout(layout2)\n if win2active == True: \n ev1, vals2 = window2.Read()\n vcounter = 0\n if ev1 == 'Cancel':\n win2active = False\n window2.Close()\n start_flag = False\n break\n \n if ev1 == 'Cancel':\n win2active = False\n window2.Close()\n start_flag = False\n break\n if ev1 is None or ev1 == 'OK': \n window2.Close()\n win2active = False\n try:\n for val in vals2:\n tables[vcounter]['entries'] = int(val)\n vcounter += 1\n except ValueError:\n sg.Popup(\"Invalid Data Types\")\n start_flag = False\n \n \n \n while start_flag == True:\n Dropper(tables, txt_name)\n try:\n Constraint(tables, txt_name)\n except KeyError:\n pass\n #tables = multikeysort(tables)\n Inserter(tables, txt_name, faker)\n if event == 'Display':\n try:\n os.startfile(txt_name)\n except NameError:\n pass\n start_flag == False\n break\n break\n \n\n","sub_path":"TableGenerator7.py","file_name":"TableGenerator7.py","file_ext":"py","file_size_in_byte":25410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"523538207","text":"import onnxruntime\n\nimport os\nfrom .clip import _download, available_models\n\n_S3_BUCKET = 'https://clip-as-service.s3.us-east-2.amazonaws.com/models/onnx/'\n_MODELS = {\n 'RN50': ('RN50/textual.onnx', 'RN50/visual.onnx'),\n 'RN101': ('RN101/textual.onnx', 'RN101/visual.onnx'),\n 'RN50x4': ('RN50x4/textual.onnx', 'RN50x4/visual.onnx'),\n 'RN50x16': ('RN50x16/textual.onnx', 'RN50x16/visual.onnx'),\n 'RN50x64': ('RN50x64/textual.onnx', 'RN50x64/visual.onnx'),\n 'ViT-B/32': ('ViT-B-32/textual.onnx', 'ViT-B-32/visual.onnx'),\n 'ViT-B/16': ('ViT-B-16/textual.onnx', 'ViT-B-16/visual.onnx'),\n 'ViT-L/14': ('ViT-L-14/textual.onnx', 'ViT-L-14/visual.onnx'),\n}\n\n\nclass CLIPOnnxModel:\n def __init__(\n self,\n name: str = None,\n ):\n if name in _MODELS:\n cache_dir = os.path.expanduser(f'~/.cache/clip/{name.replace(\"/\", \"-\")}')\n self._textual_path = _download(_S3_BUCKET + _MODELS[name][0], cache_dir)\n self._visual_path = _download(_S3_BUCKET + _MODELS[name][1], cache_dir)\n else:\n raise RuntimeError(\n f'Model {name} not found; available models = {available_models()}'\n )\n\n def start_sessions(\n self,\n **kwargs,\n ):\n self._visual_session = onnxruntime.InferenceSession(self._visual_path, **kwargs)\n self._textual_session = onnxruntime.InferenceSession(\n self._textual_path, **kwargs\n )\n\n def encode_image(self, onnx_image):\n onnx_input_image = {self._visual_session.get_inputs()[0].name: onnx_image}\n (visual_output,) = self._visual_session.run(None, onnx_input_image)\n return visual_output\n\n def encode_text(self, onnx_text):\n onnx_input_text = {self._textual_session.get_inputs()[0].name: onnx_text}\n (textual_output,) = self._textual_session.run(None, onnx_input_text)\n return textual_output\n","sub_path":"server/clip_server/model/clip_onnx.py","file_name":"clip_onnx.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"75402852","text":"#!/usr/bin/env python3\n\"\"\"Usage:\n\"\"\"\n\n__version__ = '1.0'\n\nimport os\nimport sys\nimport shutil\nfrom subprocess import run\nfrom jpconfig import Config\n\n\nclass Dot(object):\n def __init__(self):\n self.args = sys.argv[1:]\n self.home = os.environ['HOME']\n self.local = os.path.join(self.home, '.cfg')\n self.old_dotfiles = os.path.join(self.home, \".old_dotfiles\")\n self.cfg = Config(file=os.path.join(self.home, '.dot'))\n if len(self.args) > 0 and self.args[0] == 'init':\n self.cfg.username = input('What\\'s your full name for git')\n self.cfg.remote = input('What\\'s your git repository url')\n self.cfg.email = input('What\\'s your email')\n self.git_commands = ['add','am','apply','archive','bisect','blame','branch','bundle', 'checkout', 'cherry','cherry-pick','citool','clean','clone','commit','config','describe','diff','difftool','fetch','format-patch','fsck','gc','gitk','grep','gui','help','init','instaweb','log', 'ls-tree', 'merge','mergetool','mv','notes','push','range-diff','rebase','reflog','remote','repack','replace','request-pull','reset','revert','rm','send-email','shortlog','show','show-branch','stage','stash','status','submodule','tag','whatchanged','worktree',]\n self.git_opts = [\"git\", f\"--git-dir={self.local}\", f\"--work-tree={self.home}\", \"-c\", f\"user.name={self.cfg.username}\", \"-c\", f\"user.email={self.cfg.email}\"]\n self.commands = ['ls']\n self.check_create_repo()\n if len(self.args) > 0 and self.args[0] in self.commands:\n self.__getattribute__(self.args[0])()\n elif len(self.args) > 0 and self.args[0] in self.git_commands:\n run(self.git_opts + self.args)\n else:\n run(self.git_opts + ['status', '-s'])\n\n def check_create_repo(self):\n if not os.path.exists(self.local):\n with open(os.path.join(self.home, '.gitignore'), 'w') as file:\n file.write(\".cfg\")\n clone = run([\"git\", \"clone\", \"--bare\", self.cfg.remote, self.local])\n if clone.returncode == 0:\n run(self.git_opts + ['config', '--local', 'status.showUntrackedFiles', 'no'])\n run(self.git_opts + [\"master\", \".\"])\n\n def ls(self):\n print('Files currently being tracked by dot:')\n run(self.git_opts + [\"ls-tree\", \"master\", \"--name-only\", \"--full-tree\", \"-r\"])\n\ndef main():\n Dot()\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"jpdot/jpdot.py","file_name":"jpdot.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"389602904","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"This is a simple pythonic replacement for the windows 'dir' command. \r\n\r\n\r\n Once added to the Windows PATH environmental variable\r\n And added to the PATHEXT environmental variable this\r\n tool can be used in any directory 'lsd' and look! Otherwise\r\n run in the same directory as this script as 'python lsd.py'\r\n This assumes Python3 and the time is not correct yet.\"\"\"\r\n\r\nimport os \r\nimport win32api\r\nimport time\r\nfrom colorama import init\r\nfrom termcolor import colored\r\n\r\n__author__ = \"hippybear\"\r\n__license__ = \"MIT\"\r\n__email__ = \"yosi@codeblind.org\"\r\n__copyright__ = \"Copyright 2017, Code Blind\"\r\n__status__ = \"Development\"\r\n\r\n\r\ninit()\r\n\r\nclock = time.localtime()\r\ndir_path = os.path.dirname(os.path.realpath(__file__))\r\nt = win32api.GetVolumeInformation(\"C:\\\\\")\r\nlocalTime = str(clock.tm_hour) + \":\" + str(clock.tm_min)\r\n\r\nprint(\" LocalTime: {0}\".format( colored(localTime, 'white') ) )\r\nprint(\"\\n\")\r\nprint(\" Volume in drive C is {0}\" .format( colored(t[0] , 'white') ))\r\nprint(\" Volume serial number is {0}\" .format( colored(t[1] , 'white') ))\r\nprint(\"\\n\")\r\nprint(\" Directory of {0}\" .format( colored(dir_path, 'white')))\r\nprint(\"\\n\")\r\nprint(\" File(s)\")\r\nfor file in os.listdir(dir_path):\r\n print(\" {0}\" .format(colored(file, 'white')))\r\n","sub_path":"lsd.py","file_name":"lsd.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"299663666","text":"import math\nimport timex\n\ndef dV():\n \n isp = float(input('Enter Isp: '))\n m0 = float(input('Enter initial mass: '))\n m1 = float(input('Enter final mass: '))\n \n g0 = float(9.80665)\n\n dVrocket = isp * g0 * math.log(m0/m1)\n\n return dVrocket\n\n\n\n\n\n\ndef burntime():\n \n dVrequired = float(input('Enter the required dV: '))\n isp = float(input('Enter Isp in seconds: '))\n mass = float(input('Enter the current mass: '))\n thrust = float(input('Enter the total thrust: '))\n g0 = float(9.80665)\n\n print()\n\n # Massloss rate\n massloss_per_sec = thrust / isp / g0\n\n # Burntime in seconds\n xs = (mass / math.e ** (dVrequired / (isp * g0)) - mass) / (-massloss_per_sec)\n\n # Burntime in hours\n xh = xs / 3600\n\n # Half Burntime\n xhhalf = xh / 2\n\n # Extend the hours to full hours, minutes and seconds\n hours, minutes, seconds = timex.time_extend(xh)\n \n hr, mi, se = timex.time_s(hours, minutes, seconds)\n\n print('Full burntime:', hours, hr, minutes, mi, seconds, se)\n\n hours, minutes, seconds = timex.time_extend(xhhalf)\n\n hr, mi, se = timex.time_s(hours, minutes, seconds)\n \n print('Half burntime:', hours, hr, minutes, mi, seconds, se)\n\n\n\n\n\n","sub_path":"deltaV/tsiolkovsky.py","file_name":"tsiolkovsky.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"97879385","text":"from dataclasses import field\n\nfrom wecs.core import Proxy\nfrom wecs.core import ProxyType\nfrom wecs.core import Component\nfrom wecs.core import System\nfrom wecs.core import and_filter\nfrom wecs.core import or_filter\n\nfrom wecs.panda3d.input import Input\nfrom wecs.panda3d.character import CharacterController, FallingMovement\nfrom wecs.panda3d.prototype import Actor\n\n\n@Component()\nclass Animation:\n to_play: list = field(default_factory=list)\n playing: list = field(default_factory=list)\n blends: list = field(default_factory=list)\n framerate: int = 1\n\n\nclass AnimateCharacter(System):\n entity_filters = {\n 'animated_character': and_filter([\n Proxy('actor'),\n Animation,\n CharacterController\n ])\n }\n proxies = {'actor': ProxyType(Actor, 'node')}\n\n def update(self, entities_by_filter):\n for entity in entities_by_filter['animated_character']:\n controller = entity[CharacterController]\n animation = entity[Animation]\n actor_proxy = self.proxies['actor']\n actor = actor_proxy.field(entity)\n\n if FallingMovement in entity:\n grounded = entity[FallingMovement].ground_contact\n else:\n grounded = False\n\n initial = \"idle\"\n if not grounded:\n if controller.translation.z > 0.1:\n initial = \"jump\"\n elif controller.translation.z < -0.1:\n initial = \"fall\"\n elif controller.crouches:\n initial = \"crouch\"\n animation.to_play = [initial, \"walk_forward\", \"run_forward\"]\n # TODO: bad constant, 1.4? Should be fixed in animation\n # when the right value is found in lab.\n forward_speed = abs(controller.translation.y*1.4)\n idle = max(0, (1 - forward_speed))\n walk = 1 - abs(forward_speed - 0.5) * 2\n run = max(0, forward_speed * 2 - 1)\n blends = [idle, walk, run]\n # sideways movement\n # TODO: same here, another constant. Fix in animation after lab.\n strafe_speed = (controller.translation.x*1.4)\n if not strafe_speed == 0:\n blends.append(abs(strafe_speed))\n if strafe_speed > 0:\n animation.to_play.append(\"walk_right\")\n elif strafe_speed < 0:\n animation.to_play.append(\"walk_left\")\n\n animation.framerate = (0.5+(forward_speed + abs(strafe_speed)))\n # If walking backwards simply play the animation in reverse\n # TODO: Only do this when there's no animations for walking backwards.\n if controller.translation.y < 0:\n animation.framerate = -animation.framerate\n if controller.translation.z < -0.2:\n animation.framerate *= 0.2\n\n animation.blends = blends\n\n # # vertical animation\n # vertical_speed = controller.last_translation_speed.z\n # blends = [1]\n # if vertical_speed > 0.1:\n # animation.to_play = [\"jumping\"]\n # elif vertical_speed < -0.1:\n # animation.to_play = [\"falling\"]\n # else:\n # # forward animation\n # if controller.crouches:\n # # TODO: Don't crouch instantly but ease in (bounce?).\n # initial = \"crouch\"\n # else:\n # initial = \"idle\"\n # animation.to_play = [initial, \"walk_forward\", \"run_forward\"]\n # forward_speed = abs(controller.last_translation_speed.y)\n # idle = max(0, (1 - forward_speed * 2))\n # walk = 1 - abs(forward_speed - 0.5) * 2\n # run = max(0, forward_speed * 2 - 1)\n # blends = [idle, walk, run]\n # # strafe animation\n # strafe_speed = controller.last_translation_speed.x\n # if not strafe_speed == 0:\n # blends.append(abs(strafe_speed))\n # if strafe_speed > 0:\n # animation.to_play.append(\"walk_right\")\n # elif strafe_speed < 0:\n # animation.to_play.append(\"walk_left\")\n #\n # animation.framerate = (0.5+(forward_speed + abs(strafe_speed)))\n # # If walking backwards simply play the animation in reverse\n # # Only do this when there's no animations for walking backwards?\n # if controller.last_translation_speed.y < 0:\n # animation.framerate = -animation.framerate\n #\n # animation.blends = blends\n\n\nclass Animate(System):\n entity_filters = {\n 'animation': and_filter([\n Proxy('actor'),\n Animation,\n ])\n }\n proxies = {'actor': ProxyType(Actor, 'node')}\n\n def update(self, entities_by_filter):\n for entity in entities_by_filter['animation']:\n animation = entity[Animation]\n actor_proxy = self.proxies['actor']\n actor = actor_proxy.field(entity)\n\n if not animation.playing == animation.to_play:\n if len(animation.to_play) > 0:\n actor.enableBlend()\n else:\n actor.disableBlend()\n\n # TODO: Don't stop and swap different animations instantly\n # but ease in (and bounce?) between them.\n\n # Stop animations not in to_play.\n for name in animation.playing:\n if name not in animation.to_play:\n actor.stop(name)\n actor.setControlEffect(name, 0)\n\n # Play newly added animations.\n for n, name in enumerate(animation.to_play):\n if name not in animation.playing:\n actor.loop(name)\n animation.playing = animation.to_play\n\n # Set blends each frame\n for b, blend in enumerate(animation.blends):\n if b < len(animation.playing):\n name = animation.playing[b]\n actor.setControlEffect(name, blend/len(animation.playing))\n\n # Set framerate each frame\n for name in animation.playing:\n actor.setPlayRate(animation.framerate, name)\n","sub_path":"wecs/panda3d/animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":6453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"184803207","text":"# MIT License\n#\n# Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport torch\nimport torch.nn as nn\nfrom typing import Tuple, Optional\n\nfrom openspeech.encoders import OpenspeechEncoder\nfrom openspeech.modules import Transpose, Linear\n\n\nclass ConvolutionalLSTMEncoder(OpenspeechEncoder):\n r\"\"\"\n Converts low level speech signals into higher level features with convolutional extractor.\n\n Args:\n input_dim (int): dimension of input vector\n num_classes (int): number of classification\n hidden_state_dim (int): the number of features in the encoders hidden state `h`\n num_layers (int, optional): number of recurrent layers (default: 3)\n bidirectional (bool, optional): if True, becomes a bidirectional encoders (default: False)\n extractor (str): type of CNN extractor (default: vgg)\n conv_activation (str): activation function of convolutional extractor (default: hardtanh)\n rnn_type (str, optional): type of RNN cell (default: lstm)\n dropout_p (float, optional): dropout probability of encoders (default: 0.2)\n joint_ctc_attention (bool, optional): flag indication joint ctc attention or not\n\n Inputs: inputs, input_lengths\n - **inputs**: list of sequences, whose length is the batch size and within which each sequence is list of tokens\n - **input_lengths**: list of sequence lengths\n\n Returns: encoder_outputs, encoder_log__probs, output_lengths\n - **encoder_outputs**: tensor containing the encoded features of the input sequence\n - **encoder_log__probs**: tensor containing log probability for encoder_only loss\n - **output_lengths**: list of sequence lengths produced by Listener\n \"\"\"\n supported_rnns = {\n 'lstm': nn.LSTM,\n 'gru': nn.GRU,\n 'rnn': nn.RNN,\n }\n\n def __init__(\n self,\n input_dim: int,\n num_classes: int = None,\n hidden_state_dim: int = 512,\n dropout_p: float = 0.3,\n num_layers: int = 3,\n bidirectional: bool = True,\n rnn_type: str = 'lstm',\n extractor: str = 'vgg',\n conv_activation: str = 'hardtanh',\n joint_ctc_attention: bool = False,\n ) -> None:\n super(ConvolutionalLSTMEncoder, self).__init__()\n extractor = self.supported_extractors[extractor.lower()]\n self.conv = extractor(input_dim=input_dim, activation=conv_activation)\n self.conv_output_dim = self.conv.get_output_dim()\n\n self.num_classes = num_classes\n self.joint_ctc_attention = joint_ctc_attention\n\n self.hidden_state_dim = hidden_state_dim\n self.rnn = self.supported_rnns[rnn_type.lower()](\n input_size=self.conv_output_dim,\n hidden_size=hidden_state_dim,\n num_layers=num_layers,\n bias=True,\n batch_first=True,\n dropout=dropout_p,\n bidirectional=bidirectional,\n )\n\n if self.joint_ctc_attention:\n self.fc = nn.Sequential(\n Transpose(shape=(1, 2)),\n nn.Dropout(dropout_p),\n Linear(hidden_state_dim << 1, num_classes, bias=False),\n )\n\n def forward(\n self,\n inputs: torch.Tensor,\n input_lengths: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:\n r\"\"\"\n Forward propagate a `inputs` for encoders training.\n\n Args:\n inputs (torch.FloatTensor): A input sequence passed to encoders. Typically for inputs this will be a padded\n `FloatTensor` of size ``(batch, seq_length, dimension)``.\n input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``\n\n Returns:\n (Tensor, Tensor, Tensor):\n\n * outputs: A output sequence of encoders. `FloatTensor` of size ``(batch, seq_length, dimension)``\n * encoder_logits: Log probability of encoders outputs will be passed to CTC Loss.\n If joint_ctc_attention is False, return None.\n * encoder_output_lengths: The length of encoders outputs. ``(batch)``\n \"\"\"\n encoder_logits = None\n\n conv_outputs, output_lengths = self.conv(inputs, input_lengths)\n\n conv_outputs = nn.utils.rnn.pack_padded_sequence(conv_outputs.transpose(0, 1), output_lengths.cpu())\n outputs, hidden_states = self.rnn(conv_outputs)\n outputs, _ = nn.utils.rnn.pad_packed_sequence(outputs)\n outputs = outputs.transpose(0, 1)\n\n if self.joint_ctc_attention:\n encoder_logits = self.fc(outputs.transpose(1, 2)).log_softmax(dim=2)\n\n return outputs, encoder_logits, output_lengths\n","sub_path":"openspeech/encoders/convolutional_lstm_encoder.py","file_name":"convolutional_lstm_encoder.py","file_ext":"py","file_size_in_byte":5793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"629006184","text":"import socket\n\n#============================================================\n# Module: victim.py\n# Author: Patrick Blanchard\n# Purpose: Creates victim udp server.\n# Date: November 8, 2016\n#=============================================================\n\nPORT = 5000\nHOST = \"\"\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.bind((HOST, PORT))\n\nwhile True:\n msg, add = s.recvfrom(1024)\n","sub_path":"udp_victim.py","file_name":"udp_victim.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"169162231","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfilenames1 = [\n\t\"Q_reflection_thin_mirror.CSV\",\n\t\"Q_reflection_experiment.CSV\",\n]\n\n\nfilenames5 = [\n\t\"resonant_frequencies_reflection_thin_mirror.CSV\",\n\t\"resonant_frequencies_reflection_experiment.CSV\"\n]\n\nfilenames6 = [\n\t\"background_level_reflection_thin_mirror.CSV\",\n\t\"background_level_reflection_experiment.CSV\"\n]\ncavity_length_experiment = np.array([17,17.5,18,18.5,19,19.5,20])\ncavity_length_simulation = np.array([17,17.5,18,18.5,19,19.5,20.26])\nfinal_table = np.ndarray(shape = (25,3))\ntable_q_loaded = np.ndarray(shape = (7,3))\nfor index in range(0, len(filenames1)):\n\tA = np.genfromtxt(filenames1[index])\n\ttable_q_loaded[:,index] = A\ntable_q_loaded = np.absolute(table_q_loaded)\n#np.savetxt(\"sd.CSV\",table,delimiter = \",\")\ntable_resonant_frequencies = np.ndarray(shape = (7,3))\nfor index in range(0, len(filenames5)):\n\tA = np.genfromtxt(filenames5[index])\n\ttable_resonant_frequencies[:,index] = A\ntable_resonant_frequencies = np.absolute(table_resonant_frequencies)\n\ntable_background_level = np.ndarray(shape = (7,3))\nfor index in range(0, len(filenames6)):\n\tA = np.genfromtxt(filenames6[index])\n\ttable_background_level[:,index] = A\n\nfinal_table[0:7,:] = table_q_loaded\nfinal_table[9:16,:] = table_resonant_frequencies\nfinal_table[18:25,:] = table_background_level\n\n\nresfre = np.ndarray(shape = (7,5))\nresfre[:,0:3] = table_resonant_frequencies\nresfre[:,3] = [17.8719,17.3613,16.8790,16.4228,15.9907,15.5806,15.1191]\nresfre[:,4] = resfre[:,2]-resfre[:,3]\n#print(resfre)\n#np.set_printoptions(suppress=True,formatter={'float_kind':'{:f}'.format})\n#print(final_table)\n#table = pd.DataFrame(final_table)\n#table.to_csv(\"table.CSV\")\n#table_q_loaded = np.log(table_q_loaded)\n#plt.plot(cavity_length_simulation,table_q_loaded[:,0],'r-',label = 'thick mirror',marker = 'o')\nplt.plot(cavity_length_simulation,table_q_loaded[:,1],'g-',label = 'thin mirror',marker = '*')\nplt.plot(cavity_length_experiment,table_q_loaded[:,2],'b-',label = 'experiment',marker = '^')\nplt.xlabel('Cavity Length(cm)')\nplt.ylabel('Quality Factor(log)')\nplt.legend()\nplt.title('Quality Factors')\nplt.autoscale(enable=True, axis='both', tight=None)\n#plt.yscale('log')\nplt.show()\n#plt.savefig('Q.pdf', bbox_inches='tight')\n#plt.close()\n#table_q_unloaded = np.log(table_q_unloaded)\n\n#plt.plot(cavity_length_simulation,resfre[:,0],'r-',label = 'thick mirror',marker = 'o')\n# plt.plot(cavity_length_simulation,resfre[:,1],'g-',label = 'thin mirror',marker = '*',alpha = 0.8)\n# #plt.plot(cavity_length_experiment,resfre[:,2],'b-',label = 'experiment',marker = '^',linewidth = 1)\n# plt.plot(cavity_length_simulation,resfre[:,3],'y--',label = 'predicted',marker = 's')\n# plt.plot(cavity_length_experiment,resfre[:,2],'b-',label = 'experiment',marker = '^')\n# plt.errorbar(cavity_length_experiment,resfre[:,2],yerr = resfre[:,4])\n# plt.xlabel('Cavity Length(cm)')\n# plt.ylabel('Resonant Frequency(GHz)')\n# plt.legend()\n# plt.title('Resonant Frequencies')\n# plt.tight_layout()\n# plt.autoscale(enable=True, axis='both')\n# plt.show()\n#plt.savefig('Resonant_Frequencies.pdf', bbox_inches='tight')\n#plt.close()\n\n\n","sub_path":"reflection_table.py","file_name":"reflection_table.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"220084541","text":"\"\"\"\nDerived module from profilebase.py to provide the airfoil coordinates.\n\"\"\"\nfrom scipy.interpolate import splev, splrep\nimport numpy as np\nfrom .profilebase import ProfileBase\n\n\nclass CustomProfile(ProfileBase):\n \"\"\"\n Provide custom profile for the airfoil coordinates.\n\n :param numpy.ndarray xup: 1D array that contains the X-components of the\n airfoil's upper surface\n :param numpy.ndarray xdown: 1D array that contains the X-components of the\n airfoil's lower surface\n :param numpy.ndarray yup: 1D array that contains the Y-components of the\n airfoil's upper surface\n :param numpy.ndarray ydown: 1D array that contains the Y-components of the\n airfoil's lower surface\n \"\"\"\n\n def __init__(self, xup, yup, xdown, ydown):\n super(CustomProfile, self).__init__()\n self.xup_coordinates = xup\n self.yup_coordinates = yup\n self.xdown_coordinates = xdown\n self.ydown_coordinates = ydown\n self._check_coordinates()\n\n def _check_coordinates(self):\n \"\"\"\n Private method that checks whether the airfoil coordinates defined\n are provided correctly.\n\n We note that each array of coordinates must be consistent with the\n other arrays. The upper and lower surfaces should start from exactly\n the same point, the leading edge, and proceed on the way till the\n trailing edge. The trailing edge might have a non-zero thickness as\n in the case of some NACA-airfoils. In case of an open trailing edge,\n the average coordinate between upper and lower part is taken as the\n unique value.\n\n :raises ValueError: if either xup, xdown, yup, ydown is None\n :raises ValueError: if the 1D arrays xup, yup or xdown, ydown do not\n have the same length\n :raises ValueError: if array yup not greater than or equal array ydown\n element-wise\n :raises ValueError: if xdown[0] != xup[0] or ydown[0] != yup[0]\n or xdown[-1] != xup[-1]\n \"\"\"\n if self.xup_coordinates is None:\n raise ValueError(\n 'object \"xup_coordinates\" refers to an empty array.')\n if self.xdown_coordinates is None:\n raise ValueError(\n 'object \"xdown_coordinates\" refers to an empty array.')\n if self.yup_coordinates is None:\n raise ValueError(\n 'object \"yup_coordinates\" refers to an empty array.')\n if self.ydown_coordinates is None:\n raise ValueError(\n 'object \"ydown_coordinates\" refers to an empty array.')\n\n if not isinstance(self.xup_coordinates, np.ndarray):\n self.xup_coordinates = np.asarray(self.xup_coordinates, dtype=float)\n if not isinstance(self.xdown_coordinates, np.ndarray):\n self.xdown_coordinates = np.asarray(\n self.xdown_coordinates, dtype=float)\n if not isinstance(self.yup_coordinates, np.ndarray):\n self.yup_coordinates = np.asarray(self.yup_coordinates, dtype=float)\n if not isinstance(self.ydown_coordinates, np.ndarray):\n self.ydown_coordinates = np.asarray(\n self.ydown_coordinates, dtype=float)\n\n # Therefore the arrays xup_coordinates and yup_coordinates must have\n # the same length = N, same holds for the arrays xdown_coordinates\n # and ydown_coordinates.\n if self.xup_coordinates.shape != self.yup_coordinates.shape:\n raise ValueError(\n 'xup_coordinates and yup_coordinates must have same shape.')\n if self.xdown_coordinates.shape != self.ydown_coordinates.shape:\n raise ValueError(\n 'xdown_coordinates and ydown_coordinates must have same shape.')\n\n # The condition yup_coordinates >= ydown_coordinates must be satisfied\n # element-wise to the whole elements in the mentioned arrays.\n if not all(\n np.greater_equal(self.yup_coordinates, self.ydown_coordinates)):\n raise ValueError(\n 'yup_coordinates is not >= ydown_coordinates elementwise.')\n\n if not self.xdown_coordinates[0] == self.xup_coordinates[0]:\n raise ValueError(\n '(xdown_coordinates[0]=xup_coordinates[0]) not satisfied.')\n if not self.ydown_coordinates[0] == self.yup_coordinates[0]:\n raise ValueError(\n '(ydown_coordinates[0]=yup_coordinates[0]) not satisfied.')\n if not self.xdown_coordinates[-1] == self.xup_coordinates[-1]:\n raise ValueError(\n '(xdown_coordinates[-1]=xup_coordinates[-1]) not satisfied.')\n\n\nclass NacaProfile(ProfileBase):\n \"\"\"\n Generate 4- and 5-digit NACA profiles.\n\n The NACA airfoils are airfoil shapes for aircraft wings developed by the\n National Advisory Committee for Aeronautics (NACA). The shape of the NACA\n airfoils is described using a series of digits following the word \"NACA\".\n The parameters in the numerical code can be entered into equations to\n precisely generate the cross-section of the airfoil and calculate its\n properties.\n\n The NACA four-digit series describes airfoil by the format MPTT, where:\n\n - M/100: indicates the maximum camber in percentage, with respect to the\n chord length.\n\n - P/10: indicates the location of the maximum camber measured from the\n leading edge. The location is normalized by the chord length.\n \n - TT/100: the maximum thickness as fraction of the chord length.\n\n The profile 00TT refers to a symmetrical NACA airfoil.\n\n The NACA five-digit series describes more complex airfoil shapes.\n Its format is: LPSTT, where:\n \n - L: the theoretical optimum lift coefficient at ideal\n angle-of-attack = 0.15*L\n \n - P: the x-coordinate of the point of maximum camber\n (max camber at x = 0.05*P)\n \n - S: indicates whether the camber is simple (S=0) or reflex (S=1)\n TT/100: the maximum thickness in percent of chord, as in a four-digit\n NACA airfoil code\n\n References:\n \n - Moran, Jack (2003). An introduction to theoretical and computational\n aerodynamics. Dover. p. 7. ISBN 0-486-42879-6.\n \n - Abbott, Ira (1959). Theory of Wing Sections: Including a Summary of\n Airfoil Data. New York: Dover Publications. p. 115. ISBN 978-0486605869.\n\n :param str digits: 4 or 5 digits that describes the NACA profile\n :param int n_points: number of discrete points that represents the\n airfoil profile. Default value is 240\n :param bool cosine_spacing: if True, then a cosine spacing is used for the\n airfoil coordinate distribution, otherwise linear spacing is used.\n Default value is True\n :raises ValueError: if n_points is not positive\n :raises TypeError: if n_points is not of type int\n :raises SyntaxError: if digits is not a string\n :raises Exception: if digits is not of length 4 or 5\n \"\"\"\n\n def __init__(self, digits, n_points=240, cosine_spacing=True):\n super(NacaProfile, self).__init__()\n self.digits = digits\n self.n_points = n_points\n self.cosine_spacing = cosine_spacing\n self._check_args()\n self._generate_coordinates()\n\n def _check_args(self):\n \"\"\"\n Private method to check that the number of the airfoil discrete points\n is a positive integer.\n \"\"\"\n if not isinstance(self.digits, str):\n raise TypeError('digits must be of type string.')\n if isinstance(self.n_points, float):\n self.n_points = int(self.n_points)\n if not isinstance(self.n_points, int):\n raise TypeError('n_points must be of type integer.')\n if self.n_points < 0:\n raise ValueError('n_points must be positive.')\n\n def _generate_coordinates(self):\n \"\"\"\n Private method that generates the coordinates of the NACA 4 or 5 digits\n airfoil profile. The method assumes a zero-thickness trailing edge, and\n no half-cosine spacing.\n \"\"\"\n a0 = +0.2969\n a1 = -0.1260\n a2 = -0.3516\n a3 = +0.2843\n a4 = -0.1036 # zero thickness TE\n\n x = np.linspace(0.0, 1.0, num=self.n_points)\n\n if len(self.digits) == 4:\n # Returns n+1 points in [0 1] for the given 4-digits NACA string\n m = float(self.digits[0]) / 100.0\n p = float(self.digits[1]) / 10.0\n t = float(self.digits[2:]) / 100.0\n\n # half-thickness distribution\n yt = 5 * t * (a0 * np.sqrt(x) + a1 * x + a2 * np.power(x, 2) +\n a3 * np.power(x, 3) + a4 * np.power(x, 4))\n\n if p == 0:\n # Symmetric foil\n self.xup_coordinates = np.linspace(0.0, 1.0, num=self.n_points)\n self.yup_coordinates = yt\n self.xdown_coordinates = np.linspace(\n 0.0, 1.0, num=self.n_points)\n self.ydown_coordinates = -yt\n else:\n # Cambered foil\n xc1 = np.asarray([xx for xx in x if xx <= p])\n xc2 = np.asarray([xx for xx in x if xx > p])\n yc1 = m / np.power(p, 2) * xc1 * (2 * p - xc1)\n yc2 = m / np.power(1 - p, 2) * (1 - 2 * p + xc2) * (1 - xc2)\n # Y-coordinates of camber line\n yc = np.append(yc1, yc2)\n\n if self.cosine_spacing:\n # points are generated according to cosine distribution of\n # the X-coordinates of the chord\n dyc1_dx = m / np.power(p, 2) * (2 * p - 2 * xc1)\n dyc2_dx = m / np.power(1 - p, 2) * (2 * p - 2 * xc2)\n dyc_dx = np.append(dyc1_dx, dyc2_dx)\n theta = np.arctan(dyc_dx)\n self.xup_coordinates = x - yt * np.sin(theta)\n self.yup_coordinates = yc + yt * np.cos(theta)\n self.xdown_coordinates = x + yt * np.sin(theta)\n self.ydown_coordinates = yc - yt * np.cos(theta)\n else:\n # Linear spacing distribution of the foil coordinates\n self.xup_coordinates = np.linspace(\n 0.0, 1.0, num=self.n_points)\n self.xdown_coordinates = np.linspace(\n 0.0, 1.0, num=self.n_points)\n self.yup_coordinates = yc + yt\n self.ydown_coordinates = yc - yt\n\n elif len(self.digits) == 5:\n # Returns n+1 points in [0 1] for the given 5-digits NACA string\n cld = float(self.digits[0]) * 0.15\n p = 5.0 * float(self.digits[1]) / 100.0\n s = float(self.digits[2])\n t = float(self.digits[3:]) / 100.0\n\n # half-thickness distribution\n yt = 5 * t * (a0 * np.sqrt(x) + a1 * x + a2 * np.power(x, 2) +\n a3 * np.power(x, 3) + a4 * np.power(x, 4))\n\n if s == 1:\n # Relfex camber\n P = np.array([0.1, 0.15, 0.2, 0.25])\n M = np.array([0.13, 0.2170, 0.318, 0.441])\n K = np.array([51.99, 15.793, 6.520, 3.191])\n elif s == 0:\n # Standard camber\n P = np.array([0.05, 0.1, 0.15, 0.2, 0.25])\n M = np.array([0.0580, 0.1260, 0.2025, 0.2900, 0.3910])\n K = np.array([361.4, 51.64, 15.957, 6.643, 3.230])\n else:\n raise ValueError(\n 'For NACA \"LPSTT\" the value of \"S\" can be either 0 or 1.')\n\n if p == 0:\n # Symmetric foil\n self.xup_coordinates = np.linspace(0.0, 1.0, num=self.n_points)\n self.yup_coordinates = yt\n self.xdown_coordinates = np.linspace(\n 0.0, 1.0, num=self.n_points)\n self.ydown_coordinates = -yt\n else:\n # Cambered foil\n spl_m = splrep(P, M)\n spl_k = splrep(M, K)\n m = splev(p, spl_m)\n k1 = splev(m, spl_k)\n xc1 = np.asarray([xx for xx in x if xx <= m])\n xc2 = np.asarray([xx for xx in x if xx > m])\n yc1 = k1 / 6.0 * (np.power(xc1, 3) - 3 * m * np.power(xc1, 2) +\n np.power(m, 2) * (3 - m) * xc1)\n yc2 = k1 / 6.0 * np.power(m, 3) * (1 - xc2)\n yc = np.append(yc1, yc2)\n\n if self.cosine_spacing:\n # points are generated according to cosine distribution of\n # the X-coordinates of the chord\n zc = cld / 0.3 * yc\n dyc1_dx = 1.0 / 6.0 * k1 * (\n 3 * np.power(xc1, 2) - 6 * m * xc1 + np.power(m, 2) *\n (3 - m))\n dyc2_dx = np.tile(-1.0 / 6.0 * k1 * np.power(m, 3),\n len(xc2))\n dyc_dx = np.append(dyc1_dx, dyc2_dx)\n theta = np.arctan(dyc_dx)\n self.xup_coordinates = x - yt * np.sin(theta)\n self.yup_coordinates = zc + yt * np.cos(theta)\n self.xdown_coordinates = x + yt * np.sin(theta)\n self.ydown_coordinates = zc - yt * np.cos(theta)\n else:\n # Linear spacing distribution of the foil coordinates\n self.xup_coordinates = np.linspace(\n 0.0, 1.0, num=self.n_points)\n self.xdown_coordinates = np.linspace(\n 0.0, 1.0, num=self.n_points)\n self.yup_coordinates = yc + yt\n self.ydown_coordinates = yc - yt\n\n else:\n raise Exception\n","sub_path":"bladex/profiles.py","file_name":"profiles.py","file_ext":"py","file_size_in_byte":13906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"101198623","text":"import cv2\nimport matplotlib.pyplot as plt\nimport rasterio\nimport pyastar2d\nimport numpy as np\nimport sys\nfrom shapely.geometry import LineString\nimport os\n\nraster_one = rasterio.open(\"/home/bisag/.local/share/QGIS/QGIS3/profiles/default/python/plugins/raster_path/OS1_Reclassify.tif\")\n\nprint(sys.argv)\ngrid = raster_one.read(1).astype(np.float32)\n\nprint(grid[0])\ngrid[grid < 1] = np.inf\n\nstart = raster_one.index(float(sys.argv[1]), float(sys.argv[2]))\nend = raster_one.index(float(sys.argv[3]), float(sys.argv[4]))\n\nprint(start, end)\n\nprint(grid[start[0], start[1]])\nprint(grid[end[0], end[1]])\n\n# start = raster_one.index(self.xy[-4], self.xy[-3])\n# end = raster_one.index(self.xy[-2], self.xy[-1])\n\nif grid[start[0], start[1]] == np.inf or grid[end[0], end[1]] == np.inf:\n raise Exception(\"start and end points must not be obstacle\")\n\n\ndef update_grid(grid, path, margin=20):\n if path is None:\n return\n prev_point = path[1]\n for point in path[2:]:\n change_x = abs(point[1] - prev_point[1])\n change_y = abs(point[0] - prev_point[0])\n if change_y == 1:\n grid[prev_point[0], prev_point[1]: prev_point[1] + margin] = np.inf\n grid[prev_point[0], prev_point[1] - margin:prev_point[1]] = np.inf\n elif change_x == 1:\n grid[prev_point[0]: prev_point[0] + margin, prev_point[1]] = np.inf\n grid[prev_point[0] - margin: prev_point[0], prev_point[1]] = np.inf\n prev_point = point\n return grid\n\n\ndef compute_bounds(start, end):\n return [min(start[0], end[0]), min(start[1], end[1])], [max(start[0], end[0]), max(start[1], end[1])]\n\n\ndef save_image(fn, grid):\n grid[grid == np.inf] = 255\n cv2.imwrite(fn, grid.astype(np.uint8))\n\n\ndef compute_paths(grid, nb_paths=5):\n paths = [None] * nb_paths\n save_image(\"/home/bisag/.local/share/QGIS/QGIS3/profiles/default/python/plugins/raster_path/1.jpg\", grid)\n paths[0] = pyastar2d.astar_path(grid, start, end, allow_diagonal=False)\n for i in range(nb_paths - 1):\n grid = update_grid(grid, paths[i])\n save_image(\"/home/bisag/.local/share/QGIS/QGIS3/profiles/default/python/plugins/raster_path/\"+f\"{i + 2}.jpg\", grid)\n paths[i+1] = pyastar2d.astar_path(grid, start, end, allow_diagonal=False)\n return paths\n\n\npaths = compute_paths(grid)\n\npoints = []\n\nczml_list = []\n\nwith open(\"/home/bisag/.local/share/QGIS/QGIS3/profiles/default/python/plugins/raster_path/path.txt\", \"w\") as f:\n for path in paths:\n points = []\n if path is None:\n continue\n for location in path:\n points.append(raster_one.xy(location[0], location[1]))\n path_ls = LineString(points)\n f.write(path_ls.wkt + os.linesep)\nprint(points)\n# with open(\"/home/bisag/.local/share/QGIS/QGIS3/profiles/default/python/plugins/raster_path/path.txt\", \"w\") as f:\n# for location in path:\n# points.append(raster_one.xy(location[0], location[1]))\n# path_ls = LineString(points)\n# f.write(path_ls.wkt)\n\nwith open(\"/home/bisag/.local/share/QGIS/QGIS3/profiles/default/python/plugins/raster_path/path_points.txt\", 'w') as f:\n for point in points:\n f.write(str(point)+ os.linesep)\n\n\nindex_file = open(\"/home/bisag/.local/share/QGIS/QGIS3/profiles/default/python/plugins/raster_path/index.html\", \"w\")\nindex_file.truncate()\nindex_file.close()\n\nwith open(\"/home/bisag/.local/share/QGIS/QGIS3/profiles/default/python/plugins/raster_path/index.html\", 'w') as f:\n mycarto_cords= \"\"\n for point in points:\n mycarto_cords += str(point).replace(\"(\",\"\").replace(\")\",\", 0,\")\n str1 = '''\n \n \n \n \n \n \n \n Index\n \n \n \n \n\n \n \n
\n \n \n \n\n '''\n\n f.write(str1)\n","sub_path":"shortest_path.py","file_name":"shortest_path.py","file_ext":"py","file_size_in_byte":5733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"237235543","text":"import unittest\nfrom google.protobuf import json_format\nimport json\n\nimport rastervision as rv\nfrom rastervision.core.class_map import ClassItem\nfrom rastervision.protos.task_pb2 import TaskConfig as TaskConfigMsg\nfrom rastervision.protos.class_item_pb2 import ClassItem as ClassItemMsg\n\n\nclass TestChipClassificationConfig(unittest.TestCase):\n def test_build_task(self):\n classes = ['one', 'two']\n expected = [ClassItem(1, 'one'), ClassItem(2, 'two')]\n\n t = rv.TaskConfig.builder(rv.CHIP_CLASSIFICATION) \\\n .with_classes(classes) \\\n .build()\n\n self.assertEqual(t.task_type, rv.CHIP_CLASSIFICATION)\n self.assertListEqual(t.class_map.get_items(), expected)\n\n def test_build_task_from_proto(self):\n task_config = {\n 'task_type': rv.CHIP_CLASSIFICATION,\n 'chip_classification_config': {\n 'chip_size':\n 500,\n 'class_items': [{\n 'id': 1,\n 'name': 'car',\n 'color': 'red'\n }, {\n 'id': 2,\n 'name': 'building',\n 'color': 'blue'\n }, {\n 'id': 3,\n 'name': 'background',\n 'color': 'black'\n }]\n }\n }\n msg = json_format.Parse(json.dumps(task_config), TaskConfigMsg())\n\n task = rv.TaskConfig.from_proto(msg)\n\n self.assertEqual(task.class_map.get_by_name('building').id, 2)\n self.assertEqual(task.chip_size, 500)\n\n def test_create_proto_from_task(self):\n t = rv.TaskConfig.builder(rv.CHIP_CLASSIFICATION) \\\n .with_classes(['car', 'boat']) \\\n .with_chip_size(500) \\\n .build()\n\n msg = t.to_proto()\n\n expected_classes = [\n ClassItemMsg(name='car', id=1),\n ClassItemMsg(name='boat', id=2)\n ]\n\n self.assertEqual(msg.task_type, rv.CHIP_CLASSIFICATION)\n self.assertEqual(msg.chip_classification_config.chip_size, 500)\n\n actual_class_items = dict(\n [(i.id, i) for i in msg.chip_classification_config.class_items])\n expected_class_items = dict([(i.id, i) for i in expected_classes])\n\n self.assertDictEqual(actual_class_items, expected_class_items)\n\n def test_missing_config_class_map(self):\n with self.assertRaises(rv.ConfigError):\n rv.TaskConfig.builder(rv.CHIP_CLASSIFICATION).build()\n\n def test_no_missing_config(self):\n try:\n rv.TaskConfig.builder(rv.CHIP_CLASSIFICATION).with_classes(\n ['car']).build()\n except rv.ConfigError:\n self.fail('ConfigError raised unexpectedly')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/task/test_chip_classification_config.py","file_name":"test_chip_classification_config.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"20959520","text":"import csv\r\nfrom random import shuffle\r\n\r\n\r\ndef getWordsTuple(file, col=0, lowerbound=0):\r\n\twords = []\r\n\twith open(file) as f:\r\n\t\twordreader = csv.reader(f, delimiter = ',')\r\n\t\tfor row in wordreader:\r\n\t\t\twords.append(row[col].strip())\r\n\tshuffle(words)\r\n\tprint (words[lowerbound])\r\n\r\n\r\nword_csv_name = \"SimpsonsFreq.csv\"\r\ncol = 1\r\ngetWordsTuple(word_csv_name, col)","sub_path":"SingleWord.py","file_name":"SingleWord.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"651997864","text":"#coding=utf-8\n'''\n在test5的基础上,来源网络,采用CohFrictMat材料,绿球固定,其余两球掉落,因为内聚力不会掉落\n'''\nfrom yade import ymport, pack, plot\nimport operator\nrMean = 0.0025\n\nO.materials.append(\n CohFrictMat(young=50000,\n poisson=1,\n density=70000,\n frictionAngle=radians(0),\n isCohesive=True,\n normalCohesion=10000,\n shearCohesion=10000,\n etaRoll=0.1,\n momentRotationLaw=True,\n alphaKr=0.1,\n alphaKtw=0.1,\n label=\"sphereMat\"))\n\nid1=O.bodies.append(\n utils.sphere(center=(2e-2, 4e-2 + (2 * rMean), 0e-2),\n radius=rMean,\n material=\"sphereMat\",\n fixed=False,\n color=(1, 0, 0)))\nO.bodies.append(\n utils.sphere(center=(2e-2 + (2 * rMean), 4e-2, 0e-2),\n radius=rMean,\n material=\"sphereMat\",\n fixed=True,\n color=(0, 0, 1)))\nO.bodies.append(\n utils.sphere(center=(2e-2, 4e-2, 0e-2),\n radius=rMean,\n material=\"sphereMat\",\n fixed=True,\n color=(0, 1, 0)))\n\nO.engines = [\n ForceResetter(),\n InsertionSortCollider(\n [Bo1_Sphere_Aabb(aabbEnlargeFactor=1.5),\n Bo1_Facet_Aabb()]),\n InteractionLoop([\n Ig2_Sphere_Sphere_ScGeom6D(interactionDetectionFactor=1.5),\n # Ig2_Facet_Sphere_ScGeom()\n ], [\n # Ip2_FrictMat_FrictMat_FrictPhys(),\n Ip2_CohFrictMat_CohFrictMat_CohFrictPhys(setCohesionNow=True,\n label=\"cohesiveIp\")\n ], [\n # Law2_ScGeom_FrictPhys_CundallStrack(),\n Law2_ScGeom6D_CohFrictPhys_CohesionMoment(useIncrementalForm=True,\n label='cohesiveLaw')\n ]),\n NewtonIntegrator(damping=0.8),\n PyRunner(command='check()', iterPeriod=100),\n]\nO.dt = .0005 * utils.PWaveTimeStep()\n\nt=0.1\ndef check():\n f=O.forces.f(id1)\n plot.addData(t=O.time, ff=f[1])\n cohesiveIp.setCohesionNow=True\n if O.time < t:\n vel2=0.01\n O.bodies[0].state.vel=[0, vel2, 0]\n # O.bodies[id14].state.vel=[0, 0, vel2]\n elif O.time < 2*t:\n vel2=-0.01\n O.bodies[0].state.vel=[0, vel2, 0] \n else:\n O.pause()\n\nplot.plots={'t':('ff')}\nplot.plot(subPlots=False)\n\nfrom yade import qt\nqt.View()\nO.saveTmp()\n","sub_path":"test8.py","file_name":"test8.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"544255145","text":"# -*- coding: utf-8 -*-\nimport webapp2\nfrom db import Data_Model, Root_Model\n\n\nclass Cms(webapp2.RequestHandler):\n def __init__(self, request, response, **kwargs):\n #webapp2.RequestHandler.__init__(self, request, response, **kwargs)\n self.initialize(request, response, **kwargs)\n #root_model = Root_Model()\n #self.rkey=root_model.put_data('this is root one')\n self.data_model = Data_Model(parent=Data_Model.get_url_key('ag5kZXZ-ZGVidWdkdWRlN3IXCxIKUm9vdF9Nb2RlbBiAgICAgOD_CQw'))\n\n def get(self):\n self.response.headers['Content-Type'] = 'text/html'\n name = self.request.get('name', 'World')\n self.save_name(name)\n self.response.write(\"\")\n self.response.write(\"

Hello, %s!\" % name)\n\n def save_name(self, name):\n self.data_model.put_data(name)\n\n def get_names(self, key):\n res=''\n names = Data_Model.query_model(key).fetch(20)\n for nm in names:\n res=res+'
%s
' % nm.name\n return res\n\napplication = webapp2.WSGIApplication([\n ('/', Cms),\n], debug=True)\n\n\ndef main():\n application.run()\n\nif __name__ == '__main__':\n main()","sub_path":"cms.py","file_name":"cms.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"212473254","text":"\"\"\" locationAPI.py\n\n This module implements the 3taps Location API.\n\"\"\"\nimport traceback\n\nimport simplejson as json\n\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.gis.geos import Polygon, Point\n\nfrom data.models import Level, Location, Name, LocationName\nfrom data.models import Outline, TableauCacheEntry\n\nimport tableauGenerator\n\n#############################################################################\n\n@csrf_exempt\ndef get(request):\n \"\"\" Implement the \"/geo/api/location/get\" API call.\n \"\"\"\n locations = get_param(request, \"locations\")\n if locations == None:\n location = get_param(request, \"location\")\n if location == None:\n return error_response(code=400,\n message=\"Missing 'locations' or 'location' \"\n +\"parameter.\",\n callback=get_param(request, \"callback\"))\n locations = [location]\n has_multi = False\n else:\n try:\n locations = json.loads(locations)\n except:\n return error_response(code=400,\n message=\"Invalid 'locations' parameter.\",\n callback=get_param(request, \"callback\"))\n has_multi = True\n\n results = []\n for loc_code in locations:\n try:\n location = Location.objects.get(code=loc_code)\n except Location.DoesNotExist:\n return error_response(code=400,\n message=\"Missing or invalid location code\",\n callback=get_param(request, \"callback\"))\n\n loc_data = {}\n loc_data['code'] = location.code\n loc_data['level'] = level_to_name(location.level)\n loc_data['name'] = location.name\n loc_data['displayName'] = location.display_name\n loc_data['abbreviation'] = location.abbreviation\n loc_data['minZoomLat'] = float(location.min_zoom_lat)\n loc_data['maxZoomLat'] = float(location.max_zoom_lat)\n loc_data['minZoomLong'] = float(location.min_zoom_long)\n loc_data['maxZoomLong'] = float(location.max_zoom_long)\n loc_data['context'] = get_context(location)\n\n if location.population != None:\n loc_data['population'] = location.population\n\n if location.area != None:\n loc_data['area'] = location.area\n\n if location.averageIncome != None:\n loc_data['averageIncome'] = int(location.averageIncome)\n\n results.append(loc_data)\n\n if has_multi:\n results = json.dumps({'locations' : results})\n else:\n results = json.dumps({'location' : results[0]})\n\n callback = get_param(request, \"callback\")\n if callback != None:\n results = callback + \"(\" + results + \")\" # Add JSONP callback.\n\n return HttpResponse(results, mimetype=\"application/json\")\n\n#############################################################################\n\n@csrf_exempt\ndef parents(request):\n \"\"\" Implement the \"/geo/api/location/parents\" API call.\n \"\"\"\n loc_code = get_param(request, \"location\")\n\n try:\n location = Location.objects.get(code=loc_code)\n except Location.DoesNotExist:\n return error_response(code=400,\n message=\"Missing or invalid location code\",\n callback=get_param(request, \"callback\"))\n\n parents = []\n for parent in location.parents.all():\n parents.append(parent.code)\n\n results = json.dumps({'parents' : parents})\n\n callback = get_param(request, \"callback\")\n if callback != None:\n results = callback + \"(\" + results + \")\" # Add JSONP callback.\n\n return HttpResponse(results, mimetype=\"application/json\")\n\n#############################################################################\n\n@csrf_exempt\ndef children(request):\n \"\"\" Implement the \"/geo/api/location/children\" API call.\n \"\"\"\n loc_code = get_param(request, \"location\")\n\n if loc_code != None:\n # We've been asked to generate a list of all children of the given\n # location.\n try:\n location = Location.objects.get(code=loc_code)\n except Location.DoesNotExist:\n return error_response(code=400,\n message=\"Missing or invalid location code\",\n callback=get_param(request, \"callback\"))\n\n children = []\n for child in location.children.all():\n children.append(child.code)\n\n results = json.dumps({'children' : children})\n\n callback = get_param(request, \"callback\")\n if callback != None:\n results = callback + \"(\" + results + \")\" # Add JSONP callback.\n\n return HttpResponse(results, mimetype=\"application/json\")\n\n # If we get here, we don't have a parent location -> assemble a list of all\n # the top-level (country) locations.\n\n countryLevel = Level.objects.get(level=1)\n\n countries = []\n for country in Location.objects.filter(level=countryLevel):\n countries.append(country.code)\n\n results = json.dumps({'children' : countries})\n\n callback = get_param(request, \"callback\")\n if callback != None:\n results = callback + \"(\" + results + \")\" # Add JSONP callback.\n\n return HttpResponse(results, mimetype=\"application/json\")\n\n#############################################################################\n\n@csrf_exempt\ndef neighbors(request):\n \"\"\" Implement the \"/geo/api/location/neighbors\" API call.\n \"\"\"\n loc_code = get_param(request, \"location\")\n\n try:\n location = Location.objects.get(code=loc_code)\n except Location.DoesNotExist:\n return error_response(code=400,\n message=\"Missing or invalid location code\",\n callback=get_param(request, \"callback\"))\n\n neighbours = []\n for neighbour in location.neighbors.all():\n neighbours.append(neighbour.code)\n\n results = json.dumps({'neighbors' : neighbours})\n\n callback = get_param(request, \"callback\")\n if callback != None:\n results = callback + \"(\" + results + \")\" # Add JSONP callback.\n\n return HttpResponse(results, mimetype=\"application/json\")\n\n#############################################################################\n\n@csrf_exempt\ndef search_by_name(request):\n \"\"\" Implement the \"/geo/api/location/search/name\" API call.\n \"\"\"\n # Extract our parameters.\n\n levels = []\n\n level_param = get_param(request, \"level\")\n if level_param != None:\n level = name_to_level(level_param)\n if level == None:\n return error_response(code=400,\n message=\"Unknown level: \"+repr(level_param),\n callback=get_param(request, \"callback\"))\n levels.append(level)\n else:\n levels_param = get_param(request, \"levels\")\n if levels_param != None:\n for level_name in levels_param.split(\",\"):\n level = name_to_level(level_name)\n if level == None:\n return error_response(code=400,\n message=\"Unknown level: \"+repr(level_param),\n callback=get_param(request, \"callback\"))\n levels.append(level)\n\n text = get_param(request, \"text\")\n\n if text == None:\n return error_response(code=400, message=\"Missing 'text' parameter.\",\n callback=get_param(request, \"callback\"))\n if len(text) < 3:\n return error_response(code=400, message=\"'text' parameter too short.\",\n callback=get_param(request, \"callback\"))\n\n type = get_param(request, \"type\")\n\n if type != None:\n type = type.lower()\n if not type in [\"exact\", \"contains\", \"startswith\", \"endswith\",\n \"iexact\", \"icontains\", \"istartswith\", \"iendswith\"]:\n return error_response(code=400,\n message=\"Invalid 'type' parameter: \" +\n repr(type),\n callback=get_param(request, \"callback\"))\n else:\n type = \"istartswith\" # Default search type.\n\n # Perform the appropriate type of name-based search.\n\n args = {'name__' + str(type) : text}\n if len(levels) > 0:\n args['level__in'] = levels\n\n query = Name.objects.filter(**args).order_by(\"level__level\", \"name\")\n results = {}\n\n num_matches = query.count()\n results['numMatches'] = num_matches\n\n if num_matches <= 20:\n matches = []\n matched_locs = set() # Used to only include each location once.\n\n for name in query:\n for loc_name in name.locationname_set.all():\n location = loc_name.location\n if location in matched_locs:\n # Only include each location once.\n continue\n\n matches.append({'level' : level_to_name(location.level),\n 'code' : location.code,\n 'foundName' : name.name,\n 'locationName' : location.name,\n 'displayName' : location.display_name,\n 'abbreviation' : location.abbreviation,\n 'context' : get_context(location)})\n\n matched_locs.add(location)\n\n results['locations'] = matches\n\n # Finally, return the results back to the caller.\n\n results = json.dumps(results)\n callback = get_param(request, \"callback\")\n if callback != None:\n results = callback + \"(\" + results + \")\" # Add JSONP callback.\n\n return HttpResponse(results, mimetype=\"application/json\")\n\n#############################################################################\n\n@csrf_exempt\ndef search_by_bbox(request):\n \"\"\" Implement the \"/geo/api/location/search/bbox\" API call.\n \"\"\"\n # Extract our parameters.\n\n levels = [] # List of desired Level objects.\n\n levels_param = get_param(request, \"levels\")\n if levels_param != None:\n for level_name in levels_param.split(\",\"):\n level = name_to_level(level_name)\n if level == None:\n return error_response(code=400, message=\"Unknown level: \" +\n repr(level_name),\n callback=get_param(request, \"callback\"))\n else:\n levels.append(level)\n\n minlat = get_param(request, \"minlat\")\n maxlat = get_param(request, \"maxlat\")\n minlong = get_param(request, \"minlong\")\n maxlong = get_param(request, \"maxlong\")\n\n try:\n minlat = float(minlat)\n except:\n return error_response(code=400,\n message=\"Invalid minlat: \" + repr(minlat),\n callback=get_param(request, \"callback\"))\n\n try:\n maxlat = float(maxlat)\n except:\n return error_response(code=400,\n message=\"Invalid maxlat: \" + repr(maxlat),\n callback=get_param(request, \"callback\"))\n\n try:\n minlong = float(minlong)\n except:\n return error_response(code=400,\n message=\"Invalid minlong: \" + repr(minlong),\n callback=get_param(request, \"callback\"))\n\n try:\n maxlong = float(maxlong)\n except:\n return error_response(code=400,\n message=\"Invalid maxlong: \" + repr(maxlong),\n callback=get_param(request, \"callback\"))\n\n \n # Create a Polygon geometry that encompasses the specified bounding box.\n\n bounds = Polygon.from_bbox((minlong,minlat,maxlong,maxlat))\n\n # Perform a spatial query to return all objects that *might* be in our\n # bounding box. Note that, because of limitations in MySQL, we have to\n # then check each object individually.\n\n locations = [] # List of all location codes within our desired bounds.\n\n for outline in Outline.objects.filter(location__level__in=levels,\n outline__intersects=bounds):\n mpoly = outline.outline\n if mpoly.intersects(bounds):\n locations.append(outline.location.code)\n\n # Finally, return the results back to the caller.\n\n results = json.dumps({'locations' : locations})\n\n callback = get_param(request, \"callback\")\n if callback != None:\n results = callback + \"(\" + results + \")\" # Add JSONP callback.\n\n return HttpResponse(results, mimetype=\"application/json\")\n\n#############################################################################\n\n@csrf_exempt\ndef search_by_latlong(request):\n \"\"\" Implement the \"/geo/api/location/search/latlong\" API call.\n \"\"\"\n # Process our CGI parameters.\n\n try:\n latitude = float(request.GET['lat'])\n except:\n return error_response(code=400,\n message=\"Missing or invalid 'lat' parameter.\",\n callback=get_param(request, \"callback\"))\n\n try:\n longitude = float(request.GET['long'])\n except:\n return error_response(code=400,\n message=\"Missing or invalid 'long' parameter.\",\n callback=get_param(request, \"callback\"))\n\n try:\n strategy = request.GET['strategy']\n except KeyError:\n return error_response(code=400,\n message=\"Missing 'strategy' parameter.\",\n callback=get_param(request, \"callback\"))\n\n if strategy == \"all\":\n pass\n elif strategy == \"level\":\n try:\n levels_param = request.GET['levels']\n except KeyError:\n return error_response(code=400,\n message=\"Missing 'levels' parameter.\",\n callback=get_param(request, \"callback\"))\n\n levels = [] # List of desired Level objects.\n for level_name in levels_param.split(\",\"):\n level = name_to_level(level_name)\n if level != None:\n levels.append(level)\n else:\n return error_response(code=400, message=\"Unknown level: \" +\n repr(level_name),\n callback=get_param(request, \"callback\"))\n elif strategy == \"parent\":\n try:\n loc_code = request.GET['location']\n except KeyError:\n return error_response(code=400,\n message=\"Missing 'location' parameter.\",\n callback=get_param(request, \"callback\"))\n\n if loc_code == \"WORLD\":\n location = None\n else:\n try:\n location = Location.objects.get(code=loc_code)\n except Location.DoesNotExist:\n return error_response(code=400,\n message=\"Unknown location \" +\n repr(loc_code),\n callback=get_param(request, \"callback\"))\n else:\n return error_response(code=400,\n message=\"Invalid strategy \" + repr(strategy),\n callback=get_param(request, \"callback\"))\n\n # Calculate the matching locations, using the specified strategy.\n\n pt = Point(longitude, latitude, srid=4326)\n\n locations = []\n\n if strategy == \"all\":\n for outline in Outline.objects.filter(outline__bbcontains=pt):\n if outline.outline.contains(pt):\n locations.append(outline.location.code)\n elif strategy == \"level\":\n for level in levels:\n for outline in Outline.objects.filter(location__level=level,\n outline__bbcontains=pt):\n if outline.outline.contains(pt):\n locations.append(outline.location.code)\n elif strategy == \"parent\":\n # Check the starting location's children.\n outlineIDs = []\n if location != None:\n for child in location.children.all():\n outline = get_outline(child)\n if outline != None:\n outlineIDs.append(outline.id)\n else:\n # We're at the top level -> check the countries.\n for child in Location.objects.filter(level__level=1):\n outline = get_outline(child)\n if outline != None:\n outlineIDs.append(outline.id)\n\n for outline in Outline.objects.filter(id__in=outlineIDs,\n outline__bbcontains=pt):\n if outline.outline.contains(pt):\n locations.append(outline.location.code)\n break\n\n if len(locations) == 0:\n # We didn't find a child location -> search for locations starting\n # at the same level as the parent, going up to the country level.\n if location != None:\n for level in range(location.level.level, 0, -1):\n query = Outline.objects.filter(outline__bbcontains=pt,\n location__level__level=level)\n for outline in query:\n if outline.outline.contains(pt):\n locations.append(outline.location.code)\n break\n if len(locations) > 0:\n break # Only find the first matching location.\n\n # Finally, return the found locations back to the caller.\n\n results = json.dumps({'locations' : locations})\n\n callback = get_param(request, \"callback\")\n if callback != None:\n results = callback + \"(\" + results + \")\" # Add JSONP callback.\n\n return HttpResponse(results, mimetype=\"application/json\")\n\n#############################################################################\n\n@csrf_exempt\ndef tableau(request):\n \"\"\" Implement the \"/geo/api/location/tableau\" API call.\n \"\"\"\n # Extract our CGI parameters.\n\n location = get_param(request, \"location\")\n if location == None:\n return error_response(code=400,\n message=\"Missing 'location' parameter.\",\n callback=get_param(request, \"callback\"))\n\n name = get_param(request, \"name\")\n\n ok = True # initially.\n width = get_param(request, \"width\")\n if width == None:\n ok = False\n else:\n try:\n width = int(width)\n except ValueError:\n ok = False\n\n if ok:\n if width < 10 or width > 2000:\n ok = False\n\n if not ok:\n return error_response(code=400,\n message=\"Missing or invalid 'width' parameter.\",\n callback=get_param(request, \"callback\"))\n\n ok = True # initially.\n height = get_param(request, \"height\")\n if height == None:\n ok = False\n else:\n try:\n height = int(height)\n except ValueError:\n ok = False\n\n if ok:\n if height < 10 or height > 2000:\n ok = False\n\n if not ok:\n return error_response(code=400,\n message=\"Missing or invalid 'height' parameter.\",\n callback=get_param(request, \"callback\"))\n\n # See which tableau we need to generate.\n\n tableau = tableauGenerator.select_tableau(location, name)\n if tableau == None:\n return error_response(code=500, message=\"No tableau found.\",\n callback=get_param(request, \"callback\"))\n\n # See if this tableau already exists in the tableau cache for the requested\n # size. If so, we use the cached JSON data directly.\n\n try:\n cacheEntry = TableauCacheEntry.objects.get(tableau=tableau,\n width=width, height=height)\n except TableauCacheEntry.DoesNotExist:\n cacheEntry = None\n\n if cacheEntry != None:\n results = cacheEntry.json_data\n\n # If we didn't have a cache entry for this tableau and size, we have to\n # generate it.\n\n if cacheEntry == None:\n try:\n generated_tableau = tableauGenerator.generate_tableau(tableau,\n width,\n height)\n except:\n # Something went wrong. Print the traceback into the Django log\n # and return an error message back to the caller.\n traceback.print_exc()\n return error_response(code=500, message=\"Internal server error.\",\n callback=get_param(request, \"callback\"))\n\n results = json.dumps({'tableau' : generated_tableau})\n\n # Add the generated tableau into the cache so that we can use it next\n # time.\n\n# cacheEntry = TableauCacheEntry()\n# cacheEntry.tableau = tableau\n# cacheEntry.width = width\n# cacheEntry.height = height\n# cacheEntry.json_data = results\n# cacheEntry.save()\n \n # Finally, return the results back to the caller.\n\n callback = get_param(request, \"callback\")\n if callback != None:\n results = callback + \"(\" + results + \")\" # Add JSONP callback.\n\n return HttpResponse(results, mimetype=\"application/json\")\n\n#############################################################################\n\n@csrf_exempt\ndef outline(request):\n \"\"\" Implement the \"/geo/api/location/outline\" API call.\n \"\"\"\n # Get the list of locations to return the outline for.\n\n locations = get_param(request, \"locations\")\n if locations == None:\n location = get_param(request, \"location\")\n if location == None:\n return error_response(code=400,\n message=\"Missing 'locations' or 'location' \"\n +\"parameter.\",\n callback=get_param(request, \"callback\"))\n locations = [location]\n else:\n try:\n locations = json.loads(locations)\n except:\n return error_response(code=400,\n message=\"Invalid 'locations' parameter.\",\n callback=get_param(request, \"callback\"))\n\n # Get the desired output format.\n\n format = get_param(request, \"format\")\n\n if format not in [\"wkt\", \"gml\", \"geojson\", \"kml\"]:\n return error_response(code=400,\n message=\"Missing or invalid 'format' \" +\n +\"parameter: \" + repr(format),\n callback=get_param(request, \"callback\"))\n\n # Extract the desired outlines.\n\n results = []\n for loc_code in locations:\n try:\n location = Location.objects.get(code=loc_code)\n except Location.DoesNotExist:\n return error_response(code=400,\n message=\"There is no location with code \" +\n repr(loc_code),\n callback=get_param(request, \"callback\"))\n\n try:\n outline = Outline.objects.get(location=location)\n\n if True:\n orig_size = len(outline.outline.wkt)\n outline = outline.outline.simplify(0.3515/2, True)\n simplified_size = len(outline.wkt)\n# print \"%d -> %d\" % (orig_size, simplified_size)\n else:\n outline = outline.outline\n except Outline.DoesNotExist:\n outline = None\n\n result = {'location' : loc_code}\n if outline != None:\n if format == \"wkt\":\n result['outline'] = outline.wkt\n elif format == \"gml\":\n result['outline'] = outline.ogr.gml\n elif format == \"geojson\":\n result['outline'] = outline.geojson\n elif format == \"kml\":\n result['outline'] = outline.kml\n\n results.append(result)\n\n results = json.dumps({'outlines' : results})\n\n callback = get_param(request, \"callback\")\n if callback != None:\n results = callback + \"(\" + results + \")\" # Add JSONP callback.\n\n return HttpResponse(results, mimetype=\"application/json\")\n\n#############################################################################\n# #\n# P R I V A T E D E F I N I T I O N S #\n# #\n#############################################################################\n\ndef get_param(request, param):\n \"\"\" Return the given parameter from our CGI request parameters.\n\n We return the CGI parameter from the given request object, allowing for\n the parameter to be in the GET or POST parameters, depending on the\n HTTP method used by this request.\n\n If the given parameter was not supplied, we return None.\n \"\"\"\n if request.method == \"GET\":\n return request.GET.get(param)\n elif request.method == \"POST\":\n return request.POST.get(param)\n else:\n return None\n\n#############################################################################\n\ndef error_response(code, message, callback=None):\n \"\"\" Return an HttpResponse object with the given error code and message.\n\n If 'callback' is not None, it will be used as the JSONP callback\n value to wrap the JSON response in.\n \"\"\"\n response = json.dumps({'error' : {'code' : code,\n 'message' : message}})\n\n if callback != None:\n response = callback + \"(\" + response + \")\" # Add JSONP callback.\n\n return HttpResponse(response, mimetype=\"application/json\")\n\n#############################################################################\n\ndef get_outline(location):\n \"\"\" Return the Outline object for the given Location object.\n\n If the given location doesn't exist or has no outline, we return None.\n \"\"\"\n for outline in Outline.objects.filter(location=location):\n return outline\n return None\n\n#############################################################################\n\ndef get_context(location):\n \"\"\" Return the context dictionary for the given Location object.\n\n The \"context\" for a location contains information about the\n higher-level locations which the given location is part of.\n\n We return a dictionary with zero or more of the following fields:\n\n countries\n states\n metros\n regions\n counties\n cities\n localities\n zipcodes\n\n Each field, if present, will be a list of locations at that level.\n Each list item will be a dictionary with the following fields:\n\n code\n name\n displayName\n abbreviation\n \"\"\"\n context = {}\n \n # The following helper function recursively scans the parent list for the\n # given location, adding each found location in turn to the 'context'\n # dictionary.\n\n def _addLocation(location, context):\n for parent in location.parents.all():\n if parent.level.level == 1:\n field = \"countries\"\n elif parent.level.level == 2:\n field = \"states\"\n elif parent.level.level == 3:\n field = \"metros\"\n elif parent.level.level == 4:\n field = \"regions\"\n elif parent.level.level == 5:\n field = \"counties\"\n elif parent.level.level == 6:\n field = \"cities\"\n elif parent.level.level == 7:\n field = \"localities\"\n elif parent.level.level == 8:\n field = \"zipcodes\"\n else:\n continue # Should never happen.\n\n found = False # initially.\n if field in context:\n for loc_info in context[field]:\n if parent.code == loc_info['code']:\n found = True\n break\n\n if not found:\n loc_info = {'code' : parent.code,\n 'name' : parent.name,\n 'displayName' : parent.display_name,\n 'abbreviation' : parent.abbreviation}\n\n try:\n context[field].append(loc_info)\n except KeyError:\n context[field] = [loc_info]\n\n _addLocation(parent, context)\n\n # Now recursively calculate our context, and return it back to the caller.\n\n _addLocation(location, context)\n return context\n\n#############################################################################\n\ndef name_to_level(level_name):\n \"\"\" Convert a level name to its corresponding Level object.\n\n The following level names are acceptable:\n\n country\n state\n metro\n region\n county\n city\n locality\n zipcode\n\n If there is no level with that name, we return None.\n \"\"\"\n level_name = level_name.strip().upper()\n if level_name == \"COUNTRY\":\n return Level.objects.get(level=1)\n elif level_name == \"STATE\":\n return Level.objects.get(level=2)\n elif level_name == \"METRO\":\n return Level.objects.get(level=3)\n elif level_name == \"REGION\":\n return Level.objects.get(level=4)\n elif level_name == \"COUNTY\":\n return Level.objects.get(level=5)\n elif level_name == \"CITY\":\n return Level.objects.get(level=6)\n elif level_name == \"LOCALITY\":\n return Level.objects.get(level=7)\n elif level_name == \"ZIPCODE\":\n return Level.objects.get(level=8)\n else:\n return None\n\n#############################################################################\n\ndef level_to_name(level):\n \"\"\" Convert a Level object to its corresponding level name.\n\n The appropriate level name will be selected from the following list:\n\n country\n state\n metro\n region\n county\n city\n locality\n zipcode\n \"\"\"\n if level.level == 1:\n return \"country\"\n elif level.level == 2:\n return \"state\"\n elif level.level == 3:\n return \"metro\"\n elif level.level == 4:\n return \"region\"\n elif level.level == 5:\n return \"county\"\n elif level.level == 6:\n return \"city\"\n elif level.level == 7:\n return \"locality\"\n elif level.level == 8:\n return \"zipcode\"\n else:\n return None\n\n","sub_path":"api/locationAPI.py","file_name":"locationAPI.py","file_ext":"py","file_size_in_byte":31212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"490848660","text":"from wsgiref.simple_server import make_server\n\ndef myapp(environ, start_response):\n body = []\n body.append(\"PATH_INFO: %s\\n\" % environ.get('PATH_INFO'))\n body.append(\"QUERY_STRING: %s\\n\" % environ.get('QUERY_STRING'))\n body.append(\"REQUEST_METHOD: %s\\n\" % environ.get('REQUEST_METHOD'))\n body.append(\"HTTP_HEADERNAME: %s\\n\" % environ.get('HTTP_HEADERNAMEZZZ'))\n headers = [('Content-Type', 'text/plain')]\n start_response('200 OK', headers)\n return body\n\nclass SummitMiddleware(object):\n def __init__(self, app, *args, **kwargs):\n self.app = app\n\n def __call__(self, env, start_response):\n response = self.app(env, start_response)\n if env.get('PATH_INFO') == '/echo':\n length = int(env.get('CONTENT_LENGTH') or 0)\n return env.get('wsgi.input').read(length) + '\\n'\n return response\n\nsrv = make_server('localhost', 8000, SummitMiddleware(myapp))\nsrv.serve_forever()\n\n","sub_path":"swift_mw/mw.py","file_name":"mw.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"65446178","text":"# -*- coding: utf-8 -*-\nfrom odoo import http, fields, api, SUPERUSER_ID\nimport json\nfrom odoo.http import request, Response\nfrom dateutil import parser\nimport time\n\nDEFAULT_LIMIT = 80\n\nNORMAL_RESULT_FIELDS_READ = ['vin', 'id', 'knr', 'product_id', 'assembly_line_id', 'result_ids']\n\n\nclass SaConfiguration(http.Controller):\n @http.route(['/api/v1/mrp.productions', '/api/v1/mrp.productions/'], type='http',\n methods=['GET', 'OPTIONS'], auth='none', cors='*', csrf=False)\n def _get_productions(self, vin=None, **kw):\n domain = []\n env = api.Environment(request.cr, SUPERUSER_ID, request.context)\n if vin:\n production_ids = env['mrp.production'].search([('vin', '=', vin)])\n else:\n if 'vins' in kw:\n vins = kw['vins'].split(',')\n domain += [('vin', 'in', vins)]\n if 'limit' in kw.keys():\n limit = int(kw['limit'])\n else:\n limit = DEFAULT_LIMIT\n production_ids = env['mrp.production'].search(domain, limit=limit)\n if not production_ids:\n body = json.dumps({'msg': \"MO not existed\"})\n headers = [('Content-Type', 'application/json'), ('Content-Length', len(body))]\n return Response(body, status=404, headers=headers)\n vals = [{\n 'id': production.id,\n 'vin': production.vin,\n 'knr': production.knr,\n 'product_id': production.product_id.id,\n 'assembly_line_id': production.assembly_line_id.id,\n 'result_ids': production.result_ids.ids,\n } for production in production_ids]\n ret = vals[0] if vin else vals\n body = json.dumps(ret)\n return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))], status=200)\n\n @http.route('/api/v1/mrp.productions', type='json', methods=['POST', 'OPTIONS'], auth='none', cors='*', csrf=False)\n def assemble_mo_create(self):\n env = api.Environment(request.cr, SUPERUSER_ID, request.context)\n vals = request.jsonrequest\n # print(vals)\n vin = vals['vin'] if 'vin' in vals else None\n if not vin:\n body = json.dumps({\"msg\": \"Track Number(Serial Number/VIN) not exists in parameters\"})\n return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))],\n status=405)\n mo_name = u'{0}--V001--{1}-{2}-{3}={4}'.format(\n vals['equipment_name'], vals['factory_name'], vals['year'], vals['pin'], vals['pin_check_code'])\n\n count = env['mrp.production'].search_count(\n [('name', '=', mo_name)])\n if count > 0:\n # MO已存在\n body = json.dumps({\"msg\": \"MO name \" + mo_name + \" already exists\"})\n return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))],\n status=405)\n\n count = env['mrp.production'].search_count(\n [('vin', '=', vin)])\n if count > 0:\n # MO已存在\n body = json.dumps({\"msg\": \"MO vin \" + vin + \" already exists\"})\n return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))],\n status=405)\n\n vechile_code = vals['model'] if 'model' in vals else None\n if not vechile_code:\n body = json.dumps({\"msg\": \"Vehicle Type code not exists in parameters\"})\n return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))],\n status=405)\n vals.pop('model')\n records = env['product.product'].search(\n [('default_code', 'ilike', vechile_code)], limit=1)\n\n if not records:\n # 找不到对应车型\n body = json.dumps({\"msg\": \"vehicle model \" + vechile_code + \" not found\"})\n return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))],\n status=400)\n\n product_id = records[0]\n\n assemble_line = vals['assembly_line'] if 'assembly_line' in vals else None\n if not assemble_line:\n body = json.dumps({\"msg\": \"assembly_line not exists in parameters\"})\n return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))],\n status=405)\n\n vals.pop('assembly_line')\n records = env['mrp.assemblyline'].search(\n ['|', ('name', 'ilike', assemble_line), ('code', 'ilike', assemble_line)], limit=1)\n\n if not records:\n # 找不到对应装配线\n records = env['mrp.assemblyline'].create({'name': assemble_line, 'code': assemble_line})\n # Response.status = \"400 Bad Request\"\n # return {\"msg\": \"Assembly line \" + assemble_line + \" not found\"}\n\n assembly_line_id = records[0]\n\n vals.update({'name': mo_name})\n vals.update({'product_id': product_id.id,\n 'bom_id': product_id.active_bom_id.id,\n 'product_tmpl_id': product_id.product_tmpl_id.id,\n 'product_uom_id': product_id.active_bom_id.product_uom_id.id,\n 'routing_id': product_id.active_bom_id.routing_id.id,\n 'assembly_line_id': assembly_line_id.id})\n\n prs = vals['prs']\n vals.pop('prs')\n vals.update(\n {'production_routings': json.dumps(prs)}\n )\n\n if 'date_planned_start' in vals:\n _t = parser.parse(vals['date_planned_start']) if vals['date_planned_start'] else None\n if _t:\n vals.update({\n 'date_planned_start': fields.Datetime.to_string((_t - _t.utcoffset()))\n })\n production = env['mrp.production'].create(vals)\n production.plan_by_prs() ### 模拟点击安排,自动生成工单\n\n if not production:\n body = json.dumps({\"msg\": \"create MO failed\"})\n return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))],\n status=400)\n\n # 创建MO成功\n vals = {\n 'id': production.id,\n 'vin': production.vin,\n 'knr': production.knr,\n 'product_id': production.product_id.id,\n 'assembly_line_id': production.assembly_line_id.id,\n 'result_ids': production.result_ids.ids if production.result_ids else [],\n 'workorder_ids': production.workorder_ids.ids if production.workorder_ids else [],\n }\n body = json.dumps(vals)\n return Response(body, headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))], status=201)\n","sub_path":"sa_addons/svw_enhanced/controllers/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":6892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"199364690","text":"from collections import deque\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.optimizers import RMSprop\nimport copy\nimport random\nimport os\nimport numpy as np\n\n\nclass Q_learner:\n \n def __init__(self, environment, pool_size, gamma, init_epsilon, hidden_layer_dim):\n '''\n https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf\n Build and compile keras q-net.\n \n Parameters:\n ---------------------\n num_actions - the number of actions for the given environment\n the output layer of the agent's model would have this many nodes\n state_space_dim - the size of the state for the given environment\n the input layer of the agent's model would have this many nodes\n init_epsilon - this regulates the probability of choosing a random action \n hence balancing exploration versus exploitation.\n Begin with initial value 1.0, anneal gradually after experience pool collection\n is complete. Final epsilon value (mainly exploitative) is 0.05 by deafult.\n Decrement init_epsilon gradually after training starts \n The rate with which you anneal init_epsilon is very crucial in the training quality\n For the CDS Index AMM, we found that we were annealing too early, not allowing the\n agent to explore sufficiently\n gamma - The decay coefficient for future rewards\n Probably the most important parameter, set it to less than 1 for discount.\n A value of 1 indicates no discount. Gamma decays exponentially e.g. for two time steps\n discount of an immediate reward of 100 will be 100*gamma^2, and likewise for\n 100 time steps it will be gamma^100. \n Choose gamma wisely, depending on the expected and max lengths of an episode.\n Check gamma_values.ods. Initially I was using gamma = 0.75 for the cartpole problem\n which is grossly small, check the Excel sheet\n experience_pool_size - the size of the agent's experience pool (i.e. buffer, or memory)\n This is implemented as a deque and has to be a sufficient size.\n If the experience pool is too small, this affects learning negatively.I have set it\n to 1500 to improve results compared to when it was 500. \n model - Q, the current version of the agent's function approximator\n frozen_model - Q_hat, the old version of the agent's function approximator\n '''\n \n self.epsilon = init_epsilon\n self.gamma = gamma\n self.experience_pool = deque([], pool_size)\n self.num_actions = environment.action_space.n # number of actions\n self.state_space_dim = environment.observation_space.shape[0] # state space size\n self.hold_out_experiences = None # fill it from the experience pool\n \n self.model = self.build_model(hidden_layer_dim)\n self.frozen_model = copy.deepcopy(self.model) # initialise Q_hat to Q\n \n\n def build_model(self, hidden_layer_dim):\n '''\n Parameters:\n ------------------\n hidden_layer_dim - the number of nodes in the 1st hidden layer\n '''\n model = Sequential()\n model.add(Dense(hidden_layer_dim, init='glorot_normal', input_shape=(self.state_space_dim,)))\n model.add(Activation('tanh'))\n \n model.add(Dense(hidden_layer_dim/2, init='glorot_normal'))\n model.add(Activation('tanh'))\n \n model.add(Dense(self.num_actions, init='glorot_normal'))\n model.add(Activation('linear')) #linear output so we can have range of real-valued outputs\n \n rms = RMSprop()\n model.compile(loss='mse', optimizer=rms)\n \n return model\n\n def pick_action_epsilon_greedy(self, state, environment):\n '''\n Given the current state of the environment, either pick a random or\n the best action (with the max Q value) according to the agent.\n '''\n # pick action\n if (random.random() < self.epsilon): #choose random action\n action = environment.action_space.sample()\n else: #choose best action from Q(s,a) values\n qval = self.model.predict(state.reshape(1,self.state_space_dim), batch_size=1)\n action = (np.argmax(qval))\n return action\n \n def update_frozen_model(self, q_hat_path):\n '''\n Updates the agent's frozen model (Q_hat) by saving the weights of the model to an .h5 file\n and loading them to the frozen model.\n '''\n if not os.path.exists(q_hat_path): os.makedirs(q_hat_path) # make dir if it does not exists. \n #frozen_model_path = q_hat_path + time.strftime(\"%Y_%m_%d %H_%M_%S\")+\".h5\" # full file path. \n frozen_model_path = q_hat_path + 'frozen_model.h5'\n # dump the online model weights. \n self.model.save_weights(frozen_model_path, overwrite=True) \n # load the online model weights into Q_hat. \n self.frozen_model.load_weights(frozen_model_path) # load the model weights. \n #print self.model.get_weights()[0].flatten()[0:5]\n #print self.frozen_model.get_weights()[0].flatten()[0:5] \n \n \n def calc_average_q_value(self):\n '''\n Calculate average of the max q values for the hold-out set of experiences.\n (Currently in-sample and copied from the initial experience pool)\n '''\n q_vals = np.zeros((len(self.hold_out_experiences), self.num_actions))\n for i in range( len(self.hold_out_experiences) ):\n s, action, reward, s_prime, termin_st = self.hold_out_experiences[i]\n q_vals[i] = self.model.predict(s.reshape(1,self.state_space_dim), batch_size=1)\n \n # Average of the MAX q values. \n q_avg = np.mean(map(lambda x: max(x), q_vals))\n \n return q_avg\n \n def sample_mini_batch(self, batchSize): \n '''\n Sample minibatch from self.experience pool for training self.model\n The function outputs X_train and y_train\n This is the crux of the Q_net algorithm\n ''' \n #randomly sample our experience replay memory\n minibatch = random.sample(self.experience_pool, batchSize)\n X_train = []\n y_train = []\n \n for experience in minibatch: # for each experience in minibatch, calc target and pred Q\n #Get max_Q(S',a)\n s, action, reward, s_prime, termin_st = experience\n pred_Q_vals = self.model.predict(s.reshape(1,self.state_space_dim), batch_size=1)# calc by current Q net\n target_Q_vals = self.frozen_model.predict(s_prime.reshape(1,self.state_space_dim), batch_size=1)# calc by frozen Q net \n maxQ = np.max(target_Q_vals)\n y = np.zeros((1,self.num_actions))\n y[:] = pred_Q_vals[:]\n if not termin_st : #non-terminal state\n update = (reward + (self.gamma * maxQ))\n else: #terminal state\n update = reward\n y[0][action] = update\n X_train.append(s.reshape(self.state_space_dim,))\n y_train.append(y.reshape(self.num_actions,)) \n \n X_train = np.array(X_train)\n y_train = np.array(y_train)\n \n return X_train, y_train","sub_path":"q_learner_270916.py","file_name":"q_learner_270916.py","file_ext":"py","file_size_in_byte":7680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"137220551","text":"from twilio.rest import Client\n\n\n# Your Account Sid and Auth Token from twilio.com/console\naccount_sid = 'ACe1afcddece492f9de304fa50af9e8d96'\nauth_token = 'f47c85e641ff407906c18049f4e2b9df'\nclient = Client(account_sid, auth_token)\n\nmessage = client.messages.create(\n body='Hello there!',\n from_='+972526285309',\n to='+972504205408'\n )\n\nprint(message.sid)","sub_path":"arrivelVerification/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"577071433","text":"import os\r\n\r\nAPI_LINK = 'https://api.vk.com/method/{method_name}'\r\n\r\nAPI_VERSION = '5.124'\r\n\r\nAPI_SECRET_KEY = 'ffac7be94d1a488e35d13eacaa05e66d47aee17eeb68b16530'\r\n\r\n# Токен группы\r\nTOKEN = '2ba9703dc3633922f2753422de186c352aaf5b28705eeb84aaa16ebb59b65594a6290431cfbf18efb16e3'\r\n\r\n# Личный токен для загрузки фото, время жизни - сутки, после этого надо вручную обновлять\r\nACCESS_TOKEN = '0d28c309889e646ffeb42c7d398d790ca72174336a32f0a64f4930300af187e2a4757d39fb31f16223240'\r\n# получение токена: https://oauth.vk.com/authorize?client_id=7603413&display=page&redirect_uri=http://35.226.30.8/&scope=photos,offline&response_type=token&v=5.124\r\n\r\nAPP_SEVICE_KEY = '486e62ac486e62ac486e62acbc481dd90e4486e486e62ac170cd2b8a84e928d100cda4f'\r\n\r\nCONFIRMATION_TOKEN = '85ee715e'\r\n\r\nAPI_APP = 'vkchatbot2'\r\n\r\nAPI_KEY = '89551b60cb453ad3a0bcc6edc169ef1c6628ff99'\r\n\r\nVK_GROUP_ID = 198392433\r\n\r\nGROUP_PHOTO_ALBUM_ID = 277400019\r\n\r\nPROJECTS_AMOUNT = 3\r\n\r\nPROJECTS_DATA = 'https://dobro.mail.ru/projects/rss/target/'\r\n\r\nPAYMENT_LINK = 'https://dobro.mail.ru/api/chatbot/create_payment/?api_app=vkchatbot2&api_key=89551b60cb453ad3a0bcc6edc169ef1c6628ff99&amount={amount}&project_id={project_id}&user_id={user_id}'\r\n# вместо ссылки на проект надо подсунуть:\r\n# link = config.PAYMENT_LINK.format(\r\n# amount=сумма пожертвования,\r\n# project_id=id проекта,\r\n# user_id=id пользователя)\r\n\r\nXML_URL = None\r\n\r\nPATTERN_MAX_ERROR = 0.6\r\n\r\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\r\n\r\nLOG_DIR = os.path.join(BASE_DIR, \"BotLogic/History/\")\r\n\r\n# Время через которое пользователь становится неактивным если он не совершал каких-либо действий\r\nUSER_MAX_ACTIVE_TIME_WITHOUT_ACTIVITY = 20 #seconds\r\n\r\n# Время через которое срабатывает действие\r\nREMIND_TIME = 20 #seconds\r\n\r\n# Время ограничивающее отправку пользователью по разнице текущего времени и времени последней активности пользователя в группе\r\nREMIND_DELAY = 30 #seconds\r\n\r\n# Время ограничивающее отправку по разнице текущего времени и времени последней оплаты\r\nPAYMENT_DELAY = 50 #seconds\r\n\r\n# Время через которое обновляется база данных\r\nUPDATE_DATABASE_TIME = 86400 #seconds == 1 day\r\n\r\n# размер фотографии для карусели\r\nCAROUSEL_IMG_SIZE = (221, 136)\r\n","sub_path":"Bot_4.6/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"533337817","text":"\"\"\"Test ingest metadata using the icatingest script.\n\"\"\"\n\nfrom subprocess import CalledProcessError\nimport pytest\nimport icat\nimport icat.config\nfrom icat.query import Query\nfrom conftest import (DummyDatafile, require_dumpfile_backend,\n gettestdata, getConfig, callscript)\n\n\n# Test input\nds_params = str(gettestdata(\"ingest-ds-params.xml\"))\ndatafiles = str(gettestdata(\"ingest-datafiles.xml\"))\n\n@pytest.fixture(scope=\"module\")\ndef client(setupicat):\n client, conf = getConfig(confSection=\"acord\", ids=\"mandatory\")\n client.login(conf.auth, conf.credentials)\n return client\n\n@pytest.fixture(scope=\"module\")\ndef cmdargs(setupicat):\n require_dumpfile_backend(\"XML\")\n _, conf = getConfig(confSection=\"acord\", ids=\"mandatory\")\n return conf.cmdargs + [\"-f\", \"XML\"]\n\n@pytest.fixture(scope=\"function\")\ndef dataset(client):\n \"\"\"A dataset to be used in the test.\n\n The dataset is not created by the fixture, it is assumed that the\n test does it. The dataset will be eventually be deleted after the\n test.\n \"\"\"\n inv = client.assertedSearch(\"Investigation [name='10100601-ST']\")[0]\n dstype = client.assertedSearch(\"DatasetType [name='raw']\")[0]\n dataset = client.new(\"Dataset\",\n name=\"e208343\", complete=False,\n investigation=inv, type=dstype)\n yield dataset\n try:\n ds = client.searchMatching(dataset)\n dataset.id = ds.id\n except icat.SearchResultError:\n # Dataset not found, maybe the test failed, nothing to\n # clean up then.\n pass\n else:\n # If any datafile has been uploaded (i.e. the location is\n # not NULL), need to delete it from IDS first. Any other\n # datafile or dataset parameter will be deleted\n # automatically with the dataset by cascading in the ICAT\n # server.\n query = Query(client, \"Datafile\", \n conditions={\"dataset.id\": \"= %d\" % dataset.id,\n \"location\": \"IS NOT NULL\"})\n client.deleteData(client.search(query))\n client.delete(dataset)\n\n\n# Test datafiles to be created by test_ingest_datafiles:\ntestdatafiles = [\n {\n 'dfname': \"e208343.dat\",\n 'size': 394,\n 'mtime': 1286600400,\n },\n {\n 'dfname': \"e208343.nxs\",\n 'size': 52857,\n 'mtime': 1286600400,\n },\n]\n\n\ndef verify_dataset_params(client, dataset, params):\n query = Query(client, \"DatasetParameter\", \n conditions={\"dataset.id\": \"= %d\" % dataset.id}, \n includes={\"type\"})\n ps = client.search(query)\n assert len(ps) == len(params)\n values = { (p.type.name, p.numericValue, p.type.units) for p in ps }\n assert values == params\n\n\ndef test_ingest_dataset_params(client, dataset, cmdargs):\n \"\"\"Ingest a file setting some dataset parameters.\n \"\"\"\n dataset.create()\n args = cmdargs + [\"-i\", ds_params]\n callscript(\"icatingest.py\", args)\n verify_dataset_params(client, dataset, { \n (\"Magnetic field\", 5.3, \"T\"), \n (\"Reactor power\", 10.0, \"MW\"), \n (\"Sample temperature\", 293.15, \"K\") \n })\n\n\ndef test_ingest_duplicate_throw(client, dataset, cmdargs):\n \"\"\"Ingest with a collision of a duplicate object.\n\n Same test as above, but now place a duplicate object in the way.\n \"\"\"\n dataset.create()\n ptype = client.assertedSearch(\"ParameterType [name='Reactor power']\")[0]\n p = client.new(\"DatasetParameter\", numericValue=5.0,\n dataset=dataset, type=ptype)\n p.create()\n args = cmdargs + [\"-i\", ds_params]\n # FIXME: should inspect stderr and verify ICATObjectExistsError.\n with pytest.raises(CalledProcessError) as err:\n callscript(\"icatingest.py\", args)\n # Verify that the params have been set. The exceptions should\n # have been raised while trying to ingest the second parameter.\n # The first one (Magnetic field) should have been created and\n # Reactor power should still have the value set above.\n verify_dataset_params(client, dataset, { \n (\"Magnetic field\", 5.3, \"T\"), \n (\"Reactor power\", 5.0, \"MW\") \n })\n\n\ndef test_ingest_duplicate_ignore(client, dataset, cmdargs):\n \"\"\"Ingest with a collision of a duplicate object.\n\n Same test as above, but now ignore the duplicate.\n \"\"\"\n dataset.create()\n ptype = client.assertedSearch(\"ParameterType [name='Reactor power']\")[0]\n p = client.new(\"DatasetParameter\", numericValue=5.0,\n dataset=dataset, type=ptype)\n p.create()\n args = cmdargs + [\"-i\", ds_params, \"--duplicate\", \"IGNORE\"]\n callscript(\"icatingest.py\", args)\n verify_dataset_params(client, dataset, { \n (\"Magnetic field\", 5.3, \"T\"), \n (\"Reactor power\", 5.0, \"MW\"), \n (\"Sample temperature\", 293.15, \"K\") \n })\n\n\ndef test_ingest_duplicate_check_err(client, dataset, cmdargs):\n \"\"\"Ingest with a collision of a duplicate object.\n\n Same test as above, but use CHECK which fails due to mismatch.\n \"\"\"\n dataset.create()\n ptype = client.assertedSearch(\"ParameterType [name='Reactor power']\")[0]\n p = client.new(\"DatasetParameter\", numericValue=5.0,\n dataset=dataset, type=ptype)\n p.create()\n args = cmdargs + [\"-i\", ds_params, \"--duplicate\", \"CHECK\"]\n # FIXME: should inspect stderr and verify ICATObjectExistsError.\n with pytest.raises(CalledProcessError) as err:\n callscript(\"icatingest.py\", args)\n verify_dataset_params(client, dataset, { \n (\"Magnetic field\", 5.3, \"T\"), \n (\"Reactor power\", 5.0, \"MW\") \n })\n\n\ndef test_ingest_duplicate_check_ok(client, dataset, cmdargs):\n \"\"\"Ingest with a collision of a duplicate object.\n\n Same test as above, but now it matches, so CHECK should return ok.\n \"\"\"\n dataset.create()\n ptype = client.assertedSearch(\"ParameterType [name='Reactor power']\")[0]\n p = client.new(\"DatasetParameter\", numericValue=10.0,\n dataset=dataset, type=ptype)\n p.create()\n args = cmdargs + [\"-i\", ds_params, \"--duplicate\", \"CHECK\"]\n callscript(\"icatingest.py\", args)\n verify_dataset_params(client, dataset, { \n (\"Magnetic field\", 5.3, \"T\"), \n (\"Reactor power\", 10.0, \"MW\"), \n (\"Sample temperature\", 293.15, \"K\") \n })\n\n\ndef test_ingest_duplicate_overwrite(client, dataset, cmdargs):\n \"\"\"Ingest with a collision of a duplicate object.\n\n Same test as above, but now overwrite the old value.\n \"\"\"\n dataset.create()\n ptype = client.assertedSearch(\"ParameterType [name='Reactor power']\")[0]\n p = client.new(\"DatasetParameter\", numericValue=5.0,\n dataset=dataset, type=ptype)\n p.create()\n args = cmdargs + [\"-i\", ds_params, \"--duplicate\", \"OVERWRITE\"]\n callscript(\"icatingest.py\", args)\n verify_dataset_params(client, dataset, { \n (\"Magnetic field\", 5.3, \"T\"), \n (\"Reactor power\", 10.0, \"MW\"), \n (\"Sample temperature\", 293.15, \"K\") \n })\n\n\n# Minimal example, a Datafile featuring a string.\ningest_data_string = \"\"\"\n\n \n \n \n dup_test_str.dat\n \n \n \n\n\"\"\"\n# A Datafile featuring an int.\ningest_data_int = \"\"\"\n\n \n \n \n 42\n dup_test_int.dat\n \n \n \n\n\"\"\"\n# A Dataset featuring a boolean.\ningest_data_boolean = \"\"\"\n\n \n \n false\n e208343\n \n \n \n \n\n\"\"\"\n# A DatasetParameter featuring a float.\ningest_data_float = \"\"\"\n\n \n \n \n 5.3\n \n \n \n \n\n\"\"\"\n# A Datafile featuring a date.\ningest_data_date = \"\"\"\n\n \n \n \n 2008-06-18T09:31:11+02:00\n dup_test_date.dat\n \n \n \n\n\"\"\"\n\n@pytest.mark.parametrize(\"inputdata\", [\n ingest_data_string,\n ingest_data_int,\n ingest_data_boolean,\n ingest_data_float,\n ingest_data_date,\n])\ndef test_ingest_duplicate_check_types(tmpdirsec, dataset, cmdargs, inputdata):\n \"\"\"Ingest with a collision of a duplicate object.\n\n Similar to test_ingest_duplicate_check_ok(), but trying several\n input datasets that test different data types. Issue #9.\n \"\"\"\n # Most input data create a datafile or a dataset parameter related\n # to dataset and thus assume the dataset to already exist. Only\n # ingest_data_boolean creates the dataset itself.\n if inputdata is not ingest_data_boolean:\n dataset.create()\n # We simply ingest twice the same data, using duplicate=CHECK the\n # second time. This obviously leads to matching duplicates.\n inpfile = tmpdirsec / \"ingest.xml\"\n with inpfile.open(\"wt\") as f:\n f.write(inputdata)\n args = cmdargs + [\"-i\", str(inpfile)]\n callscript(\"icatingest.py\", args)\n callscript(\"icatingest.py\", args + [\"--duplicate\", \"CHECK\"])\n\n\ndef test_ingest_datafiles(tmpdirsec, client, dataset, cmdargs):\n \"\"\"Ingest a dataset with some datafiles.\n \"\"\"\n dummyfiles = [ f['dfname'] for f in testdatafiles ]\n args = cmdargs + [\"-i\", datafiles]\n callscript(\"icatingest.py\", args)\n # Verify that the datafiles have been uploaded.\n dataset = client.searchMatching(dataset)\n for fname in dummyfiles:\n query = Query(client, \"Datafile\", conditions={\n \"name\": \"= '%s'\" % fname,\n \"dataset.id\": \"= %d\" % dataset.id,\n })\n df = client.assertedSearch(query)[0]\n assert df.location is None\n\n\ndef test_ingest_datafiles_upload(tmpdirsec, client, dataset, cmdargs):\n \"\"\"Upload datafiles to IDS from icatingest.\n\n Same as last test, but set the --upload-datafiles flag so that\n icatingest will not create the datafiles as objects in the ICAT,\n but upload the files to IDS instead.\n \"\"\"\n dummyfiles = [ DummyDatafile(tmpdirsec, f['dfname'], f['size'], f['mtime'])\n for f in testdatafiles ]\n args = cmdargs + [\"-i\", datafiles, \"--upload-datafiles\", \n \"--datafile-dir\", str(tmpdirsec)]\n callscript(\"icatingest.py\", args)\n # Verify that the datafiles have been uploaded.\n dataset = client.searchMatching(dataset)\n for f in dummyfiles:\n query = Query(client, \"Datafile\", conditions={\n \"name\": \"= '%s'\" % f.name,\n \"dataset.id\": \"= %d\" % dataset.id,\n })\n df = client.assertedSearch(query)[0]\n assert df.location is not None\n assert df.fileSize == f.size\n assert df.checksum == f.crc32\n if f.mtime:\n assert df.datafileModTime == f.mtime\n","sub_path":"tests/test_06_icatingest.py","file_name":"test_06_icatingest.py","file_ext":"py","file_size_in_byte":11732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"554202220","text":"#------------------------------------------------------------------------------------------------------\r\n# Joon-Ho Lee, School of Electrical Engineering, Korea Advanced Institute of Science and Technology\r\n# Text book : Data-Driven Modeling & Scientific Computation(by J. Nathan Kutz) \r\n# p.109, Python code converted from Matlab code in the book\r\n#------------------------------------------------------------------------------------------------------\r\nimport numpy as np\r\nfrom scipy.optimize import linprog\r\nc = np.array([-2, -1])\r\n\r\nA_ub = np.array([[1, 8/3], [1, 1], [2, 0], [ -1, 0], [0, -1]])\r\nb_ub = np.array([4, 2, 3, 0, 0])\r\n\r\nx0_bounds = (0, None)\r\nx1_bounds = (0, 5.0)\r\n\r\nbounds = [x0_bounds, x1_bounds]\r\n\r\nresult = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds)\r\n\r\nprint(result)","sub_path":"2021-1/Kutz-Ch5/Ch5_p109.py","file_name":"Ch5_p109.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"249903989","text":"import numpy as np\n\n#样本个数\ndata_size = 1000\n#μ\nmu = np.array([200,100,50])\n#Σ\nsigma = np.array([[50,0,0],\n [0,50,0],\n [0,0,50]])\n\n#生成二维服从正太分布的样本数据\ndata = np.random.multivariate_normal(mean=mu,cov=sigma,size=data_size)\n'''\n[[x,x,x]\n [x,x,x]\n ...]\n'''\n#最大似然估计\n\n#1计算均值\nmean_ = data.sum(axis=0)/data_size\n\n#2计算三维协方差矩阵\ncov_ = 1/(data_size-1) * np.matmul((data-mean_).T,(data-mean_))\n\nprint('设定均值:\\n{}'.format(mu))\nprint('设定方差:\\n{}'.format(sigma))\nprint('计算均值:\\n{}'.format(mean_))\nprint('计算方差:\\n{}'.format(cov_))\n","sub_path":"01_MLE/mLE.py","file_name":"mLE.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"643595375","text":"import datetime\n\nfrom django.db import models, IntegrityError\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .exceptions import NotLocked, AlreadyLocked\n\nDEFAULT_MAX_AGE = getattr(settings, 'LOCK_MAX_AGE', 0)\n\n\ndef _get_lock_name(obj):\n return '%s.%s__%d' % (obj.__module__, obj.__class__.__name__, obj.id)\n\n\nclass LockManager(models.Manager):\n def acquire_lock(self, obj=None, max_age=DEFAULT_MAX_AGE, lock_name=''):\n '''Acquire a lock on the object'''\n if obj is not None:\n lock_name = _get_lock_name(obj)\n\n try:\n lock, created = self.get_or_create(locked_object=lock_name,\n max_age=max_age)\n except IntegrityError:\n raise AlreadyLocked()\n\n if not created:\n # check whether lock is expired\n if lock.is_expired:\n lock.created_on = datetime.datetime.now()\n lock.save()\n return lock\n raise AlreadyLocked()\n\n return lock\n\n def is_locked(self, obj):\n '''Check whether a lock exists on a certain object'''\n qs = self.filter(locked_object=_get_lock_name(obj))\n return qs.count() > 0\n\n def get_expired_locks(self):\n '''Get all expired locks'''\n result = []\n for l in self.all():\n if l.is_expired:\n result.append(l.id)\n return self.filter(id__in=result)\n\n\nclass Lock(models.Model):\n locked_object = models.CharField(\n max_length=255, verbose_name=_('locked object'), unique=True\n )\n created_on = models.DateTimeField(\n auto_now_add=True, verbose_name=_('created on'), db_index=True\n )\n max_age = models.PositiveIntegerField(\n default=DEFAULT_MAX_AGE, verbose_name=_('Maximum lock age'),\n help_text=_('The age of a lock before it can be overwritten. '\n '0 means indefinitely.')\n )\n\n objects = LockManager()\n\n class Meta:\n verbose_name = _('Lock')\n verbose_name_plural = _('Locks')\n ordering = ['created_on']\n\n def __unicode__(self):\n values = {'object': self.locked_object,\n 'creation_date': self.created_on}\n return _('Lock exists on %(object)s since %(creation_date)s') % values\n\n def release(self, silent=True):\n '''Release the lock'''\n if not getattr(self, 'unlocked', False):\n self.delete()\n self.unlocked = True\n return True\n if not silent:\n raise NotLocked()\n\n @property\n def expires_on(self):\n '''\n This ``Lock`` expires on. If ``max_age`` is 0, it will return\n ``created_on``.\n '''\n return self.created_on + datetime.timedelta(seconds=self.max_age)\n\n @property\n def is_expired(self):\n '''Is the ``Lock`` expired?'''\n if self.max_age == 0:\n return False\n else:\n return self.expires_on < datetime.datetime.now()\n","sub_path":"locking/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"596337383","text":"from mlgame.gameconfig import GameConfig\n\ndef ml_mode(config: GameConfig):\n \"\"\"Start the game in the machine learning mode\n\n Create a game and a machine learning processes.\n \"\"\"\n level = _get_level(config.game_params)\n\n from mlgame.process import ProcessManager\n\n process_manager = ProcessManager()\n process_manager.set_game_process(_start_game_process, \\\n args = (config.fps, level, \\\n config.record_progress, config.one_shot_mode))\n process_manager.add_ml_process(config.input_modules[0], \"ml\")\n\n process_manager.start()\n\ndef _start_game_process(fps, level, record_progress, one_shot_mode):\n \"\"\"Start the game process\n\n @param fps Specify the updating rate of the game\n @param level Specify the level of the game\n @param record_progress Whether to record the game progress\n @param one_shot_mode Whether to run the game for only one round\n \"\"\"\n from .game.arkanoid_ml import Arkanoid\n\n game = Arkanoid(fps, level, record_progress, one_shot_mode)\n game.game_loop()\n\ndef manual_mode(config: GameConfig):\n \"\"\"Play the game as a normal game\n \"\"\"\n from .game.arkanoid import Arkanoid\n\n level = _get_level(config.game_params)\n\n game = Arkanoid(config.fps, level, config.record_progress, config.one_shot_mode)\n game.game_loop()\n\ndef _get_level(game_params):\n \"\"\"Get the level from the parameter\n \"\"\"\n try:\n level = int(game_params[0])\n if level < 1:\n raise ValueError\n except IndexError:\n print(\"Level is not specified. Set to 1.\")\n level = 1\n except ValueError:\n print(\"Invalid level value. Set to 1.\")\n level = 1\n\n return level\n\ndef get_log_dir():\n import os.path\n return os.path.join(os.path.dirname(__file__), \"log\")","sub_path":"MLGame-master/games/arkanoid/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"559817607","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport envs\nimport genotype\n\n\nclass ArgumentParser(dict):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.__dict__ = self\n\n\ndef save_model(model, path):\n pth = {\n 'model': model,\n 'checkpoint': model.state_dict(),\n }\n torch.save(pth, path)\n\n\ndef load_model(path):\n pth = torch.load(path, map_location=lambda storage, loc: storage)\n model = pth['model']\n model.load_state_dict(pth['checkpoint'])\n return model\n\n\ndef load_genome(genome, args):\n assert args.type is not None\n env = getattr(envs, args.env)(args)\n if args.type == 'cnn':\n size = tuple([args.dim, *env['size'][1:]])\n stem = nn.Sequential(\n nn.Conv2d(env['size'][0], args.dim, 3, padding=1),\n nn.Dropout2d(args.dropout)\n )\n cells = nn.ModuleList(\n [genotype.cell.CNNCell(size, genome) for _ in range(args.cells)]\n )\n classifier = nn.Sequential(\n nn.Dropout(args.dropout),\n nn.Linear(\n args.dim*np.prod(env['size'][1:]),\n env['num_classes']\n )\n )\n return genotype.network.FeedForward(stem, cells, classifier)\n\n elif args.type == 'rnn':\n size = tuple([args.dim, 1])\n stem = nn.Sequential(\n nn.Linear(env['size'][1], args.dim),\n nn.Dropout(args.dropout)\n )\n cell = genotype.cell.RNNCell(size, genome)\n classifier = nn.Sequential(\n nn.Dropout(args.dropout),\n nn.Linear(\n args.dim,\n env['num_classes']\n )\n )\n return genotype.network.Recurrent(stem, cell, classifier)\n\n elif args.type == 'transformer':\n size = tuple([env['size'][0], args.dim])\n stem = nn.Sequential(\n nn.Linear(env['size'][1], args.dim),\n nn.Dropout(args.dropout)\n )\n cells = nn.ModuleList(\n ([genotype.cell.TransformerCell(size, genome)\n for _ in range(args.cells)])\n )\n classifier = nn.Sequential(\n nn.Dropout(args.dropout),\n nn.Linear(\n args.dim*env['size'][0],\n env['num_classes']\n )\n )\n return genotype.network.FeedForward(stem, cells, classifier)\n\n else:\n raise NotImplementedError\n","sub_path":"utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"156423817","text":"from django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\nfrom store.models import *\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom datetime import date\ndef index(request):\n return render(request, 'store/index.html')\n\ndef bookDetailView(request, bid):\n template_name = 'store/book_detail.html'\n book = Book.objects.get(id=bid)\n availbooks= BookCopy.objects.filter(book=book,status=True)\n i=availbooks.count()\n context = {\n 'book': book,\n 'num_available': i,\n }\n return render(request, template_name, context=context)\n\n\n@csrf_exempt\ndef bookListView(request):\n template_name = 'store/book_list.html'\n # Searching \n bookdata = Book.objects.all()\n get_data = request.GET\n some= get_data.keys()\n if (len(some)!=0):\n if get_data['title'] =='' :\n if get_data['author']=='' :\n if get_data['genre']=='' :\n bookdata = Book.objects.all()\n else: \n bookdata = Book.objects.filter(genre=get_data['genre'])\n else:\n if get_data['genre']=='' :\n bookdata = Book.objects.filter(author=get_data['author'])\n else: \n bookdata = Book.objects.filter(genre=get_data['genre'],author=get_data['author'])\n else:\n if get_data['author']=='' :\n if get_data['genre']=='' :\n bookdata = Book.objects.filter(title=get_data['title'])\n else: \n bookdata = Book.objects.filter(genre=get_data['genre'],title=get_data['title'])\n else:\n if get_data['genre']=='' :\n bookdata = Book.objects.filter(author=get_data['author'],title=get_data['title'])\n else: \n bookdata = Book.objects.filter(genre=get_data['genre'],author=get_data['author'],title=get_data['title'])\n \n context = {\n 'books': bookdata,\n }\n return render(request, template_name, context=context)\n\n@login_required\ndef viewLoanedBooks(request):\n template_name = 'store/loaned_books.html'\n if request.user.is_authenticated:\n books = BookCopy.objects.filter(borrower=request.user)\n context = {\n 'books': books,\n }\n return render(request, template_name, context=context)\n\n@csrf_exempt\n@login_required\ndef loanBookView(request):\n book_id = request.POST.get('bid')\n availBooks=BookCopy.objects.filter(book=Book.objects.get(id=book_id),status=True)\n print(len(availBooks))\n if len(availBooks)!=0:\n booktoget = availBooks.first()\n booktoget.status=False\n booktoget.borrow_date=date.today()\n booktoget.borrower=request.user\n booktoget.save(update_fields=['status','borrow_date','borrower'])\n response_data = {\n 'message': 'success',\n }\n else:\n response_data = {\n 'message': 'failure',\n }\n return JsonResponse(response_data)\n\n@csrf_exempt\n@login_required\ndef returnBookView(request):\n bcid = request.POST.get('bcid')\n booktoret = BookCopy.objects.get(id=bcid)\n booktoret.status=True\n booktoret.borrower = None\n booktoret.borrow_date=None\n booktoret.save(update_fields=['status','borrower','borrow_date'])\n response_data = {\n 'message': 'success',\n }\n return JsonResponse(response_data)\n\n\ndef rateBook(request):\n bid = request.POST.get('bid')\n rating = request.POST.get('rating')\n ratingbook=Book.objects.get(id=bid)\n try:\n rate=Rate.objects.get(rater=request.user)\n rate.rating=rating\n rate.save(update_fields=['rating'])\n except Rate.DoesNotExist:\n ratingobj = Rate(book=ratingbook,rater=request.user,rating=rating)\n ratingobj.save()\n ratings_of_book = Rate.objects.filter(book=ratingbook)\n final_rating=0\n for rate_of_book in ratings_of_book:\n final_rating+=rate_of_book.rating/ratings_of_book.count()\n ratingbook.rating=final_rating\n ratingbook.save(update_fields=['rating']) \n context={\n \"message\":'success'\n }\n return JsonResponse(context) ","sub_path":"store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"201678456","text":"import csv\r\nclass superuser:\r\n\r\n def __init__(self):\r\n self.user_member = []\r\n self.regimen = []\r\n cv = csv.reader(open(\"regimen_list.csv\", \"r\", newline=\"\"))\r\n for row in cv:\r\n self.regimen.append(row)\r\n dv = csv.reader(open(\"user_member_list.csv\", \"r\", newline=\"\"))\r\n for row in dv:\r\n self.user_member.append(row)\r\n\r\n def create_member(self):\r\n print('Member Creation page...!!!'.center(10, '~'))\r\n while True:\r\n try:\r\n full_name = input(\"Enter a Full Name:\")\r\n age = int(input(\"Enter a Age:\"))\r\n gender = input(\"Enter a Gender M or F or T:\")\r\n ph_no = self.ph_no()\r\n email_id = self.check_email()\r\n bmi = float(input('Enter a BMI:'))\r\n duration = self.duration()\r\n self.user_member.append([full_name.title(), age, gender.upper(), ph_no, email_id, bmi, duration])\r\n ab = csv.writer(open(\"user_member_list.csv\", 'w', newline=\"\"))\r\n ab.writerows(self.user_member)\r\n print(\"Member Created Successfully...!!!\")\r\n # print(self.user)\r\n return False\r\n except:\r\n print(\"Invalid Input\")\r\n\r\n def ph_no(self):\r\n flag = True\r\n while flag:\r\n try:\r\n ph_no = input(\"Enter a Phone Number:\")\r\n if ph_no.isdigit() and len(ph_no) == 10:\r\n if self.user_member:\r\n for i in self.user_member:\r\n if i:\r\n if i[3] == ph_no:\r\n print(\"Entered Phone Number Already Present\")\r\n break\r\n else:\r\n return ph_no\r\n flag = False\r\n else:\r\n return ph_no\r\n flag = False\r\n else:\r\n print(\"Enter in a digit format... \\nOnly 10 Number are allowed...\")\r\n except:\r\n print(\"Invalid Input.....\")\r\n\r\n def check_email(self):\r\n while True:\r\n email_id = input(\"Enter a Email_ID:\")\r\n try:\r\n if self.user_member:\r\n for i in self.user_member:\r\n if i:\r\n if i[4] == email_id:\r\n print(\"Email ID is Already Available...!!!\")\r\n break\r\n else:\r\n return email_id\r\n break\r\n else:\r\n return email_id\r\n break\r\n except:\r\n print(\"Invalid Input...!!!!\")\r\n\r\n def duration(self):\r\n while True:\r\n print(\"Available Duration \\nPress 1 for 1-Month Duration \\nPress 2 for 3-Month Duration \\nPress 3 for 6-Month Duration \\nPress 4 for 12-Month Duration \\nPress C for Cancel Membership Duration\")\r\n duration = int(input(\"Enter a Given Available duration:\"))\r\n try:\r\n if duration == 1:\r\n return \"1-Month\"\r\n break\r\n elif duration == 2:\r\n return \"3-Month\"\r\n break\r\n elif duration == 3:\r\n return \"6-Month\"\r\n break\r\n elif duration == 4:\r\n return \"12-Month\"\r\n break\r\n elif duration.upper() == 'C':\r\n return \"Cancel Member\"\r\n else:\r\n print(\"Please enter in available duration limit.....!!!\")\r\n except:\r\n print(\"Invalid Input...!!!!\")\r\n\r\n\r\n def view_member(self):\r\n with open(\"user_member_list.csv\",'r', newline=\"\") as fb:\r\n read = csv.reader(fb)\r\n print(\"List Of Member....!!!\")\r\n first = 1\r\n for row in read:\r\n if first:\r\n first = 0\r\n print(\"First Name\".center(25),\"Age\".center(10),\"Gender\".center(10),\"Mobile Number\".center(20),\"Email\".center(20),\"BMI\".center(20),\"Membership Duration\".center(20), end=\"\\n\")\r\n print(row[0].center(25),row[1].center(10),row[2].center(10),row[3].center(20),row[4].center(20),row[5].center(20),row[6].center(20), end=\"\\n\")\r\n\r\n def remove_member(self):\r\n while True:\r\n try:\r\n n = int(input(\"Enter a Mobile Number of a Member You Want To Remove:\"))\r\n a = 0\r\n for i in self.user_member:\r\n if int(i[3]) == n:\r\n a = 1\r\n self.user_member.remove(i)\r\n print(\"Successfully Removed....!!!!\")\r\n break\r\n if a==0:\r\n print(\"Mobile Number Not Available...!!!\")\r\n else:\r\n ab = csv.writer(open(\"user_member_list.csv\",'w', newline=\"\"))\r\n ab.writerows(self.user_member)\r\n return False\r\n except:\r\n print(\"Invalid Input\")\r\n\r\n def update_member(self):\r\n while True:\r\n try:\r\n n = int(input(\"Enter a Mobile Number of a Member You Want To Edit:\"))\r\n a = 0\r\n for i in self.user_member:\r\n if int(i[3]) == n:\r\n a = 1\r\n print(\"Full Name:{0} \\nAge:{1} \\nGender:{2} \\nMobile Number:{3} \\nEmail:{4} \\nBMI:{5} \\nMembership :{6}\".format(i[0],i[1],i[2],i[3],i[4],i[5],i[6]))\r\n show = int(input(\"Press 1 To Edit Full Name \\nPress 2 To Edit Age \\nPress 3 To Edit Gender \\nPress 4 To Edit BMI \\nPress 5 To Edit Membership Duration \\nPress 0 To Exit\"))\r\n if show == 1:\r\n full_name = input(\"Enter a Full Name:\")\r\n i[0] = full_name\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 2:\r\n age = int(input(\"Enter a Age:\"))\r\n i[1] = age\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 3:\r\n gender = input(\"Enter a Gender M or F or T:\")\r\n i[2] = gender\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 4:\r\n bmi = float(input('Enter a BMI:'))\r\n i[5] = bmi\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 5:\r\n duration = self.duration()\r\n i[6] = duration\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 0:\r\n print(\"Quited....!!!!\")\r\n return False\r\n else:\r\n print(\"Enter a Number within a given option...!!!\")\r\n if a == 0:\r\n print(n,\"-Mobile NUmber is Not Available\")\r\n else:\r\n ab = csv.writer(open(\"user_member_list.csv\",'w', newline=\"\"))\r\n ab.writerows(self.user_member)\r\n return False\r\n except:\r\n print(\"Invalid Input..!!!\")\r\n\r\n def create_regimen(self):\r\n print('Workout Regimen Creation page...!!!!!'.center(10, '~'))\r\n while True:\r\n try:\r\n bmi = float(input(\"Enter Workout Regimen BMI:\"))\r\n mon = input(\"Enter a Monday Workout Regimen:\")\r\n tue = input(\"Enter a Tuesday Workout Regimen:\")\r\n wed = input(\"Enter a Wednesday Workout Regimen:\")\r\n thu = input(\"Enter a Thursday Workout Regimen:\")\r\n fri = input(\"Enter a Friday Workout Regimen:\")\r\n sat = input(\"Enter a Saturday Workout Regimen:\")\r\n sun = input(\"Enter a Sunday Workout Regimen:\")\r\n self.regimen.append([bmi, mon.title(), tue.title(), wed.title(), thu.title(), fri.title(), sat.title(), sun.title()])\r\n cb = csv.writer(open(\"regimen_list.csv\", 'w', newline=\"\"))\r\n cb.writerows(self.regimen)\r\n print(\"Workout Regimen Created Successfully...!!!\")\r\n return False\r\n except:\r\n print(\"Invalid Input\")\r\n\r\n\r\n def view_regimen(self):\r\n with open(\"regimen_list.csv\",'r', newline=\"\") as fb:\r\n read = csv.reader(fb)\r\n print(\"List Of Workout Regimen....!!!\")\r\n first = 1\r\n for row in read:\r\n if first:\r\n first = 0\r\n print(\"BMI\".center(10),\"Monday\".center(10),\"Tuesday\".center(10),\"Wednesday\".center(10),\"Thursday\".center(10),\"Friday\".center(10),\"Saturday\".center(10),\"Sunday\".center(10), end=\"\\n\")\r\n print(row[0].center(10),row[1].center(10),row[2].center(10),row[3].center(10),row[4].center(10),row[5].center(10),row[6].center(10),row[7].center(10), end=\"\\n\")\r\n\r\n def remove_regimen(self):\r\n while True:\r\n try:\r\n n = float(input(\"Enter a BMI of a Workout Regimen You Want To Remove:\"))\r\n a = 0\r\n for i in self.regimen:\r\n if float(i[0]) == n:\r\n a = 1\r\n self.regimen.remove(i)\r\n print(\"Successfully Removed....!!!!\")\r\n break\r\n if a == 0:\r\n print(\"BMI Not Available...!!!\")\r\n else:\r\n ab = csv.writer(open(\"regimen_list.csv\",'w', newline=\"\"))\r\n ab.writerows(self.regimen)\r\n return False\r\n except:\r\n print(\"Invalid Input\")\r\n\r\n def update_regimen(self):\r\n while True:\r\n try:\r\n n = float(input(\"Enter a BMI of a Workout Regimen You Want To Edit:\"))\r\n a = 0\r\n for i in self.regimen:\r\n if float(i[0]) == n:\r\n a = 1\r\n print(\"BMI:{0} \\nMonday:{1} \\nTuesday:{2} \\nWednesday:{3} \\nThursday:{4} \\nFriday:{5} \\nSaturday:{5} \\nSunday:{6}\".format(i[0],i[1],i[2],i[3],i[4],i[5],i[6]))\r\n show = int(input(\"Press 1 To Edit Monday Workout Regimen \\nPress 2 To Edit Tuesday Workout Regimen \\nPress 3 To Edit Wednesday Workout Regimen \\nPress 4 To Edit Thursday Workout Regimen\"\r\n \" \\nPress 5 To Edit Friday Workout Regimen \\nPress 6 To Edit Saturday Workout Regimen \\nPress 7 To Edit Sunday Workout Regimen \\nPress 0 To Exit\"))\r\n if show == 1:\r\n mon = input(\"Enter a Monday Workout Regimen:\")\r\n i[0] = mon.title()\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 2:\r\n tue = int(input(\"Enter a Tuesday Workout Regimen:\"))\r\n i[1] = tue.title()\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 3:\r\n wed = input(\"Enter a Wednesday Workout Regimen:\")\r\n i[2] = wed.title()\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 4:\r\n thu = input('Enter a Thursday Workout Regimen:')\r\n i[5] = thu.title()\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 5:\r\n fri = input('Enter a Friday Workout Regimen:')\r\n i[6] = fri.title()\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 6:\r\n sat = input('Enter a Saturday Workout Regimen:')\r\n i[6] = sat.title()\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 7:\r\n sun = input('Enter a Sunday Workout Regimen:')\r\n i[6] = sun.title()\r\n print(\"Successfully Edited....!!!!\")\r\n break\r\n elif show == 0:\r\n print(\"Quited....!!!!\")\r\n return False\r\n else:\r\n print(\"Enter a Number within a given option...!!!\")\r\n if a == 0:\r\n print(n,\"-Mobile NUmber is Not Available\")\r\n else:\r\n ab = csv.writer(open(\"user_list.csv\",'w', newline=\"\"))\r\n ab.writerows(self.user_member)\r\n return False\r\n except:\r\n print(\"Invalid Input..!!!\")\r\n\r\n def menu(self):\r\n flag = True\r\n while flag:\r\n try:\r\n self.choice = int(input(\"\\nPress 1 To Create a Member \\nPress 2 To View a Member \\nPress 3 To Remove a Member \\nPress 4 To Update a Member \\nPress 5 To Create Workout Regimen \\nPress 6 To View Workout Regimen \\nPress 7 To Remove Workout Regimen \\nPress 8 To Update Workout Regimen \\nPress 0 To Exit\"))\r\n if self.choice == 1:\r\n self.create_member()\r\n elif self.choice == 2:\r\n self.view_member()\r\n elif self.choice == 3:\r\n self.remove_member()\r\n elif self.choice == 4:\r\n self.update_member()\r\n elif self.choice == 5:\r\n self.create_regimen()\r\n elif self.choice == 6:\r\n self.view_regimen()\r\n elif self.choice == 7:\r\n self.remove_regimen()\r\n elif self.choice == 8:\r\n self.update_regimen()\r\n elif self.choice == 0:\r\n print(\"Thank You....!!!!\")\r\n flag = False\r\n else:\r\n print(\"Not Valid Choice, Try Again....!!!!\")\r\n except:\r\n print(\"Invalid Input------!!!\")\r\n\r\n#obj = superuser()\r\n","sub_path":"user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":15038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"54653170","text":"import sys\nsys.path.append(\"../\")\nfrom Sensorization import config\nimport requests\nimport xlsxwriter\nimport pprint\n\npp = pprint.PrettyPrinter(indent=4)\n\n# ------------- xls global data -------------\n\nworkbook = xlsxwriter.Workbook('openUV.xlsx')\nworksheet = workbook.add_worksheet(\"Data\")\n\nrow = 0\ncolumn = 0\n\n# ------------- request -------------\n\ncoordinates = (41.55032, -8.42005) # Braga\n\nurl = f'https://api.openuv.io/api/v1/uv?lat={coordinates[0]}&lng={coordinates[1]}'\n\nheaders = {'content-type': 'application/json',\n 'x-access-token': config.openuv_api_key}\n\nresponse = requests.get(url, headers=headers).json()[\"result\"]\n\npp.pprint(response)\n\n# ------------- response handling -------------\n\nuv_data = {\n 'time' : 'uv_time',\n 'uv' : 'uv',\n 'day_max_uv' : 'uv_max',\n 'day_max_uv_time' : 'uv_max_time'\n}\n\nfor name, id in uv_data.items():\n worksheet.write(row, column, name)\n worksheet.write(row+1, column, response[id])\n column += 1\n\nexposure_time = response[\"safe_exposure_time\"]\nfor st, max_time in exposure_time.items():\n worksheet.write(row, column, st)\n worksheet.write(row+1, column, max_time)\n column += 1\n\n\nworkbook.close()\n","sub_path":"Project/Excel/openUV_request.py","file_name":"openUV_request.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"487962436","text":"from bootstrapvz.base import Task\nfrom .. import phases\nimport os\nimport shutil\n\n\nclass ClearMOTD(Task):\n\tdescription = 'Clearing the MOTD'\n\tphase = phases.system_cleaning\n\n\t@classmethod\n\tdef run(cls, info):\n\t\twith open('/var/run/motd', 'w'):\n\t\t\tpass\n\n\nclass CleanTMP(Task):\n\tdescription = 'Removing temporary files'\n\tphase = phases.system_cleaning\n\n\t@classmethod\n\tdef run(cls, info):\n\t\ttmp = os.path.join(info.root, 'tmp')\n\t\tfor tmp_file in [os.path.join(tmp, f) for f in os.listdir(tmp)]:\n\t\t\tif os.path.isfile(tmp_file):\n\t\t\t\tos.remove(tmp_file)\n\t\t\telse:\n\t\t\t\tshutil.rmtree(tmp_file)\n\n\t\tlog = os.path.join(info.root, 'var/log/')\n\t\tos.remove(os.path.join(log, 'bootstrap.log'))\n\t\tos.remove(os.path.join(log, 'dpkg.log'))\n","sub_path":"bootstrapvz/common/tasks/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"653073054","text":"# coding=utf-8\r\n\r\n# This is a module, used as an interface serves the ciga.py\r\n# It implements to extract watermelons' informatioin from a particular frame text\r\n# file. Or rather, get a list of tuple, in which there are cigas' attributes' values\r\n# and y as determined class or label\r\n\r\n# Provided we have open the text file delimited by comma,\r\n# and ciga_string is one line\r\n\r\n#\"color,root,knock,textrue,navel,touch,label\r\n#\"green,crul,ringing,clear,plain,smooth,good\"\r\n# 青绿,蜷缩,清脆, 清晰,平坦,硬滑, 好瓜\r\n\r\nimport pandas as pd\r\n\r\ndef extract_ciga(ciga_data_file_name):\r\n data = pd.read_csv(ciga_data_file_name)\r\n return data.to_dict(orient='record')\r\n\r\nif __name__ == '__main__':\r\n data = extract_ciga('test')\r\n print(data)\r\n","sub_path":"extraction.py","file_name":"extraction.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"370822106","text":"# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/items.html\nimport os\nimport scrapy\n\nfrom scrapy.loader.processors import MapCompose\n\n\ndef filter_id(value):\n f = os.path.basename(value)\n n, ext = os.path.splitext(f)\n v = n.split('-')[1]\n if v[:2] in ('12', '18', 'SA') or \\\n v[0] in ('M', 'Y') or \\\n v.startswith('43MF') or \\\n v in ('S0771', 'S0776', 'SF037'):\n raise ValueError\n return v\n\n\ndef filter_venue(value):\n if 'GP' not in value or \\\n 'F3' in value:\n raise ValueError\n return value\n\n\nclass SparkModelItem(scrapy.Item):\n product_id = scrapy.Field(\n input_processor=MapCompose(filter_id))\n image_url = scrapy.Field()\n title = scrapy.Field(\n input_processor=MapCompose(filter_venue))\n","sub_path":"collectr/service/crawl/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"494541881","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 10 07:28:18 2012\n\n@author: pako\n\"\"\"\n\nimport numpy as np\nfrom math import*\nimport matplotlib.pyplot as plt\n\ny0 = eval(raw_input(\"Altura inicial de la gota de agua en metros: \"))\nv0 = eval(raw_input(\"Velocidad inicial de la gota de agua en m/s: \"))\n#m = eval(raw_input(\"Masa de la gota en gramos: \"))\n#k = eval(raw_input(\"Coeficiente de la fuerza resistiva: \"))\ng,i=9.81,0\nt=np.arange(0.0,5,0.2)\na=[0.1,1,5.9,100]\n#b=m/k\ndef yr(t,a):\n y1=y0+a*g*t+(a*a-a*v0/g)*(np.exp(-g*t/a)-1)\n return y1\n \ndef vr(t,a):\n v1=a*g+(v0-a*g)*np.exp(-g*t/a)\n return v1\n \ndef yl(t):\n yl=y0+v0*t+g*t*t/2\n return yl\n \ndef vl(t):\n vl=v0+g*t\n return vl\n\nwhile i 0.5)\n \n \n #### SAVE DATA####\n y_true_pd=y_valid_split.to_frame().reset_index(drop=True)\n y_pred_pd=y_valid_scores.apply(lambda x: 1 if x==True else 0).to_frame().reset_index(drop=True).rename(columns={\"Fall\":\"output\"})\n y_pred_prob_pd=pd.DataFrame(pred, columns = [\"output_prob\"])\n \n df_subset=pd.concat([X_valid_split.reset_index(drop=True),y_true_pd,y_pred_pd,y_pred_prob_pd],axis=1)\n \n df_test=df_test.append(df_subset, ignore_index=True)\n ######\n \n ###### Save the metrics ####\n \n df_evaluate_proc=get_df_w_metrics(df_subset,procted_col_name,y_col_name,\"output\")\n df_evaluate_proc.to_csv(PATH+\"model\"+str(i)+\"_\"+procted_col_name+\".csv\")\n \n \n df_evaluate_together=df_subset.copy()\n df_evaluate_together[procted_col_name]=\"all\"\n df_evaluate_all=get_df_w_metrics(df_evaluate_together,procted_col_name,y_col_name,\"output\")\n df_evaluate_all.to_csv(PATH+\"model\"+str(i)+\"_all.csv\")\n \n #############################\n \n \n valid_acc.append(accuracy_score(y_valid_split, y_valid_scores))\n valid_pre.append(precision_score(y_valid_split, y_valid_scores))\n valid_recall.append(recall_score(y_valid_split, y_valid_scores))\n valid_roc_auc.append(roc_auc_score(y_valid_split, y_valid_pred.iloc[valid_index]))\n \n i=i+1\n\n\n\n# # Save all data\n\n# In[35]:\n\n\ndf_test.to_csv(PATH+\"all_test_data.csv\")\nprint(\"The full test data lies here:\",PATH+\"all_test_data.csv\")\n\n\n# # Evaluate\n\n# In[36]:\n\n\ny_pred = model.predict(X_test)\ny_proba = model.predict_proba(X_test)[:,1]\n\n\n# In[37]:\n\n\n\n#file_writer.write_cm_plot(y_test, y_pred, cfg.REPORTS_PLOTS_DIR,\n # f'{case.lower()}_xgb_cm.pdf', case)\n#file_writer.write_joblib(model, model_dir, f'{case.lower()}_xgboost.joblib')\n\nprint(f\"Scores for XGBoost model:\")\nprint(f\"Accuracy: {np.around(accuracy_score(y_test, y_pred), decimals=3)}\")\nprint(f\"Precision: {np.around(precision_score(y_test, y_pred), decimals=3)}\")\nprint(f\"Recall: {np.around(recall_score(y_test, y_pred), decimals=3)}\")\nprint(f\"ROC AUC: {np.around(roc_auc_score(y_test, y_proba), decimals=3)}\\n\")\n\n\n# # Save the confusion data\n\n# In[38]:\n\n\ncolumn_names = [\"Group\", \"ML\", \"Measure\",\"Value\"]\n\ndf_out = pd.DataFrame(columns = column_names)\n\nfor i in [0,1,2,3,4,5,6,7,8,9]:\n \n PATH_loop=PATH+\"model\"+str(i)+\"_all.csv\"\n \n data=pd.read_csv(PATH_loop)\n for group in [\"all\"]:\n for measure in ['FPR', 'FNR', 'ACC', 'F1', 'FDR', 'LRminus','LRplus', 'NPV', 'PPV', 'TNR', 'TPR','TP','TN','FN','FP']:\n value=float(data[data[procted_col_name]==group][measure])\n\n df_out=df_out.append({'Group': group,\"ML\":\"Xgboost\"+str(i),\"Measure\":measure,\"Value\":value}, ignore_index=True)\n\ndf_out.to_csv(PATH+\"/Xgboost_metrics_crossvalidated_all.csv\")\n\n\n# In[39]:\n\n\nglobal_all_bar=sns.barplot(data=df_out[df_out[\"Measure\"].isin([\"FPR\",\"FNR\",\"TPR\",\"TNR\"])],x=\"Group\", y=\"Value\", ci=95,hue=\"Measure\")\nglobal_all_bar.set_title('All')\nglobal_all_bar.get_figure().savefig(PATH_orig+\"/barplot_all.png\")\n\n\n# In[ ]:\n\n\n\n\n\n# In[40]:\n\n\ncolumn_names = [\"Group\", \"ML\", \"Measure\",\"Value\"]\n\ndf_out = pd.DataFrame(columns = column_names)\n\nfor i in [0,1,2,3,4,5,6,7,8,9]:\n\n PATH_loop=PATH+\"model\"+str(i)+\"_\"+procted_col_name+\".csv\"\n \n data=pd.read_csv(PATH_loop)\n for group in list(data[procted_col_name].unique()):\n for measure in ['FPR', 'FNR', 'ACC', 'F1', 'FDR', 'LRminus','LRplus', 'NPV', 'PPV', 'TNR', 'TPR','TP','TN','FN','FP']:\n value=float(data[data[procted_col_name]==group][measure])\n\n df_out=df_out.append({'Group': group,\"ML\":\"Xgboost\"+str(i),\"Measure\":measure,\"Value\":value}, ignore_index=True)\n\ndf_out.to_csv(PATH+\"Xgboost_metrics_crossvalidated_\"+procted_col_name+\".csv\")\n\n\n# In[41]:\n\n\nglobal_proc_bar=sns.barplot(data=df_out[df_out[\"Measure\"].isin([\"FPR\",\"FNR\",\"TPR\",\"TNR\"])],x=\"Group\", y=\"Value\", ci=95,hue=\"Measure\")\nglobal_proc_bar.set_title('Proctected: '+procted_col_name)\nglobal_proc_bar.get_figure().savefig(PATH_orig+\"/barplot_proc.png\")\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Legacy/Lau/Xgboost/Xg_boost.py","file_name":"Xg_boost.py","file_ext":"py","file_size_in_byte":7390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"375758729","text":"import base64\nimport gzip\nimport json\nfrom collections import defaultdict\nfrom datetime import datetime, timezone\nfrom typing import Any, Callable, DefaultDict, Dict, Generator, List, Optional\n\nfrom dateutil.parser import ParserError, parse\nfrom sentry_sdk.api import capture_exception\n\nfrom posthog.models import utils\nfrom posthog.models.session_recording.metadata import (\n DecompressedRecordingData,\n SessionRecordingEventSummary,\n SnapshotData,\n SnapshotDataTaggedWithWindowId,\n)\nfrom posthog.utils import flatten\n\nFULL_SNAPSHOT = 2\n\n\n# NOTE: For reference here are some helpful enum mappings from rrweb\n# https://github.com/rrweb-io/rrweb/blob/master/packages/rrweb/src/types.ts\n\n# event.type\n\n\nclass RRWEB_MAP_EVENT_TYPE:\n DomContentLoaded = 0\n Load = 1\n FullSnapshot = 2\n IncrementalSnapshot = 3\n Meta = 4\n Custom = 5\n Plugin = 6\n\n\n# event.data.source\nclass RRWEB_MAP_EVENT_DATA_SOURCE:\n Mutation = 0\n MouseMove = 1\n MouseInteraction = 2\n Scroll = 3\n ViewportResize = 4\n Input = 5\n TouchMove = 6\n MediaInteraction = 7\n StyleSheetRule = 8\n CanvasMutation = 9\n Font = 1\n Log = 1\n Drag = 1\n StyleDeclaration = 1\n Selection = 1\n\n\n# event.data.type\nclass RRWEB_MAP_EVENT_DATA_TYPE:\n MouseUp = 0\n MouseDown = 1\n Click = 2\n ContextMenu = 3\n DblClick = 4\n Focus = 5\n Blur = 6\n TouchStart = 7\n TouchMove_Departed = 8\n TouchEnd = 9\n TouchCancel = 10\n\n\n# List of properties from the event payload we care about for our uncompressed `events_summary`\n# NOTE: We should keep this as minimal as possible\nEVENT_SUMMARY_DATA_INCLUSIONS = [\n \"type\",\n \"source\",\n \"tag\",\n \"plugin\",\n \"href\",\n \"width\",\n \"height\",\n \"payload.href\",\n \"payload.level\",\n]\n\n\nEvent = Dict[str, Any]\n\n\ndef legacy_preprocess_session_recording_events_for_clickhouse(\n events: List[Event], chunk_size=512 * 1024\n) -> List[Event]:\n return _process_windowed_events(events, lambda x: legacy_compress_and_chunk_snapshots(x, chunk_size=chunk_size))\n\n\ndef legacy_compress_and_chunk_snapshots(events: List[Event], chunk_size=512 * 1024) -> Generator[Event, None, None]:\n data_list = list(flatten([event[\"properties\"][\"$snapshot_data\"] for event in events], max_depth=1))\n session_id = events[0][\"properties\"][\"$session_id\"]\n window_id = events[0][\"properties\"].get(\"$window_id\")\n has_full_snapshot = any(snapshot_data[\"type\"] == RRWEB_MAP_EVENT_TYPE.FullSnapshot for snapshot_data in data_list)\n compressed_data = compress_to_string(json.dumps(data_list))\n\n id = str(utils.UUIDT())\n chunks = chunk_string(compressed_data, chunk_size)\n\n for index, chunk in enumerate(chunks):\n yield {\n **events[0],\n \"properties\": {\n **events[0][\"properties\"],\n \"$session_id\": session_id,\n \"$window_id\": window_id,\n # If it is the first chunk we include all events\n \"$snapshot_data\": {\n \"chunk_id\": id,\n \"chunk_index\": index,\n \"chunk_count\": len(chunks),\n \"data\": chunk,\n \"compression\": \"gzip-base64\",\n \"has_full_snapshot\": has_full_snapshot,\n # We only store this field on the first chunk as it contains all events, not just this chunk\n \"events_summary\": get_events_summary_from_snapshot_data(data_list) if index == 0 else None,\n },\n },\n }\n\n\ndef split_replay_events(events: List[Event]) -> List[Event]:\n replay, other = [], []\n\n for event in events:\n replay.append(event) if is_unprocessed_snapshot_event(event) else other.append(event)\n\n return replay, other\n\n\ndef preprocess_replay_events_for_blob_ingestion(events: List[Event], max_size_bytes=1024 * 1024) -> List[Event]:\n return _process_windowed_events(events, lambda x: preprocess_replay_events(x, max_size_bytes=max_size_bytes))\n\n\ndef preprocess_replay_events(events: List[Event], max_size_bytes=1024 * 1024) -> List[Event]:\n \"\"\"\n The events going to blob ingestion are uncompressed (the compression happens in the Kafka producer)\n 1. Since posthog-js {version} we are grouping events on the frontend in a batch and passing their size in $snapshot_bytes\n These are easy to group as we can simply make sure the total size is not higher than our max message size in Kafka.\n If one message has this property, they all do (thanks to batching).\n 2. If this property isn't set, we estimate the size (json.dumps) and if it is small enough - merge it all together in one event\n 3. If not, we split out the \"full snapshots\" from the rest (they are typically bigger) and send them individually, trying one more time to group the rest, otherwise sending them individually\n \"\"\"\n\n if len(events) == 0:\n return []\n\n size_with_headroom = max_size_bytes * 0.95 # Leave 5% headroom\n\n distinct_id = events[0][\"properties\"][\"distinct_id\"]\n session_id = events[0][\"properties\"][\"$session_id\"]\n window_id = events[0][\"properties\"].get(\"$window_id\")\n\n def new_event(items: List[dict] = None) -> Event:\n return {\n **events[0],\n \"event\": \"$snapshot_items\", # New event name to avoid confusion with the old $snapshot event\n \"properties\": {\n \"distinct_id\": distinct_id,\n \"$session_id\": session_id,\n \"$window_id\": window_id,\n # We instantiate here instead of in the arg to avoid mutable default args\n \"$snapshot_items\": items or [],\n },\n }\n\n # 1. Group by $snapshot_bytes if any of the events have it\n if events[0][\"properties\"].get(\"$snapshot_bytes\"):\n current_event = None\n current_event_size = 0\n\n for event in events:\n additional_bytes = event[\"properties\"][\"$snapshot_bytes\"]\n additional_data = flatten([event[\"properties\"][\"$snapshot_data\"]], max_depth=1)\n\n if not current_event or current_event_size + additional_bytes > size_with_headroom:\n # If adding the new data would put us over the max size, yield the current event and start a new one\n if current_event:\n yield current_event\n current_event = new_event()\n current_event_size = 0\n\n # Add the existing data to the base event\n current_event[\"properties\"][\"$snapshot_items\"].extend(additional_data)\n current_event_size += additional_bytes\n\n yield current_event\n else:\n snapshot_data_list = list(flatten([event[\"properties\"][\"$snapshot_data\"] for event in events], max_depth=1))\n\n # 2. Otherwise, try and group all the events if they are small enough\n if byte_size_dict(snapshot_data_list) < size_with_headroom:\n event = new_event(snapshot_data_list)\n yield event\n else:\n # 3. If not, split out the full snapshots from the rest\n full_snapshots = []\n other_snapshots = []\n\n for snapshot_data in snapshot_data_list:\n if snapshot_data[\"type\"] == RRWEB_MAP_EVENT_TYPE.FullSnapshot:\n full_snapshots.append(snapshot_data)\n else:\n other_snapshots.append(snapshot_data)\n\n # Send the full snapshots individually\n for snapshot_data in full_snapshots:\n event = new_event([snapshot_data])\n yield event\n\n # Try and group the rest\n if byte_size_dict(other_snapshots) < size_with_headroom:\n event = new_event(other_snapshots)\n yield event\n else:\n # If not, send them individually\n for snapshot_data in other_snapshots:\n event = new_event([snapshot_data])\n yield event\n\n\ndef _process_windowed_events(events: List[Event], fn: Callable[[List[Event], Any], List[Event]]) -> List[Event]:\n \"\"\"\n Helper method to simplify grouping events by window_id and session_id, processing them with the given function, and then returning the flattened list\n \"\"\"\n result = []\n snapshots_by_session_and_window_id = defaultdict(list)\n\n for event in events:\n session_id = event[\"properties\"][\"$session_id\"]\n window_id = event[\"properties\"].get(\"$window_id\")\n snapshots_by_session_and_window_id[(session_id, window_id)].append(event)\n\n for _, snapshots in snapshots_by_session_and_window_id.items():\n result.extend(fn(snapshots))\n\n return result\n\n\ndef chunk_string(string: str, chunk_length: int) -> List[str]:\n \"\"\"Split a string into chunk_length-sized elements. Reversal operation: `''.join()`.\"\"\"\n return [string[0 + offset : chunk_length + offset] for offset in range(0, len(string), chunk_length)]\n\n\ndef is_unprocessed_snapshot_event(event: Dict) -> bool:\n try:\n is_snapshot = event[\"event\"] == \"$snapshot\"\n except KeyError:\n raise ValueError('All events must have the event name field \"event\"!')\n except TypeError:\n raise ValueError(f\"All events must be dictionaries not '{type(event).__name__}'!\")\n try:\n return is_snapshot and \"compression\" not in event[\"properties\"][\"$snapshot_data\"]\n except KeyError:\n capture_exception()\n raise ValueError('$snapshot events must contain property \"$snapshot_data\"!')\n\n\ndef compress_to_string(json_string: str) -> str:\n compressed_data = gzip.compress(json_string.encode(\"utf-16\", \"surrogatepass\"))\n return base64.b64encode(compressed_data).decode(\"utf-8\")\n\n\ndef decompress(base64data: str) -> str:\n compressed_bytes = base64.b64decode(base64data)\n return gzip.decompress(compressed_bytes).decode(\"utf-16\", \"surrogatepass\")\n\n\ndef decompress_chunked_snapshot_data(\n all_recording_events: List[SnapshotDataTaggedWithWindowId],\n limit: Optional[int] = None,\n offset: int = 0,\n return_only_activity_data: bool = False,\n) -> DecompressedRecordingData:\n \"\"\"\n Before data is stored in clickhouse, it is compressed and then chunked. This function\n gets back to the original data by unchunking the events and then decompressing the data.\n\n If limit + offset is provided, then it will paginate the decompression by chunks (not by events, because\n you can't decompress an incomplete chunk).\n\n Depending on the size of the recording, this function can return a lot of data. To decrease the\n memory used, you should either use the pagination parameters or pass in 'return_only_activity_data' which\n drastically reduces the size of the data returned if you only want the activity data (used for metadata calculation)\n \"\"\"\n\n if len(all_recording_events) == 0:\n return DecompressedRecordingData(has_next=False, snapshot_data_by_window_id={})\n\n snapshot_data_by_window_id = defaultdict(list)\n chunks_collector: DefaultDict[str, List[SnapshotDataTaggedWithWindowId]] = defaultdict(list)\n processed_chunk_ids = set()\n count = 0\n\n for event in all_recording_events:\n # Handle unchunked snapshots\n if \"chunk_id\" not in event[\"snapshot_data\"]:\n count += 1\n\n if offset >= count:\n continue\n\n if event[\"snapshot_data\"].get(\"data_items\"):\n decompressed_items = [json.loads(decompress(x)) for x in event[\"snapshot_data\"][\"data_items\"]]\n\n # New format where the event is a list of raw rrweb events\n snapshot_data_by_window_id[event[\"window_id\"]].extend(\n event[\"snapshot_data\"][\"events_summary\"] if return_only_activity_data else decompressed_items\n )\n else:\n # Really old format where the event is just a single raw rrweb event\n snapshot_data_by_window_id[event[\"window_id\"]].append(\n get_events_summary_from_snapshot_data([event[\"snapshot_data\"]])[0]\n if return_only_activity_data\n else event[\"snapshot_data\"]\n )\n else:\n # Handle chunked snapshots\n if event[\"snapshot_data\"][\"chunk_id\"] in processed_chunk_ids:\n continue\n\n chunks = chunks_collector[event[\"snapshot_data\"][\"chunk_id\"]]\n chunks.append(event)\n\n deduplicated_chunks = {}\n for chunk in chunks:\n # reduce the chunks into deduplicated chunks by chunk_id taking only the first seen for each chunk_id\n if chunk[\"snapshot_data\"][\"chunk_index\"] not in deduplicated_chunks:\n deduplicated_chunks[chunk[\"snapshot_data\"][\"chunk_index\"]] = chunk\n\n chunks = chunks_collector[event[\"snapshot_data\"][\"chunk_id\"]] = list(deduplicated_chunks.values())\n\n if len(chunks) == event[\"snapshot_data\"][\"chunk_count\"]:\n count += 1\n chunks_collector[event[\"snapshot_data\"][\"chunk_id\"]] = None\n\n # Somehow mark this chunk_id as processed...\n processed_chunk_ids.add(event[\"snapshot_data\"][\"chunk_id\"])\n\n if offset >= count:\n continue\n\n b64_compressed_data = \"\".join(\n chunk[\"snapshot_data\"][\"data\"]\n for chunk in sorted(chunks, key=lambda c: c[\"snapshot_data\"][\"chunk_index\"])\n )\n decompressed_data = json.loads(decompress(b64_compressed_data))\n\n if type(decompressed_data) is dict:\n decompressed_data = [decompressed_data]\n\n if return_only_activity_data:\n events_with_only_activity_data = get_events_summary_from_snapshot_data(decompressed_data)\n snapshot_data_by_window_id[event[\"window_id\"]].extend(events_with_only_activity_data)\n else:\n snapshot_data_by_window_id[event[\"window_id\"]].extend(decompressed_data)\n\n if limit and count >= offset + limit:\n break\n\n has_next = count < len(all_recording_events)\n\n return DecompressedRecordingData(has_next=has_next, snapshot_data_by_window_id=snapshot_data_by_window_id)\n\n\ndef is_active_event(event: SessionRecordingEventSummary) -> bool:\n \"\"\"\n Determines which rr-web events are \"active\" - meaning user generated\n \"\"\"\n active_rr_web_sources = [\n 1, # MouseMove,\n 2, # MouseInteraction,\n 3, # Scroll,\n 4, # ViewportResize,\n 5, # Input,\n 6, # TouchMove,\n 7, # MediaInteraction,\n 12, # Drag,\n ]\n return event[\"type\"] == 3 and event[\"data\"].get(\"source\") in active_rr_web_sources\n\n\ndef parse_snapshot_timestamp(timestamp: int):\n return datetime.fromtimestamp(timestamp / 1000, timezone.utc)\n\n\ndef convert_to_timestamp(source: str) -> int:\n return int(parse(source).timestamp() * 1000)\n\n\ndef get_events_summary_from_snapshot_data(snapshot_data: List[SnapshotData]) -> List[SessionRecordingEventSummary]:\n \"\"\"\n Extract a minimal representation of the snapshot data events for easier querying.\n 'data' and 'data.payload' values are included as long as they are strings or numbers\n and in the inclusion list to keep the payload minimal\n \"\"\"\n events_summary = []\n\n for event in snapshot_data:\n if not event or \"timestamp\" not in event or \"type\" not in event:\n continue\n\n # Get all top level data values\n data = {\n key: value\n for key, value in event.get(\"data\", {}).items()\n if type(value) in [str, int] and key in EVENT_SUMMARY_DATA_INCLUSIONS\n }\n # Some events have a payload, some values of which we want\n if event.get(\"data\", {}).get(\"payload\"):\n # Make sure the payload is a dict before we access it\n if isinstance(event[\"data\"][\"payload\"], dict):\n data[\"payload\"] = {\n key: value\n for key, value in event[\"data\"][\"payload\"].items()\n if type(value) in [str, int] and f\"payload.{key}\" in EVENT_SUMMARY_DATA_INCLUSIONS\n }\n\n # noinspection PyBroadException\n try:\n events_summary.append(\n SessionRecordingEventSummary(\n timestamp=int(event[\"timestamp\"])\n if isinstance(event[\"timestamp\"], (int, float))\n else convert_to_timestamp(event[\"timestamp\"]),\n type=event[\"type\"],\n data=data,\n )\n )\n except ParserError:\n capture_exception()\n\n # No guarantees are made about order so, we sort here to be sure\n events_summary.sort(key=lambda x: x[\"timestamp\"])\n\n return events_summary\n\n\ndef byte_size_dict(x: Dict | List) -> int:\n return len(json.dumps(x))\n","sub_path":"posthog/session_recordings/session_recording_helpers.py","file_name":"session_recording_helpers.py","file_ext":"py","file_size_in_byte":16939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"619180377","text":"\"\"\"\n@file : train_framework.py\n@License : (C)Copyright 2021 Haoran Jia, Fudan University. All Rights Reserved\n@Contact : 21211140001@m.fudan.edu.cn\n@Desc : \n\n@Modify Time @Author @Version \n------------ ------- -------- \n2021/8/31 14:15 JHR 1.0 \n\"\"\"\nimport tensorflow as tf\nimport datetime\nimport time\nimport os\nfrom tqdm import tqdm\n\nimport data\nfrom utils import visualization, Loss, Metrics\n\n\nclass TrainFramework(object):\n def __init__(self, model):\n # 生成数据集\n self.train_ds, self.validation_ds, self.test_ds = data.create_dataset(\n split_method=\"split1\",\n origin_path=\"dataset\\\\treated mixed\\\\Origin\",\n seg_path=\"dataset\\\\treated mixed\\\\Seg_binary\"\n )\n\n self.model = model\n\n # 定义优化器\n self.optimizer = tf.keras.optimizers.Adam(learning_rate=2e-4, beta_1=0.5)\n\n # 检查点\n self.CURRENT_TIME = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n checkpoint_dir = \"checkpoints/\" + self.CURRENT_TIME\n self.checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')\n self.checkpoint = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model)\n\n # tensorboard\n train_log_dir = \"logs/\" + self.CURRENT_TIME + \"/train\"\n test_log_dir = \"logs/\" + self.CURRENT_TIME + \"/test\"\n self.train_summary_writer = tf.summary.create_file_writer(train_log_dir)\n self.test_summary_writer = tf.summary.create_file_writer(test_log_dir)\n\n # 计数\n self.test_per_n_epoch = 1 # 每n轮进行一次测试\n self.save_test_image_per_n_epoch = 10 # 每n轮保存一次测试图片,应为test_per_n_epoch的整数倍\n self.save_model_per_n_epoch = 50 # 每n轮保存一次模型\n\n @tf.function\n def train_step(self, origin, target):\n with tf.GradientTape() as g:\n # 网络生成图像\n seg = self.model(origin, training=True)\n # 计算损失函数\n loss = Loss.BinaryCrossentropy(y_true=target, y_pred=seg)\n # 计算梯度\n gradient = g.gradient(loss, self.model.trainable_variables)\n # 利用梯度进行参数更新\n self.optimizer.apply_gradients(zip(gradient, self.model.trainable_variables))\n\n return loss\n\n def test_step(self, n, origin, target, epoch, save_image):\n seg = self.model(origin, training=True)\n dice = Metrics.dice_coef(target, seg)\n if save_image:\n figure = visualization.plot_seg(origin, target, seg)\n with self.test_summary_writer.as_default():\n tf.summary.image('test result' + str(n.numpy()), visualization.plot_to_image(figure), step=epoch)\n return dice\n\n def fit(self, epochs):\n print(\"Start Time: \", self.CURRENT_TIME)\n time.sleep(0.01)\n start = time.time()\n\n for epoch in range(epochs):\n \"\"\"\n 训练\n \"\"\"\n # loss保存一轮中每一批的损失函数(在一批中求平均?)\n loss = []\n with tqdm(self.train_ds.enumerate()) as bar:\n bar.set_description(\"Epoch %i\" % epoch)\n for n, (origin, target) in bar:\n loss_add = self.train_step(origin, target)\n loss.append(loss_add)\n # 对所有的批求平均,得到本轮的平均损失函数\n loss = tf.reduce_mean(loss, axis=0)\n # 记录到tensorboard中\n with self.train_summary_writer.as_default():\n tf.summary.scalar('loss', loss, step=epoch)\n \"\"\"\n 测试\n \"\"\"\n # 如果进行测试:\n if (epoch + 1) % self.test_per_n_epoch == 0:\n metrics = []\n # 如果保存测试时的图片结果:\n save_image = False\n if (epoch + 1) % self.save_test_image_per_n_epoch == 0:\n save_image = True\n # 进行测试,同时保存测试结果\n for n, (origin, target) in self.test_ds.enumerate():\n metrics_add = self.test_step(n, origin, target, epoch, save_image)\n metrics.append(metrics_add)\n # 测试结果对批取平均\n metrics = tf.reduce_mean(metrics, axis=0)\n # 记录测试结果\n with self.test_summary_writer.as_default():\n tf.summary.scalar('dice', metrics, step=epoch)\n # tf.summary.scalar('', metrics[1], step=epoch)\n \"\"\"\n 保存模型\n \"\"\"\n if (epoch + 1) % self.save_model_per_n_epoch == 0:\n self.checkpoint.save(file_prefix=self.checkpoint_prefix)\n\n # 保存最终模型\n self.checkpoint.save(file_prefix=self.checkpoint_prefix)\n end = time.time()\n print('Training Finished, Run Time: ', time.strftime('%H:%M:%S', time.gmtime(end - start)))\n","sub_path":"train_framework.py","file_name":"train_framework.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"86313055","text":"#!/usr/bin/env python\n#===============================================================================\n# CreateListofSites\n# \n# Description:\n# Script to open raw export from Cisco Transport gear (i.e. CTC or Cisco\n# Transport Controller) and process into a standardized tab-separated format.\n# Output file is saved as Original_File_Name (minus the .csv extension) plus\n# the custom pyInvSites.txt extension.\n#\n# Print and FileWrite flags defaults can be changed in the main method\n#\n# Version:\n# MM.mm DD/MM/YY\n# 00.00 21/11/17 First version\n# 00.01 30/11/17 Add Log function for debug-like statements\n# 00.02 25/06/18 Add function createSiteMenu for drop-down list access\n# 00.03 18/07/18 Add createStateMenu and createMCMA menus. Helps with\n# filtering list size down to reasonable on-monitor quantity\n# 00.04 28/03/19 Add script for short list (using user input list of TIDs)\n# 00.05 22/08/19 Correct ExtendTIDList to remove duplicates (\"set\" it)\n# 00.06 07/01/20 Abstract out menu and radiomenu creations to DrawItemPopup\n#\n# Example/Usage:\n# Input file from directory: \"EPNInv_ALL_2017-10-24.csv\"\n# Output file name: \"EPNInv_ALL_2017-10-24pyInvSites.txt\"\n#\n#===============================================================================\nimport json\nimport os\nimport re\n\nfrom draw.DrawItemMenuPopup import ItemMenu, ItemRadio\n\nfrom parsers.CreateDictInventory import setINVDictFields\nfrom src.CreateHeaderLists import initStateDict, initMCMADict\nfrom src.OpenFileInvMgr import openRawFile\nfrom src.SetMetroNameInv import MetroLookup, filterTIDbyState, filterTIDbyMCMA\nfrom src.WriteFileInvMgr import writeLogMessage, writePyFile\n\n\n[KEYSHSLPT, KEYTID, KEYSTATE, KEYPRODUCTID, KEYPARTNUM, KEYVERSION,\n KEYEQUIPNAME, KEYSERIALNUM, KEYCLEI, KEYLOCATION, KEYOPSTATE,\n KEYMFGDATE, KEYSITESSP, KEYSHELF, KEYSLOT, KEYPORT] = setINVDictFields()\n\n\ndef buildListSiteTID(fileINV):\n # pre-allocate variable for Inv list\n setSiteTID = set([])\n \n # set up split character\n if re.search('.csv',fileINV):\n splitChar = ','\n indx = 0\n elif re.search('pyInvSum.txt', fileINV):\n splitChar = '\\t'\n indx = 0\n\n else: #if re.search('.txt', fileINV):\n splitChar = '\\t'\n indx = 1\n\n # Open Inventory text file for reading\n with open(fileINV) as f:\n f.readline() # reads first line (header row)\n for line in f:\n # equipment description line\n newLine = line.strip().split(splitChar)\n Site = newLine[indx].strip()\n\n setSiteTID.add(Site)\n f.close()\n \n # need to check for duplicate circuits\n listSiteTID = list(setSiteTID)\n listSiteTID.sort()\n return listSiteTID\n\n\ndef buildTIDListFromJSON(fileINV):\n with open(fileINV) as f:\n jsonSrc = json.loads(f.read())\n f.close()\n Server = list(jsonSrc.keys())[0]\n jsonSource = jsonSrc[Server]\n setSiteTID = list(jsonSource.keys())\n listSiteTID = list(setSiteTID)\n listSiteTID.sort()\n return listSiteTID\n\n\ndef extendTIDList(src0, src1):\n src0.extend(src1)\n newSrc = list(set(src0))\n newSrc.sort()\n return newSrc\n\n\ndef buildListSiteTIDShort(fileTIDs):\n listSiteTID = []\n with open(fileTIDs) as f:\n for line in f:\n listSiteTID.append(line.strip())\n f.close()\n return listSiteTID\n\n\ndef createSiteMenu(fileINV):\n if re.search('json', fileINV):\n listSiteTID = buildTIDListFromJSON(fileINV)\n else:\n listSiteTID = buildListSiteTID(fileINV)\n if len(listSiteTID) < 1:\n return\n\n POPUPWIDTH = 300\n POPUPHEIGHT = 100\n POPUPX = 100\n POPUPY = 150\n inputTitle = 'Select a desired hub site'\n myMenu = ItemMenu(inputTitle, POPUPWIDTH, POPUPHEIGHT, POPUPX, POPUPY,\n listSiteTID)\n selectSite = myMenu.buildItemMenu()\n\n return selectSite\n\n\ndef createSiteMenuState(fileINV, dirINV):\n selState = createStateMenu()\n if re.search('json', fileINV):\n listSiteTID = buildTIDListFromJSON(fileINV)\n else:\n listSiteTID = buildListSiteTID(fileINV)\n \n # now filter list to selected state\n filteredList = filterTIDbyState(listSiteTID, selState)\n if len(filteredList) < 1:\n logMsg = 'No sites for \\\"' + selState + '\\\" in ' + fileINV\n writeLogMessage(logMsg, dirINV)\n return\n elif len(filteredList) > 40: # list too long to display on monitor\n selNetType = createMCMAMenu()\n filteredList = filterTIDbyMCMA(filteredList, selNetType)\n if len(filteredList) < 1:\n logMsg = 'No sites for \\\"' + selState + '\\\" of type ' + selNetType\n writeLogMessage(logMsg, dirINV)\n return\n\n POPUPWIDTH = 300\n POPUPHEIGHT = 100\n POPUPX = 200\n POPUPY = 150\n inputTitle = 'Select a desired hub site'\n myMenu = ItemMenu(inputTitle, POPUPWIDTH, POPUPHEIGHT, POPUPX, POPUPY,\n filteredList)\n selectTID = myMenu.buildItemMenu()\n\n return selectTID\n \n \ndef createStateMenu():\n dictState = initStateDict()\n listState = [(k,v) for k,v in dictState.items()]\n\n POPUPWIDTH = 300\n POPUPHEIGHT = 25 * len(listState)\n POPUPX = 100\n POPUPY = 150\n inputTitle = 'Select a network type'\n myMenu = ItemRadio(inputTitle, POPUPWIDTH, POPUPHEIGHT, POPUPX, POPUPY,\n listState)\n selectItem = myMenu.buildItemMenu()\n\n return selectItem\n\n\ndef createMCMAMenu():\n dictMCMA = initMCMADict()\n listMCMA = [(k,v) for k,v in dictMCMA.items()]\n\n POPUPWIDTH = 300\n POPUPHEIGHT = 25 * len(listMCMA)\n POPUPX = 100\n POPUPY = 150\n inputTitle = 'Select a network type'\n myMenu = ItemRadio(inputTitle, POPUPWIDTH, POPUPHEIGHT, POPUPX, POPUPY,\n listMCMA)\n selectItem = myMenu.buildItemMenu()\n\n return selectItem\n\n\ndef printSiteListToConsole(List_SiteTID, Metro):\n print(Metro)\n print('----------')\n print('\\n'.join(List_SiteTID))\n print('There are', len(List_SiteTID), 'sites in this metro.')\n print('\\n')\n\n\ndef massageFileName(fileINV):\n if re.search('pyInv', fileINV):\n fileName = os.path.split(fileINV)[1]\n fileName = fileName.split('pyInv')[0]\n else:\n # for raw files, split at '.'\n fileName = os.path.split(fileINV)[1]\n fileName = fileName.split('.')[0]\n return fileName\n\n\ndef createSiteListUnit(writeToFileFlag=False, printFlag=True):\n fileName, fileINV, dirINV = openRawFile(fileXt=['*.csv','*.txt','*.json'])\n if fileName == '': return\n fileName = massageFileName(fileINV)\n Metro = MetroLookup(fileName)\n writeLogMessage('Creating site list for ' + fileName, dirINV)\n \n # build site TID list\n if re.search('json', fileINV):\n listSiteTID = buildTIDListFromJSON(fileINV)\n else:\n listSiteTID = buildListSiteTID(fileINV)\n \n if printFlag:\n printSiteListToConsole(listSiteTID, Metro)\n \n fileXt0 = 'pyInvSites.txt'\n if writeToFileFlag:\n writePyFile(dirINV, fileName, listSiteTID, fileXt0)\n else:\n writeQuery = input('Do you wish to save the Inventory processed file (Y/N)?:')\n if re.search('y',writeQuery) or re.search('Y',writeQuery):\n writePyFile(dirINV, fileName, listSiteTID, fileXt0)\n \n writeLogMessage('Script complete.', dirINV) \n \n \ndef main(writeToFileFlag=True, printFlag=True):\n createSiteListUnit(writeToFileFlag, printFlag)\n \n \nif __name__ == '__main__':\n main()\n ","sub_path":"src/CreateListofSites.py","file_name":"CreateListofSites.py","file_ext":"py","file_size_in_byte":7525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"104454730","text":"import random\n\n\nclass MediaId(object):\n DELIMITER_CHAR = \".\"\n PREFIX_ROOT = \"root\"\n PREFIX_PLAYLISTS = \"playlists\"\n PREFIX_PLAYLIST = \"PLAYLIST\"\n PREFIX_VIDEO = \"video\"\n PREFIX_SUBSCRIPTIONS = \"subscriptions\"\n PREFIX_CHANNEL = \"channel\"\n PREFIX_SEARCH_VIDEO = \"searchvideo\"\n PREFIX_SEARCH_ID = \"searchid\"\n PREFIX_SEARCH_CHANNEL = \"searchchannel\"\n PREFIX_CACHE = \"cache\"\n PREFIX_SEARCH = \"search\"\n\n def __init__(self, prefix, key=\"\"):\n self.prefix = prefix\n self.key = key\n\n def __str__(self):\n return \"{0}{1}{2}\".format(\n self.prefix, MediaId.DELIMITER_CHAR, self.key).rstrip(MediaId.DELIMITER_CHAR)\n\n @property\n def mediaid(self):\n return \"{0}{1}{2}\".format(\n self.prefix, MediaId.DELIMITER_CHAR, self.key).rstrip(MediaId.DELIMITER_CHAR)\n\n @staticmethod\n def parse(mediaid):\n delimiter_index = mediaid.find(MediaId.DELIMITER_CHAR)\n\n if delimiter_index > -1:\n split_mediaid = mediaid.split(\".\")\n return MediaId(split_mediaid[0], split_mediaid[1])\n else:\n return MediaId(mediaid)\n\n\nclass LastUpdate(object):\n\n def __init__(self):\n self.favorites = 0\n self.catalog = random.randint(0, 100)\n\n def todict(self):\n return {\"getLastUpdateResult\": {\n \"catalog\": str(self.catalog),\n \"favorites\": str(self.favorites)}}\n\n\nclass MediaUri(object):\n\n def __init__(self, host, mediaid):\n self.host = host\n self.mediaid = mediaid\n\n @property\n def uri(self):\n return self.host.format(self.mediaid.key)\n\n\nclass SearchResult(object):\n\n def __init__(self):\n self.index = 0\n self.mediacollection = []\n self.mediametadatacollection = []\n\n @property\n def count(self):\n return len(self.mediacollection) + len(self.mediametadatacollection)\n\n @property\n def total(self):\n return len(self.mediacollection) + len(self.mediametadatacollection)\n\n def todict(self):\n result = [{\"index\": self.index, \"count\": self.count, \"total\": self.total}]\n\n for media in self.mediacollection:\n result.append(media.todict())\n\n for mediametadata in self.mediametadatacollection:\n result.append({\"mediaMetadata\": mediametadata.todict()})\n\n return {\"searchResult\": result}\n\n\nclass TrackMetadata(object):\n\n def __init__(self, artist, albumarturi=\"\", album=\"\",\n genre=\"\", duration=0, canplay=True,\n canskip=True, can_add_to_favorites=False):\n self.artist = artist\n self.albumarturi = albumarturi\n self.album = album\n self.genre = genre\n self.duration = duration\n self.canplay = canplay\n self.canskip = canskip\n self.can_add_to_favorites = can_add_to_favorites\n\n def todict(self):\n return {\"artist\": self.artist,\n \"albumArtURI\": self.albumarturi,\n \"album\": self.album,\n \"genre\": self.genre,\n \"duration\": self.duration,\n \"canPlay\": self.canplay,\n \"canSkip\": self.canskip,\n \"canAddToFavorites\": self.can_add_to_favorites}\n\n\nclass MediaMetadata(object):\n\n def __init__(self, mediaid, title, trackmetadata,\n itemtype=\"track\", mimetype=\"audio/aac\"):\n self.mediaid = mediaid\n self.title = title\n self.trackmetadata = trackmetadata\n self.itemtype = itemtype\n self.mimetype = mimetype\n\n def todict(self):\n return {\"id\": self.mediaid.mediaid,\n \"title\": self.title,\n \"itemType\": self.itemtype,\n \"mimeType\": self.mimetype,\n \"trackMetadata\": self.trackmetadata.todict()}\n\n\nclass MediaCollectionItem(object):\n\n def __init__(self, mediaid, title, itemtype=\"container\",\n cancache=False, albumarturi=\"\", canenumerate=True,\n canscroll=False, canplay=False):\n self.mediaid = mediaid\n self.title = title\n self.itemtype = itemtype\n self.cancache = cancache\n self.albumarturi = albumarturi\n self.canenumerate = canenumerate\n self.canscroll = canscroll\n self.canplay = canplay\n\n def todict(self):\n return {\"mediaCollection\": {\n \"id\": self.mediaid.mediaid,\n \"title\": self.title,\n \"itemType\": self.itemtype,\n \"canCache\": self.cancache,\n \"albumArtURI\": self.albumarturi,\n \"canEnumerate\": self.canenumerate,\n \"canScroll\": self.canscroll,\n \"canPlay\": self.canplay}}\n\n\nclass MetadataResult(object):\n\n def __init__(self):\n self.index = 0\n self.mediacollection = []\n self.mediametadatacollection = []\n\n @property\n def count(self):\n return len(self.mediacollection) + len(self.mediametadatacollection)\n\n @property\n def total(self):\n return len(self.mediacollection) + len(self.mediametadatacollection)\n\n def todict(self):\n result = [{\"index\": self.index, \"count\": self.count, \"total\": self.total}]\n\n for media in self.mediacollection:\n result.append(media.todict())\n\n for mediametadata in self.mediametadatacollection:\n result.append({\"mediaMetadata\": mediametadata.todict()})\n\n return {\"getMetadataResult\": result}\n\n\nclass CollectionItemType(object):\n CONTAINER = \"container\"\n TRACK = \"track\"\n TRACKLIST = \"trackList\"\n ALBUMLIST = \"albumList\"\n\n\nif __name__ == \"__main__\":\n mid = \"root.1234\"\n # t = MediaId.parse(mid)\n t = MediaId(\"root\")\n print(t)\n","sub_path":"sonostube/sonos/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"271041276","text":"from django.test import TestCase\nfrom budget_tool.serializers import *\nfrom django.contrib.auth.models import User\n\nclass SerializerTest(TestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.user = User(username=\"Test\", password=\"fiscaltest\")\n cls.user.save()\n\n cls.existing = Expense.objects.create(user_id=cls.user.id, amount=100, transaction_date=\"2021-03-05\",\n description=\"Rent Payment\", category=\"Essential\")\n\n cls.success_data = {\n \"user\": cls.user.id,\n \"amount\": 100.50,\n \"transaction_date\": \"2021-03-29\",\n \"description\": \"Fi$cal merch\",\n \"category\": \"Essential\"\n }\n\n def test_expense_validity(self):\n serializer = ExpenseSerializer(data=self.success_data)\n self.assertTrue(serializer.is_valid(), serializer.errors)\n\n def test_expense_create(self):\n serializer = ExpenseSerializer(data=self.success_data)\n self.assertTrue(serializer.is_valid(), serializer.errors)\n self.assertTrue(isinstance(serializer.save(), Expense), serializer.errors)\n\n def test_expense_update(self):\n update_data = {\n \"user\": self.user.id,\n \"amount\": 100,\n \"transaction_date\": \"2021-03-05\",\n \"description\": \"March Rent Payment\",\n \"category\": \"Housing\"\n }\n serializer = ExpenseSerializer(self.existing, data=update_data)\n self.assertTrue(serializer.is_valid(), serializer.errors)\n self.assertTrue(isinstance(serializer.save(), Expense), serializer.errors)\n\n def test_expense_contains_expected_fields(self):\n serializer = ExpenseSerializer(self.existing)\n self.assertEqual(set(serializer.data.keys()),\n set(self.success_data.keys()).union([\"id\"]))\n\n\n","sub_path":"fiscal/budget_tool/tests/test_serializers.py","file_name":"test_serializers.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"556397042","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport os\n\nfrom typing import Any, Dict, List, Optional, Tuple, Type, Union, cast, TYPE_CHECKING\n\nfrom pyspark import keyword_only, since, SparkContext\nfrom pyspark.ml.base import Estimator, Model, Transformer\nfrom pyspark.ml.param import Param, Params\nfrom pyspark.ml.util import (\n MLReadable,\n MLWritable,\n JavaMLWriter,\n JavaMLReader,\n DefaultParamsReader,\n DefaultParamsWriter,\n MLWriter,\n MLReader,\n JavaMLReadable,\n JavaMLWritable,\n)\nfrom pyspark.ml.wrapper import JavaParams\nfrom pyspark.ml.common import inherit_doc\nfrom pyspark.sql.dataframe import DataFrame\n\nif TYPE_CHECKING:\n from pyspark.ml._typing import ParamMap, PipelineStage\n from py4j.java_gateway import JavaObject\n\n\n@inherit_doc\nclass Pipeline(Estimator[\"PipelineModel\"], MLReadable[\"Pipeline\"], MLWritable):\n \"\"\"\n A simple pipeline, which acts as an estimator. A Pipeline consists\n of a sequence of stages, each of which is either an\n :py:class:`Estimator` or a :py:class:`Transformer`. When\n :py:meth:`Pipeline.fit` is called, the stages are executed in\n order. If a stage is an :py:class:`Estimator`, its\n :py:meth:`Estimator.fit` method will be called on the input\n dataset to fit a model. Then the model, which is a transformer,\n will be used to transform the dataset as the input to the next\n stage. If a stage is a :py:class:`Transformer`, its\n :py:meth:`Transformer.transform` method will be called to produce\n the dataset for the next stage. The fitted model from a\n :py:class:`Pipeline` is a :py:class:`PipelineModel`, which\n consists of fitted models and transformers, corresponding to the\n pipeline stages. If stages is an empty list, the pipeline acts as an\n identity transformer.\n\n .. versionadded:: 1.3.0\n \"\"\"\n\n stages: Param[List[\"PipelineStage\"]] = Param(\n Params._dummy(), \"stages\", \"a list of pipeline stages\"\n )\n\n _input_kwargs: Dict[str, Any]\n\n @keyword_only\n def __init__(self, *, stages: Optional[List[\"PipelineStage\"]] = None):\n \"\"\"\n __init__(self, \\\\*, stages=None)\n \"\"\"\n super(Pipeline, self).__init__()\n kwargs = self._input_kwargs\n self.setParams(**kwargs)\n\n def setStages(self, value: List[\"PipelineStage\"]) -> \"Pipeline\":\n \"\"\"\n Set pipeline stages.\n\n .. versionadded:: 1.3.0\n\n Parameters\n ----------\n value : list\n of :py:class:`pyspark.ml.Transformer`\n or :py:class:`pyspark.ml.Estimator`\n\n Returns\n -------\n :py:class:`Pipeline`\n the pipeline instance\n \"\"\"\n return self._set(stages=value)\n\n @since(\"1.3.0\")\n def getStages(self) -> List[\"PipelineStage\"]:\n \"\"\"\n Get pipeline stages.\n \"\"\"\n return self.getOrDefault(self.stages)\n\n @keyword_only\n @since(\"1.3.0\")\n def setParams(self, *, stages: Optional[List[\"PipelineStage\"]] = None) -> \"Pipeline\":\n \"\"\"\n setParams(self, \\\\*, stages=None)\n Sets params for Pipeline.\n \"\"\"\n kwargs = self._input_kwargs\n return self._set(**kwargs)\n\n def _fit(self, dataset: DataFrame) -> \"PipelineModel\":\n stages = self.getStages()\n for stage in stages:\n if not (isinstance(stage, Estimator) or isinstance(stage, Transformer)):\n raise TypeError(\"Cannot recognize a pipeline stage of type %s.\" % type(stage))\n indexOfLastEstimator = -1\n for i, stage in enumerate(stages):\n if isinstance(stage, Estimator):\n indexOfLastEstimator = i\n transformers: List[Transformer] = []\n for i, stage in enumerate(stages):\n if i <= indexOfLastEstimator:\n if isinstance(stage, Transformer):\n transformers.append(stage)\n dataset = stage.transform(dataset)\n else: # must be an Estimator\n model = stage.fit(dataset)\n transformers.append(model)\n if i < indexOfLastEstimator:\n dataset = model.transform(dataset)\n else:\n transformers.append(cast(Transformer, stage))\n return PipelineModel(transformers)\n\n def copy(self, extra: Optional[\"ParamMap\"] = None) -> \"Pipeline\":\n \"\"\"\n Creates a copy of this instance.\n\n .. versionadded:: 1.4.0\n\n Parameters\n ----------\n extra : dict, optional\n extra parameters\n\n Returns\n -------\n :py:class:`Pipeline`\n new instance\n \"\"\"\n if extra is None:\n extra = dict()\n that = Params.copy(self, extra)\n stages = [stage.copy(extra) for stage in that.getStages()]\n return that.setStages(stages)\n\n @since(\"2.0.0\")\n def write(self) -> MLWriter:\n \"\"\"Returns an MLWriter instance for this ML instance.\"\"\"\n allStagesAreJava = PipelineSharedReadWrite.checkStagesForJava(self.getStages())\n if allStagesAreJava:\n return JavaMLWriter(self) # type: ignore[arg-type]\n return PipelineWriter(self)\n\n @classmethod\n @since(\"2.0.0\")\n def read(cls) -> \"PipelineReader\":\n \"\"\"Returns an MLReader instance for this class.\"\"\"\n return PipelineReader(cls)\n\n @classmethod\n def _from_java(cls, java_stage: \"JavaObject\") -> \"Pipeline\":\n \"\"\"\n Given a Java Pipeline, create and return a Python wrapper of it.\n Used for ML persistence.\n \"\"\"\n # Create a new instance of this stage.\n py_stage = cls()\n # Load information from java_stage to the instance.\n py_stages: List[\"PipelineStage\"] = [\n JavaParams._from_java(s) for s in java_stage.getStages()\n ]\n py_stage.setStages(py_stages)\n py_stage._resetUid(java_stage.uid())\n return py_stage\n\n def _to_java(self) -> \"JavaObject\":\n \"\"\"\n Transfer this instance to a Java Pipeline. Used for ML persistence.\n\n Returns\n -------\n py4j.java_gateway.JavaObject\n Java object equivalent to this instance.\n \"\"\"\n\n gateway = SparkContext._gateway\n assert gateway is not None and SparkContext._jvm is not None\n\n cls = SparkContext._jvm.org.apache.spark.ml.PipelineStage\n java_stages = gateway.new_array(cls, len(self.getStages()))\n for idx, stage in enumerate(self.getStages()):\n java_stages[idx] = cast(JavaParams, stage)._to_java()\n\n _java_obj = JavaParams._new_java_obj(\"org.apache.spark.ml.Pipeline\", self.uid)\n _java_obj.setStages(java_stages)\n\n return _java_obj\n\n\n@inherit_doc\nclass PipelineWriter(MLWriter):\n \"\"\"\n (Private) Specialization of :py:class:`MLWriter` for :py:class:`Pipeline` types\n \"\"\"\n\n def __init__(self, instance: Pipeline):\n super(PipelineWriter, self).__init__()\n self.instance = instance\n\n def saveImpl(self, path: str) -> None:\n stages = self.instance.getStages()\n PipelineSharedReadWrite.validateStages(stages)\n PipelineSharedReadWrite.saveImpl(self.instance, stages, self.sc, path)\n\n\n@inherit_doc\nclass PipelineReader(MLReader[Pipeline]):\n \"\"\"\n (Private) Specialization of :py:class:`MLReader` for :py:class:`Pipeline` types\n \"\"\"\n\n def __init__(self, cls: Type[Pipeline]):\n super(PipelineReader, self).__init__()\n self.cls = cls\n\n def load(self, path: str) -> Pipeline:\n metadata = DefaultParamsReader.loadMetadata(path, self.sc)\n if \"language\" not in metadata[\"paramMap\"] or metadata[\"paramMap\"][\"language\"] != \"Python\":\n return JavaMLReader(cast(Type[\"JavaMLReadable[Pipeline]\"], self.cls)).load(path)\n else:\n uid, stages = PipelineSharedReadWrite.load(metadata, self.sc, path)\n return Pipeline(stages=stages)._resetUid(uid)\n\n\n@inherit_doc\nclass PipelineModelWriter(MLWriter):\n \"\"\"\n (Private) Specialization of :py:class:`MLWriter` for :py:class:`PipelineModel` types\n \"\"\"\n\n def __init__(self, instance: \"PipelineModel\"):\n super(PipelineModelWriter, self).__init__()\n self.instance = instance\n\n def saveImpl(self, path: str) -> None:\n stages = self.instance.stages\n PipelineSharedReadWrite.validateStages(cast(List[\"PipelineStage\"], stages))\n PipelineSharedReadWrite.saveImpl(\n self.instance, cast(List[\"PipelineStage\"], stages), self.sc, path\n )\n\n\n@inherit_doc\nclass PipelineModelReader(MLReader[\"PipelineModel\"]):\n \"\"\"\n (Private) Specialization of :py:class:`MLReader` for :py:class:`PipelineModel` types\n \"\"\"\n\n def __init__(self, cls: Type[\"PipelineModel\"]):\n super(PipelineModelReader, self).__init__()\n self.cls = cls\n\n def load(self, path: str) -> \"PipelineModel\":\n metadata = DefaultParamsReader.loadMetadata(path, self.sc)\n if \"language\" not in metadata[\"paramMap\"] or metadata[\"paramMap\"][\"language\"] != \"Python\":\n return JavaMLReader(cast(Type[\"JavaMLReadable[PipelineModel]\"], self.cls)).load(path)\n else:\n uid, stages = PipelineSharedReadWrite.load(metadata, self.sc, path)\n return PipelineModel(stages=cast(List[Transformer], stages))._resetUid(uid)\n\n\n@inherit_doc\nclass PipelineModel(Model, MLReadable[\"PipelineModel\"], MLWritable):\n \"\"\"\n Represents a compiled pipeline with transformers and fitted models.\n\n .. versionadded:: 1.3.0\n \"\"\"\n\n def __init__(self, stages: List[Transformer]):\n super(PipelineModel, self).__init__()\n self.stages = stages\n\n def _transform(self, dataset: DataFrame) -> DataFrame:\n for t in self.stages:\n dataset = t.transform(dataset)\n return dataset\n\n def copy(self, extra: Optional[\"ParamMap\"] = None) -> \"PipelineModel\":\n \"\"\"\n Creates a copy of this instance.\n\n .. versionadded:: 1.4.0\n\n :param extra: extra parameters\n :returns: new instance\n \"\"\"\n if extra is None:\n extra = dict()\n stages = [stage.copy(extra) for stage in self.stages]\n return PipelineModel(stages)\n\n @since(\"2.0.0\")\n def write(self) -> MLWriter:\n \"\"\"Returns an MLWriter instance for this ML instance.\"\"\"\n allStagesAreJava = PipelineSharedReadWrite.checkStagesForJava(\n cast(List[\"PipelineStage\"], self.stages)\n )\n if allStagesAreJava:\n return JavaMLWriter(self) # type: ignore[arg-type]\n return PipelineModelWriter(self)\n\n @classmethod\n @since(\"2.0.0\")\n def read(cls) -> PipelineModelReader:\n \"\"\"Returns an MLReader instance for this class.\"\"\"\n return PipelineModelReader(cls)\n\n @classmethod\n def _from_java(cls, java_stage: \"JavaObject\") -> \"PipelineModel\":\n \"\"\"\n Given a Java PipelineModel, create and return a Python wrapper of it.\n Used for ML persistence.\n \"\"\"\n # Load information from java_stage to the instance.\n py_stages: List[Transformer] = [JavaParams._from_java(s) for s in java_stage.stages()]\n # Create a new instance of this stage.\n py_stage = cls(py_stages)\n py_stage._resetUid(java_stage.uid())\n return py_stage\n\n def _to_java(self) -> \"JavaObject\":\n \"\"\"\n Transfer this instance to a Java PipelineModel. Used for ML persistence.\n\n :return: Java object equivalent to this instance.\n \"\"\"\n\n gateway = SparkContext._gateway\n assert gateway is not None and SparkContext._jvm is not None\n\n cls = SparkContext._jvm.org.apache.spark.ml.Transformer\n java_stages = gateway.new_array(cls, len(self.stages))\n for idx, stage in enumerate(self.stages):\n java_stages[idx] = cast(JavaParams, stage)._to_java()\n\n _java_obj = JavaParams._new_java_obj(\n \"org.apache.spark.ml.PipelineModel\", self.uid, java_stages\n )\n\n return _java_obj\n\n\n@inherit_doc\nclass PipelineSharedReadWrite:\n \"\"\"\n Functions for :py:class:`MLReader` and :py:class:`MLWriter` shared between\n :py:class:`Pipeline` and :py:class:`PipelineModel`\n\n .. versionadded:: 2.3.0\n \"\"\"\n\n @staticmethod\n def checkStagesForJava(stages: List[\"PipelineStage\"]) -> bool:\n return all(isinstance(stage, JavaMLWritable) for stage in stages)\n\n @staticmethod\n def validateStages(stages: List[\"PipelineStage\"]) -> None:\n \"\"\"\n Check that all stages are Writable\n \"\"\"\n for stage in stages:\n if not isinstance(stage, MLWritable):\n raise ValueError(\n \"Pipeline write will fail on this pipeline \"\n + \"because stage %s of type %s is not MLWritable\",\n stage.uid,\n type(stage),\n )\n\n @staticmethod\n def saveImpl(\n instance: Union[Pipeline, PipelineModel],\n stages: List[\"PipelineStage\"],\n sc: SparkContext,\n path: str,\n ) -> None:\n \"\"\"\n Save metadata and stages for a :py:class:`Pipeline` or :py:class:`PipelineModel`\n - save metadata to path/metadata\n - save stages to stages/IDX_UID\n \"\"\"\n stageUids = [stage.uid for stage in stages]\n jsonParams = {\"stageUids\": stageUids, \"language\": \"Python\"}\n DefaultParamsWriter.saveMetadata(instance, path, sc, paramMap=jsonParams)\n stagesDir = os.path.join(path, \"stages\")\n for index, stage in enumerate(stages):\n cast(MLWritable, stage).write().save(\n PipelineSharedReadWrite.getStagePath(stage.uid, index, len(stages), stagesDir)\n )\n\n @staticmethod\n def load(\n metadata: Dict[str, Any], sc: SparkContext, path: str\n ) -> Tuple[str, List[\"PipelineStage\"]]:\n \"\"\"\n Load metadata and stages for a :py:class:`Pipeline` or :py:class:`PipelineModel`\n\n Returns\n -------\n tuple\n (UID, list of stages)\n \"\"\"\n stagesDir = os.path.join(path, \"stages\")\n stageUids = metadata[\"paramMap\"][\"stageUids\"]\n stages = []\n for index, stageUid in enumerate(stageUids):\n stagePath = PipelineSharedReadWrite.getStagePath(\n stageUid, index, len(stageUids), stagesDir\n )\n stage: \"PipelineStage\" = DefaultParamsReader.loadParamsInstance(stagePath, sc)\n stages.append(stage)\n return (metadata[\"uid\"], stages)\n\n @staticmethod\n def getStagePath(stageUid: str, stageIdx: int, numStages: int, stagesDir: str) -> str:\n \"\"\"\n Get path for saving the given stage.\n \"\"\"\n stageIdxDigits = len(str(numStages))\n stageDir = str(stageIdx).zfill(stageIdxDigits) + \"_\" + stageUid\n stagePath = os.path.join(stagesDir, stageDir)\n return stagePath\n","sub_path":"python/pyspark/ml/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":15641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"70733760","text":"import cv2 \nimport numpy as np\nimport time\n\nimg= cv2.imread(\"imgs/mobile.jpg\", cv2.IMREAD_COLOR)\n\n\ncv2.line(img, (0,0), (50,0), (0, 255, 0), 10)\n\ncv2.rectangle(img, (100, 100), (200, 200), (0,0,255), 10)\n\ncv2.circle(img, (50, 50), 20, (155, 240, 0), 20)\n\ncv2.circle(img, (90, 90), 20, (155, 240, 0), -1)\n\npts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)\ncv2.polylines(img, [pts], True, (0,255,255), 3)\n\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\ncv2.putText(img,'Shivam Agrawal',(0,110), font, 1, (200,255,155), 2, cv2.LINE_AA)\n\n\n\n\nsp= (0,0)\nspeed= 2\nfor i in range(2000):\n time.sleep(0.2)\n dp= sp[0]+speed, sp[1]+speed\n cv2.line(img, sp, dp, (255, 255, 0), 15)\n sp= dp\n cv2.imshow(\"Board\", img)\n #time.sleep(0.3)\n if(cv2.waitKey(1) & 0xFF == ord('q')):\n break \n\n\n\n\n#cv2.imshow(\"Board\", img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n","sub_path":"draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"34108635","text":"#!/usr/bin/env python3\n\"\"\"\nClass that inherits from tensorflow.keras.layers.Layer\nto perform multi head attention.\nhttps://www.tensorflow.org/tutorials/text/transformer\n\"\"\"\nimport tensorflow as tf\nsdp_attention = __import__('5-sdp_attention').sdp_attention\n\n\nclass MultiHeadAttention(tf.keras.layers.Layer):\n \"\"\"\n Performs multi head attention\n \"\"\"\n def __init__(self, dm, h):\n \"\"\"\n Class constructor\n \"\"\"\n super().__init__()\n # Number of heads\n self.h = h\n # Dimensionality of the model\n self.dm = dm\n # Depth of each attention head\n self.depth = dm // h\n # Dense layer used to generate the query matrix\n self.Wq = tf.keras.layers.Dense(units=dm)\n # Dense layer used to generate the key matrix\n self.Wk = tf.keras.layers.Dense(units=dm)\n # Dense layer used to generate the value matrix\n self.Wv = tf.keras.layers.Dense(units=dm)\n # Dense layer used to generate the attention output\n self.linear = tf.keras.layers.Dense(units=dm)\n\n def split_heads(self, x, batch):\n \"\"\"\n Split the last dimension into (h, depth).\n Transpose the result such that the shape is\n (batch_size, h, seq_len, depth)\n \"\"\"\n x = tf.reshape(x, (batch, -1, self.h, self.depth))\n return tf.transpose(x, perm=[0, 2, 1, 3])\n\n def call(self, Q, K, V, mask):\n \"\"\"\n Returns: output, weights\n \"\"\"\n batch = tf.shape(Q)[0]\n # Helping Kelsie\n # batch = Q.get_shape().as_list()[0]\n\n # (batch, seq_len_q, dk)\n Q = self.Wq(Q)\n # (batch, seq_len_v, dk)\n K = self.Wk(K)\n # (batch, seq_len_v, dv)\n V = self.Wv(V)\n\n # (batch, h, seq_len_q, depth)\n Q = self.split_heads(Q, batch)\n # (batch, h, seq_len_k, depth)\n K = self.split_heads(K, batch)\n # (batch, h, seq_len_v, depth)\n V = self.split_heads(V, batch)\n\n # scaled_attention.shape == (batch, h, seq_len_q, depth)\n # weights.shape == (batch, h, seq_len_q, seq_len_k)\n scaled_attention, weights = sdp_attention(Q, K, V, mask)\n\n # (batch, seq_len_q, h, depth)\n scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3])\n\n # (batch, seq_len_q, dm)\n concat_attention = \\\n tf.reshape(scaled_attention, (batch, -1, self.dm))\n\n # (batch, seq_len_q, dm)\n output = self.linear(concat_attention)\n\n return output, weights\n","sub_path":"supervised_learning/0x11-attention/6-multihead_attention.py","file_name":"6-multihead_attention.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"194400051","text":"import os, threading, time\nfrom bottle import route, run, template\n\ndef load():\n while True: range(10000) and None; time.sleep(0.00000001)\nt1 = threading.Thread(target=load)\nt2 = threading.Thread(target=load)\n\n@route('/')\ndef index():\n return template('Hi {{student}}, I am {{server_id}}!',\n server_id=os.environ['SERVER_ID'],\n student=os.environ['STUDENT'])\n\n@route('/load')\ndef load():\n t1.start()\n t2.start()\n return 'Loading'\n\nrun(host='0.0.0.0', port=8080)\n","sub_path":"webservice/webservice.py","file_name":"webservice.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"200347771","text":"#! -*- coding:utf8 -*-\n\nfrom PyQt5.QtWidgets import QTextEdit\nfrom .. import BaseWidget\n\n\n#class MemoList(QWidget):\nclass MemoList(BaseWidget):\n\n name = \"Memo\"\n\n def init_ui(self):\n super(MemoList, self).init_ui()\n\n self.text = QTextEdit(self)\n self.v_layout.addWidget(self.cal)\n self.v_layout.addWidget(self.text)\n self.v_layout.addLayout(self.h_layout)\n self.setLayout(self.v_layout)\n\n","sub_path":"client/base/memo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"142308042","text":"from evaluate.evaluate_research_data.evaluater_proto import Evaluator\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\nimport os\nimport numpy as np\nimport json\ncurrent_file_path = os.path.dirname(os.path.abspath(__file__))\nclass coco_evaluater(Evaluator):\n\tdef __init__(self, model, config, visiual=True):\n\t\tsuper().__init__(model, config, visiual)\n\t\tself.gt_save_path = os.path.join(current_file_path, \"voc_format_research_data_test.json\")\n\t\tself.pred_save_path = os.path.join(current_file_path, \"pred_result.json\")\n\t\tself.generate_eval_result_json()\n\n\tdef generate_eval_result_json(self):\n\t\tdata_dict = []\n\t\tfor img_ind, bboxes_pred in self.yiled_result_bboxes_prd():\n\t\t\tfor bbox in bboxes_pred:\n\t\t\t\tcoor = np.array(bbox[:4], dtype=np.int32)\n\t\t\t\tscore = bbox[4]\n\t\t\t\tscore = float('%.4f' % score)\n\t\t\t\tclass_ind = int(bbox[5])\n\t\t\t\txmin, ymin, xmax, ymax = map(float, coor)\n\t\t\t\tbbox = [xmin, ymin, xmax-xmin, ymax-ymin]\n\t\t\t\tA = {\"image_id\":img_ind, \"category_id\": class_ind,\n\t\t\t\t\t \"bbox\": bbox,\n\t\t\t\t\t \"score\": score} # COCO json format\n\t\t\t\tdata_dict.append(A)\n\t\tif len(data_dict) > 0:\n\t\t\tprint('evaluating ......')\n\t\t\tjson.dump(data_dict, open(self.pred_save_path, 'w'))\n\n\tdef eval(self):\n\t\tcocoGt = COCO(self.gt_save_path) # 标注文件的路径及文件名,json文件形式\n\t\tcocoDt = cocoGt.loadRes(self.pred_save_path) # 自己的生成的结果的路径及文件名,json文件形式\n\t\tcocoEval = COCOeval(cocoGt, cocoDt, \"bbox\")\n\t\tcocoEval.evaluate()\n\t\tcocoEval.accumulate()\n\t\tstate = cocoEval.summarize()\n\t\tif self.config[\"generate_analyze_figure\"]:\n\t\t\tcocoEval.analyze('./'+self.config['generate_analyze_figure_dir_name'])\n\t\treturn state\n\nif __name__ == '__main__':\n\tcocoGt = COCO('./voc_format_research_data_test.json')\n\tcocoDt = cocoGt.loadRes('./pred_result.json')\n\tcocoEval = COCOeval(cocoGt, cocoDt, \"bbox\")\n\tcocoEval.evaluate()\n\tcocoEval.accumulate()\n\tstate = cocoEval.summarize()\n\tcocoEval.analyze('./Analyze_LFFD')\n\n\n\n\n\n\n","sub_path":"evaluate/evaluate_research_data/coco_evaluater.py","file_name":"coco_evaluater.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"48519102","text":"from commands import Commands\nimport settings\nfrom deal import get_deals\nfrom tasks import initialize_channels, ScheduledTasks\nfrom utils import update_guild_config\nimport logging\nimport yaml\n\nimport discord\nfrom discord.ext import commands\n\nbot = commands.Bot(command_prefix=settings.PREFIX + ' ')\n\n\n@bot.event\nasync def on_guild_join(guild: discord.Guild):\n logging.info(f'Joined guild {guild.name}')\n category, channels = await initialize_channels(guild)\n update_guild_config(filename='config.yaml',\n guild=guild,\n category=category,\n channels=channels)\n deals_list = await get_deals()\n scheduled_tasks_cog: ScheduledTasks = await bot.get_cog(\"ScheduledTasks\")\n await scheduled_tasks_cog.deals_task(guild, deals_list)\n\n\n@bot.event\nasync def on_command_error(ctx: commands.Context, error):\n if hasattr(ctx.command, 'on_error'):\n return\n\n if isinstance(error, discord.ext.commands.CommandNotFound):\n await ctx.channel.send('```fix\\n'\n 'Unknown command\\n'\n f'Type {settings.PREFIX} help for possible commands```')\n\n\n@bot.event\nasync def on_ready():\n await bot.change_presence(status=discord.Status.online, activity=discord.Game(f\"Listening on {settings.PREFIX}\"))\n logging.info('Bot started')\n try:\n open('config.yaml', 'x')\n logging.info('Created new config file')\n except FileExistsError:\n pass\n\n\nlogging.basicConfig(format=\"%(asctime)s %(levelname)s: %(message)s\", level=logging.INFO)\nbot.add_cog(ScheduledTasks(bot))\nbot.add_cog(Commands(bot))\n\nbot.run(settings.BOT_TOKEN)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"507451477","text":"def write01():\n #텍스트 파일 쓰기\n f = open('./sample/test.txt', 'w', encoding=\"utf-8\")\n size = f.write(\"Life is too short, you need Python\") #내용을 쓰고 길이를 반환\n print(\"write size : {}\".format(size))\n f.close() #열었으면 꼭 닫아 줍시다\n\n#write01()\n\ndef read01():\n #텍스트 파일 읽기\n f = open(\"./sample/test.txt\", 'r', encoding=\"utf-8\")\n text = f.read()\n print(text)\n f.close\n\n#read01()\n\ndef write02():\n #여러줄을 만들어 봅시다\n f = open(\"./sample/multilines.txt\", 'w', encoding=\"utf-8\")\n for i in range(1, 10):\n f.write(\"Line %d\\n\" % i)\n f.close\n\n# write02()\n\ndef read02():\n f = open(\"./sample/multilines.txt\", 'r', encoding=\"utf-8\")\n text = f.read()\n print(text)\n f.close()\n\n#read02() \n#메모리를 통채로 읽어오기때문에 Line단위로 끊어서 읽어오자\n\ndef read02_1():\n f = open(\"./sample/multilines.txt\", 'r', encoding=\"utf-8\")\n #루프를 돌면서 한줄씩 읽어와 보자\n while True:\n line = f.readline()\n if not line: #읽을 라인이 없다면 break\n break\n print(line) #end로 하면 개행이 일어나지 않는다\n f.close()\n\n# read02_1()\n\ndef read02_2():\n f = open(\"./sample/multilines.txt\", 'r', encoding=\"utf-8\")\n lines = f.readlines()\n print(lines)\n line = lines[5]\n print(line)\n f.close()\n\n#read02_2() \n#적당한 크기의 파일사이즈를 할때 좋음. 크기가 크면 메모리 부담이 간다\n\n'''\nsample 디렉토리 안에 sangbuk.csv 파일을 열고\n각 줄을 dict으로 만들고 리스트에 저장해 봅시다\n'''\n\ndef slamdunk():\n members = []\n \n f = open(\"./sample/sangbuk.csv\", 'r', encoding=\"utf-8\")\n while True:\n line = f.readline() #한줄씩 읽어올거여\n if not line:\n break\n line = line.strip().replace(\" \",\"\") #공백 문자를 없애고 중간의 공백문자도 없애자\n info = line.split(\",\") #,로 구분자를 나눠본다\n member = {\"name\":info[0], \"number\": info[1],\n \"height\": info[2], \"position\":[3]}\n members.append(member)\n\n print(members)\n f.close()\nslamdunk() #window라서 cp949로 저장된 파일이다.\n\n#바이너리 파일 다루기 모드 : b\ndef binfile():\n f_src = open(\"./sample/rose-flower.jpeg\", \"rb\")\n data = f_src.read()\n f_src.close()\n\n f_dest = open(\"./sample/rose-flower-copy.jpeg\", \"wb\") #사진 파일을 복사해서 집어넣었다\n f_dest.write(data)\n f_dest.close()\n\n#binfile()\n\ndef safe_file():\n #파일은 open하면 반드시 닫아줘야 하는데\n #with ~ as를 이용하면 파이썬이 사용 후 닫아준다\n\n with open('./sample/multilines.txt', 'r') as f:\n for line in f.readlines(): #모든 줄을 스트링 배열로 변환\n print(line, end=\"\") #개행 없애기\n\n print()\n #f가 닫혀 있는지 확인\n print(f.closed) #닫혀있는지 확인하는건 closed이다\n\nsafe_file()\n","sub_path":"file_ex.py","file_name":"file_ex.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"248831221","text":"# -*- coding: utf-8 -*-\n#Fixed By JMD #IStandForFreedom\nfrom osv import osv, fields\n\n\nclass no_conformidad(osv.osv):\n _name = 'no_conformidad'\n _inherit = \"mail.thread\"\n\n def action_generada(self, cr, uid, ids):\n self.write(cr, uid, ids, {'state': 'generada'})\n return True\n\n def action_validada(self, cr, uid, ids):\n self.write(cr, uid, ids, {'state': 'validada'})\n return True\n\n def action_resuelta(self, cr, uid, ids):\n self.write(cr, uid, ids, {'state': 'resuelta'})\n return True\n\n _columns = {\n 'name': fields.char('Clave', required=True),\n 'generador': fields.many2one('hr.employee', string='Generador'),\n 'gnombre': fields.related(\"generador\", \"nombre\", type=\"char\",\n string=\"Nombre\", readonly=True, store=False),\n 'responsable': fields.many2one('hr.employee', string='Responsable'),\n 'rnombre': fields.related(\"responsable\", \"nombre\", type=\"char\",\n string=\"Nombre\", readonly=True, store=False),\n 'jefe_del_responsable': fields.many2one('hr.employee',\n string='Jefe del responsable'),\n 'jnombre': fields.related(\"jefe_del_responsable\", \"nombre\", type=\"char\",\n string=\"Nombre\", readonly=True, store=False),\n 'area': fields.many2one(\"hr.department\", string=\"Departamento\"),\n 'fecha': fields.date('Fecha'),\n 'prioridad': fields.selection([('baja', 'Baja'), ('media', 'Media'),\n ('alta', 'Alta')], 'Prioridad'),\n 'state': fields.selection([('generada', 'Generada'),\n ('validada', 'Validada'), ('resuelta', 'Resuelta')], 'Estado'),\n 'descripcion': fields.text('Descripcion'),\n 'acciones': fields.one2many('no_conformidad.acciones',\n 'relation_no_confomidad', 'Acciones'),\n 'consecuencias': fields.text(\"Consecuencias\"),\n 'concepto': fields.char(\"Concepto\"),\n 'auditoria': fields.many2one('auditoria', string='Auditoria de Origen'),\n }\n\n\nclass acciones(osv.osv):\n _name = 'no_conformidad.acciones'\n _columns = {\n 'name': fields.char(string=\"Nombre\", size=40),\n 'persona': fields.many2one('hr.employee', string='Empleado'),\n 'nombre': fields.related(\"persona\", \"nombre\", type=\"char\",\n string=\"Nombre\", readonly=True, store=False),\n 'accion': fields.char('Accion'),\n 'fecha': fields.date('Fecha'),\n 'horas_dedicas': fields.boolean('Realizado'),\n 'relation_no_confomidad': fields.many2one(\"no_conformidad\",\n string=\"Relacion con no conformidad\", ondelete=\"set null\")\n }\n","sub_path":"ea/estadistica_aplicada2/no_conformidad/no_conformidad.py","file_name":"no_conformidad.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"108471476","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 1 01:36:27 2020\r\n\r\n@author: sabareesh\r\n\"\"\"\r\n\r\nfrom .user_based import UserBased\r\nfrom .item_based import ItemBased\r\nfrom collections import defaultdict\r\nfrom .metrics import Metrics\r\nfrom surprise import KNNBasic\r\n\r\nclass HybridAlgorithm:\r\n '''\r\n Combines the user based and item based approaches.\r\n '''\r\n def __init__(self, type_of_alg = [UserBased, ItemBased], base_alg = \\\r\n [KNNBasic(sim_options={'user_based':True}), \\\r\n KNNBasic(sim_options={'user_based':False})]):\r\n self.algorithms = []\r\n for algorithm, base in zip(type_of_alg, base_alg):\r\n self.algorithms.append(eval(algorithm.__name__)(base, algorithm.__name__))\r\n \r\n def fit(self, trainSet):\r\n '''\r\n Calls fit method on all the algorithms\r\n '''\r\n for algorithm in self.algorithms:\r\n algorithm.fit(trainSet)\r\n \r\n def addAlgorithm(self, algorithm, base_alg):\r\n '''\r\n Possibility of adding other algorithms.\r\n '''\r\n self.algorithms.append(eval(algorithm.__name__)(base_alg, algorithm.__name__))\r\n \r\n def sampleTopNRecs(self, ECom, n=10, testOrderID=68137):\r\n '''\r\n Prints out the top N recommendations for a particular order.\r\n '''\r\n trainSet = ECom.surpData.fullTrainSet\r\n print('\\nRecommendations:')\r\n for itemID, _ in self.getTopNRecs(trainSet, testOrderID, n=10):\r\n print(ECom.getItemName(itemID))\r\n \r\n def getTopNRecs(self, trainSet, testOrderID, n=10):\r\n sum_preds = {}\r\n for algorithm in self.algorithms:\r\n sum_preds = self.combine(sum_preds, algorithm.getAllRecs(trainSet, testOrderID))\r\n \r\n topN = []\r\n rank = 1\r\n for itemID, count in sorted(sum_preds.items(), key=lambda x: x[1], reverse=True):\r\n topN.append([itemID, rank])\r\n if rank>n: break\r\n rank += 1\r\n return topN\r\n \r\n def combine(self, dict1, dict2):\r\n '''\r\n Combines the predictions from the different algorithms.\r\n '''\r\n return {k: 1/dict1.get(k, 1000) + 1/dict2.get(k, 1000) for k in set(dict1) | set(dict2)}\r\n \r\n def evaluate(self, ECom, n=10, verbose=True):\r\n '''\r\n Measures the performance of the algorithm by testing on 'leave one out' training data.\r\n '''\r\n metrics = {}\r\n leftOutPredictions = ECom.surpData.GetLOOCVTestSet()\r\n leftOutTrainingSet = ECom.surpData.GetLOOCVTrainSet()\r\n self.fit(leftOutTrainingSet)\r\n \r\n topNPredicted = defaultdict(list)\r\n for orderID, itemID, _ in leftOutPredictions:\r\n topNPredicted[int(orderID)] = self.getTopNRecs(leftOutTrainingSet, orderID)\r\n print(\"Evaluating hit rate...\")\r\n metrics[\"HR\"] = Metrics.HitRate(topNPredicted, leftOutPredictions)\r\n return metrics\r\n","sub_path":"rec_modules/hybrid_algorithm.py","file_name":"hybrid_algorithm.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"220270066","text":"import webapp2\nimport config\nimport json\nfrom google.appengine.api import urlfetch\nfrom google.appengine.api import memcache\n\nurl = {\n 'balance': 'https://coinbase.com/api/v1/account/balance?api_key=' + config.api_key,\n 'rate': 'https://coinbase.com/api/v1/prices/spot_rate'\n}\n\nclass InfoCtrl(webapp2.RequestHandler):\n\n def get(self):\n self.response.headers['Content-Type'] = 'text/json'\n self.response.headers['Access-Control-Allow-Origin'] = '*'\n balance = memcache.get('balance')\n\n if balance is None:\n result = urlfetch.fetch(url['balance'])\n if result.status_code == 200:\n b = json.loads(result.content)\n balance = b['amount']\n else:\n balance = 'Error'\n\n rate = memcache.get('rate')\n\n if rate is None:\n result = urlfetch.fetch(url['rate'])\n if result.status_code == 200:\n r = json.loads(result.content)\n rate = r['amount']\n else:\n balance = 'Error'\n\n self.response.write('{ \"balance\":' + balance + ', \"rate\":' + rate + ' }')\n\napplication = webapp2.WSGIApplication([\n ('/info', InfoCtrl),\n])","sub_path":"app_engine/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"438750987","text":"class Card:\n\n\tFACES = {11: 'J', 12: 'Q', 13: 'K', 14: 'A', 15: 'JO'}\n\t# 0 spades, 1 hearts, 2 clubs, 3 diamonds, 4 smol joker, 5 big joker\n\tSUITS = {0: chr(0x2660), 1: chr(0x2661), 2: chr(0x2663), 3: chr(0x2662), 4: chr(0x2726), 5: chr(0x2606)}\n\n\tdef __init__(self, rank, suit, trump=False):\n\t\tself.suit = suit\n\t\tself.rank = rank\n\t\tself.trump = trump\n\n\tdef __str__(self):\n\t\tif self.rank <= 10:\n\t\t\treturn str(self.rank) + self.SUITS[self.suit]\n\t\telse:\n\t\t\treturn self.FACES[self.rank] + self.SUITS[self.suit]\n\n\tdef point(self):\n\t\tif self.rank == 5:\n\t\t\treturn 5\n\t\telif self.rank == 10 or self.rank == 13:\n\t\t\treturn 10\n\t\telse:\n\t\t\treturn 0\n\n\t# eariler card played should always go first\n\t# def __eq__(self, card):\n\t# \treturn self.suit == card.suit and self.rank == card.rank\n\n\t# def __ne__(self, card):\n\t# \treturn self.suit != card.suit or self.rank != card.rank\n\n\t# def __lt__(self, other):\n\t# \tif self.trump and other.Trump:\n\t# \t\t","sub_path":"card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"279721051","text":"from unittest import TestCase\n\nfrom configman import (\n configuration,\n)\n\nfrom blender.main import (\n default_data_structures,\n required_config,\n create_preliminary_headlist,\n estimate_optin_probabilities\n)\n\nstandards_from_figure_9 = {\n '*': [0.9108, 0.9103, 0.9199, 0.9100, 0.1468, ],\n 'google': [0.0213, 0.0216, 0.0213, 0.0217, 0.0216, ],\n 'yahoo': [0.0067, 0.0070, 0.0046, 0.0073, 0.0325,],\n 'google.com': [0.0067, 0.0056, 0.0023, 0.0061, 0.0194,],\n 'myspace.com': [0.0057, 0.0052, 0.0022, 0.0057, 0.0258,],\n 'mapquest': [0.0054, 0.0051, 0.0062, 0.0053, 0.0192,],\n 'yahoo.com': [0.0043, 0.0043, 0.0021, 0.0048, 0.0192,],\n 'www.google.com': [0.0034, 0.0004, 0.0004, 0.0032, 0.0098,],\n 'myspace': [0.0033, 0.0034, 0.0042, 0.0035, 0.0255,],\n 'ebay': [0.0028, 0.0026, 0.0028, 0.0028, 0.0254,],\n}\n\naol_pq = 0\nblender_pq = 1\noptin_pq = 2\noptin_sum = 3\nclient_pq = 4\nclient_sum = 5\n\nstandards_from_analyze_aol = {\n '*': [0, 0.9609944925686271, ],\n 'google': [0, 0.013611629573536801, ],\n 'yahoo': [0, 0.00552769611162353,],\n 'google.com': [0, 0.0027381056655940584,],\n 'myspace.com': [0, 0.002800751482347638,],\n 'mapquest': [0, 0.002955617290430584,],\n 'yahoo.com': [0, 0.003163202279279063,],\n 'www.google.com': [0, 0.0013820654696103754,],\n 'myspace': [0, 0.003147103641640417,],\n 'ebay': [0, 0.0036793359173104023,],\n}\n\nacceptance_config = {\n \"epsilon\": 4,\n \"delta\": 0.000001,\n \"m_o\": 1.0,\n \"m_c\": 1.0,\n \"f_c\": 0.85,\n \"optin_database_s_filename\": \"tests/optin_s.data.json\",\n \"optin_database_t_filename\": \"tests/optin_t.data.json\",\n \"client_database_filename\": \"tests/client.data.json\",\n \"output_filename\": \"tests/out.data\",\n}\n\nconfig = configuration(\n definition_source=required_config,\n values_source_list=[\n # create the overriding hierarchy for the sources of configuration.\n # each source will override values from sources higher in the list\n default_data_structures,\n acceptance_config,\n ]\n)\n\n\nclass TestDirectBenderFunctionImplementations(TestCase):\n def testCreationOfHeadList(self):\n optin_database_s = config.optin_db.optin_db_class(config.optin_db)\n optin_database_s.load(config.optin_database_s_filename)\n preliminary_head_list = create_preliminary_headlist(\n config,\n optin_database_s\n )\n optin_database_t = config.optin_db.optin_db_class(config.optin_db)\n optin_database_t.load(config.optin_database_t_filename)\n head_list_with_probabilities = estimate_optin_probabilities(\n preliminary_head_list,\n optin_database_t\n )\n\n #for query_str in standards_from_figure_9.keys():\n for query_str in standards_from_analyze_aol.keys():\n print (\"{} {}: {}\".format(query_str, blender_pq, standards_from_analyze_aol[query_str][blender_pq]))\n self.assertAlmostEqual(\n head_list_with_probabilities[query_str].probability,\n standards_from_analyze_aol[query_str][blender_pq],\n 3\n )\n","sub_path":"tests/test_acceptance.py","file_name":"test_acceptance.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"32913740","text":"# coding=utf-8\n# !/usr/bin/env python\nfrom rdflib import Graph, RDF, RDFS, OWL, BNode, URIRef\nfrom rdflib import Literal\nfrom toolz import unique\nfrom collections import defaultdict, Counter\nfrom ontospy.libs.queryHelper import QueryHelper\nfrom rdflib.namespace import FOAF, XSD, XMLNS as xml, SKOS, DC, ClosedNamespace, Namespace, NamespaceManager\nfrom operator import itemgetter, attrgetter, methodcaller\nfrom orderedmultidict import omdict\nfrom rdflib.term import Genid, Identifier, Node, _parseHTML, _parseXML\nfrom click import get_terminal_size\n\ndef get_homedir():\n\t\"\"\"\n\tReturn the best guess for the users home directory.\n\t\"\"\"\n\thomedir = os.getenv(\"HOME\")\n\tif not homedir:\n\t\thomedir = os.getcwd()\n\n\treturn homedir\n\nhomedir = get_homedir()\n\nRDFS_TERMS = sorted(RDFS._ClosedNamespace__uris.keys())\nRDF_TERMS = sorted(RDF._ClosedNamespace__uris.keys())\n\ndef terminal_width(): return get_terminal_size()[0]\n\nclass URI(URIRef):\n\tdef __repr__(self):\n\t\tnamespace = str(self)\n\t\tif namespace.__contains__('#'):\n\t\t\tbase = namespace.split('#')[-1]\n\t\telse:\n\t\t\tbase = os.path.basename(namespace)\n\t\treturn 'URI({})'.format(base)\n\nclass AllProperties:\n\tdef __init__(self, graph = None):\n\t\tif graph is not None:\n\t\t\tself.graph = graph\n\t\telse:\n\t\t\tself.graph = rdflib.graph.Graph()\n\t\tself.annotation_properties = set(self.graph.subjects(RDF.type, OWL.AnnotationProperty)) or set()\n\t\tself.object_properties = set(self.graph.subjects(RDF.type, OWL.ObjectProperty)) or set()\n\t\tself.functional_properties = set(self.graph.subjects(RDF.type, OWL.FunctionalProperty)) or set()\n\t\tself.transitive_properties = set(self.graph.subjects(RDF.type, OWL.TransitiveProperty)) or set()\n\t\tself.inverse_functional_properties = set(self.graph.subjects(RDF.type, OWL.InverseFunctionalProperty)) or set()\n\t\tself.datatype_properties = set(self.graph.subjects(RDF.type, OWL.DatatypeProperty)) or set()\n\t\tself.asymmetric_properties = set(self.graph.subjects(RDF.type, OWL.AsymmetricProperty)) or set()\n\t\tself.symmetric_properties = set(self.graph.subjects(RDF.type, OWL.SymmetricProperty)) or set()\n\t\tself.ontology_properties = set(self.graph.subjects(RDF.type, OWL.OntologyProperty)) or set()\n\t\tself.reflexive_properties = set(self.graph.subjects(RDF.type, OWL.ReflexiveProperty)) or set()\n\t\tself.irreflexive_properties = set(self.graph.subjects(RDF.type, OWL.IrreflexiveProperty)) or set()\n\t\tself._allproperties = set()\n\n\tdef counts(self):\n\t\tkeys = ['annotation_properties', 'asymmetric_properties', 'datatype_properties', 'functional_properties',\n\t\t 'inverse_functional_properties', 'irreflexive_properties', 'object_properties',\n\t\t 'ontology_properties', 'reflexive_properties', 'symmetric_properties', 'transitive_properties']\n\t\tindent = max([len(k) for k in keys]) + 3\n\t\tdata = self.__dict__\n\t\tfor key in keys:\n\t\t\tlength = '{} items for this property'.format(len(data[key]))\n\t\t\tentry = key.ljust(indent) + ' '+ length\n\t\t\tprint(entry)\n\n\tdef get_all_properties(self):\n\t\tresults = set()\n\t\tkeys = keys = ['annotation_properties', 'asymmetric_properties', 'datatype_properties', 'functional_properties',\n\t\t 'inverse_functional_properties', 'irreflexive_properties', 'object_properties',\n\t\t 'ontology_properties', 'reflexive_properties', 'symmetric_properties', 'transitive_properties']\n\t\tdata = self.__dict__\n\t\tfor key in keys:\n\t\t\tif data[key]:\n\t\t\t\tfor d in data[key]:\n\t\t\t\t\tresults.add(d)\n\t\tself._allproperties = results\n\t\treturn results\n\n\n\n\n\n\nontology_portal ={'AntarcticArea': rdflib.term.URIRef('http://www.adampease.org/OP/AntarcticArea'),\n 'Brandy': rdflib.term.URIRef('http://www.adampease.org/OP/Brandy'),\n 'CelsiusDegree': rdflib.term.URIRef('http://www.adampease.org/OP/CelsiusDegree'),\n 'Centimeter': rdflib.term.URIRef('http://www.adampease.org/OP/Centimeter'),\n 'ChangeOfControl': rdflib.term.URIRef('http://www.adampease.org/OP/ChangeOfControl'),\n 'Fish': rdflib.term.URIRef('http://www.adampease.org/OP/Fish'),\n 'FootLength': rdflib.term.URIRef('http://www.adampease.org/OP/FootLength'),\n 'Meter': rdflib.term.URIRef('http://www.adampease.org/OP/Meter'),\n 'Mile': rdflib.term.URIRef('http://www.adampease.org/OP/Mile'),\n 'MilitaryGeneral': rdflib.term.URIRef('http://www.adampease.org/OP/MilitaryGeneral'),\n 'TheaterProfession': rdflib.term.URIRef('http://www.adampease.org/OP/TheaterProfession'),\n 'Wing': rdflib.term.URIRef('http://www.adampease.org/OP/Wing')}\n\n\n\ndef p(): return{\n\t'AnnotationProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#AnnotationProperty'),\n 'AsymmetricProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#AsymmetricProperty'),\n 'BottomDataProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#BottomDataProperty'),\n 'BottomObjectProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#BottomObjectProperty'),\n 'DatatypeProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#DatatypeProperty'),\n 'DeprecatedProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#DeprecatedProperty'),\n 'FunctionalProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#FunctionalProperty'),\n 'InverseFunctionalProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#InverseFunctionalProperty'),\n 'IrreflexiveProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#IrreflexiveProperty'),\n 'NegativePropertyAssertion': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#NegativePropertyAssertion'),\n 'ObjectProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#ObjectProperty'),\n 'OntologyProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#OntologyProperty'),\n 'Property': rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#Property'),\n 'ReflexiveProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#ReflexiveProperty'),\n 'SymmetricProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#SymmetricProperty'),\n 'TopDataProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#TopDataProperty'),\n 'TopObjectProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#TopObjectProperty'),\n 'TransitiveProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#TransitiveProperty'),\n 'annotatedProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#annotatedProperty'),\n 'assertionProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#assertionProperty'),\n 'equivalentProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#equivalentProperty'),\n 'onProperty': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#onProperty'),\n 'propertyChainAxiom': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#propertyChainAxiom'),\n 'propertyDisjointWith': rdflib.term.URIRef('http://www.w3.org/2002/07/owl#propertyDisjointWith'),\n 'subPropertyOf': rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#subPropertyOf')}\n\n\nsumo_source = \"http://www.adampease.org/OP/SUMO.owl\"\n\nrdf = RDF\nrdfs = RDFS\nowl = OWL\nxml = Namespace('http://www.w3.org/XML/1998/namespace')\nxsd = Namespace('http://www.w3.org/2001/XMLSchema#')\nsumo = Namespace('http://www.ontologyportal.org/SUMO.owl#')\nwn = Namespace('http://www.ontologyportal.org/WordNet.owl#')\nop = Namespace('http://www.adampease.org/OP/SUMO.owl#')\nirw = Namespace(\"http://www.ontologydesignpatterns.org/ont/web/irw.owl#\")\nfoaf = Namespace(\"http://xmlns.com/foaf/0.1/\")\ntag = Namespace(\"http://www.holygoat.co.uk/owl/redwood/0.1/tags/\")\n\n\nsortkey = lambda x: x.uri.toPython()\n\ndef get_str(entity):\n\tif entity.__class__.__name__ == 'BNode':\n\t\treturn entity.toPython()\n\telif entity.__class__.__name__ == 'Literal':\n\t\treturn entity._value\n\telif entity.__class__.__name__ == 'URIRef':\n\t\tif entity.toPython().__contains__('#'):\n\t\t\treturn entity.toPython().rsplit('#')[1]\n\t\telse:\n\t\t\treturn entity.toPython()\n\telif entity.__class__.__name__ == 'Class' or 'ObjectProperty':\n\t\tif entity.uri.__class__.__name__ == 'URIRef':\n\t\t\treturn entity.uri.toPython().rsplit('#')[1]\n\t\telse:\n\t\t\treturn entity.uri.toPython()\n\telse:\n\t\treturn entity\n\n\nannotation_properties = lambda graph: set(graph.subjects(RDF.type, OWL.AnnotationProperty))\nobject_properties = lambda graph: set(graph.subjects(RDF.type, OWL.ObjectProperty))\n\nfunctional_properties = lambda graph: set(graph.subjects(RDF.type, OWL.FunctionalProperty))\ntransitive_properties = lambda graph: set(graph.subjects(RDF.type, OWL.TransitiveProperty))\ninverse_functional_properties = lambda graph: set(graph.subjects(RDF.type, OWL.InverseFunctionalProperty))\ndatatype_properties = lambda graph: set(graph.subjects(RDF.type, OWL.DatatypeProperty))\nasymmetric_properties = lambda graph: set(graph.subjects(RDF.type, OWL.AsymmetricProperty))\nsymmetric_properties = lambda graph: set(graph.subjects(RDF.type, OWL.SymmetricProperty))\nontology_properties = lambda graph: set(graph.subjects(RDF.type, OWL.OntologyProperty))\nreflexive_properties = lambda graph: set(graph.subjects(RDF.type, OWL.ReflexiveProperty))\nirreflexive_properties = lambda graph: set(graph.subjects(RDF.type, OWL.IrreflexiveProperty))\n\ndef properties(self):\n\treturn annotation_properties(self) | object_properties(self) | functional_properties(self) \\\n\t | transitive_properties(self) | inverse_functional_properties(self) | datatype_properties(self) \\\n\t | asymmetric_properties(self) | symmetric_properties(self) | ontology_properties(self) \\\n\t | reflexive_properties(self) | irreflexive_properties(self)\n\ndef entities(self):\n\treturn properties(self) | classes(self) | individuals(self)\n\n#######\n\naxioms = lambda graph, uri: set(graph.objects(uri, sumo.axiom)) #ADD\nsubsumingRelation = rdflib.term.URIRef('http://www.ontologyportal.org/SUMO.owl#subsumingRelation')\n\nRDF.resource\nOWL.Thing = rdflib.term.URIRef('http://www.w3.org/2002/07/owl#Thing')\nRDFS.isDefinedBy = rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#isDefinedBy')\nRDF.resource = rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#resource')\nsumo.Human\nrdfs = RDFS\nthings = lambda graph: set(graph.subjects(RDF.type, OWL.Thing)) #ADD\n\ndefined_by = lambda graph, uri: set(graph.objects(uri, RDFS.isDefinedBy))\n\nresource = lambda graph, uri: set(graph.objects(uri, RDF.resource))\n\n\nAxioms = lambda graph, uri: set(graph.objects(uri, OWL.Axiom))\n\nequivalent_class = lambda graph, uri: set(graph.objects(uri, OWL.equivalentClass))\ndisjoint_with = lambda graph, uri: set(graph.objects(uri, OWL.disjointWith))\ncomments = lambda graph, uri: set(graph.objects(uri, RDFS.comment))\nparents = lambda graph, uri: set(graph.objects(uri, RDFS.subClassOf))\nchildren = lambda graph, uri: set(graph.subjects(RDFS.subClassOf, uri))\nlabels = lambda graph, uri: set(graph.objects(uri, RDFS.label))\ndomain = lambda graph, uri: set(graph.objects(uri, RDFS.domain)) #ADD\nrange = lambda graph, uri: set(graph.objects(uri, RDFS.range))\n\nsubproperty_of = lambda graph, uri: set(graph.objects(uri, OWL.subPropertyOf)) #ADD\nsuperproperty_of = lambda graph, uri: set(graph.subjects(OWL.subPropertyOf, uri)) #ADD\nhumans = lambda graph: set(graph.subjects(RDF.type, op.Human)) #ADD\n\nsuper_properties = lambda graph, uri: set(graph.objects(uri, RDFS.subPropertyOf))\nsub_properties = lambda graph, uri: set(graph.subjects(RDFS.subPropertyOf, uri))\ninverse_of = lambda graph, uri: set(graph.subjects(OWL.inverseOf, self.uri))\n#indiv_type = lambda self: [o for o in set(self.ontology.graph.objects(self.uri, RDF.type))]\n\nclasses = lambda graph: set(graph.subjects(RDF.type, OWL.Class))\n\nrestrictions = lambda graph: set(graph.subjects(RDF.type, OWL.Restriction))\nresources = lambda graph: set(graph.objects(RDF.type, OWL.Resource))\ndisjoints = lambda graph: set(graph.subjects(RDF.type, OWL.AllDisjointClasses))\nindividuals = lambda graph: set(graph.subjects(RDF.type, OWL.NamedIndividual))\nthings = lambda graph: set(graph.subjects(RDF.type, OWL.Thing))\nindividual_type = lambda graph, uri: set(graph.objects(uri, RDF.type))\ntriples = lambda graph, uri: set(graph.triples((uri, None, None))) \\\n | set(graph.triples((None, uri, None))) \\\n | set(graph.triples((None, None, uri)))\n\ntriples = lambda graph, uri: list(graph.query(\n\t\"\"\"CONSTRUCT {<%s> ?y ?z } WHERE { { <%s> ?y ?z }}\"\"\" % (uri, uri)))\n\n#test triples(g, op.subAttribute) #todo ADD\n\ndef entityTriples(graph, uri): return list(\n\tgraph.query(\"\"\"CONSTRUCT {<%s> ?y ?z } WHERE { { <%s> ?y ?z }}\"\"\" % (uri, uri)))\n\n#property_all_subs = lambda graph, uri: list(graph.query(\n#\t\"\"\"SELECT DISTINCT ?x WHERE { { ?x rdfs:subPropertyOf+ <%s> } FILTER (!isBlank(?x)) }\"\"\" % (uri)))\n#\n#property_all_supers = lambda graph, uri: list(graph.query(\n#\t\"\"\"SELECT DISTINCT ?x WHERE { { <%s> rdfs:subPropertyOf+ ?x } FILTER (!isBlank(?x)) }\"\"\" % (uri)))\n#\n#property_direct_supers = lambda graph, uri: list(graph.query(\n#\t\"\"\"SELECT DISTINCT ?x WHERE { { <%s> rdfs:subPropertyOf ?x } FILTER (!isBlank(?x)) } ORDER BY ?x \"\"\" % (uri)))\n\nclass RDFGraph(rdflib.graph.Graph):\n\tdef __init__(self, data):\n\t\tif data.__class__.__name__ == 'Graph' and G.__class__.__module__ == 'rdflib.graph':\n\t\t\tself.graph = data\n\t\telse:\n\t\t\tself.graph = rdflib.graph.Graph()\n\t\tself.classes = set()\n\t\tself.individuals = set()\n\t\tself.object_properties = set()\n\t\tself.annotation_properties = set()\n\t\tself.data_properties = set()\n\n\t@property\n\tdef entities(self):\n\t\treturn self.classes | self.individuals | self.properties\n\n\t@property\n\tdef properties(self):\n\t\treturn self.object_properties | self.annotation_properties | self.data_properties\n\n\tdef _load_classes(self):\n\t\turis = set(uri for uri in self.graph.subjects(RDF.type, OWL.Class)) | set(\n\t\t\turi for uri in self.graph.subjects(RDF.type, OWL.Restriction))\n\t\tentities = set()\n\t\tfor uri in uris:\n\t\t\tentities.add(Class(uri=uri, ontology=self))\n\t\treturn entities\n\n\tdef _load_individuals(self):\n\t\turis = [uri for uri in self.graph.subjects(RDF.type, OWL.NamedIndividual)]\n\t\tentities = set()\n\t\tfor uri in uris:\n\t\t\tentities.add(Individual(uri=uri, ontology=self))\n\t\treturn entities\n\n\tdef _load_object_properties(self):\n\t\turis = [uri for uri in self.graph.subjects(RDF.type, OWL.ObjectProperty)]\n\t\tentities = set()\n\t\tfor uri in uris:\n\t\t\tentities.add(ObjectProperty(uri=uri, ontology=self))\n\t\treturn entities\n\n\tdef exists(self, uri):\n\t\tgraph = self.graph\n\t\turis = set(graph.subjects()).union(graph.predicates()).union(graph.objects())\n\n\t\tif uri in uris:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef get_annotations(self, entity):\n\t\ttuples = [(pred, obj) for (pred, obj) in self.graph.predicate_objects(entity.uri)]\n\n\t\tannotations = set()\n\n\t\tfor prop, obj in tuples:\n\t\t\tif prop in self.graph.subjects(RDF.type, OWL.AnnotationProperty):\n\t\t\t\tannotations.add((prop, obj))\n\n\t\treturn annotations\n\n\tdef get_triples(self, entity):\n\t\tentity = self.convert(entity)\n\t\treturn set(self.graph.triples((entity.uri, None, None))) | set(\n\t\t\tself.graph.triples((None, entity.uri, None))) | set(self.graph.triples((None, RDF.first, entity.uri)))\n\n\tdef get_super_classes(self, cls):\n\t\tcls = self.convert(cls)\n\t\tparent_uris = set(self.graph.objects(cls.uri, RDFS.subClassOf))\n\t\tparents = [acls for acls in self.classes if acls.uri in parent_uris]\n\n\t\treturn set(parents)\n\n\tdef get_sub_classes(self, cls):\n\t\tcls = self.convert(cls)\n\t\tchildren_uris = set(self.graph.subjects(RDFS.subClassOf, cls.uri))\n\n\t\tchildren = [acls for acls in self.classes if acls.uri in children_uris]\n\n\t\treturn set(children)\n\n\tdef get_super_properties(self, prop):\n\t\tprop = self.convert(prop)\n\t\tparent_uris = set(self.graph.objects(prop.uri, RDFS.subPropertyOf))\n\n\t\tparents = [aprop for aprop in self.properties if aprop.uri in parent_uris]\n\n\t\treturn set(parents)\n\n\tdef get_sub_properties(self, prop):\n\t\tprop = self.convert(prop)\n\t\tchildren_uris = set(self.graph.objects(RDFS.subPropertyOf, prop.uri))\n\n\t\tchildren = [aprop for aprop in self.properties if aprop.uri in children_uris]\n\n\t\treturn set(children)\n\n","sub_path":"ontology/rdfutility.py","file_name":"rdfutility.py","file_ext":"py","file_size_in_byte":16726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"251808841","text":"# coding: utf-8\nfrom pyNastran.bdf.bdf import BDF\nfrom pyNastran.op2.op2 import OP2\nfrom numpy import zeros, searchsorted, arange\n\n#def pack_nodes(fmt, data):\n #return ''\n\ndef pack_int_array(fmt, data):\n return ' '.join([str(val) for val in data]) + '\\n'\n\ndef pack_float_1d_array(fmt, data):\n return ' '.join([str(val) for val in data.ravel()]) + '\\n'\n\ndef pack_float_3d_array(fmt, data):\n msg = ''\n for datai in data[0, :, :]:\n msgi = ''\n for dataii in datai:\n msgi += '%s ' % dataii\n msg += msgi[:-1] + '\\n'\n return msg #+ '\\n\\n'\n\ndef pack_float_2d_array(fmt, data):\n msg = ''\n for datai in data:\n msgi = ''\n for dataii in datai:\n msgi += '%s ' % dataii\n msg += msgi[:-1] + '\\n'\n return msg #+ '\\n'\n\n#def pack(fmt, data):\n# return ''\n\ndef export_to_vtk(model):\n bdf_filename = model + '.bdf'\n op2_filename = model + '.op2'\n vtk_filename = model + '.vtk'\n export_to_vtk_filename(bdf_filename, op2_filename, vtk_filename)\n model.log.info('finished exporting %s' % vtk_filename)\n\ndef export_to_vtk_filename(bdf_filename, op2_filename, vtk_filename, debug=False, log=None):\n with open(vtk_filename, 'w') as vtk_file:\n vtk_file.write('# vtk DataFile Version 3.1\\n')\n vtk_file.write('created by pyNastran\\n')\n #vtk_file.write('BINARY\\n')\n vtk_file.write('ASCII\\n')\n vtk_file.write('DATASET UNSTRUCTURED_GRID\\n')\n\n etype_map = {\n # line\n 'CDAMP1' : 3,\n 'CDAMP2' : 3,\n 'CDAMP3' : 3,\n 'CDAMP4' : 3,\n 'CELAS1' : 3,\n 'CELAS2' : 3,\n 'CELAS3' : 3,\n 'CELAS4' : 3,\n 'CBAR' : 3,\n 'CBEAM' : 3,\n 'CROD' : 3,\n 'CONROD' : 3,\n 'CTUBE' : 3,\n\n 'CTRIA3' : 5, # triangle\n 'CQUAD4' : 9, # quad\n 'CSHEAR' : 9, # quad\n\n # quadratic\n 'CTRIA6' : 22, # quadratic triangle\n #'CQUAD8' : 23/28/30,\n\n 'CTETRA' : 10,\n 'CPENTA' : 13, # wedge\n 'CPYRAM' : 14,\n 'CHEXA' : 12, # hex\n\n # quadratic solids\n #'CTETRA' : 64,\n #'CPENTA' : 65, # wedge\n #'CPYRAM' : 66,\n #'CHEXA' : 67, # hex\n }\n\n bdf = BDF(debug=debug, log=log)\n bdf.read_bdf(bdf_filename)\n op2 = OP2(debug=debug, log=log)\n op2.read_op2(op2_filename)\n\n out = bdf.get_card_ids_by_card_types()\n #print('cards = [', ', '.join(sorted(out.keys())), ']')\n grids = sorted(out['GRID'])\n spoint = sorted(out['SPOINT'])\n epoint = sorted(out['EPOINT'])\n ngrid = len(grids)\n nspoint = len(spoint)\n nepoint = len(epoint)\n nnodes = ngrid + nspoint + nepoint\n\n ncrod = len(out['CROD'])\n nconrod = len(out['CONROD'])\n nctube = len(out['CTUBE'])\n ncbeam = len(out['CBEAM'])\n ncbar = len(out['CBAR'])\n nline = ncrod + nconrod + nctube + ncbeam + ncbar\n\n ncelas1 = len(out['CELAS1'])\n ncelas2 = len(out['CELAS2'])\n ncelas3 = len(out['CELAS3'])\n ncelas4 = len(out['CELAS4'])\n\n ncdamp1 = len(out['CDAMP1'])\n ncdamp2 = len(out['CDAMP2'])\n ncdamp3 = len(out['CDAMP3'])\n ncdamp4 = len(out['CDAMP4'])\n n0d = (ncelas1 + ncelas2 + ncelas3 + ncelas4 +\n ncdamp1 + ncdamp2 + ncdamp3 + ncdamp4)\n\n nctria3 = len(out['CTRIA3'])\n ncquad4 = len(out['CQUAD4'])\n nctria6 = len(out['CTRIA6'])\n ncquad8 = len(out['CQUAD8'])\n ncshear = len(out['CSHEAR'])\n nshell = nctria3 + ncquad4 + nctria6 + ncquad8 + ncshear\n\n nctetra4 = len(out['CTETRA'])\n ncpyram5 = len(out['CPYRAM'])\n ncpenta6 = len(out['CPENTA'])\n nchexa8 = len(out['CHEXA'])\n nctetra10 = 0\n ncpyram8 = 0\n ncpenta15 = 0\n nchexa20 = 0\n nsolid = (nctetra4 + ncpyram5 + ncpenta6 + nchexa8 +\n nctetra10 + ncpyram8 + ncpenta15 + nchexa20)\n\n #nelements = n0d + nline + nshell + nsolid\n nelements = 0\n etypes = [\n 'CELAS1', 'CELAS2', 'CELAS3', 'CELAS4',\n 'CDAMP1', 'CDAMP2', 'CDAMP3', 'CDAMP4',\n 'CROD', 'CONROD', 'CTUBE',\n 'CBAR', 'CBEAM',\n 'CFAST', 'CBUSH', 'CBUSH1D', 'CBUSH2D',\n\n 'CTRIA3', 'CQUAD4', 'CTRIA6', 'CQUAD8', 'CSHEAR',\n\n 'CTETRA', 'CPENTA', 'CPYRAM', 'CHEXA',\n ]\n assert len(etypes) == len(set(etypes)), 'there are duplicate etypes'\n for etype in etypes:\n if etype in out:\n ne = len(out[etype])\n nelements += ne\n nproperties = nelements\n\n bdf_nelements = bdf.nelements\n\n # SPOINT & EPOINT are implicitly defined\n xyz_cid0 = zeros((nnodes, 3), dtype='float32')\n nids = zeros(nnodes, dtype='float32')\n for i, nid in enumerate(grids):\n xyz_cid0[i, :] = bdf.nodes[nid].get_position()\n nids[:ngrid] = grids\n if nspoint:\n nids[i:i+nspoint] = spoint\n if nepoint:\n nids[i+nspoint:] = epoint\n\n nid_fmt = '%ii' % nnodes\n xyz_fmt = '%ii' % (nnodes * 3)\n vtk_file.write('POINTS %i float\\n' % nnodes)\n vtk_file.write(pack_float_2d_array(xyz_fmt, xyz_cid0))\n\n nelements = n0d + nline + nshell + nsolid\n nmaterials = nelements\n\n eid_fmt = '%ii' % nelements\n eids = zeros(nelements, dtype='int32')\n cell_types = zeros(nelements, dtype='int32')\n pids = zeros(nelements, dtype='int32')\n mids = zeros(nelements, dtype='int32')\n\n # we'll add 1 to the slot count of each\n # so for a single CROD, it has 2 nodes and 1 extra value (to indicate it's a line)\n # for a total of 3\n nline_slots = nline * 3\n nshell_slots = 4 * nctria3 + 5 * (ncquad4 + ncshear) + 7 * nctria6 + 9 * ncquad8\n nsolid_slots = 5 * nctetra4 + 6 * ncpyram5 + 7 * ncpenta6 + 9 * nchexa8\n bdf.log.debug('nline=%s nshell=%s nsolid=%s' % (nline, nshell, nsolid))\n assert nelements == bdf_nelements, 'nelements=%s bdf.nelements=%s card_count=\\n%s' % (\n nelements, bdf_nelements, bdf.card_count)\n nelements_slots = nline_slots + nshell_slots + nsolid_slots\n\n i = 0\n vtk_file.write('CELLS %i %i\\n' % (nelements, nelements_slots))\n for eid, elem in sorted(bdf.elements.items()):\n etype = etype_map[elem.type]\n nids2 = searchsorted(nids, elem.node_ids)\n\n nnodesi = len(nids2)\n vtk_file.write('%i %s\\n' % (nnodesi, str(nids2)[1:-1]))\n if elem.type in ['CTETRA', 'CPENTA', 'CHEXA', 'CPYRAM', 'CBEAM', 'CROD', 'CBAR']:\n pid = elem.Pid()\n mid = elem.Mid()\n elif elem.type in ['CELAS1', 'CELAS2', 'CELAS3', 'CELAS4',\n 'CDAMP1', 'CDAMP2', 'CDAMP3', 'CDAMP4', 'CBUSH', 'CFAST']:\n pid = elem.Pid()\n mid = 0\n elif elem.type in ['CQUAD4', 'CQUAD8', 'CQUADX', 'CQUADX8', 'CQUAD',\n 'CTRIA3', 'CTRIA6', 'CTRIAX', 'CTRIAX6', 'CSHEAR']:\n pid = elem.Pid()\n prop = elem.pid_ref\n if prop.type in ['PCOMP', 'PCOMPG']:\n mid = prop.Mid(0)\n elif prop.type in ['PSHELL']:\n mid = prop.Mid1()\n elif prop.type in ['PSHEAR']:\n mid = prop.Mid()\n else:\n raise NotImplementedError(prop)\n elif elem.type in ['CONROD']:\n pid = 0\n mid = elem.Mid()\n else:\n raise NotImplementedError(elem)\n\n eids[i] = eid\n pids[i] = pid\n mids[i] = mid\n cell_types[i] = etype\n i += 1\n assert nelements == bdf_nelements, 'i=%s nelements=%s bdf.nelements=%s' % (i, nelements, bdf_nelements)\n\n #vtk_file.write('\\n')\n vtk_file.write('CELL_TYPES %i\\n' % nelements)\n vtk_file.write(pack_int_array(eid_fmt, cell_types))\n vtk_file.write('\\n')\n\n vtk_file.write('POINT_DATA %i\\n' % nnodes)\n vtk_file.write('NodeID %i float\\n' % nnodes)\n vtk_file.write(pack_int_array(nid_fmt, nids))\n\n fmt = '%si' % nelements\n if nelements:\n vtk_file.write('ElementID %i float\\n' % nelements)\n vtk_file.write(pack_int_array(eid_fmt, eids))\n if nproperties:\n vtk_file.write('PropertyID %i float\\n' % nproperties)\n vtk_file.write(pack_int_array(eid_fmt, pids))\n if nmaterials:\n vtk_file.write('MaterialID %i float\\n' % nmaterials)\n vtk_file.write(pack_int_array(eid_fmt, mids))\n\n nodal_cases = [op2.eigenvectors, op2.displacements, op2.velocities, op2.accelerations]\n fmt = '%sf' % (nnodes * 6)\n for cases in nodal_cases:\n keys = list(cases.keys())\n if not keys:\n continue\n key0 = keys[0]\n #print(key0)\n node_ids = cases[key0].node_gridtype[:, 0]\n\n if nnodes == len(node_ids):\n # every node exists\n i = arange(nnodes)\n ni = nnodes\n else:\n # node_ids is a subset of nids\n i = searchsorted(nids, node_ids)\n ni = len(i)\n\n names = ['T1', 'T2', 'T3', 'R1', 'R2', 'R3']\n for isubcase, case in sorted(cases.items()):\n if case.is_real:\n #if i is None:\n #data = case.data\n #ni = nnodes\n #else:\n #data = zeros((nnodes, 6), dtype='float32')\n #data[:, i, :] = case.data\n data = case.data[:, i, :]\n ntimes = case.data.shape[0]\n case_type = case.__class__.__name__\n for itime in range(ntimes):\n if 0:\n for icol, name in enumerate(names):\n title = '%s_%s_isubcase=%s_itime=%s' % (case_type, name, isubcase, itime)\n vtk_file.write('SCALARS %s float\\n' % title)\n vtk_file.write('LOOKUP_TABLE default\\n')\n #datai = data[itime, i, icol]\n vtk_file.write(pack_float_1d_array(fmt, data[itime, i, icol]))\n if 1:\n title = '%s_isubcase=%s_itime=%s' % (case_type, isubcase, itime)\n #FIELD RealDisplacementArray_FIELD_isubcase=1_itime=0 6\n #t1 1 72 float\n #0.00764469 0.00762899 ...\n vtk_file.write('FIELD %s 6\\n' % title)\n for icol, name in enumerate(names):\n vtk_file.write('%s 1 %s float\\n' % (name, ni))\n datai = case.data[itime, i, icol]\n vtk_file.write(pack_float_1d_array(fmt, data[itime, i, icol]))\n\n if 0:\n title = '%s_FIELD_isubcase=%s_itime=%s' % (case_type, isubcase, itime)\n vtk_file.write('FIELD %s 6 %i float\\n' % (title, ni))\n vtk_file.write('LOOKUP_TABLE default\\n')\n vtk_file.write(pack_float_2d_array(fmt, data[itime, i, :]))\n\n #CELLS 217 1039\n","sub_path":"pyNastran/op2/export_to_vtk.py","file_name":"export_to_vtk.py","file_ext":"py","file_size_in_byte":11708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"652664959","text":"import pickle\nimport csv\nimport os\nimport pprint\nimport time\nfrom collections import defaultdict\nfrom basketball_mapping import *\n\npp = pprint.PrettyPrinter(indent=2)\npprint = pp.pprint\nimport_headers = [\"event_id\", \"game_id\", \"game_date\", \"quarter\", \"timestamp\", \"game_clock\",\n \"shot_clock\", \"team_id\", \"player_id\", \"x_loc\", \"y_loc\", \"radius\"]\n\nexport_headers = [\"Sample_idx\", \"timestamp_ms\", \"adjusted_game_time\", \"player_id\", \"realX\", \"realY\"]\n\nsteph = 201939\nmax_clock = 720.0*4\nSAMPLE_INTERVAL = 110 #milliseconds\nMIN_SAMPLES_TO_KEEP = 500\n\ndef getPlayerString(pid):\n return f\"{pid}_{players[player]['firstname']}_{players[player]['lastname']}_{players[player]['jersey']}_{players[player]['position']}\"\nstartT = time.time()\ngameFile = \"0021500135-LALatDAL-2015-11-13\"\ndata = pickle.load(open(f\"test_data/{gameFile}.pickle\", \"rb\"))\nplayers = pickle.load(open(\"test_data/0_players.pickle\", 'rb'))\n\nplayerToSamples = defaultdict(lambda: [])\nplayerToFinalSamples = defaultdict(lambda: [])\n\nt = time.time()\ncounter = 0\nfor moment in data:\n pid = moment[8]\n if pid==-1: continue\n # if pid!=steph: continue\n quarter, game_clock = moment[3], moment[5]\n adjustedTime = (4-quarter)*720.0 + game_clock\n footX, footY = moment[9], moment[10]\n meterX, meterY = footToMeter(footX), footToMeter(footY)\n playerToSamples[pid].append([int(moment[4]%1e10), round(adjustedTime,2), moment[8], round(meterX, 4), round(meterY, 4)])\n counter+=1\n if counter%100000==0:\n print(f\"Processed {counter} moments in {time.time()-t} seconds\")\n t = time.time()\n\nfor samples in playerToSamples.values():\n samples.sort(key=lambda x: x[0])\n\nt = time.time()\nfor player, samples in playerToSamples.items():\n downsampledSamples = []\n timestamp = samples[0][0]\n for sample in samples:\n if sample[0] > timestamp:\n if sample[0] <= timestamp+2*SAMPLE_INTERVAL:\n downsampledSamples.append(sample)\n timestamp = sample[0] + SAMPLE_INTERVAL\n else: #jump in data\n if len(downsampledSamples)>MIN_SAMPLES_TO_KEEP:\n playerToFinalSamples[player].append(downsampledSamples)\n downsampledSamples = [sample]\n timestamp = sample[0]\n # print(f\"Processed {getPlayerString(player)} moments into {len(downsampledSamples)} samples in {time.time()-t} seconds\")\n t = time.time()\n\nfor player, sampleList in playerToFinalSamples.items():\n playerString = getPlayerString(player)\n dir = f\"test_data{os.sep}{gameFile}{os.sep}{playerString}\"\n if not os.path.exists(dir):\n os.makedirs(dir)\n for i, samples in enumerate(sampleList):\n with open(f\"{dir}/{playerString}_{i}_{len(samples)}.csv\", \"w+\", newline='') as f:\n cW = csv.writer(f)\n cW.writerow(export_headers)\n for i, row in enumerate(samples):\n cW.writerow([i]+row)\n\nprint(f\"DONE. Took {time.time()-startT} seconds\")","sub_path":"Simulator+Localizer/filterNBAData.py","file_name":"filterNBAData.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"386624139","text":"import io\nimport sys\n_INPUT = \"\"\"\\\n10 3 5 30\n\"\"\"\nsys.stdin = io.StringIO(_INPUT)\n\nV, T, S, D = map(int, input().split())\n\nif(V*T<=D and D<=V*S):\n print(\"No\")\nelse:\n print(\"Yes\")","sub_path":"practice/2021/2021-02-06/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"469846496","text":"from theis_wrapper import theis\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nP0 = 3.6e6 # Pa\nb = 100 # m\nr = 0.05 # m\nQ0 = -0.005 # m^3/s\nk = 1e-12 # m^2\nphi = 0.1\nrho = 813.37 # Water at 240 degrees celsius\nnu = 0.0001111 # Water at 240 degrees celsius\nc = 0.001303 # Water at 240 degrees celsius\nt0 = 0\ndt = 200\nt1 = 54000\nnumData = 271\n\n# time = np.linspace(0,54000,271)\nstart = time.time()\npressure = theis(k, nu, phi, rho, c, b, Q0, P0, r, t0, dt, t1, numData)\nend = time.time()\nprint('Time elapsed = {}'.format(end-start))\n# print(pressure)\n\n# plt.plot(time,pressure, 'k-',label='Fortran Module')\n# plt.show()\n","sub_path":"awtas/logic/wrappers/theis_solution/theis_wrapper_test.py","file_name":"theis_wrapper_test.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"65240775","text":"from aiohttp import web\nimport json\n\n\nclass IPNHelper:\n status_levels = {\n \"Canceled_Reversal\": 1,\n \"Completed\": 1,\n \"Created\": 0,\n \"Denied\": -1,\n \"Expired\": -1,\n \"Failed\": -1,\n \"Pending\": 0,\n \"Refunded\": -1,\n \"Reversed\": -1,\n \"Processed\": 0,\n \"Voided\": 0,\n\n \"chargeback\": -1,\n \"complaint\": 0,\n \"dispute\": 0,\n \"bankreturn\": -1\n }\n\n def __init__(self, bot):\n self.bot = bot\n self.last_transaction = None\n\n async def _verify_notification(self, data):\n \"\"\"\n Verify that the notification comes from PayPal and is valid\n \"\"\"\n resp = await self.bot.session.post(\n url=self.bot.config.paypal_ipn,\n data={\n \"cmd\": \"_notify-validate\",\n **data\n }\n )\n return await resp.text() == \"VERIFIED\"\n\n def _is_duplicate(self, data):\n \"\"\"\n Check if the notification is an duplicate of the last notification\n \"\"\"\n is_dup = False\n type = (data.get(\"txn_type\") or data.get(\"case_type\"))\n if self.last_transaction is not None:\n is_dup = data[\"txn_id\"] == self.last_transaction[0] and type == self.last_transaction[1]\n\n self.last_transaction = [data[\"txn_id\"], type]\n return is_dup\n\n def notification_processor(self, handler):\n \"\"\"\n A wrapper function that processes and verifies the notification\n The handler function is doing the main logic\n \"\"\"\n async def process_notification(req):\n data = dict(await req.post())\n if not await self._verify_notification(data):\n raise web.HTTPBadRequest()\n\n if not self._is_duplicate(data):\n # Wrap the coroutine in a task to prevent it from blocking the response\n self.bot.loop.create_task(handler(data))\n\n # Respond with 200 even if the notification is a duplicate to prevent another duplicate\n return web.Response(status=200)\n\n return process_notification\n","sub_path":"discord_pay/util/ipn.py","file_name":"ipn.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"321544041","text":"import asyncio\r\nimport multiprocessing\r\nimport os\r\nimport subprocess\r\nimport sys\r\nimport tempfile\r\nimport unittest\r\n\r\nfrom distutils import spawn\r\n\r\nimport grp\r\n\r\nimport vanir.config\r\nimport vanir.devices\r\nimport vanir.tests\r\nimport vanir.vm.appvm\r\nimport vanir.vm.templatevm\r\n\r\nTEST_DATA = b\"0123456789\" * 1024\r\n\r\n\r\nclass TC_00_AppVMMixin(object):\r\n def setUp(self):\r\n super(TC_00_AppVMMixin, self).setUp()\r\n self.init_default_template(self.template)\r\n if self._testMethodName == 'test_210_time_sync':\r\n self.init_networking()\r\n self.testvm1 = self.app.add_new_vm(\r\n vanir.vm.appvm.AppVM,\r\n label='red',\r\n name=self.make_vm_name('vm1'),\r\n template=self.app.domains[self.template])\r\n self.loop.run_until_complete(self.testvm1.create_on_disk())\r\n self.testvm2 = self.app.add_new_vm(\r\n vanir.vm.appvm.AppVM,\r\n label='red',\r\n name=self.make_vm_name('vm2'),\r\n template=self.app.domains[self.template])\r\n self.loop.run_until_complete(self.testvm2.create_on_disk())\r\n self.app.save()\r\n\r\n def test_000_start_shutdown(self):\r\n # TODO: wait_for, timeout\r\n self.loop.run_until_complete(self.testvm1.start())\r\n self.assertEqual(self.testvm1.get_power_state(), \"Running\")\r\n self.loop.run_until_complete(self.wait_for_session(self.testvm1))\r\n self.loop.run_until_complete(self.testvm1.shutdown(wait=True))\r\n self.assertEqual(self.testvm1.get_power_state(), \"Halted\")\r\n\r\n @unittest.skipUnless(spawn.find_executable('xdotool'),\r\n \"xdotool not installed\")\r\n def test_010_run_xterm(self):\r\n self.loop.run_until_complete(self.testvm1.start())\r\n self.assertEqual(self.testvm1.get_power_state(), \"Running\")\r\n\r\n self.loop.run_until_complete(self.wait_for_session(self.testvm1))\r\n p = self.loop.run_until_complete(self.testvm1.run('xterm'))\r\n try:\r\n title = 'user@{}'.format(self.testvm1.name)\r\n if self.template.count(\"whonix\"):\r\n title = 'user@host'\r\n self.wait_for_window(title)\r\n\r\n self.loop.run_until_complete(asyncio.sleep(0.5))\r\n subprocess.check_call(\r\n ['xdotool', 'search', '--name', title,\r\n 'windowactivate', 'type', 'exit\\n'])\r\n\r\n self.wait_for_window(title, show=False)\r\n finally:\r\n try:\r\n p.terminate()\r\n self.loop.run_until_complete(p.wait())\r\n except ProcessLookupError: # already dead\r\n pass\r\n\r\n @unittest.skipUnless(spawn.find_executable('xdotool'),\r\n \"xdotool not installed\")\r\n def test_011_run_gnome_terminal(self):\r\n if \"minimal\" in self.template:\r\n self.skipTest(\"Minimal template doesn't have 'gnome-terminal'\")\r\n if 'whonix' in self.template:\r\n self.skipTest(\"Whonix template doesn't have 'gnome-terminal'\")\r\n self.loop.run_until_complete(self.testvm1.start())\r\n self.assertEqual(self.testvm1.get_power_state(), \"Running\")\r\n self.loop.run_until_complete(self.wait_for_session(self.testvm1))\r\n p = self.loop.run_until_complete(self.testvm1.run('gnome-terminal'))\r\n try:\r\n title = 'user@{}'.format(self.testvm1.name)\r\n if self.template.count(\"whonix\"):\r\n title = 'user@host'\r\n self.wait_for_window(title)\r\n\r\n self.loop.run_until_complete(asyncio.sleep(0.5))\r\n subprocess.check_call(\r\n ['xdotool', 'search', '--name', title,\r\n 'windowactivate', '--sync', 'type', 'exit\\n'])\r\n\r\n wait_count = 0\r\n while subprocess.call(['xdotool', 'search', '--name', title],\r\n stdout=open(os.path.devnull, 'w'),\r\n stderr=subprocess.STDOUT) == 0:\r\n wait_count += 1\r\n if wait_count > 100:\r\n self.fail(\"Timeout while waiting for gnome-terminal \"\r\n \"termination\")\r\n self.loop.run_until_complete(asyncio.sleep(0.1))\r\n finally:\r\n try:\r\n p.terminate()\r\n self.loop.run_until_complete(p.wait())\r\n except ProcessLookupError: # already dead\r\n pass\r\n\r\n @unittest.skipUnless(spawn.find_executable('xdotool'),\r\n \"xdotool not installed\")\r\n def test_012_vanir_desktop_run(self):\r\n self.loop.run_until_complete(self.testvm1.start())\r\n self.assertEqual(self.testvm1.get_power_state(), \"Running\")\r\n xterm_desktop_path = \"/usr/share/applications/xterm.desktop\"\r\n # Debian has it different...\r\n xterm_desktop_path_debian = \\\r\n \"/usr/share/applications/debian-xterm.desktop\"\r\n try:\r\n self.loop.run_until_complete(self.testvm1.run_for_stdio(\r\n 'test -r {}'.format(xterm_desktop_path_debian)))\r\n except subprocess.CalledProcessError:\r\n pass\r\n else:\r\n xterm_desktop_path = xterm_desktop_path_debian\r\n self.loop.run_until_complete(self.wait_for_session(self.testvm1))\r\n self.loop.run_until_complete(\r\n self.testvm1.run('vanir-desktop-run {}'.format(xterm_desktop_path)))\r\n title = 'user@{}'.format(self.testvm1.name)\r\n if self.template.count(\"whonix\"):\r\n title = 'user@host'\r\n self.wait_for_window(title)\r\n\r\n self.loop.run_until_complete(asyncio.sleep(0.5))\r\n subprocess.check_call(\r\n ['xdotool', 'search', '--name', title,\r\n 'windowactivate', '--sync', 'type', 'exit\\n'])\r\n\r\n self.wait_for_window(title, show=False)\r\n\r\n def test_050_qrexec_simple_eof(self):\r\n \"\"\"Test for data and EOF transmission dom0->VM\"\"\"\r\n\r\n # XXX is this still correct? this is no longer simple qrexec,\r\n # but vanir.VMShell\r\n\r\n self.loop.run_until_complete(self.testvm1.start())\r\n try:\r\n (stdout, stderr) = self.loop.run_until_complete(asyncio.wait_for(\r\n self.testvm1.run_for_stdio('cat', input=TEST_DATA),\r\n timeout=10))\r\n except asyncio.TimeoutError:\r\n self.fail(\r\n \"Timeout, probably EOF wasn't transferred to the VM process\")\r\n\r\n self.assertEqual(stdout, TEST_DATA,\r\n 'Received data differs from what was sent')\r\n self.assertFalse(stderr,\r\n 'Some data was printed to stderr')\r\n\r\n def test_051_qrexec_simple_eof_reverse(self):\r\n \"\"\"Test for EOF transmission VM->dom0\"\"\"\r\n\r\n @asyncio.coroutine\r\n def run(self):\r\n p = yield from self.testvm1.run(\r\n 'echo test; exec >&-; cat > /dev/null',\r\n stdin=subprocess.PIPE,\r\n stdout=subprocess.PIPE,\r\n stderr=subprocess.PIPE)\r\n\r\n # this will hang on test failure\r\n stdout = yield from asyncio.wait_for(p.stdout.read(), timeout=10)\r\n\r\n p.stdin.write(TEST_DATA)\r\n yield from p.stdin.drain()\r\n p.stdin.close()\r\n self.assertEqual(stdout.strip(), b'test',\r\n 'Received data differs from what was expected')\r\n # this may hang in some buggy cases\r\n self.assertFalse((yield from p.stderr.read()),\r\n 'Some data was printed to stderr')\r\n\r\n try:\r\n yield from asyncio.wait_for(p.wait(), timeout=1)\r\n except asyncio.TimeoutError:\r\n self.fail(\"Timeout, \"\r\n \"probably EOF wasn't transferred from the VM process\")\r\n\r\n self.loop.run_until_complete(self.testvm1.start())\r\n self.loop.run_until_complete(self.wait_for_session(self.testvm1))\r\n self.loop.run_until_complete(run(self))\r\n\r\n def test_052_qrexec_vm_service_eof(self):\r\n \"\"\"Test for EOF transmission VM(src)->VM(dst)\"\"\"\r\n\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.wait_for_session(self.testvm1),\r\n self.wait_for_session(self.testvm2)]))\r\n self.loop.run_until_complete(self.testvm2.run_for_stdio(\r\n 'cat > /etc/vanir-rpc/test.EOF',\r\n user='root',\r\n input=b'/bin/cat'))\r\n\r\n with self.qrexec_policy('test.EOF', self.testvm1, self.testvm2):\r\n try:\r\n stdout, _ = self.loop.run_until_complete(asyncio.wait_for(\r\n self.testvm1.run_for_stdio('''\\\r\n /usr/lib/vanir/qrexec-client-vm {} test.EOF \\\r\n /bin/sh -c 'echo test; exec >&-; cat >&$SAVED_FD_1'\r\n '''.format(self.testvm2.name)),\r\n timeout=10))\r\n except asyncio.TimeoutError:\r\n self.fail(\"Timeout, probably EOF wasn't transferred\")\r\n\r\n self.assertEqual(stdout, b'test\\n',\r\n 'Received data differs from what was expected')\r\n\r\n @unittest.expectedFailure\r\n def test_053_qrexec_vm_service_eof_reverse(self):\r\n \"\"\"Test for EOF transmission VM(src)<-VM(dst)\"\"\"\r\n\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n self.create_remote_file(self.testvm2, '/etc/vanir-rpc/test.EOF',\r\n 'echo test; exec >&-; cat >/dev/null')\r\n\r\n with self.qrexec_policy('test.EOF', self.testvm1, self.testvm2):\r\n try:\r\n stdout, _ = self.loop.run_until_complete(asyncio.wait_for(\r\n self.testvm1.run_for_stdio('''\\\r\n /usr/lib/vanir/qrexec-client-vm {} test.EOF \\\r\n /bin/sh -c 'cat >&$SAVED_FD_1'\r\n '''.format(self.testvm2.name)),\r\n timeout=10))\r\n except asyncio.TimeoutError:\r\n self.fail(\"Timeout, probably EOF wasn't transferred\")\r\n\r\n self.assertEqual(stdout, b'test',\r\n 'Received data differs from what was expected')\r\n\r\n def test_055_qrexec_dom0_service_abort(self):\r\n \"\"\"\r\n Test if service abort (by dom0) is properly handled by source VM.\r\n\r\n If \"remote\" part of the service terminates, the source part should\r\n properly be notified. This includes closing its stdin (which is\r\n already checked by test_053_qrexec_vm_service_eof_reverse), but also\r\n its stdout - otherwise such service might hang on write(2) call.\r\n \"\"\"\r\n\r\n self.loop.run_until_complete(self.testvm1.start())\r\n self.create_local_file('/etc/vanir-rpc/test.Abort',\r\n 'sleep 1')\r\n\r\n with self.qrexec_policy('test.Abort', self.testvm1, 'dom0'):\r\n try:\r\n stdout, _ = self.loop.run_until_complete(asyncio.wait_for(\r\n self.testvm1.run_for_stdio('''\\\r\n /usr/lib/vanir/qrexec-client-vm dom0 test.Abort \\\r\n /bin/cat /dev/zero; test $? -eq 141'''),\r\n timeout=10))\r\n except asyncio.TimeoutError:\r\n self.fail(\"Timeout, probably stdout wasn't closed\")\r\n\r\n def test_060_qrexec_exit_code_dom0(self):\r\n self.loop.run_until_complete(self.testvm1.start())\r\n self.loop.run_until_complete(self.testvm1.run_for_stdio('exit 0'))\r\n with self.assertRaises(subprocess.CalledProcessError) as e:\r\n self.loop.run_until_complete(self.testvm1.run_for_stdio('exit 3'))\r\n self.assertEqual(e.exception.returncode, 3)\r\n\r\n def test_065_qrexec_exit_code_vm(self):\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n with self.qrexec_policy('test.Retcode', self.testvm1, self.testvm2):\r\n self.create_remote_file(self.testvm2, '/etc/vanir-rpc/test.Retcode',\r\n 'exit 0')\r\n (stdout, stderr) = self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('''\\\r\n /usr/lib/vanir/qrexec-client-vm {} test.Retcode;\r\n echo $?'''.format(self.testvm2.name)))\r\n self.assertEqual(stdout, b'0\\n')\r\n\r\n self.create_remote_file(self.testvm2, '/etc/vanir-rpc/test.Retcode',\r\n 'exit 3')\r\n (stdout, stderr) = self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('''\\\r\n /usr/lib/vanir/qrexec-client-vm {} test.Retcode;\r\n echo $?'''.format(self.testvm2.name)))\r\n self.assertEqual(stdout, b'3\\n')\r\n\r\n def test_070_qrexec_vm_simultaneous_write(self):\r\n \"\"\"Test for simultaneous write in VM(src)->VM(dst) connection\r\n\r\n This is regression test for #1347\r\n\r\n Check for deadlock when initially both sides writes a lot of data\r\n (and not read anything). When one side starts reading, it should\r\n get the data and the remote side should be possible to write then more.\r\n There was a bug where remote side was waiting on write(2) and not\r\n handling anything else.\r\n \"\"\"\r\n\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n self.create_remote_file(self.testvm2, '/etc/vanir-rpc/test.write', '''\\\r\n # first write a lot of data\r\n dd if=/dev/zero bs=993 count=10000 iflag=fullblock\r\n # and only then read something\r\n dd of=/dev/null bs=993 count=10000 iflag=fullblock\r\n ''')\r\n\r\n with self.qrexec_policy('test.write', self.testvm1, self.testvm2):\r\n try:\r\n self.loop.run_until_complete(asyncio.wait_for(\r\n # first write a lot of data to fill all the buffers\r\n # then after some time start reading\r\n self.testvm1.run_for_stdio('''\\\r\n /usr/lib/vanir/qrexec-client-vm {} test.write \\\r\n /bin/sh -c '\r\n dd if=/dev/zero bs=993 count=10000 iflag=fullblock &\r\n sleep 1;\r\n dd of=/dev/null bs=993 count=10000 iflag=fullblock;\r\n wait'\r\n '''.format(self.testvm2.name)), timeout=10))\r\n except subprocess.CalledProcessError:\r\n self.fail('Service call failed')\r\n except asyncio.TimeoutError:\r\n self.fail('Timeout, probably deadlock')\r\n\r\n def test_071_qrexec_dom0_simultaneous_write(self):\r\n \"\"\"Test for simultaneous write in dom0(src)->VM(dst) connection\r\n\r\n Similar to test_070_qrexec_vm_simultaneous_write, but with dom0\r\n as a source.\r\n \"\"\"\r\n\r\n self.loop.run_until_complete(self.testvm2.start())\r\n\r\n self.create_remote_file(self.testvm2, '/etc/vanir-rpc/test.write', '''\\\r\n # first write a lot of data\r\n dd if=/dev/zero bs=993 count=10000 iflag=fullblock\r\n # and only then read something\r\n dd of=/dev/null bs=993 count=10000 iflag=fullblock\r\n ''')\r\n\r\n # can't use subprocess.PIPE, because asyncio will claim those FDs\r\n pipe1_r, pipe1_w = os.pipe()\r\n pipe2_r, pipe2_w = os.pipe()\r\n try:\r\n local_proc = self.loop.run_until_complete(\r\n asyncio.create_subprocess_shell(\r\n # first write a lot of data to fill all the buffers\r\n \"dd if=/dev/zero bs=993 count=10000 iflag=fullblock & \"\r\n # then after some time start reading\r\n \"sleep 1; \"\r\n \"dd of=/dev/null bs=993 count=10000 iflag=fullblock; \"\r\n \"wait\", stdin=pipe1_r, stdout=pipe2_w))\r\n\r\n service_proc = self.loop.run_until_complete(self.testvm2.run_service(\r\n \"test.write\", stdin=pipe2_r, stdout=pipe1_w))\r\n finally:\r\n os.close(pipe1_r)\r\n os.close(pipe1_w)\r\n os.close(pipe2_r)\r\n os.close(pipe2_w)\r\n\r\n try:\r\n self.loop.run_until_complete(\r\n asyncio.wait_for(service_proc.wait(), timeout=10))\r\n except asyncio.TimeoutError:\r\n self.fail(\"Timeout, probably deadlock\")\r\n else:\r\n self.assertEqual(service_proc.returncode, 0,\r\n \"Service call failed\")\r\n finally:\r\n try:\r\n service_proc.terminate()\r\n except ProcessLookupError:\r\n pass\r\n\r\n def test_072_qrexec_to_dom0_simultaneous_write(self):\r\n \"\"\"Test for simultaneous write in dom0(src)<-VM(dst) connection\r\n\r\n Similar to test_071_qrexec_dom0_simultaneous_write, but with dom0\r\n as a \"hanging\" side.\r\n \"\"\"\r\n\r\n self.loop.run_until_complete(self.testvm2.start())\r\n\r\n self.create_remote_file(self.testvm2, '/etc/vanir-rpc/test.write', '''\\\r\n # first write a lot of data\r\n dd if=/dev/zero bs=993 count=10000 iflag=fullblock &\r\n # and only then read something\r\n dd of=/dev/null bs=993 count=10000 iflag=fullblock\r\n sleep 1;\r\n wait\r\n ''')\r\n\r\n # can't use subprocess.PIPE, because asyncio will claim those FDs\r\n pipe1_r, pipe1_w = os.pipe()\r\n pipe2_r, pipe2_w = os.pipe()\r\n try:\r\n local_proc = self.loop.run_until_complete(\r\n asyncio.create_subprocess_shell(\r\n # first write a lot of data to fill all the buffers\r\n \"dd if=/dev/zero bs=993 count=10000 iflag=fullblock & \"\r\n # then, only when all written, read something\r\n \"dd of=/dev/null bs=993 count=10000 iflag=fullblock; \",\r\n stdin=pipe1_r, stdout=pipe2_w))\r\n\r\n service_proc = self.loop.run_until_complete(self.testvm2.run_service(\r\n \"test.write\", stdin=pipe2_r, stdout=pipe1_w))\r\n finally:\r\n os.close(pipe1_r)\r\n os.close(pipe1_w)\r\n os.close(pipe2_r)\r\n os.close(pipe2_w)\r\n\r\n try:\r\n self.loop.run_until_complete(\r\n asyncio.wait_for(service_proc.wait(), timeout=10))\r\n except asyncio.TimeoutError:\r\n self.fail(\"Timeout, probably deadlock\")\r\n else:\r\n self.assertEqual(service_proc.returncode, 0,\r\n \"Service call failed\")\r\n finally:\r\n try:\r\n service_proc.terminate()\r\n except ProcessLookupError:\r\n pass\r\n\r\n def test_080_qrexec_service_argument_allow_default(self):\r\n \"\"\"Qrexec service call with argument\"\"\"\r\n\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n self.create_remote_file(self.testvm2, '/etc/vanir-rpc/test.Argument',\r\n '/usr/bin/printf %s \"$1\"')\r\n with self.qrexec_policy('test.Argument', self.testvm1, self.testvm2):\r\n stdout, stderr = self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('/usr/lib/vanir/qrexec-client-vm '\r\n '{} test.Argument+argument'.format(self.testvm2.name)))\r\n self.assertEqual(stdout, b'argument')\r\n\r\n def test_081_qrexec_service_argument_allow_specific(self):\r\n \"\"\"Qrexec service call with argument - allow only specific value\"\"\"\r\n\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n self.create_remote_file(self.testvm2, '/etc/vanir-rpc/test.Argument',\r\n '/usr/bin/printf %s \"$1\"')\r\n\r\n with self.qrexec_policy('test.Argument', '$anyvm', '$anyvm', False):\r\n with self.qrexec_policy('test.Argument+argument',\r\n self.testvm1.name, self.testvm2.name):\r\n stdout, stderr = self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio(\r\n '/usr/lib/vanir/qrexec-client-vm '\r\n '{} test.Argument+argument'.format(self.testvm2.name)))\r\n self.assertEqual(stdout, b'argument')\r\n\r\n def test_082_qrexec_service_argument_deny_specific(self):\r\n \"\"\"Qrexec service call with argument - deny specific value\"\"\"\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n self.create_remote_file(self.testvm2, '/etc/vanir-rpc/test.Argument',\r\n '/usr/bin/printf %s \"$1\"')\r\n with self.qrexec_policy('test.Argument', '$anyvm', '$anyvm'):\r\n with self.qrexec_policy('test.Argument+argument',\r\n self.testvm1, self.testvm2, allow=False):\r\n with self.assertRaises(subprocess.CalledProcessError,\r\n msg='Service request should be denied'):\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio(\r\n '/usr/lib/vanir/qrexec-client-vm {} '\r\n 'test.Argument+argument'.format(self.testvm2.name)))\r\n\r\n def test_083_qrexec_service_argument_specific_implementation(self):\r\n \"\"\"Qrexec service call with argument - argument specific\r\n implementatation\"\"\"\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n self.create_remote_file(self.testvm2,\r\n '/etc/vanir-rpc/test.Argument',\r\n '/usr/bin/printf %s \"$1\"')\r\n self.create_remote_file(self.testvm2,\r\n '/etc/vanir-rpc/test.Argument+argument',\r\n '/usr/bin/printf \"specific: %s\" \"$1\"')\r\n\r\n with self.qrexec_policy('test.Argument', self.testvm1, self.testvm2):\r\n stdout, stderr = self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('/usr/lib/vanir/qrexec-client-vm '\r\n '{} test.Argument+argument'.format(self.testvm2.name)))\r\n\r\n self.assertEqual(stdout, b'specific: argument')\r\n\r\n def test_084_qrexec_service_argument_extra_env(self):\r\n \"\"\"Qrexec service call with argument - extra env variables\"\"\"\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n self.create_remote_file(self.testvm2, '/etc/vanir-rpc/test.Argument',\r\n '/usr/bin/printf \"%s %s\" '\r\n '\"$QREXEC_SERVICE_FULL_NAME\" \"$QREXEC_SERVICE_ARGUMENT\"')\r\n\r\n with self.qrexec_policy('test.Argument', self.testvm1, self.testvm2):\r\n stdout, stderr = self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('/usr/lib/vanir/qrexec-client-vm '\r\n '{} test.Argument+argument'.format(self.testvm2.name)))\r\n\r\n self.assertEqual(stdout, b'test.Argument+argument argument')\r\n\r\n def test_100_qrexec_filecopy(self):\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n with self.qrexec_policy('vanir.Filecopy', self.testvm1, self.testvm2):\r\n try:\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio(\r\n 'qvm-copy-to-vm {} /etc/passwd'.format(\r\n self.testvm2.name)))\r\n except subprocess.CalledProcessError as e:\r\n self.fail('qvm-copy-to-vm failed: {}'.format(e.stderr))\r\n\r\n try:\r\n self.loop.run_until_complete(self.testvm2.run_for_stdio(\r\n 'diff /etc/passwd /home/user/VanirIncoming/{}/passwd'.format(\r\n self.testvm1.name)))\r\n except subprocess.CalledProcessError:\r\n self.fail('file differs')\r\n\r\n try:\r\n self.loop.run_until_complete(self.testvm1.run_for_stdio(\r\n 'test -f /etc/passwd'))\r\n except subprocess.CalledProcessError:\r\n self.fail('source file got removed')\r\n\r\n def test_105_qrexec_filemove(self):\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n self.loop.run_until_complete(self.testvm1.run_for_stdio(\r\n 'cp /etc/passwd /tmp/passwd'))\r\n with self.qrexec_policy('vanir.Filecopy', self.testvm1, self.testvm2):\r\n try:\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio(\r\n 'qvm-move-to-vm {} /tmp/passwd'.format(\r\n self.testvm2.name)))\r\n except subprocess.CalledProcessError as e:\r\n self.fail('qvm-move-to-vm failed: {}'.format(e.stderr))\r\n\r\n try:\r\n self.loop.run_until_complete(self.testvm2.run_for_stdio(\r\n 'diff /etc/passwd /home/user/VanirIncoming/{}/passwd'.format(\r\n self.testvm1.name)))\r\n except subprocess.CalledProcessError:\r\n self.fail('file differs')\r\n\r\n with self.assertRaises(subprocess.CalledProcessError):\r\n self.loop.run_until_complete(self.testvm1.run_for_stdio(\r\n 'test -f /tmp/passwd'))\r\n\r\n def test_101_qrexec_filecopy_with_autostart(self):\r\n self.loop.run_until_complete(self.testvm1.start())\r\n\r\n with self.qrexec_policy('vanir.Filecopy', self.testvm1, self.testvm2):\r\n try:\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio(\r\n 'qvm-copy-to-vm {} /etc/passwd'.format(\r\n self.testvm2.name)))\r\n except subprocess.CalledProcessError as e:\r\n self.fail('qvm-copy-to-vm failed: {}'.format(e.stderr))\r\n\r\n self.testvm2._libvirt_domain = None\r\n self.assertTrue(self.testvm2.is_running())\r\n\r\n try:\r\n self.loop.run_until_complete(self.testvm2.run_for_stdio(\r\n 'diff /etc/passwd /home/user/VanirIncoming/{}/passwd'.format(\r\n self.testvm1.name)))\r\n except subprocess.CalledProcessError:\r\n self.fail('file differs')\r\n\r\n try:\r\n self.loop.run_until_complete(self.testvm1.run_for_stdio(\r\n 'test -f /etc/passwd'))\r\n except subprocess.CalledProcessError:\r\n self.fail('source file got removed')\r\n\r\n def test_110_qrexec_filecopy_deny(self):\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n with self.qrexec_policy('vanir.Filecopy', self.testvm1, self.testvm2,\r\n allow=False):\r\n with self.assertRaises(subprocess.CalledProcessError):\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio(\r\n 'qvm-copy-to-vm {} /etc/passwd'.format(\r\n self.testvm2.name)))\r\n\r\n with self.assertRaises(subprocess.CalledProcessError):\r\n self.loop.run_until_complete(self.testvm1.run_for_stdio(\r\n 'test -d /home/user/VanirIncoming/{}'.format(\r\n self.testvm1.name)))\r\n\r\n @unittest.skip(\"Xen gntalloc driver crashes when page is mapped in the \"\r\n \"same domain\")\r\n def test_120_qrexec_filecopy_self(self):\r\n self.testvm1.start()\r\n self.qrexec_policy('vanir.Filecopy', self.testvm1.name,\r\n self.testvm1.name)\r\n p = self.testvm1.run(\"qvm-copy-to-vm %s /etc/passwd\" %\r\n self.testvm1.name, passio_popen=True,\r\n passio_stderr=True)\r\n p.wait()\r\n self.assertEqual(p.returncode, 0, \"qvm-copy-to-vm failed: %s\" %\r\n p.stderr.read())\r\n retcode = self.testvm1.run(\r\n \"diff /etc/passwd /home/user/VanirIncoming/{}/passwd\".format(\r\n self.testvm1.name),\r\n wait=True)\r\n self.assertEqual(retcode, 0, \"file differs\")\r\n\r\n @unittest.skipUnless(spawn.find_executable('xdotool'),\r\n \"xdotool not installed\")\r\n def test_130_qrexec_filemove_disk_full(self):\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start()]))\r\n\r\n self.loop.run_until_complete(self.wait_for_session(self.testvm1))\r\n\r\n # Prepare test file\r\n self.loop.run_until_complete(self.testvm1.run_for_stdio(\r\n 'yes teststring | dd of=/tmp/testfile bs=1M count=50 '\r\n 'iflag=fullblock'))\r\n\r\n # Prepare target directory with limited size\r\n self.loop.run_until_complete(self.testvm2.run_for_stdio(\r\n 'mkdir -p /home/user/VanirIncoming && '\r\n 'chown user /home/user/VanirIncoming && '\r\n 'mount -t tmpfs none /home/user/VanirIncoming -o size=48M',\r\n user='root'))\r\n\r\n with self.qrexec_policy('vanir.Filecopy', self.testvm1, self.testvm2):\r\n p = self.loop.run_until_complete(self.testvm1.run(\r\n 'qvm-move-to-vm {} /tmp/testfile'.format(\r\n self.testvm2.name)))\r\n\r\n # Close GUI error message\r\n try:\r\n self.enter_keys_in_window('Error', ['Return'])\r\n except subprocess.CalledProcessError:\r\n pass\r\n self.loop.run_until_complete(p.wait())\r\n self.assertNotEqual(p.returncode, 0)\r\n\r\n # the file shouldn't be removed in source vm\r\n self.loop.run_until_complete(self.testvm1.run_for_stdio(\r\n 'test -f /tmp/testfile'))\r\n\r\n def test_200_timezone(self):\r\n \"\"\"Test whether timezone setting is properly propagated to the VM\"\"\"\r\n if \"whonix\" in self.template:\r\n self.skipTest(\"Timezone propagation disabled on Whonix templates\")\r\n\r\n self.loop.run_until_complete(self.testvm1.start())\r\n vm_tz, _ = self.loop.run_until_complete(self.testvm1.run_for_stdio(\r\n 'date +%Z'))\r\n dom0_tz = subprocess.check_output(['date', '+%Z'])\r\n self.assertEqual(vm_tz.strip(), dom0_tz.strip())\r\n\r\n # Check if reverting back to UTC works\r\n vm_tz, _ = self.loop.run_until_complete(self.testvm1.run_for_stdio(\r\n 'TZ=UTC date +%Z'))\r\n self.assertEqual(vm_tz.strip(), b'UTC')\r\n\r\n def test_210_time_sync(self):\r\n \"\"\"Test time synchronization mechanism\"\"\"\r\n if self.template.startswith('whonix-'):\r\n self.skipTest('qvm-sync-clock disabled for Whonix VMs')\r\n self.loop.run_until_complete(asyncio.wait([\r\n self.testvm1.start(),\r\n self.testvm2.start(),]))\r\n start_time = subprocess.check_output(['date', '-u', '+%s'])\r\n\r\n try:\r\n self.app.clockvm = self.testvm1\r\n self.app.save()\r\n # break vm and dom0 time, to check if qvm-sync-clock would fix it\r\n subprocess.check_call(['sudo', 'date', '-s', '2001-01-01T12:34:56'],\r\n stdout=subprocess.DEVNULL)\r\n self.loop.run_until_complete(\r\n self.testvm2.run_for_stdio('date -s 2001-01-01T12:34:56',\r\n user='root'))\r\n\r\n self.loop.run_until_complete(\r\n self.testvm2.run_for_stdio('qvm-sync-clock',\r\n user='root'))\r\n\r\n p = self.loop.run_until_complete(\r\n asyncio.create_subprocess_exec('sudo', 'qvm-sync-clock',\r\n stdout=asyncio.subprocess.DEVNULL))\r\n self.loop.run_until_complete(p.wait())\r\n self.assertEqual(p.returncode, 0)\r\n vm_time, _ = self.loop.run_until_complete(\r\n self.testvm2.run_for_stdio('date -u +%s'))\r\n self.assertAlmostEquals(int(vm_time), int(start_time), delta=30)\r\n\r\n dom0_time = subprocess.check_output(['date', '-u', '+%s'])\r\n self.assertAlmostEquals(int(dom0_time), int(start_time), delta=30)\r\n\r\n except:\r\n # reset time to some approximation of the real time\r\n subprocess.Popen(\r\n [\"sudo\", \"date\", \"-u\", \"-s\", \"@\" + start_time.decode()])\r\n raise\r\n finally:\r\n self.app.clockvm = None\r\n\r\n @unittest.skipUnless(spawn.find_executable('parecord'),\r\n \"pulseaudio-utils not installed in dom0\")\r\n def test_220_audio_playback(self):\r\n if 'whonix-gw' in self.template:\r\n self.skipTest('whonix-gw have no audio')\r\n self.loop.run_until_complete(self.testvm1.start())\r\n try:\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('which parecord'))\r\n except subprocess.CalledProcessError:\r\n self.skipTest('pulseaudio-utils not installed in VM')\r\n\r\n self.loop.run_until_complete(\r\n self.wait_for_session(self.testvm1))\r\n # and some more...\r\n self.loop.run_until_complete(asyncio.sleep(1))\r\n # generate some \"audio\" data\r\n audio_in = b'\\x20' * 44100\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('cat > audio_in.raw', input=audio_in))\r\n local_user = grp.getgrnam('vanir').gr_mem[0]\r\n with tempfile.NamedTemporaryFile() as recorded_audio:\r\n os.chmod(recorded_audio.name, 0o666)\r\n # FIXME: -d 0 assumes only one audio device\r\n p = subprocess.Popen(['sudo', '-E', '-u', local_user,\r\n 'parecord', '-d', '0', '--raw', recorded_audio.name],\r\n stdout=subprocess.PIPE)\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('paplay --raw audio_in.raw'))\r\n # wait for possible parecord buffering\r\n self.loop.run_until_complete(asyncio.sleep(1))\r\n p.terminate()\r\n # for some reason sudo do not relay SIGTERM sent above\r\n subprocess.check_call(['pkill', 'parecord'])\r\n p.wait()\r\n # allow few bytes missing, don't use assertIn, to avoid printing\r\n # the whole data in error message\r\n if audio_in[:-8] not in recorded_audio.file.read():\r\n self.fail('played sound not found in dom0')\r\n\r\n def _configure_audio_recording(self, vm):\r\n '''Connect VM's output-source to sink monitor instead of mic'''\r\n local_user = grp.getgrnam('vanir').gr_mem[0]\r\n sudo = ['sudo', '-E', '-u', local_user]\r\n source_outputs = subprocess.check_output(\r\n sudo + ['pacmd', 'list-source-outputs']).decode()\r\n\r\n last_index = None\r\n found = False\r\n for line in source_outputs.splitlines():\r\n if line.startswith(' index: '):\r\n last_index = line.split(':')[1].strip()\r\n elif line.startswith('\\t\\tapplication.name = '):\r\n app_name = line.split('=')[1].strip('\" ')\r\n if vm.name == app_name:\r\n found = True\r\n break\r\n if not found:\r\n self.fail('source-output for VM {} not found'.format(vm.name))\r\n\r\n subprocess.check_call(sudo +\r\n ['pacmd', 'move-source-output', last_index, '0'])\r\n\r\n @unittest.skipUnless(spawn.find_executable('parecord'),\r\n \"pulseaudio-utils not installed in dom0\")\r\n def test_221_audio_record_muted(self):\r\n if 'whonix-gw' in self.template:\r\n self.skipTest('whonix-gw have no audio')\r\n self.loop.run_until_complete(self.testvm1.start())\r\n try:\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('which parecord'))\r\n except subprocess.CalledProcessError:\r\n self.skipTest('pulseaudio-utils not installed in VM')\r\n\r\n self.loop.run_until_complete(\r\n self.wait_for_session(self.testvm1))\r\n # and some more...\r\n self.loop.run_until_complete(asyncio.sleep(1))\r\n # connect VM's recording source output monitor (instead of mic)\r\n self._configure_audio_recording(self.testvm1)\r\n\r\n # generate some \"audio\" data\r\n audio_in = b'\\x20' * 44100\r\n local_user = grp.getgrnam('vanir').gr_mem[0]\r\n record = self.loop.run_until_complete(\r\n self.testvm1.run('parecord --raw audio_rec.raw'))\r\n # give it time to start recording\r\n self.loop.run_until_complete(asyncio.sleep(0.5))\r\n p = subprocess.Popen(['sudo', '-E', '-u', local_user,\r\n 'paplay', '--raw'],\r\n stdin=subprocess.PIPE)\r\n p.communicate(audio_in)\r\n # wait for possible parecord buffering\r\n self.loop.run_until_complete(asyncio.sleep(1))\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('pkill parecord'))\r\n record.wait()\r\n recorded_audio, _ = self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('cat audio_rec.raw'))\r\n # should be empty or silence, so check just a little fragment\r\n if audio_in[:32] in recorded_audio:\r\n self.fail('VM recorded something, even though mic disabled')\r\n\r\n @unittest.skipUnless(spawn.find_executable('parecord'),\r\n \"pulseaudio-utils not installed in dom0\")\r\n def test_222_audio_record_unmuted(self):\r\n if 'whonix-gw' in self.template:\r\n self.skipTest('whonix-gw have no audio')\r\n self.loop.run_until_complete(self.testvm1.start())\r\n try:\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('which parecord'))\r\n except subprocess.CalledProcessError:\r\n self.skipTest('pulseaudio-utils not installed in VM')\r\n\r\n self.loop.run_until_complete(\r\n self.wait_for_session(self.testvm1))\r\n # and some more...\r\n self.loop.run_until_complete(asyncio.sleep(1))\r\n da = vanir.devices.DeviceAssignment(self.app.domains[0], 'mic')\r\n self.loop.run_until_complete(\r\n self.testvm1.devices['mic'].attach(da))\r\n # connect VM's recording source output monitor (instead of mic)\r\n self._configure_audio_recording(self.testvm1)\r\n\r\n # generate some \"audio\" data\r\n audio_in = b'\\x20' * 44100\r\n local_user = grp.getgrnam('vanir').gr_mem[0]\r\n record = self.loop.run_until_complete(\r\n self.testvm1.run('parecord --raw audio_rec.raw'))\r\n # give it time to start recording\r\n self.loop.run_until_complete(asyncio.sleep(0.5))\r\n p = subprocess.Popen(['sudo', '-E', '-u', local_user,\r\n 'paplay', '--raw'],\r\n stdin=subprocess.PIPE)\r\n p.communicate(audio_in)\r\n # wait for possible parecord buffering\r\n self.loop.run_until_complete(asyncio.sleep(1))\r\n self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('pkill parecord'))\r\n record.wait()\r\n recorded_audio, _ = self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio('cat audio_rec.raw'))\r\n # allow few bytes to be missing\r\n if audio_in[:-8] not in recorded_audio:\r\n self.fail('VM not recorded expected data')\r\n\r\n def test_250_resize_private_img(self):\r\n \"\"\"\r\n Test private.img resize, both offline and online\r\n :return:\r\n \"\"\"\r\n # First offline test\r\n self.loop.run_until_complete(\r\n self.testvm1.storage.resize('private', 4*1024**3))\r\n self.loop.run_until_complete(self.testvm1.start())\r\n df_cmd = '( df --output=size /rw || df /rw | awk \\'{print $2}\\' )|' \\\r\n 'tail -n 1'\r\n # new_size in 1k-blocks\r\n new_size, _ = self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio(df_cmd))\r\n # some safety margin for FS metadata\r\n self.assertGreater(int(new_size.strip()), 3.8*1024**2)\r\n # Then online test\r\n self.loop.run_until_complete(\r\n self.testvm1.storage.resize('private', 6*1024**3))\r\n # new_size in 1k-blocks\r\n new_size, _ = self.loop.run_until_complete(\r\n self.testvm1.run_for_stdio(df_cmd))\r\n # some safety margin for FS metadata\r\n self.assertGreater(int(new_size.strip()), 5.7*1024**2)\r\n\r\n @unittest.skipUnless(spawn.find_executable('xdotool'),\r\n \"xdotool not installed\")\r\n def test_300_bug_1028_gui_memory_pinning(self):\r\n \"\"\"\r\n If VM window composition buffers are relocated in memory, GUI will\r\n still use old pointers and will display old pages\r\n :return:\r\n \"\"\"\r\n\r\n # this test does too much asynchronous operations,\r\n # so let's rewrite it as a coroutine and call it as such\r\n return self.loop.run_until_complete(\r\n self._test_300_bug_1028_gui_memory_pinning())\r\n\r\n @asyncio.coroutine\r\n def _test_300_bug_1028_gui_memory_pinning(self):\r\n self.testvm1.memory = 800\r\n self.testvm1.maxmem = 800\r\n\r\n # exclude from memory balancing\r\n self.testvm1.features['service.meminfo-writer'] = False\r\n yield from self.testvm1.start()\r\n yield from self.wait_for_session(self.testvm1)\r\n\r\n # and allow large map count\r\n yield from self.testvm1.run('echo 256000 > /proc/sys/vm/max_map_count',\r\n user=\"root\")\r\n\r\n allocator_c = '''\r\n#include \r\n#include \r\n#include \r\n\r\nint main(int argc, char **argv) {\r\n int total_pages;\r\n char *addr, *iter;\r\n\r\n total_pages = atoi(argv[1]);\r\n addr = mmap(NULL, total_pages * 0x1000, PROT_READ | PROT_WRITE,\r\n MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0);\r\n if (addr == MAP_FAILED) {\r\n perror(\"mmap\");\r\n exit(1);\r\n }\r\n\r\n printf(\"Stage1\\\\n\");\r\n fflush(stdout);\r\n getchar();\r\n for (iter = addr; iter < addr + total_pages*0x1000; iter += 0x2000) {\r\n if (mlock(iter, 0x1000) == -1) {\r\n perror(\"mlock\");\r\n fprintf(stderr, \"%d of %d\\\\n\", (iter-addr)/0x1000, total_pages);\r\n exit(1);\r\n }\r\n }\r\n\r\n printf(\"Stage2\\\\n\");\r\n fflush(stdout);\r\n for (iter = addr+0x1000; iter < addr + total_pages*0x1000; iter += 0x2000) {\r\n if (munmap(iter, 0x1000) == -1) {\r\n perror(\\\"munmap\\\");\r\n exit(1);\r\n }\r\n }\r\n\r\n printf(\"Stage3\\\\n\");\r\n fflush(stdout);\r\n fclose(stdout);\r\n getchar();\r\n\r\n return 0;\r\n}\r\n'''\r\n\r\n yield from self.testvm1.run_for_stdio('cat > allocator.c',\r\n input=allocator_c.encode())\r\n\r\n try:\r\n yield from self.testvm1.run_for_stdio(\r\n 'gcc allocator.c -o allocator')\r\n except subprocess.CalledProcessError as e:\r\n self.skipTest('allocator compile failed: {}'.format(e.stderr))\r\n\r\n # drop caches to have even more memory pressure\r\n yield from self.testvm1.run_for_stdio(\r\n 'echo 3 > /proc/sys/vm/drop_caches', user='root')\r\n\r\n # now fragment all free memory\r\n stdout, _ = yield from self.testvm1.run_for_stdio(\r\n \"grep ^MemFree: /proc/meminfo|awk '{print $2}'\")\r\n memory_pages = int(stdout) // 4 # 4k pages\r\n\r\n alloc1 = yield from self.testvm1.run(\r\n 'ulimit -l unlimited; exec /home/user/allocator {}'.format(\r\n memory_pages),\r\n user=\"root\",\r\n stdin=subprocess.PIPE, stdout=subprocess.PIPE,\r\n stderr=subprocess.PIPE)\r\n\r\n # wait for memory being allocated; can't use just .read(), because EOF\r\n # passing is unreliable while the process is still running\r\n alloc1.stdin.write(b'\\n')\r\n yield from alloc1.stdin.drain()\r\n try:\r\n alloc_out = yield from alloc1.stdout.readexactly(\r\n len('Stage1\\nStage2\\nStage3\\n'))\r\n except asyncio.IncompleteReadError as e:\r\n alloc_out = e.partial\r\n\r\n if b'Stage3' not in alloc_out:\r\n # read stderr only in case of failed assert (), but still have nice\r\n # failure message (don't use self.fail() directly)\r\n #\r\n # stderr isn't always read, because on not-failed run, the process\r\n # is still running, so stderr.read() will wait (indefinitely).\r\n self.assertIn(b'Stage3', alloc_out,\r\n (yield from alloc1.stderr.read()))\r\n\r\n # now, launch some window - it should get fragmented composition buffer\r\n # it is important to have some changing content there, to generate\r\n # content update events (aka damage notify)\r\n proc = yield from self.testvm1.run(\r\n 'xterm -maximized -e top')\r\n\r\n if proc.returncode is not None:\r\n self.fail('xterm failed to start')\r\n # get window ID\r\n winid = yield from self.wait_for_window_coro(\r\n self.testvm1.name + ':xterm',\r\n search_class=True)\r\n xprop = yield from asyncio.get_event_loop().run_in_executor(None,\r\n subprocess.check_output,\r\n ['xprop', '-notype', '-id', winid, '_VANIR_VMWINDOWID'])\r\n vm_winid = xprop.decode().strip().split(' ')[4]\r\n\r\n # now free the fragmented memory and trigger compaction\r\n alloc1.stdin.write(b'\\n')\r\n yield from alloc1.stdin.drain()\r\n yield from alloc1.wait()\r\n yield from self.testvm1.run_for_stdio(\r\n 'echo 1 > /proc/sys/vm/compact_memory', user='root')\r\n\r\n # now window may be already \"broken\"; to be sure, allocate (=zero)\r\n # some memory\r\n alloc2 = yield from self.testvm1.run(\r\n 'ulimit -l unlimited; /home/user/allocator {}'.format(memory_pages),\r\n user='root', stdout=subprocess.PIPE)\r\n yield from alloc2.stdout.read(len('Stage1\\n'))\r\n\r\n # wait for damage notify - top updates every 3 sec by default\r\n yield from asyncio.sleep(6)\r\n\r\n # stop changing the window content\r\n subprocess.check_call(['xdotool', 'key', '--window', winid, 'd'])\r\n\r\n # now take screenshot of the window, from dom0 and VM\r\n # choose pnm format, as it doesn't have any useless metadata - easy\r\n # to compare\r\n vm_image, _ = yield from self.testvm1.run_for_stdio(\r\n 'import -window {} pnm:-'.format(vm_winid))\r\n\r\n dom0_image = yield from asyncio.get_event_loop().run_in_executor(None,\r\n subprocess.check_output, ['import', '-window', winid, 'pnm:-'])\r\n\r\n if vm_image != dom0_image:\r\n self.fail(\"Dom0 window doesn't match VM window content\")\r\n\r\nclass TC_10_Generic(vanir.tests.SystemTestCase):\r\n def setUp(self):\r\n super(TC_10_Generic, self).setUp()\r\n self.init_default_template()\r\n self.vm = self.app.add_new_vm(\r\n vanir.vm.appvm.AppVM,\r\n name=self.make_vm_name('vm'),\r\n label='red',\r\n template=self.app.default_template)\r\n self.loop.run_until_complete(self.vm.create_on_disk())\r\n self.app.save()\r\n self.vm = self.app.domains[self.vm.qid]\r\n\r\n def test_000_anyvm_deny_dom0(self):\r\n '''$anyvm in policy should not match dom0'''\r\n policy = open(\"/etc/vanir-rpc/policy/test.AnyvmDeny\", \"w\")\r\n policy.write(\"%s $anyvm allow\" % (self.vm.name,))\r\n policy.close()\r\n self.addCleanup(os.unlink, \"/etc/vanir-rpc/policy/test.AnyvmDeny\")\r\n\r\n flagfile = '/tmp/test-anyvmdeny-flag'\r\n if os.path.exists(flagfile):\r\n os.remove(flagfile)\r\n\r\n self.create_local_file('/etc/vanir-rpc/test.AnyvmDeny',\r\n 'touch {}\\necho service output\\n'.format(flagfile))\r\n\r\n self.loop.run_until_complete(self.vm.start())\r\n with self.qrexec_policy('test.AnyvmDeny', self.vm, '$anyvm'):\r\n with self.assertRaises(subprocess.CalledProcessError,\r\n msg='$anyvm matched dom0') as e:\r\n self.loop.run_until_complete(\r\n self.vm.run_for_stdio(\r\n '/usr/lib/vanir/qrexec-client-vm dom0 test.AnyvmDeny'))\r\n stdout = e.exception.output\r\n stderr = e.exception.stderr\r\n self.assertFalse(os.path.exists(flagfile),\r\n 'Flag file created (service was run) even though should be denied,'\r\n ' qrexec-client-vm output: {} {}'.format(stdout, stderr))\r\n\r\ndef create_testcases_for_templates():\r\n return vanir.tests.create_testcases_for_templates('TC_00_AppVM',\r\n TC_00_AppVMMixin, vanir.tests.SystemTestCase,\r\n module=sys.modules[__name__])\r\n\r\ndef load_tests(loader, tests, pattern):\r\n tests.addTests(loader.loadTestsFromNames(\r\n create_testcases_for_templates()))\r\n return tests\r\n\r\nvanir.tests.maybe_create_testcases_on_import(create_testcases_for_templates)\r\n","sub_path":"vanir/tests/integ/vm_qrexec_gui.py","file_name":"vm_qrexec_gui.py","file_ext":"py","file_size_in_byte":49016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"350762748","text":"#!/usr/bin/env python3\n# The BaseHTTPServer module has been merged into http.server in Python 3.\n# Every time you see BaseHTTPServer just use http.server\n# imports Server\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nimport cgi\n\n# Imports DB\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Restaurant, MenuItem\n\n# TODO: Make a connection to DB\n# Retrive the data\n# loop through restaurant list\n\n# Handler\n# class ClassName(ParentClass) == class ClassName extends ParentClass\n\n################ Create Connection to DB ################\n# init connection with DB\nengine = create_engine('sqlite:///restaurantmenu.db')\n\n# Connection between class def and corresp table in DB\nBase.metadata.bind = engine\n# Create delete and other commands Alchemy does via an interface called a Session\nDBSession = sessionmaker(bind=engine)\n\nsession = DBSession()\n\nclass webserverHandler(BaseHTTPRequestHandler):\n\n################ Data Base functions ################\n\n def getListOfRestaurants(self):\n return session.query(Restaurant).all()\n\n def addRestaurant(self, name):\n # Adds new restaurant to DB\n # Does not do any checks yet\n restaurant = Restaurant(name = name)\n session.add(restaurant)\n session.commit()\n\n def deleteRestaurant(self, id):\n # Delete a restaurant from DB\n # Does not do any checks\n restaurant = session.query(Restaurant).filter_by(id = id).one()\n session.delete(restaurant)\n session.commit()\n print(\"L51 %d, Restaurant %s deleted\" %(restaurant.id, restaurant.name))\n\n def updateRestaurant(self, restaurant, newName):\n # Update Restaurant name DB\n # Does not do any checks\n\n # self.getRestaurant(id)\n print(\"Old name = %s \" % restaurant.name)\n restaurant.name = newName\n print(\"New name = %s \" % restaurant.name)\n session.add(restaurant)\n session.commit()\n\n def getRestaurant(self, id):\n restaurant = session.query(Restaurant).filter_by(id=id).first()\n print(\"L67 getRestaurant() id = %d, restaurant.id = %d, restaurant.name = %s\" % (id, restaurant.id, restaurant.name))\n return restaurant\n\n ################ HTML FORMS ################\n def form_create(self):\n # Creates new Restaurant in DB\n output = '''\n
\n HOME\n
\n

Create new restaurant

\n \n \n \n
\n
\n '''\n return output\n\n def form_edit(self, name, id):\n output = '''\n
\n HOME\n

Edit restaurant name

\n
\n

{name}

\n \n \n \n
\n
\n '''\n return output.format(id=id, name=name)\n\n def form_delete(self, id, name):\n output = '''\n
\n HOME\n
\n

Please confirm permanent delition of

\n

{name} restaurant from our database.

\n

WARNING!!! Delition is permanent.

\n \n
\n
\n '''\n return output.format(id=id, name=name)\n\n def restaurant_div(self, name, id):\n output = '''\n
\n

{name}

\n EDIT\n DELETE\n
\n '''\n return output.format(name=name, id=id)\n\n ################ SERVER RESPONCES ################\n\n def do_GET(self):\n # GET method provides path variable\n # List all restaurants in DB\n try:\n if self.path.endswith(\"/restaurants\"):\n self.send_response(200)\n self.send_header('Content-type', 'text/html; charset=utf-8')\n self.end_headers()\n\n restaurants = self.getListOfRestaurants()\n\n output = \"\"\n output += \"CREATE NEW\"\n output += \"
    \"\n for restaurant in restaurants:\n output += \"
  • \"\n output += self.restaurant_div(restaurant.name, restaurant.id) \n output += \"
  • \"\n output += \"
\"\n output += \"\" \n\n self.wfile.write(output.encode())\n return\n\n if self.path.endswith(\"/edit\"):\n restaurantIdPath = self.path.split('/')[2]\n\n restaurant = self.getRestaurant(int(restaurantIdPath))\n\n # Edit restaurant name\n self.send_response(200)\n self.send_header('Content-type', 'text/html; charset=utf-8')\n self.end_headers()\n\n output = \"\" \\\n \"\" + self.form_edit(restaurant.name, restaurant.id) + \\\n \"\"\n self.wfile.write(output.encode())\n return\n\n if self.path.endswith(\"/delete\"):\n\n restaurantIdPath = self.path.split('/')[2]\n restaurant = self.getRestaurant(int(restaurantIdPath))\n\n # Confirm deletion page\n self.send_response(200)\n self.send_header('Content-type', 'text/html; charset=utf-8')\n self.end_headers()\n\n output = \"\" \\\n \"\" + self.form_delete(restaurant.id, restaurant.name) + \\\n \"\"\n self.wfile.write(output.encode())\n return\n\n if self.path.endswith(\"/restaurants/new\"):\n # Edit restaurant name\n self.send_response(200)\n self.send_header('Content-type', 'text/html; charset=utf-8')\n self.end_headers()\n\n output = \"\" \\\n \"\" + self.form_create() + \\\n \"\"\n self.wfile.write(output.encode())\n return\n\n except IOError:\n self.send_error(404, \"File not found %s\" % self.path)\n\n def do_POST(self):\n try:\n # HEADERS are now in dict/json style container\n ctype, pdict = cgi.parse_header(\n self.headers['content-type'])\n\n # boundary data needs to be encoded in a binary format\n pdict['boundary'] = bytes(pdict['boundary'], \"utf-8\")\n\n\n if self.path.endswith(\"/restaurants/new\"):\n\n if ctype == 'multipart/form-data':\n fields = cgi.parse_multipart(self.rfile, pdict)\n messagecontent = fields.get('newRestaurantName')\n\n # Add new restaurant to DB\n self.addRestaurant(messagecontent[0].decode())\n\n # Send responce to the client\n self.send_response(301)\n self.send_header('Content-type', 'text/html; charset=utf-8')\n # Location - redirects page to whatever you set to.\n self.send_header('Location', '/restaurants')\n self.end_headers()\n return\n\n if self.path.endswith(\"/delete\"):\n restaurantIdPath = self.path.split('/')[2]\n\n id = int(restaurantIdPath)\n\n # Add new restaurant to DB\n self.deleteRestaurant(id)\n\n # Send responce to the client\n self.send_response(301)\n self.send_header('Content-type', 'text/html; charset=utf-8')\n # Location - redirects page to whatever you set to.\n self.send_header('Location', '/restaurants')\n self.end_headers()\n return\n\n if self.path.endswith(\"/edit\"):\n restaurantIdPath = self.path.split('/')[2]\n\n restaurant = self.getRestaurant(int(restaurantIdPath))\n\n if ctype == 'multipart/form-data':\n fields = cgi.parse_multipart(self.rfile, pdict)\n newName = fields.get('editRestaurantName')\n\n # Add new restaurant to DB\n self.updateRestaurant(restaurant, newName[0].decode())\n\n # Send responce to the client\n self.send_response(301)\n self.send_header('Content-type', 'text/html; charset=utf-8')\n self.send_header('Location', '/restaurants')\n self.end_headers()\n return\n \n except :\n print(\"Exception thrown...\")\n raise\n \n\n############# end class \n\n# Main\n# It is added at the end of the file so python interpreter\n# can immediatly run it as it translates the script\ndef main():\n try:\n port = 8080\n server = HTTPServer(('', port), webserverHandler)\n print (\"Web server running on port %s\" % port)\n server.serve_forever()\n\n except KeyboardInterrupt:\n # Build in interupt inot python exits when user\n # holds ctrl+C. So no additional code needed\n print(\"^C entered, stopping web server...\")\n server.socket.close()\n\nif __name__ == '__main__':\n main()","sub_path":"vagrant/menu/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":10061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"257176189","text":"import bisect\n\n\nclass Array(object):\n\n def __init__(self, A):\n self.__A = sorted(A)\n\n def index(self, x):\n\n i = bisect.bisect_left(self.__A, x)\n if i != len(self.__A) and x == self.__A[i]:\n return i\n raise ValueError\n\n def find_lt(self, x):\n 'Find rightmost value less than x'\n i = bisect.bisect_left(self.__A, x)\n if i > 0:\n return self.__A[i-1]\n # raise ValueError\n return None\n\n def find_le(self, x):\n 'Find the rightmost value less than or equal to x'\n i = bisect.bisect_right(self.__A, x)\n if i:\n return self.__A[i-1]\n # raise ValueError\n return None\n\n def find_gt(self, x):\n 'Find leftmost value greater than x'\n i = bisect.bisect(self.__A, x)\n if i != len(self.__A):\n return self.__A[i]\n # raise ValueError\n return None\n\n def find_ge(self, x):\n 'Find leftmost item greater than or equal to x'\n i = bisect.bisect(self.__A, x)\n if i != len(self.__A):\n return self.__A[i]\n # raise ValueError\n return None\n\ndef main():\n\n a = [1, 2, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8]\n\n # The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i])\n # for the left side and all(val >= x for val in a[i:hi]) for the right side.\n left = bisect.bisect_left(a, 4)\n print(bisect.bisect_left(a, 4)) # 3\n print(all(x < 4 for x in a[:left]))\n\n # The returned insertion point i partitions the array a into two halves so that all(val <= x for val in a[lo:i])\n # for the left side and all(val > x for val in a[i:hi]) for the right side.\n right = bisect.bisect(a, 4)\n print(bisect.bisect_right(a, 4)) # 8\n print(all(x > 4 for x in a[right+1:]))\n\n assert( all(x == 4 for x in a[left: right]))\n\n # Insert x in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x)\n # assuming that a is already sorted. Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.\n bisect.insort_left(a, 3)\n print(a)\n\n bisect.insort_right(a, 5)\n print(a)\n\n bisect.insort(a, 4)\n print(a)\n\n # Array\n a = Array([2, 4, 5, 6, 3, 7, 1, 9])\n\n print( a.find_lt(1))\n print( a.find_lt(100))\n\n print( a.find_le(4))\n\n print( a.find_gt(4))\n\n print( a.find_gt(9))\n print( a.find_gt(-1))\n\n\nif __name__ == \"__main__\":\n\n main()\n","sub_path":"Python35/PythonSyntax/collections/bisect_util.py","file_name":"bisect_util.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"501567630","text":"# #!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2021/1/6 11:13 上午\n# @Author : 百变金刚\n# @Content : 实现可参考 https://gine.me/posts/d00e0623063b4edf843d571850c39f95\nimport yaml\n\nclass Conf():\n def __init__(self, p_conf):\n with open(p_conf) as f:\n conf = yaml.safe_load(f)\n eval('self.')\n # 暂时放弃,yaml的类型有些多,尚无法想到比较合理的方案,挂入计划","sub_path":"tools/configfile/Yamlyl/Conf.py","file_name":"Conf.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"492770699","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login\nfrom .models import Video\nfrom django.core.paginator import Paginator\nfrom .tmdb_search import TmdbSearch\n\n# Create your views here.\ndef home_page(request):\n if request.user.is_authenticated:\n queryset_list = Video.objects.all()\n query = request.GET.get(\"title\")\n if query:\n queryset_list = queryset_list.filter(title__contains=query)\n\n paginator = Paginator(queryset_list, 25)\n page = request.GET.get(\"page\")\n queryset = paginator.get_page(page) \n stuff_for_frontend = {\"search_result\": queryset}\n return render(request, 'index.html', stuff_for_frontend)\n else:\n return HttpResponseRedirect('accounts/login/')\n\ndef video_detail_view(request, id=None):\n video= get_object_or_404(Video, id=id)\n if (video.tmdb_updated == False):\n TmdbSearch().search_movie(video)\n context= {'video': video,}\n return render(request, 'video_detail.html', context)\n\n\n","sub_path":"video_library/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"278322849","text":"import numpy as np\nimport csv\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import ConstantKernel, RBF, WhiteKernel, DotProduct\nfrom sklearn.preprocessing import StandardScaler\n\n# ndata = 10\n\ncsv_file = open(\"./h2o_2d_1000.csv\", \"r\")\nreader = csv.reader(csv_file)\nreader_np = np.array(list(reader))\n\ny = np.atleast_2d(reader_np[1:,1]).T.astype(np.float32) # energy\nX = reader_np[1:,2:].astype(np.float32) # distance\n# print (X)\n# print (y)\n\nscaler_y = StandardScaler().fit(y) \n\nkernel = ConstantKernel() * RBF() + WhiteKernel() \ngpr = GaussianProcessRegressor(kernel=kernel, alpha=0) \ngpr.fit(X, scaler_y.transform(y))\n# print(gpr.kernel_)\n\ngridnum = 100;\nxlim = [0,5]\nylim = [0,5]\nx = np.arange(xlim[0], xlim[1], (xlim[1]-xlim[0])/gridnum)\ny = np.arange(ylim[0], ylim[1], (ylim[1]-ylim[0])/gridnum)\nplot_X, plot_Y = np.meshgrid(x,y)\n\nplot_XY = np.array([plot_X.ravel(), plot_Y.ravel()]).T\n# print (plot_X)\n# print (plot_Y)\n# print (plot_XY)\n\npred_mu, pred_sigma = gpr.predict(plot_XY, return_std=True) # posterior average\npred_mu = scaler_y.inverse_transform(pred_mu)\npred_sigma = pred_sigma.reshape(-1, 1) * scaler_y.scale_\n# print (pred_mu, pred_sigma)\n\n# print (plot_XY[:,0])\n# print (plot_XY[:,1])\n# print (plot_XY)\n# print (pred_mu)\n\n# For plot\nfig = plt.figure(figsize=(8, 6))\nplt.xlabel('$x0$', fontsize=16)\nplt.ylabel('$x1$', fontsize=16)\n# plt.xlim(xlim)\n# plt.ylim(ylim)\nplt.tick_params(labelsize=16)\n\n# For contour plot\n# \"\"\"\nplt.plot(X[:,0], X[:,1], 'r.', markersize=3)\nplt.contourf(plot_X, plot_Y, pred_mu.reshape(gridnum, -1))\nplt.colorbar()\n# \"\"\"\n\n# For surface plot\n\"\"\"\nax = fig.add_subplot(111, projection='3d')\nsurf = ax.plot_surface(plot_X, plot_Y, pred_mu.reshape(gridnum, -1), cmap='bwr', linewidth=0)\n\"\"\"\n\nplt.show()","sub_path":"gpr_py/gpr_2dpes.py","file_name":"gpr_2dpes.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"336229769","text":"#!/usr/bin/python3.2\n# -*- coding: utf-8 -*-\n\n# Differents auth level:\n# * master\n# * admin\n# * known\n\nfrom functions_core import Function\nimport hashlib\nfrom auth_core import uparser, loggedin, LoggedIn, getinfos, require\nfrom core import server_config, write_config, format\n\n\n@Function('auth', requestserv=True)\ndef auth(args, source, target, serv):\n # args should be (username, password)\n if args is None or len(args) < 2:\n serv.notice(source.nick, 'usage: AUTH username password')\n return\n if args[0] not in uparser.sections():\n serv.notice(source.nick, 'unknown user')\n return\n if hashlib.sha1(' '.join(args[1:]).strip().encode()).hexdigest() != uparser[args[0]]['password']:\n serv.notice(source.nick, 'invalid password')\n return\n for user in loggedin:\n if user.host == source:\n serv.notice(source.nick, 'you\\'re already logged in')\n return\n loggedin.append(LoggedIn(args[0], source))\n serv.notice(source.nick, 'you\\'re now logged in')\n\n\n@Function('whoami')\ndef whoami(args, source, target):\n ret = getinfos(source)\n if ret is None and source.nick.lower() == 'sarah':\n return 'you\\'re the most beautiful one'\n #TODO: to remove one day\n if ret is None:\n return 'you\\'re nobody'\n return 'you\\'re {0} ({1})'.format(ret['uname'], ret['level'])\n\n@Function('say', requestserv=True, authlvl='known')\ndef say(args, source, target, serv):\n # args should be (chan, text)\n if args is None or len(args) < 2:\n serv.notice(source.nick, 'args should be (chan, text)')\n return\n serv.privmsg(args[0], ' '.join(args[1:]))\n\n@Function('act', requestserv=True, authlvl='known')\ndef act(args, source, target, serv):\n # args should be (chan, text)\n if args is None or len(args) < 2:\n serv.notice(source.nick, 'args should be (chan, text)')\n return\n serv.action(args[0], ' '.join(args[1:]))\n\n@Function('nick', requestserv=True, authlvl='master')\ndef nick(args, source, target, serv):\n if args is None or len(args) != 1:\n serv.notice(source.nick, 'args should be newnickname')\n return\n serv.nick(args[0])\n\n@Function('join', requestserv=True, authlvl='admin')\ndef join(args, source, target, serv):\n if args is None or len(args) != 1:\n serv.notice(source.nick, 'args should be channel')\n return\n serv.join(args[0])\n\n@Function('part', requestserv=True, authlvl='admin')\ndef part(args, source, target, serv):\n if target[0] == '#':\n if args is None:\n serv.part(target, 'bye')\n elif len(args) == 1 and args[0][0] == '#':\n serv.part(args[0], 'bye')\n elif len(args) == 1 and args[0][0] != '#':\n serv.part(target, args[0])\n elif len(args) > 1 and args[0][0] == '#':\n serv.part(args[0], ' '.join(args[1:]))\n elif len(args) > 1 and args[0][0] != '#':\n serv.part(target, ' '.join(args))\n else:\n if args is None:\n serv.notice(target, 'invalid syntax')\n return\n elif len(args) == 1 and args[0][0] == '#':\n serv.part(args[0], 'bye')\n elif len(args) > 1 and args[0][0] == '#':\n serv.part(args[0], ' '.join(args[1:]))\n else:\n serv.notice(source.nick, 'invalid syntax')\n return\n\n@Function('die', requestserv=True, authlvl='master')\ndef die(args, source, target, serv):\n if args is None:\n serv.quit('bye')\n quit(0)\n else:\n serv.quit(' '.join(args))\n quit(0)\n\n@Function('notice', requestserv=True, authlvl='known')\ndef notice(args, source, target, serv):\n if args is None or len(args) < 2:\n serv.notice(source.nick, 'args should be (target, text)')\n return\n else:\n serv.notice(args[0], ' '.join(args[1:]))\n\n@Function('throttle', authlvl='admin')\ndef throttle(args, source, target):\n if args is not None:\n if ''.join(args).isdigit():\n server_config['details']['throttle'] = ''.join(args)\n return 'throttle set to {0}'.format(''.join(args))\n else:\n return 'usage: THROTTLE time'\n else:\n return 'throttle actually set to {0}'.format(server_config['details']['throttle'])\n\n\n@Function('saveconfig', requestchans=True, requestserv=True, authlvl='master')\ndef saveconfig(args, source, target, serv, channels):\n chans = ','.join(channels.keys())\n server_config['details']['channels'] = chans\n server_config['details']['nickname'] = serv.get_nickname()\n write_config()\n return 'config writed successfully. {0}channels{1}: {2}; {0}nickname{1}: {3}; {0}throttle{1}: {4}'.format(format['bold'],\n format['reset'],\n chans,\n serv.get_nickname(),\n serv['details']['throttle'])\n","sub_path":"admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"109985675","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport time\n\n# Para usar o vídeo\n#cap = cv2.VideoCapture('hall_box_battery_mp2.mp4')\n\n# As 3 próximas linhas são para usar a webcam\nsoma=0\nz=0\ncap = cv2.VideoCapture(0)\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n\ndef distance_to_camera(knownWidth, focalLength, perWidth):\n # compute and return the distance from the maker to the camera\n return (knownWidth * focalLength) / perWidth\ndef identifica_cor(frame):\n '''\n Segmenta o maior objeto cuja cor é parecida com cor_h (HUE da cor, no espaço HSV).\n '''\n \n # No OpenCV, o canal H vai de 0 até 179, logo cores similares ao \n # vermelho puro (H=0) estão entre H=-8 e H=8. \n # Veja se este intervalo de cores está bom\n frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n\n# cor_menor = np.array([100, 30, 50])\n# cor_maior = np.array([200, 200, 200])\n cor_menor = np.array([4, 50, 120])\n cor_maior = np.array([8, 255, 255])\n segmentado_cor = cv2.inRange(frame_hsv, cor_menor, cor_maior)\n kernel = np.ones((5,5),np.uint8)\n # segmentado_cor=cv2.morphologyEx(segmentado_cor, cv2.MORPH_OPEN, kernel)\n \n \n # x,y,w,h = cv2.boundingRect(cnt)\n # 2 cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)\n segmentado_cor=cv2.erode(segmentado_cor,kernel,iterations = 1)\n \n segmentado_cor = cv2.dilate(segmentado_cor,kernel,iterations = 1)\n segmentado_cor = cv2.morphologyEx(segmentado_cor, cv2.MORPH_OPEN, kernel)\n # Será possível limpar a imagem segmentado_cor? \n # Pesquise: https://docs.opencv.org/trunk/d9/d61/tutorial_py_morphological_ops.html\n\n\n # Encontramos os contornos na máscara e selecionamos o de maior área\n img_out, contornos, arvore = cv2.findContours(segmentado_cor.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) \n maior_contorno = None\n maior_contorno_area = 0\n global z\n global soma\n\n cv2.drawContours(frame, contornos, -1, (100, 100, 100), 5)\n\n\n for cnt in contornos:\n area = cv2.contourArea(cnt)\n\n\n if area > maior_contorno_area:\n maior_contorno = cnt\n maior_contorno_area = area\n #print(maior_contorno[0][0][1])\n \n auxmenor_i=0\n auxmaior_i=100000\n\n aux_maior=0\n aux_menor=1000000\n\n if not maior_contorno is None:\n for i in range(len(maior_contorno)):\n if maior_contorno[i][0][1]>aux_maior:\n aux_maior=maior_contorno[i][0][1]\n auxmaior_i=i\n\n if maior_contorno[i][0][1] self.parameters['min_perch_time']:\n return True\n ## if time is not up, continue the loop\n else:\n continue\n ## if current perch is no longer broken, record perch end time, give a grace period\n else:\n self.current_visit.perch_end = dt.datetime.now()\n ## if there is no grace_tokens left, immediately terminate visit\n if grace_tokens <= 0:\n self.log.debug(\"Perching not valid. Out of grace tokens.\")\n return False\n\n ## while the current perch is unperched,\n while (self.current_perch[\"IR\"].status() == False):\n ## if the grace period has ended\n grace_period = (dt.datetime.now() - self.current_visit.perch_end).total_seconds()\n if grace_period > self.parameters['perch_grace_period']:\n self.log.debug(\"Perching not valid. Exceed grace period.\")\n return False\n else:\n grace_tokens = grace_tokens - 1\n continue\n\n def validate_deperching(self):\n \"\"\"\n For any deperching behavior to be valid,\n the IR needs to be unbroken for at least one second.\n \"\"\"\n grace_tokens = self.parameters['grace_num']\n\n while True:\n ## keep asking if the current perch is still broken\n if (self.current_perch['IR'].status() == True):\n ## if the IR is still broken, no deperch\n return False\n ## if the current perch is no longer broken, record perch_end time, and give a grace period\n else:\n self.current_visit.perch_end = dt.datetime.now()\n ## if there is no grace_tokens left, immediately terminate visit\n if grace_tokens <= 0:\n self.log.debug(\"Perching Unstable. Out of grace tokens.\")\n return True\n\n ## while the current perch is unperched,\n while (self.current_perch['IR'].status() == False):\n ## if the grace period has ended, bird has deperched\n grace_period = (dt.datetime.now() - self.current_visit.perch_end).total_seconds()\n if grace_period > self.parameters['perch_grace_period']:\n self.log.debug(\"Subject Deperched. Exceed grace period.\")\n return True\n else:\n grace_tokens = grace_tokens - 1\n continue\n\n\n\n def switch_speaker(self):\n \"\"\"\n Use serial communication with the connected Arduino to switch\n \"\"\"\n self.log.debug(\"Switching speaker relay to %s\" % self.current_perch['speaker'])\n self.arduino.write(str(self.current_perch['speaker'] + 1).encode('utf-8'))\n\n def stimulus_shuffle(self):\n \"\"\"\n While perched, shuffle stimuli from a library\n \"\"\"\n\n ## if the current class is silence, don't do shit\n if self.current_visit.class_ == \"S\":\n self.log.debug(\"Silence Perching\")\n while True:\n if self.validate_deperching() == True:\n return\n ## if the current class is not silence, prep and play stimuli\n else:\n self.prep_stimuli()\n self.play_stimuli()\n\n while True:\n ## if deperching has been detected, or light schedule expires, quit this function\n if (self.validate_deperching() == True or self.check_session_schedule() == False):\n if self.check_session_schedule() == False:\n self.current_visit.perch_end = dt.datetime.now()\n self.stop_stimuli()\n return\n ## else, play audio until its length runs out,\n else:\n elapsed_time = (dt.datetime.now() - self.stimulus_event.time).total_seconds()\n if elapsed_time < self.stimulus_event.duration:\n continue\n # when it does, give an inter_stim_interval, and recurse on the function\n else:\n if elapsed_time < (self.stimulus_event.duration + self.parameters['inter_stim_interval']):\n continue\n ## when inter_stim_interval runs out, stop stimuli and go back to the stimulus_shuffle\n else:\n self.log.debug(\"Stimuli finished and inter_stim_interval has passed. \")\n self.stop_stimuli()\n ## find another clip to play\n self.prep_stimuli()\n self.play_stimuli()\n\n def perch_playlist(self):\n \"\"\"\n depending on the perch and the perch_sequence, find the correct list\n \"\"\"\n if self.current_perch_stim_class() == \"A\":\n self.log.debug(\"Perch stim class A\")\n return self.parameters['stims_A']\n if self.current_perch_stim_class() == \"B\":\n self.log.debug(\"Perch stim class B\")\n return self.parameters['stims_B']\n\n def prep_stimuli(self):\n \"\"\"\n Prep stimuli and generate a stimulus event\n \"\"\"\n ## randomly shuffle from the current perch_playlist\n stim_file = random.sample(self.perch_playlist().items(), k = 1)[0][1]\n self.log.debug(stim_file)\n stim = utils.auditory_stim_from_wav(stim_file)\n\n self.stimulus_event = utils.Event(\n time = dt.datetime.now(),\n duration = stim.duration,\n file_origin = stim.file_origin,\n )\n\n self.log.debug(\"Queuing stimulus %s\" % stim.file_origin)\n self.panel.speaker.queue(self.stimulus_event.file_origin)\n\n def play_stimuli(self):\n \"\"\"\n Play stimuli through current_perch speaker\n \"\"\"\n\n self.log.debug(\"Playing %s\" % (self.stimulus_event.file_origin))\n ## trigger speaker\n self.panel.speaker.play()\n\n def stop_stimuli(self):\n \"\"\"\n Stop stimuli, record event, and clear out event\n \"\"\"\n self.log.debug(\"Stop stimuli and flush stimulus event.\")\n self.panel.speaker.stop()\n self.current_visit.stimuli.append(self.stimulus_event.file_origin)\n self.current_visit.events.append(self.stimulus_event)\n self.stimulus_event = None\n\n def end_visit(self):\n \"\"\"\n End visit and write data of current visit to csv\n \"\"\"\n self.log.debug(\"Ending visit and record end time.\")\n self.current_visit.perch_dur = (self.current_visit.perch_end - self.current_visit.perch_strt).total_seconds()\n self.current_visit.valid = (self.current_visit.perch_dur >= self.parameters['min_perch_time'])\n self.save_visit(self.current_visit)\n\n def save_visit(self, visit):\n \"\"\"\n write visit results to CSV\n \"\"\"\n\n self.log.debug(\"Writing data to %s\" % (self.data_csv))\n visit_dict = {}\n for field in self.fields_to_save:\n try:\n visit_dict[field] = getattr(visit,field)\n except AttributeError:\n visit_dict[field] = visit.annotations[field] ## it might be in annotations for some reason\n\n with open(self.data_csv, 'ab') as data_fh:\n visitWriter = csv.DictWriter(data_fh, fieldnames = self.fields_to_save, extrasaction = 'ignore')\n visitWriter.writerow(visit_dict)\n\n def reset_perches(self):\n \"\"\"\n Reset perches\n \"\"\"\n\n self.current_perch = {'IR': None, 'IRName': None, 'speaker': None}\n self.stimulus_event = None\n self.current_visit = None\n\n def check_session_schedule(self):\n \"\"\"\n Check if perches should be open\n\n returns\n -------\n bool\n True, if sessions should be running\n \"\"\"\n return utils.check_time(self.parameters['light_schedule'])\n\n def session_main(self):\n \"\"\"\n Inside session_main, maintain a loop that controls paradigm behavior\n \"\"\"\n\n while True:\n\n '''\n Try to open all perches. The program loops in open_all_perches\n until a valid perching has been detected.\n '''\n self.open_all_perches()\n\n ## check if time of day is appropriate for a trial to commence\n if self.check_session_schedule() == False:\n return \"post\"\n\n '''\n Once perching has been detected, switch speaker to the current\n perch, and start stimuli shuffle. The program loops in stimulus_shuffle()\n until a valid deperching has been detected()\n '''\n if (self.current_perch['IR'] != None):\n if (self.current_perch['IR'].status() == True):\n self.switch_speaker()\n self.stimulus_shuffle()\n\n '''\n Once deperched, end visit and reset\n '''\n self.end_visit()\n self.reset_perches()\n\n ## check if time of day is appropriate for a trial to commence\n if self.check_session_schedule() == False:\n return \"post\"\n ##\n\n def session_post(self):\n self.log.info('Paradigm is closed. Proceed to Sleep. ')\n return None\n","sub_path":"pyoperant/behavior/place_pref.py","file_name":"place_pref.py","file_ext":"py","file_size_in_byte":16606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"612371213","text":"\"\"\"\n1. Break/return from the recursion\n2. Search element in a Tree\n\"\"\"\n\nclass Node(object):\n def __init__(self, data):\n id, price, name = self.parseNodeData(data)\n self.id = int(id)\n self.price = int(price)\n self.name = name\n self.parent = None\n self.children = []\n def __repr__(self):\n return 'Name - {0}'.format(self.name)\n def addNodeToTree(self, newNode):\n newNode.parent = self\n self.children.append(newNode)\n def addNodesToTree(self, newNodes):\n for n in newNodes:\n n.parent = self\n self.children.extend(newNodes)\n def printTreeFromNode(self, indenter):\n print(indenter+self.name) \n for each in self.children:\n each.printTreeFromNode(indenter+indenter)\n def deleteNodeOrSubTree(self, idToBeDeleted):\n if (self.id == idToBeDeleted):\n self.parent.children.remove(self)\n else:\n for each in self.children:\n each.deleteNodeOrSubTree(idToBeDeleted)\n def deleteNodeOrSubTree_v1(self, idToBeDeleted):\n if (self.id == idToBeDeleted):\n self.parent.children.remove(self)\n elif (len(self.children) != 0):\n for each in self.children:\n each.deleteNodeOrSubTree(idToBeDeleted)\n else:\n print('Product with ID - {0} not found'.format(idToBeDeleted))\n return False\n def checkNodeDiscount(self, id, discount):\n if (self.id == id):\n if (self.price > discount):\n print('Discount applied on ID - {}'.format(self.id))\n else:\n print('Discount cannot be applied on ID - {}'.format(self.id))\n else:\n for each in self.children:\n each.checkNodeDiscount(id, discount)\n def searchNodeInTreeOrSubTree(self, idToBeSearched):\n if (self.id == idToBeSearched):\n print('Node ID - {} found'.format(self.id))\n else:\n for each in self.children:\n each.searchNodeInTreeOrSubTree(idToBeSearched)\n @staticmethod\n def parseNodeData(data):\n dataArr = data.split(\" \")\n return dataArr[0],dataArr[1],dataArr[2]","sub_path":"python/CustomTreeDesign/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"645654583","text":"\"\"\"\n53. Maximum Subarray\nEasy\n\n4334\n\n145\n\nFavorite\n\nShare\nGiven an integer array nums, find the contiguous subarray (containing at least one number) which has the largest\nsum and return its sum.\n\nExample:\n\nInput: [-2,1,-3,4,-1,2,1,-5,4],\nOutput: 6\nExplanation: [4,-1,2,1] has the largest sum = 6.\nFollow up:\n\nIf you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, \nwhich is more subtle.\n\"\"\"\ndef max_sub_array(nums):\n\tmax_n = min(nums)\n\tsum_n = 0\n\tfor i in nums:\n\t\tif sum_n < 0:\n\t\t\tsum_n = i\n\t\telse:\n\t\t\tsum_n += i\n\t\tif sum_n > max_n:\n\t\t\tmax_n = sum_n\n\treturn max_n\n\n\"\"\"\ni \tsum_n\tmax_n\n-\t0\t\t-5\n-2\t-2\t\t-2\n1\t1\t\t1\n-3\t-2\t\t1\n4\t4\t\t4\n-1\t3\t\t4\n2\t5\t\t5\n1\t6\t\t6\n-5\t-5\t\t6\n4\t4\t\t6\n\"\"\"\n\nprint(max_sub_array([-2,1,-3,4,-1,2,1,-5,4]))\n\n\"\"\"\nUsing Divide and Conquer approach, we can find the maximum subarray sum in O(nLogn) time. Following is the Divide and \nConquer algorithm.\n\n\"\"\"\n\n# A Divide and Conquer based program \n# for maximum subarray sum problem \n \n# Find the maximum possible sum in \n# arr[] auch that arr[m] is part of it \ndef maxCrossingSum(arr, l, m, h) : \n \n # Include elements on left of mid. \n sm = 0; left_sum = -10000\n \n for i in range(m, l-1, -1) : \n sm = sm + arr[i] \n \n if (sm > left_sum) : \n left_sum = sm \n \n \n # Include elements on right of mid \n sm = 0; right_sum = -1000\n for i in range(m + 1, h + 1) : \n sm = sm + arr[i] \n \n if (sm > right_sum) : \n right_sum = sm \n \n \n # Return sum of elements on left and right of mid \n return left_sum + right_sum; \n\n \n# Returns sum of maxium sum subarray in aa[l..h] \ndef maxSubArraySum(arr, l, h) : \n \n # Base Case: Only one element \n if (l == h) : \n return arr[l] \n \n # Find middle point \n m = (l + h) // 2\n \n # Return maximum of following three possible cases \n # a) Maximum subarray sum in left half \n # b) Maximum subarray sum in right half \n # c) Maximum subarray sum such that the \n # subarray crosses the midpoint \n return max(maxSubArraySum(arr, l, m), \n maxSubArraySum(arr, m+1, h), \n maxCrossingSum(arr, l, m, h)) \n \n \n# Driver Code \narr = [2, 3, 4, 5, 7] \nn = len(arr) \n \nmax_sum = maxSubArraySum(arr, 0, n-1) \nprint(\"Maximum contiguous sum is \", max_sum)","sub_path":"fb/max_subarray_continues.py","file_name":"max_subarray_continues.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"224065633","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\ntiramisu_brulee.experiment.seg\n\nTraining and prediction logic for segmentation\n(usually lesion segmentation). Also, an\nimplementation of the Tiramisu network with\nthe training and prediction logic built-in.\n\nAuthor: Jacob Reinhold (jcreinhold@gmail.com)\nCreated on: May 14, 2021\n\"\"\"\n\n__all__ = [\n \"LesionSegLightningBase\",\n \"LesionSegLightningTiramisu\",\n]\n\nfrom functools import partial\nimport logging\nfrom typing import List, Optional, Tuple\n\nimport nibabel as nib\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nfrom torch import nn\nfrom torch import Tensor\nfrom torch.optim import AdamW, RMSprop, lr_scheduler\nimport torchio as tio\nimport SimpleITK as sitk\n\nfrom tiramisu_brulee.loss import (\n binary_combo_loss,\n combo_loss,\n l1_segmentation_loss,\n mse_segmentation_loss,\n)\nfrom tiramisu_brulee.model import Tiramisu2d, Tiramisu3d\nfrom tiramisu_brulee.util import init_weights\nfrom tiramisu_brulee.experiment.type import (\n ModelNum,\n nonnegative_float,\n nonnegative_int,\n ArgParser,\n positive_float,\n positive_int,\n probability_float,\n probability_float_or_none,\n)\nfrom tiramisu_brulee.experiment.data import Mixup\nfrom tiramisu_brulee.experiment.lesion_tools import (\n almost_isbi15_score,\n clean_segmentation,\n)\nfrom tiramisu_brulee.experiment.util import (\n append_num_to_filename,\n BoundingBox3D,\n minmax_scale_batch,\n)\n\n\nclass LesionSegLightningBase(pl.LightningModule):\n \"\"\"PyTorch-Lightning module for lesion segmentation\n\n Includes framework for both training and prediction,\n just drop in a PyTorch neural network module\n\n Args:\n network (nn.Module): PyTorch neural network\n n_epochs (int): number of epochs to train the network\n learning_rate (float): learning rate for the optimizer\n betas (Tuple[float, float]): momentum parameters for adam\n weight_decay (float): weight decay for optimizer\n loss_function (str): loss function to use in training\n focal_weight (Optional[float]): weight for positive class\n in focal loss if using combo loss function\n focal_gamma (float): gamma param for focal loss\n if using combo loss function (0. -> BCE)\n combo_weight (float): weight by which to balance focal and Dice\n losses in combo loss function\n decay_after (int): decay learning rate linearly after this many epochs\n rmsprop (bool): use rmsprop instead of adamw\n soft_labels (bool): use non-binary labels for training\n threshold (float): threshold by which to decide on positive class\n min_lesion_size (int): minimum lesion size in voxels in output prediction\n fill_holes (bool): use binary fill holes operation on label\n predict_probability (bool): save a probability image instead of a binary one\n mixup (bool): use mixup in training\n mixup_alpha (float): mixup parameter for beta distribution\n num_input (int): number of different images input to the network,\n differs from in_channels when using pseudo3d\n num_classes (int): number of different images output by the network\n differs from out_channels when using pseudo3d\n _model_num (ModelNum): internal param for ith of n models\n \"\"\"\n\n def __init__(\n self,\n network: nn.Module,\n n_epochs: int = 1,\n learning_rate: float = 1e-3,\n betas: Tuple[int, int] = (0.9, 0.99),\n weight_decay: float = 1e-7,\n loss_function: str = \"combo\",\n focal_weight: Optional[float] = None,\n focal_gamma: float = 0.0,\n combo_weight: float = 0.6,\n decay_after: int = 8,\n rmsprop: bool = False,\n soft_labels: bool = False,\n threshold: float = 0.5,\n min_lesion_size: int = 3,\n fill_holes: bool = True,\n predict_probability: bool = False,\n mixup: bool = False,\n mixup_alpha: float = 0.4,\n num_input: int = 1,\n num_classes: int = 1,\n _model_num: ModelNum = ModelNum(1, 1),\n **kwargs,\n ):\n super().__init__()\n self.network = network\n self._model_num = _model_num\n self.save_hyperparameters(ignore=[\"network\", \"_model_num\"])\n\n def forward(self, tensor: Tensor) -> Tensor:\n return self.network(tensor)\n\n def setup(self, stage: Optional[str] = None):\n if self.hparams.loss_function != \"combo\" and self.hparams.num_classes != 1:\n raise ValueError(\"Only combo loss supported for multi-class segmentation\")\n if self.hparams.loss_function == \"combo\":\n if self.hparams.num_classes == 1:\n self.criterion = partial(\n binary_combo_loss,\n focal_weight=self.hparams.focal_weight,\n focal_gamma=self.hparams.focal_gamma,\n combo_weight=self.hparams.combo_weight,\n )\n elif self.hparams.num_classes > 1:\n self.criterion = partial(\n combo_loss,\n num_classes=self.hparams.num_classes,\n combo_weight=self.hparams.combo_weight,\n )\n else:\n msg = f\"num_classes must be greater than zero. Got {self.num_classes}.\"\n raise ValueError(msg)\n elif self.hparams.loss_function == \"mse\":\n self.criterion = mse_segmentation_loss\n elif self.hparams.loss_function == \"l1\":\n self.criterion = l1_segmentation_loss\n else:\n raise ValueError(f\"{self.hparams.loss_function} not supported.\")\n if self.hparams.mixup:\n self._mix = Mixup(self.hparams.mixup_alpha)\n\n def training_step(self, batch: Tuple[Tensor, Tensor], batch_idx: int) -> Tensor:\n src, tgt = batch\n if self.hparams.mixup:\n src, tgt = self._mix(src, tgt)\n pred = self(src)\n loss = self.criterion(pred, tgt)\n self.log(\"loss\", loss)\n return loss\n\n def validation_step(self, batch: Tuple[Tensor, Tensor], batch_idx: int) -> dict:\n src, tgt = batch\n pred = self(src)\n loss = self.criterion(pred, tgt)\n pred_seg = torch.sigmoid(pred) > self.hparams.threshold\n isbi15_score = almost_isbi15_score(pred_seg, tgt)\n self.log(\n \"val_loss\", loss, on_step=False, on_epoch=True, prog_bar=True,\n )\n self.log(\n \"val_isbi15_score\",\n isbi15_score,\n on_step=False,\n on_epoch=True,\n prog_bar=False,\n )\n if batch_idx == 0 and self._is_3d_image_batch(src):\n images = dict(truth=tgt, pred=pred, dim=3)\n for i in range(src.shape[1]):\n images[f\"input_channel_{i}\"] = src[:, i : i + 1, ...]\n elif batch_idx == 0 and self._is_2d_image_batch(src):\n images = dict(truth=tgt, pred=pred, dim=2)\n step = src.shape[1] // self.hparams.num_input\n start = step // 2\n end = src.shape[1]\n for i in range(start, end, step):\n images[f\"input_channel_{i}\"] = src[:, i : i + 1, ...]\n else:\n images = None\n return dict(val_loss=loss, images=images)\n\n def validation_epoch_end(self, outputs: list):\n self._log_images(outputs[0][\"images\"])\n\n def predict_step(\n self, batch: dict, batch_idx: int, dataloader_idx: Optional[int] = None\n ) -> Tensor:\n if self._predict_with_patches(batch):\n return self._predict_patch_image(batch)\n else:\n return self._predict_whole_image(batch)\n\n def on_predict_batch_end(\n self,\n pred_step_outputs: Tensor,\n batch: dict,\n batch_idx: int,\n dataloader_idx: int,\n ):\n if self._predict_with_patches(batch):\n self._predict_accumulate_patches(pred_step_outputs, batch)\n if (batch_idx + 1) == batch[\"total_batches\"]:\n self._predict_save_patch_image(batch)\n else:\n self._predict_save_whole_image(pred_step_outputs, batch)\n return batch\n\n def configure_optimizers(self):\n if self.hparams.rmsprop:\n momentum, alpha = self.hparams.betas\n optimizer = RMSprop(\n self.parameters(),\n lr=self.hparams.learning_rate,\n momentum=momentum,\n alpha=alpha,\n weight_decay=self.hparams.weight_decay,\n )\n else:\n optimizer = AdamW(\n self.parameters(),\n lr=self.hparams.learning_rate,\n betas=self.hparams.betas,\n weight_decay=self.hparams.weight_decay,\n )\n\n scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=self.decay_rule)\n return [optimizer], [scheduler]\n\n def decay_rule(self, epoch: int) -> float:\n numerator = max(0, epoch - self.hparams.decay_after)\n denominator = float(self.hparams.n_epochs + 1)\n lr = 1.0 - numerator / denominator\n return lr\n\n @staticmethod\n def _predict_with_patches(batch: dict) -> bool:\n return \"grid_obj\" in batch\n\n def _predict_whole_image(self, batch: dict) -> Tensor:\n src = batch[\"src\"]\n bbox = BoundingBox3D.from_batch(src, pad=0)\n batch[\"src\"] = bbox(src)\n pred_seg = self._predict_patch_image(batch)\n pred_seg = bbox.uncrop_batch(pred_seg)\n return pred_seg\n\n def _predict_patch_image(self, batch: dict) -> Tensor:\n src = batch[\"src\"]\n pred = self(src)\n if self.hparams.num_classes == 1:\n pred_seg = torch.sigmoid(pred)\n if not self.hparams.predict_probability:\n pred_seg = pred_seg > self.hparams.threshold\n else:\n pred_seg = torch.softmax(pred, dim=1)\n pred_seg = pred_seg.float()\n return pred_seg\n\n def _clean_prediction(self, pred: np.ndarray) -> List[np.ndarray]:\n assert pred.ndim == 3\n if not self.hparams.predict_probability:\n pred = clean_segmentation(pred)\n pred = pred.astype(np.float32)\n return pred\n\n def _predict_save_whole_image(self, pred_step_outputs: Tensor, batch: dict):\n assert len(pred_step_outputs) == len(batch[\"affine\"])\n assert len(batch[\"affine\"]) == len(batch[\"path\"])\n assert len(batch[\"path\"]) == len(batch[\"out\"])\n nifti_attrs = zip(\n pred_step_outputs.detach().cpu(),\n batch[\"affine\"],\n batch[\"path\"],\n batch[\"out\"],\n )\n for pred, affine, path, fn in nifti_attrs:\n if self._model_num != ModelNum(num=1, out_of=1):\n fn = append_num_to_filename(fn, self._model_num.num)\n logging.info(f\"Saving {fn}.\")\n pred, affine = self._to_original_orientation(path, pred, affine)\n pred = pred.numpy().squeeze()\n pred = self._clean_prediction(pred)\n nib.Nifti1Image(pred, affine).to_filename(fn)\n\n def _predict_save_patch_image(self, batch: dict):\n pred = self.aggregator.get_output_tensor().detach().cpu()\n affine = batch[\"affine\"][0]\n pred, affine = self._to_original_orientation(batch[\"path\"], pred, affine)\n pred = pred.numpy().squeeze()\n pred = self._clean_prediction(pred)\n fn = batch[\"out\"][0]\n if self._model_num != ModelNum(num=1, out_of=1):\n fn = append_num_to_filename(fn, self._model_num.num)\n logging.info(f\"Saving {fn}.\")\n nib.Nifti1Image(pred, affine).to_filename(fn)\n del self.aggregator\n\n @staticmethod\n def _to_original_orientation(\n original_path: str, data: Tensor, affine: Tensor,\n ) -> Tensor:\n original = tio.ScalarImage(original_path)\n image = tio.ScalarImage(tensor=data, affine=affine)\n if original.orientation != image.orientation:\n orientation = \"\".join(original.orientation)\n reoriented = sitk.DICOMOrient(image.as_sitk(), orientation)\n reoriented_data = sitk.GetArrayFromImage(reoriented).transpose()[np.newaxis]\n image = tio.ScalarImage(tensor=reoriented_data, affine=original.affine)\n return image.data, image.affine\n\n def _predict_accumulate_patches(self, pred_step_outputs: Tensor, batch: dict):\n p3d = batch[\"pseudo3d_dim\"]\n locations = batch[\"locations\"]\n if not hasattr(self, \"aggregator\"):\n self.aggregator = tio.GridAggregator(\n batch[\"grid_obj\"], overlap_mode=\"average\",\n )\n if p3d is not None:\n locations = self._fix_pseudo3d_locations(locations, p3d)\n pred_step_outputs.unsqueeze_(p3d + 2) # +2 to offset batch/channel dims\n self.aggregator.add_batch(pred_step_outputs, locations)\n\n @staticmethod\n def _fix_pseudo3d_locations(locations: Tensor, pseudo3d_dim: int) -> Tensor:\n \"\"\"Fix locations for aggregator when using pseudo3d\n\n locations were determined by the pseudo3d input, not the 1 channel target.\n this fixes the locations to use 1 channel corresponding to the pseudo3d dim.\n \"\"\"\n for n, location in enumerate(locations):\n i_ini, j_ini, k_ini, i_fin, j_fin, k_fin = location\n if pseudo3d_dim == 0:\n i = (i_fin - i_ini) // 2 + i_ini\n i_ini = i\n i_fin = i + 1\n elif pseudo3d_dim == 1:\n j = (j_fin - j_ini) // 2 + j_ini\n j_ini = j\n j_fin = j + 1\n elif pseudo3d_dim == 2:\n k = (k_fin - k_ini) // 2 + k_ini\n k_ini = k\n k_fin = k + 1\n else:\n raise ValueError(\n f\"pseudo3d_dim must be 0, 1, or 2. Got {pseudo3d_dim}.\"\n )\n locations[n, :] = torch.tensor(\n [i_ini, j_ini, k_ini, i_fin, j_fin, k_fin],\n dtype=locations.dtype,\n device=locations.device,\n )\n return locations\n\n def _log_images(self, images: dict):\n n = self.current_epoch\n mid_slice = None\n dim = images.pop(\"dim\")\n for key, image in images.items():\n if dim == 3:\n if mid_slice is None:\n mid_slice = image.shape[-1] // 2\n image_slice = image[..., mid_slice]\n elif dim == 2:\n image_slice = image\n else:\n raise ValueError(f\"Image dimension must be either 2 or 3. Got {dim}.\")\n if self.hparams.soft_labels and key == \"pred\":\n image_slice = torch.sigmoid(image_slice)\n elif key == \"pred\":\n if self.hparams.num_classes == 1:\n threshold = self.hparams.threshold\n image_slice = torch.sigmoid(image_slice) > threshold\n else:\n image_slice = torch.argmax(image_slice, 1, keepdim=True)\n elif key == \"truth\":\n image_slice = image_slice > 0.0\n else:\n image_slice = minmax_scale_batch(image_slice)\n self.logger.experiment.add_images(key, image_slice, n, dataformats=\"NCHW\")\n\n @staticmethod\n def _is_3d_image_batch(tensor: Tensor) -> bool:\n return tensor.ndim == 5\n\n @staticmethod\n def _is_2d_image_batch(tensor: Tensor) -> bool:\n return tensor.ndim == 4\n\n @staticmethod\n def add_io_arguments(parent_parser: ArgParser) -> ArgParser:\n parser = parent_parser.add_argument_group(\"I/O\")\n parser.add_argument(\n \"-ni\",\n \"--num-input\",\n type=positive_int(),\n default=1,\n help=\"number of input images (should match the number \"\n \"of non-label/other fields in the input csv)\",\n )\n parser.add_argument(\n \"-nc\",\n \"--num-classes\",\n type=positive_int(),\n default=1,\n help=\"number of classes to segment (1 for binary segmentation)\",\n )\n return parent_parser\n\n @staticmethod\n def add_training_arguments(parent_parser: ArgParser) -> ArgParser:\n parser = parent_parser.add_argument_group(\"Training\")\n parser.add_argument(\n \"-bt\",\n \"--betas\",\n type=positive_float(),\n default=[0.9, 0.99],\n nargs=2,\n help=\"AdamW momentum parameters (for RMSprop, momentum and alpha)\",\n )\n parser.add_argument(\n \"-cen\",\n \"--checkpoint-every-n-epochs\",\n type=positive_int(),\n default=1,\n help=\"save model weights (checkpoint) every n epochs\",\n )\n parser.add_argument(\n \"-fw\",\n \"--focal-weight\",\n type=probability_float_or_none(),\n default=None,\n help=\"weight of positive class in focal loss \"\n \"component of combo loss function (None -> equal)\",\n )\n parser.add_argument(\n \"-fg\",\n \"--focal-gamma\",\n type=nonnegative_float(),\n default=0.0,\n help=\"gamma parameter for focal loss component of combo loss\",\n )\n parser.add_argument(\n \"-cw\",\n \"--combo-weight\",\n type=probability_float(),\n default=0.6,\n help=\"weight of focal loss component in combo loss\",\n )\n parser.add_argument(\n \"-da\",\n \"--decay-after\",\n type=positive_int(),\n default=8,\n help=\"decay learning rate after this number of epochs\",\n )\n parser.add_argument(\n \"-lr\",\n \"--learning-rate\",\n type=positive_float(),\n default=3e-4,\n help=\"learning rate for the optimizer\",\n )\n parser.add_argument(\n \"-lf\",\n \"--loss-function\",\n type=str,\n default=\"combo\",\n choices=(\"combo\", \"l1\", \"mse\"),\n help=\"loss function to train the network\",\n )\n parser.add_argument(\n \"-ne\",\n \"--n-epochs\",\n type=positive_int(),\n default=64,\n help=\"number of epochs\",\n )\n parser.add_argument(\n \"-rp\",\n \"--rmsprop\",\n action=\"store_true\",\n default=False,\n help=\"use rmsprop instead of adam\",\n )\n parser.add_argument(\n \"-wd\",\n \"--weight-decay\",\n type=positive_float(),\n default=1e-5,\n help=\"weight decay parameter for adamw\",\n )\n parser.add_argument(\n \"-sl\",\n \"--soft-labels\",\n action=\"store_true\",\n default=False,\n help=\"use soft labels (i.e., non-binary labels) for training\",\n )\n return parent_parser\n\n @staticmethod\n def add_other_arguments(parent_parser: ArgParser) -> ArgParser:\n parser = parent_parser.add_argument_group(\"Other\")\n parser.add_argument(\n \"-th\",\n \"--threshold\",\n type=probability_float(),\n default=0.5,\n help=\"probability threshold for segmentation\",\n )\n return parent_parser\n\n @staticmethod\n def add_testing_arguments(parent_parser: ArgParser) -> ArgParser:\n parser = parent_parser.add_argument_group(\"Testing\")\n parser.add_argument(\n \"-mls\",\n \"--min-lesion-size\",\n type=nonnegative_int(),\n default=3,\n help=\"in testing, remove lesions smaller in voxels than this\",\n )\n parser.add_argument(\n \"-fh\",\n \"--fill-holes\",\n action=\"store_true\",\n default=False,\n help=\"in testing, preform binary hole filling\",\n )\n parser.add_argument(\n \"-pp\",\n \"--predict-probability\",\n action=\"store_true\",\n default=False,\n help=\"in testing, store the probability instead of the binary prediction\",\n )\n return parent_parser\n\n\nclass LesionSegLightningTiramisu(LesionSegLightningBase):\n \"\"\"3D Tiramisu-based PyTorch-Lightning module for lesion segmentation\n\n See Also:\n Jégou, Simon, et al. \"The one hundred layers tiramisu: Fully\n convolutional densenets for semantic segmentation.\" CVPR. 2017.\n\n Zhang, Huahong, et al. \"Multiple sclerosis lesion segmentation\n with Tiramisu and 2.5D stacked slices.\" International Conference\n on Medical Image Computing and Computer-Assisted Intervention.\n Springer, Cham, 2019.\n\n Args:\n network_dim (int): use a 2D or 3D convolutions\n in_channels (int): number of input channels\n num_classes (int): number of classes to segment with the network\n down_blocks (List[int]): number of layers in each block in down path\n up_blocks (List[int]): number of layers in each block in up path\n bottleneck_layers (int): number of layers in the bottleneck\n growth_rate (int): number of channels to grow by in each layer\n first_conv_out_channels (int): number of output channels in first conv\n dropout_rate (float): dropout rate/probability\n init_type (str): method to initialize the weights of network\n gain (float): gain parameter for initialization\n n_epochs (int): number of epochs to train the network\n learning_rate (float): learning rate for the optimizer\n betas (Tuple[float, float]): momentum parameters for adam\n weight_decay (float): weight decay for optimizer\n loss_function (str): loss function to use in training\n focal_weight (Optional[float]): weight for positive class\n in focal loss if using combo loss function\n focal_gamma (float): gamma param for focal loss\n if using combo loss function (0. -> BCE)\n combo_weight (float): weight by which to balance focal and Dice\n losses in combo loss function\n decay_after (int): decay learning rate linearly after this many epochs\n rmsprop (bool): use rmsprop instead of adamw\n soft_labels (bool): use non-binary labels for training\n threshold (float): threshold by which to decide on positive class\n min_lesion_size (int): minimum lesion size in voxels in output prediction\n fill_holes (bool): use binary fill holes operation on label\n predict_probability (bool): save a probability image instead of a binary one\n mixup (bool): use mixup in training\n mixup_alpha (float): mixup parameter for beta distribution\n num_input (int): number of different images input to the network,\n differs from in_channels when using pseudo3d\n _model_num (ModelNum): internal param for ith of n models\n \"\"\"\n\n def __init__(\n self,\n network_dim: int = 3,\n in_channels: int = 1,\n num_classes: int = 1,\n down_blocks: List[int] = (4, 4, 4, 4, 4),\n up_blocks: List[int] = (4, 4, 4, 4, 4),\n bottleneck_layers: int = 4,\n growth_rate: int = 16,\n first_conv_out_channels: int = 48,\n dropout_rate: float = 0.2,\n init_type: str = \"normal\",\n gain: float = 0.02,\n n_epochs: int = 1,\n learning_rate: float = 1e-3,\n betas: Tuple[int, int] = (0.9, 0.99),\n weight_decay: float = 1e-7,\n loss_function: str = \"combo\",\n focal_weight: Optional[float] = None,\n focal_gamma: float = 0.0,\n combo_weight: float = 0.6,\n decay_after: int = 8,\n rmsprop: bool = False,\n soft_labels: bool = False,\n threshold: float = 0.5,\n min_lesion_size: int = 3,\n fill_holes: bool = True,\n predict_probability: bool = False,\n mixup: bool = False,\n mixup_alpha: float = 0.4,\n num_input: int = 1,\n _model_num: ModelNum = ModelNum(1, 1),\n **kwargs,\n ):\n if network_dim == 2:\n network_class = Tiramisu2d\n elif network_dim == 3:\n network_class = Tiramisu3d\n else:\n raise ValueError(f\"Network dim. must be 2 or 3. Got {network_dim}.\")\n network = network_class(\n in_channels,\n num_classes,\n down_blocks,\n up_blocks,\n bottleneck_layers,\n growth_rate,\n first_conv_out_channels,\n dropout_rate,\n )\n init_weights(network, init_type, gain)\n super().__init__(\n network,\n n_epochs,\n learning_rate,\n betas,\n weight_decay,\n loss_function,\n focal_weight,\n focal_gamma,\n combo_weight,\n decay_after,\n rmsprop,\n soft_labels,\n threshold,\n min_lesion_size,\n fill_holes,\n predict_probability,\n mixup,\n mixup_alpha,\n num_input,\n num_classes,\n _model_num,\n **kwargs,\n )\n self.save_hyperparameters(ignore=\"_model_num\")\n\n @staticmethod\n def add_model_arguments(parent_parser: ArgParser) -> ArgParser:\n parser = parent_parser.add_argument_group(\"Model\")\n parser.add_argument(\n \"-ic\",\n \"--in-channels\",\n type=positive_int(),\n default=1,\n help=\"number of input channels\",\n )\n parser.add_argument(\n \"-oc\",\n \"--out-channels\",\n type=positive_int(),\n default=1,\n help=\"number of output channels\",\n )\n parser.add_argument(\n \"-dr\",\n \"--dropout-rate\",\n type=positive_float(),\n default=0.2,\n help=\"dropout rate/probability\",\n )\n parser.add_argument(\n \"-it\",\n \"--init-type\",\n type=str,\n default=\"he_uniform\",\n choices=(\n \"normal\",\n \"xavier_normal\",\n \"he_normal\",\n \"he_uniform\",\n \"orthogonal\",\n ),\n help=\"use this type of initialization for the network\",\n )\n parser.add_argument(\n \"-ig\",\n \"--init-gain\",\n type=positive_float(),\n default=0.2,\n help=\"use this initialization gain for initialization\",\n )\n parser.add_argument(\n \"-db\",\n \"--down-blocks\",\n type=positive_int(),\n default=[4, 4, 4, 4, 4],\n nargs=\"+\",\n help=\"tiramisu down-sample path specification\",\n )\n parser.add_argument(\n \"-ub\",\n \"--up-blocks\",\n type=positive_int(),\n default=[4, 4, 4, 4, 4],\n nargs=\"+\",\n help=\"tiramisu up-sample path specification\",\n )\n parser.add_argument(\n \"-bl\",\n \"--bottleneck-layers\",\n type=positive_int(),\n default=4,\n help=\"tiramisu bottleneck specification\",\n )\n parser.add_argument(\n \"-gr\",\n \"--growth-rate\",\n type=positive_int(),\n default=12,\n help=\"tiramisu growth rate (number of channels \"\n \"added between each layer in a dense block)\",\n )\n parser.add_argument(\n \"-fcoc\",\n \"--first-conv-out-channels\",\n type=positive_int(),\n default=48,\n help=\"number of output channels in first conv\",\n )\n return parent_parser\n","sub_path":"tiramisu_brulee/experiment/seg.py","file_name":"seg.py","file_ext":"py","file_size_in_byte":27788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"46429525","text":"import csv\n\nwith open('genetherapy.csv', newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n dictionary = {}\n groups_list = []\n for row in reader:\n if row['Therapy'] == 'A':\n groups_list.append(int(row['expr']))\n print(groups_list)\n","sub_path":"MyCode/work_on_course.py","file_name":"work_on_course.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"574370689","text":"from __future__ import unicode_literals\nimport youtube_dl\n\n\ndef download_video(url, playlist=False):\n\n\touttmpl = 'Movies\\\\%(playlist)s\\\\%(playlist_index)s - %(title)s.%(ext)s' if playlist else 'Movies\\\\%(title)s.%(ext)s'\n\tydl_opts = {\n\t\t'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4',\n\t\t'outtmpl': outtmpl,\n\t\t'noplaylist' : not playlist,\n\t\t'nocheckcertificate' : True,\n\t}\n\n\ttry:\n\t\twith youtube_dl.YoutubeDL(ydl_opts) as ydl:\n\t\t\tydl.download([url])\n\texcept Exception as e:\n\t\tprint(e)\n\n\nif __name__ == \"__main__\":\n\turl = 'https://www.youtube.com/watch?v=KtlgYxa6BMU'\n\t# url = 'https://www.youtube.com/watch?v=_KhQT-LGb-4&list=PL4uUU2x5ZgR1JOlcY9SZB94MW6fBE8ovU'\n\tdownload_video(url, playlist=True)\n\t","sub_path":"video_win.py","file_name":"video_win.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"590862542","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 3 23:45:55 2021\n\n@author: scnc\n\"\"\"\n\nimport numpy as np\nfrom PIL import Image\nimport torch.utils.data as data\nimport torch\nfrom torchvision import transforms\nimport glob\nimport SimpleITK as sitk\nimport cv2\nfrom dataloader.class_transformations import TransformationGeneratort\n#from class_transformations import TransformationGeneratort\nfrom skimage.transform import resize\n\ndef scalRadius(img, scale):\n x = img[int(img.shape[0]/2),:,:].sum(1)\n r = (x > x.mean() / 10).sum() / 2\n if r < 0.001: # This is for the very black images\n r = scale*2\n s = scale*1.0/r\n return cv2.resize(img, (0,0), fx=s, fy=s)\n\n\ndef load_preprocess_img(dir_img):\n scale = 300\n a = cv2.imread(dir_img)\n a = scalRadius(a,scale)\n a = cv2.addWeighted(a,4,cv2.GaussianBlur(a, (0,0), scale/30), -4, 128)\n b = np.zeros(a.shape)\n cv2.circle(b, (int(a.shape[1]/2),int(a.shape[0]/2)), int(scale*0.9), (1,1,1), -1, 8, 0)\n a = a*b + 128*(1-b)\n img = Image.fromarray(np.array(a, dtype=np.int8), \"RGB\")\n return img\n\ndef load_dicom(filename):\n # Reads the image using SimpleITK\n itkimage = sitk.ReadImage(filename, sitk.sitkInt16)\n # Convert the image to a numpy array\n np_img = sitk.GetArrayFromImage(itkimage)\n np_img = np.array((np_img - np.min(np_img))/(np.max(np_img) - np.min(np_img))*255, dtype=np.int8) # Normalize between 0 and 255\n #IMG_PX_SIZE=128##\n #np_img= resize(np_img,(IMG_PX_SIZE,IMG_PX_SIZE),anti_aliasing=True)##\n return np_img[0]\n\n\nclass TC(data.Dataset):\n \"\"\" Multi-Modal Dataset.\n Args:\n dir_imgs (string): Root directory of dataset where images exist.\n transform_fundus: Tranformation applied to fundus images\n is_train (bool): image for training or test\n\tfundus_img_size (int): Size for fundus images. i.e. 224\n\tsax_img_size (array): X, Y, Z dimensions for cardiac images\n ids_set (pandas class):\n \"\"\"\n\n def __init__(self,\n dir_imgs,\n tagging_img_size,\n #sax_img_size,\n args,\n ids_set\n ):\n\n self.img_names = []\n self.tagging_img_size = tagging_img_size\n #self.sax_img_size = sax_img_size\n #self.path_imgs_sax = []\n #self.crop_c_min = []\n #self.crop_c_max = []\n #self.crop_r_min = []\n #self.crop_r_max = []\n self.roi_length = []\n self.crop_c_min_tagging = []\n self.crop_c_max_tagging = []\n self.crop_r_min_tagging = []\n self.crop_r_max_tagging = []\n # fundus image paths\n self.path_imgs_tagging = []\n # number fo participants\n self.num_parti = 0\n\n self.pad_input_tagging = TransformationGeneratort(output_size=self.tagging_img_size,\n output_spacing=[1, 1, 1],\n training=False,\n pixel_margin_ratio = 0.3,\n normalize = 0) # It could 0 or -1\n# =============================================================================\n# self.pad_input = TransformationGenerator(output_size=self.sax_img_size,\n# output_spacing=[1, 1, 1],\n# training=False,\n# pixel_margin_ratio = 0.3,\n# normalize = 0) # It could 0 or -1\n# =============================================================================\n\n\n # Obtaining repeated ED and all sax images (labels)\n for idx, ID in enumerate(ids_set.values):\n self.num_parti = self.num_parti + 1\n\n # Reading all fundus images per patient\n imgs_per_id = glob.glob(dir_imgs + 'tagging/' + str(int(ID[0])) + '/*.nii.gz')\n\n # Taking only one image orientation -> left/right\n img_21015 = [j for j in imgs_per_id if 'b2s' in j]\n #img_21015 = [j for j in imgs_per_id if '21016' in j]\n if len(img_21015) >= 1:\n imgs_per_id = img_21015[0]\n # path for fundus images\n self.path_imgs_tagging.append(imgs_per_id)\n # Image names\n self.img_names.append(imgs_per_id.split('/')[-1][:-4])\n # paths for cmr\n # self.path_imgs_sax.append(dir_imgs + 'sax/' + str(int(ID[0])) + '/' + 'image_SAX_001.vtk')\n # Coordinates\n #self.crop_c_min.append(int(ID[1]))\n #self.crop_c_max.append(int(ID[2]))\n #self.crop_r_min.append(int(ID[3]))\n #self.crop_r_max.append(int(ID[4]))\n self.roi_length.append(int(ID[5]))\n self.crop_c_min_tagging.append(int(ID[1]))\n self.crop_c_max_tagging.append(int(ID[2]))\n self.crop_r_min_tagging.append(int(ID[3]))\n self.crop_r_max_tagging.append(int(ID[4]))\n \n\n else:\n continue\n\n # # Taking max two images per participant\n # if len(imgs_per_id) > 2:\n # list_aux = []\n # img_21015 = [j for j in imgs_per_id if '21015' in j]\n # list_aux.append(img_21015[-1])\n # img_21016 = [j for j in imgs_per_id if '21016' in j]\n # list_aux.append(img_21016[-1])\n # imgs_per_id = list_aux\n\n # for n, path_fun in enumerate(imgs_per_id):\n # # path for fundus images\n # self.path_imgs_fundus.append(path_fun)\n # # Image names\n # self.img_names.append(path_fun.split('/')[-1][:-4])\n # # paths for cmr\n # self.path_imgs_sax.append(dir_imgs + 'sax/' + str(int(ID[0])) + '/' + 'image_SAX_001.vtk')\n # # Coordinates\n # self.crop_c_min.append(int(ID[1]))\n # self.crop_c_max.append(int(ID[2]))\n # self.crop_r_min.append(int(ID[3]))\n # self.crop_r_max.append(int(ID[4]))\n # self.roi_length.append(int(ID[5]))\n # # mtd LVEDV_automatic[6], LVM_automatic[10], sex[24], dbpa[30], sbpa[31], ss[33], ads[34], bmi[36], age[38], hba1c[40], chol[41], glucose[43]\n # self.mtdt.append([ID[6], ID[10], ID[24], ID[30], ID[31], ID[33], ID[34], ID[36], ID[38], ID[40], ID[41], ID[43]])\n \n # Transform for fundus images\n# =============================================================================\n# self.transform_fundus = transforms.Compose([\n# transforms.Resize((self.tagging_img_size, self.tagging_img_size)),\n# transforms.ToTensor(),\n# ])\n# =============================================================================\n\n\n # Denotes the total number of samples\n def __len__(self):\n return len(self.path_imgs_tagging) # self.num_parti\n\n # This generates one sample of data\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (fundus, sax, label, img_name, index)\n \"\"\"\n \n# =============================================================================\n# # Loading fundus image\n# # preprocessing\n# tagging = load_dicom(self.path_imgs_tagging[index])\n# # without preprocessing\n# #tagging = Image.open(self.path_imgs_tagging[index]).convert('RGB')\n# # resizing the images\n# #tagging_image = self.transform_fundus(tagging)\n# # normalizing the images\n# tagging_image = tagging\n# tagging_image = (tagging_image - torch.min(tagging_image))/(torch.max(tagging_image) - torch.min(tagging_image)) # Normalize between 0 and 1\n# tagging_image = 2.0*(tagging_image - torch.min(tagging_image))/(torch.max(tagging_image) - torch.min(tagging_image))-1.0 # Normalize between -1 and 1\n# =============================================================================\n tagging, output_image_np_mean,output_image_np_std, output_image_np_max = self.pad_input_tagging.get(self.path_imgs_tagging[index],\n self.crop_c_min_tagging[index],\n self.crop_c_max_tagging[index],\n self.crop_r_min_tagging[index],\n self.crop_r_max_tagging[index],\n self.roi_length[index]) \n \n # Loading sax\n# =============================================================================\n# sax = self.pad_input.get(self.path_imgs_sax[index],\n# self.crop_c_min[index],\n# self.crop_c_max[index],\n# self.crop_r_min[index],\n# self.crop_r_max[index],\n# self.roi_length[index])\n# =============================================================================\n\n\n #return tagging, sax, self.img_names[index] # index # torch.FloatTensor(self.mtdt[index])\n return tagging, self.img_names[index], output_image_np_mean,output_image_np_std, output_image_np_max # index # torch.FloatTensor(self.mtdt[index])\n #return sax, torch.FloatTensor(self.mtdt[index]), self.img_names[index] # index # torch.FloatTensor(self.mtdt[index])\n\n\ndef Tagging_loader(batch_size,\n tagging_img_size,\n #sax_img_size,\n num_workers,\n shuffle,\n dir_imgs,\n args,\n ids_set):\n\n\n ######### Create class Dataset MM ########\n TC_dataset = TC(dir_imgs = dir_imgs,\n tagging_img_size = tagging_img_size,\n\t\t #sax_img_size = sax_img_size,\n args = args,\n ids_set = ids_set)\n\n print('Found ' + str(len(TC_dataset)) + ' tagging images')\n\n # Dataloader\n data_loader = torch.utils.data.DataLoader(TC_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers)\n\n return data_loader\n","sub_path":"Tagging_loader.py","file_name":"Tagging_loader.py","file_ext":"py","file_size_in_byte":10274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"514122257","text":"# Task 6\n# В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться больше или меньше введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано, то вывести загаданное число.\n# Ссылка на блоксхемму: https://drive.google.com/file/d/1mCRrqO4TVaTTO1xdDyu9cQ4r495PaUD0/view?usp=sharing\nimport random\nA = random.randint(0, 100)\ni = 1\na = int(input('Угадайте число от 0 до 100: '))\nwhile True:\n if i == 10:\n print('Вы проиграли!')\n break\n elif a == A:\n print('Вы угадали!!!')\n break \n elif a > A:\n i += 1\n print(f'осталось {11 - i} попыток')\n a = int(input('Загаданное число меньше. '))\n else:\n i += 1\n print(f'осталось {11 - i} попыток')\n a = int(input('Загаданное число больше. '))\n","sub_path":"unit2/Task 6.py","file_name":"Task 6.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"361858166","text":"\n\n# __slots__\n# 限制类的实例允许绑定的属性,相当于列一个白名单\n# 限制只对本类的实例起作用,对子类的实例不起作用\n# 想对子类的实例做此限制,需要在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上所有父类的__slots__\nclass Animal(object):\n __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称\n\nclass Dog(Animal):\n __slots__ = ('weight')\n\nclass BigDog(Dog):\n __slots__ = ('size')\n\nanimal = Animal()\nanimal.name = 'ss'\nanimal.age = 22\n\ndog = Dog()\ndog.weight = 43.2\ndog.name = 'dog'\ndog.age = 12\n\nbig_dog = BigDog()\nbig_dog.weight = 43.2\nbig_dog.name = 'big_dog'\nbig_dog.age = 12\nbig_dog.size = 3.5\n\n\n# @property\n# python内置@property装饰器,负责把一个getter方法变成属性调用\n# 同时,@property会生成@attr.setter装饰器,负责把一个setter方法变成属性调用\n# 此时,getter和setter方法名就是属性名\n# 另外,如果只定义getter方法,就是只读属性,如年龄,可以通过id失算\nclass Student(object):\n\n @property\n def score(self):\n return self._score\n\n @score.setter\n def score(self, value):\n if not isinstance(value, int):\n raise ValueError('score must be an integer!')\n if value < 0 or value > 100:\n raise ValueError('score must between 0~100')\n self._score = value\n\na = Student()\na.score = 33\nprint(a.score)\n\n\n# python允许多重继承\n\n\n# 定制类1\n# __str__\n# 直接打印实例对象会打印内存地址,如果要自定义打印实例时的输出的内容,就在类中自定义__str__()方法\n\n\n","sub_path":"basic/oop/advance.py","file_name":"advance.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"155424418","text":"import time\nimport RPi.GPIO as GPIO\nimport smbus\nclass My1602(object):\n BUS = smbus.SMBus(1)\n LCD_ADDR = 0x27\n BLEN = 1\n \n def turn_light(self, key):\n self.BLEN = key\n if key == 1:\n self.BUS.write_byte(self.LCD_ADDR, 0x08)\n else:\n self.BUS.write_byte(self.LCD_ADDR, 0x00)\n \n def write_word(self, addr, data):\n temp = data\n if self.BLEN == 1:\n temp |= 0x08\n else:\n temp &= 0xF7\n self.BUS.write_byte(addr, temp)\n \n def send_command(self, comm):\n buf = comm & 0xF0\n buf |= 0x04\n self.write_word(self.LCD_ADDR, buf)\n time.sleep(0.002)\n buf &= 0xFB\n self.write_word(self.LCD_ADDR, buf)\n buf = (comm & 0x0F) << 4\n buf |= 0x04\n self.write_word(self.LCD_ADDR, buf)\n time.sleep(0.002)\n buf &= 0xFB\n self.write_word(self.LCD_ADDR, buf)\n \n def send_data(self, data):\n buf = data & 0xF0\n buf |= 0x05\n self.write_word(self.LCD_ADDR, buf)\n time.sleep(0.002)\n buf &= 0xFB\n self.write_word(self.LCD_ADDR, buf)\n buf = (data & 0x0F) << 4\n buf |= 0x05\n self.write_word(self.LCD_ADDR, buf)\n time.sleep(0.002)\n buf &= 0xFB\n self.write_word(self.LCD_ADDR, buf)\n \n def __init__(self):\n try:\n self.send_command(0x33)\n time.sleep(0.005)\n self.send_command(0x32)\n time.sleep(0.005)\n self.send_command(0x28)\n time.sleep(0.005)\n self.send_command(0x0C)\n time.sleep(0.005)\n self.send_command(0x01)\n self.BUS.write_byte(self.LCD_ADDR, 0x08)\n except:\n return None\n else:\n return None\n \n def clear_lcd(self):\n self.send_command(0x01)\n \n def print_lcd(self, x, y, str):\n if x < 0:\n x = 0\n if x > 15:\n x = 15\n if y < 0:\n y = 0\n if y > 1:\n y = 1\n addr = 0x80 + 0x40 * y + x\n self.send_command(addr)\n for chr in str:\n self.send_data(ord(chr))\nclass HC_SR04(object):\n def __init__(self, trig_pin, echo_pin):\n self.TRIG_PIN = trig_pin\n self.ECHO_PIN = echo_pin\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(self.TRIG_PIN, GPIO.OUT)\n GPIO.setup(self.ECHO_PIN, GPIO.IN)\n \n def measure_distance(self):\n GPIO.output(self.TRIG_PIN, GPIO.HIGH)\n time.sleep(0.00001)\n GPIO.output(self.TRIG_PIN, GPIO.LOW)\n while GPIO.input(self.ECHO_PIN) == GPIO.LOW:\n pass\n start_time = time.time()\n while GPIO.input(self.ECHO_PIN) == GPIO.HIGH:\n pass\n end_time = time.time()\n distance = (end_time - start_time) * 34300 / 2\n return distance\nif __name__ == '__main__':\n try:\n lcd = My1602()\n hc_sr04 = HC_SR04(11, 13)\n while True:\n distance = hc_sr04.measure_distance()\n lcd.clear_lcd()\n lcd.print_lcd(0, 0, 'Distance:')\n lcd.print_lcd(0, 1, '{:.2f} cm'.format(distance))\n \n # 在命令行终端上打印距离结果\n print('Distance: {:.2f} cm'.format(distance))\n \n time.sleep(1)\n except KeyboardInterrupt:\n pass\n finally:\n lcd.clear_lcd()\n lcd.print_lcd(0, 0, 'Program Stopped')\n GPIO.cleanup()\n","sub_path":"distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"262830097","text":"# coding: utf8 \nfrom PyQt5.QtWidgets import *\nimport class_set\nimport subprocess\nfrom PyQt5.QtWidgets import * \nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtGui import * \nfrom PyQt5.QtCore import * \nimport sys \n#import smtplib\n#from email.mime.text import MIMEText\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n\nclass IconButton():\n\n def __init__(self, icon, parent, size_x, size_y, icon_size_x, icon_size_y, tooltip = \"\"):\n\n self.button = QPushButton(\"\", parent)\n self.button.resize(size_x, size_y)\n \n \n self.button.maximumWidth = size_x\n self.button.maximumHeight = size_y\n\n self.button.setIconSize(QSize(icon_size_x, icon_size_y))\n self.button.setIcon(icon)\n\n self.button.setToolTip(tooltip)\n\n self.button.setStyleSheet(\"QPushButton { background-color: rgba(45, 45, 45, 255) ; border-style: outset; border-width: 0px; border-radius: 0px; border-color: rgba(0,0,0,0); }\" \n \"QPushButton::pressed { background-color: red }\" \n \"QPushButton::hover{background-color : rgba(15, 15, 15, 255)}\")\n\n def empty_button(parent, size_x, size_y, icon_size_x, icon_size_y):\n button = QPushButton(\"\", parent)\n button.resize(size_x, size_y)\n \n button.maximumWidth = size_x\n button.maximumHeight = size_y\n \n button.setIconSize(QSize(icon_size_x, icon_size_y))\n button.setIcon(QIcon(\"assets/empty.png\"))\n\n button.setStyleSheet(\"QPushButton { background-color: rgba(0, 0, 0, 0) ; border-style: outset; border-width: 0px; border-radius: 0px; border-color: rgba(0,0,0,0); }\")\n\n return button\n\nclass MainWindow(QMainWindow): \n \n def __init__(self): \n super().__init__()\n \n self.setStyleSheet(\"background-color: rgba(75,75,75,255);\") \n\n self.partition = None\n\n self.diese = True\n\n QtGui.QFontDatabase.addApplicationFont(\"asset/font/Lato Light Italic.ttf\")\n\n self.setWindowTitle(\"Tarpipion\") \n self.setWindowIcon(QIcon(\"assets/icon.png\"))\n self.setGeometry(0, 0, 1280, 720) \n\n self.dimensions = QDesktopWidget().screenGeometry()\n \n self.square_size = int(self.dimensions.height() / 13.5)\n\n self.menu_layout = QVBoxLayout()\n self.menu_layout.setGeometry(QRect(0, 0, self.dimensions.width(), self.dimensions.height()))\n \n\n################################################################################################################################################################################################################\n #LAYOUT ARRONDI#\n################################################################################################################################################################################################################\n\n self.partition_layout = QHBoxLayout()\n self.panel_width = int(self.dimensions.width() / 3.2)\n \n self.frame_left = QFrame(self)\n self.frame_left.setFrameShape(QFrame.Box)\n self.frame_left.resize(self.panel_width, self.square_size * 2)\n self.frame_left.setStyleSheet(\"QFrame { background-color: rgba(0, 0, 0, 0) ; border-style: outset; border-width: 0px; border-radius: 0px; border-color: rgba(0,0,0,0); }\")\n\n self.frame_right = QFrame(self)\n self.frame_right.setFrameShape(QFrame.Box)\n self.frame_right.resize(self.panel_width, self.square_size * 2)\n self.frame_right.setStyleSheet(\"QFrame { background-color: rgba(0, 0, 0, 0) ; border-style: outset; border-width: 0px; border-radius: 0px; border-color: rgba(0,0,0,0); }\")\n\n self.frame = QFrame(self)\n self.frame.setFrameShape(QFrame.Box)\n self.frame.resize(self.panel_width, self.square_size * 2)\n self.frame.setStyleSheet(\"QFrame { background-color: rgba(45, 45, 45, 255) ; border-style: outset; border-width: 0px; border-radius: \"+str(self.square_size)+\"px; border-color: rgba(0,0,0,0); }\")\n\n self.partition_layout.addWidget(self.frame_left, 1)\n self.partition_layout.addWidget(self.frame, 1)\n self.partition_layout.addWidget(self.frame_right, 1)\n\n self.partition_layout.setGeometry(QRect(0,0, self.dimensions.width(), self.square_size * 2))\n \n\n################################################################################################################################################################################################################\n #LAYOUT DE BOUTONS DE PARTITION#\n################################################################################################################################################################################################################\n\n self.partition_menu_layout = QHBoxLayout()\n self.panel_width = int(self.dimensions.width() / 3.2)\n \n self.frame_left = QFrame(self)\n self.frame_left.setFrameShape(QFrame.Box)\n self.frame_left.resize(self.panel_width, self.square_size * 2)\n self.frame_left.setStyleSheet(\"QFrame { background-color: rgba(0, 0, 0, 0) ; border-style: outset; border-width: 0px; border-radius: 0px; border-color: rgba(0,0,0,0); }\")\n\n self.frame_right = QFrame(self)\n self.frame_right.setFrameShape(QFrame.Box)\n self.frame_right.resize(self.panel_width, self.square_size * 2)\n self.frame_right.setStyleSheet(\"QFrame { background-color: rgba(0, 0, 0, 0) ; border-style: outset; border-width: 0px; border-radius: 0px; border-color: rgba(0,0,0,0); }\")\n\n self.diese_icon = QIcon(\"assets/diese_mieux.png\")\n self.bemol_icon = QIcon(\"assets/bemol_mieux.png\")\n\n #BOUTON TYPE - DEMOL / DIESE\n #self.type_button = IconButton(self.diese_icon, self, self.square_size, self.square_size*2, self.square_size, self.square_size*2, \"Changer Altération\")\n #self.type_button.button.setCheckable(True)\n #self.type_button.button.clicked.connect(self.switch_type)\n\n #SEPARATION\n #self.button_spacer = IconButton.empty_button(self, self.square_size, self.square_size*2, self.square_size, self.square_size*2)\n\n #BOUTON REDUCTION\n minus = QIcon(\"assets/minus_mieux.png\")\n self.minus_button = IconButton(minus, self, self.square_size, self.square_size*2, self.square_size, self.square_size*2, \"Baisser d'un demi ton\")\n self.minus_button.button.setCheckable(True)\n self.minus_button.button.clicked.connect(self.down_switch_note)\n\n #LABEL DEMI TON\n self.demi_ton = QLabel(self)\n pixmap = QPixmap(\"assets/demi_ton_mieux.png\")\n small_pixmap = pixmap.scaled(self.square_size * 2, self.square_size * 2, Qt.KeepAspectRatio, Qt.SmoothTransformation)\n self.demi_ton.setPixmap(small_pixmap)\n self.demi_ton.show()\n self.demi_ton.setStyleSheet(\"background-color: rgba(45,45,45,255);\") \n\n #BOUTON AUGMENTATION\n plus = QIcon(\"assets/plus_mieux.png\")\n self.plus_button = IconButton(plus, self, self.square_size, self.square_size*2, self.square_size, self.square_size*2, \"Augmenter d'un demi ton\")\n self.plus_button.button.setCheckable(True)\n self.plus_button.button.clicked.connect(self.up_switch_note)\n\n\n self.partition_menu_layout.addWidget(self.frame_left, 1)\n #self.partition_menu_layout.addWidget(self.type_button.button, 0)\n #self.partition_menu_layout.addWidget(self.button_spacer, 0)\n self.partition_menu_layout.addWidget(self.minus_button.button, 0)\n self.partition_menu_layout.addWidget(self.demi_ton, 0)\n self.partition_menu_layout.addWidget(self.plus_button.button, 0)\n\n self.partition_menu_layout.addWidget(self.frame_right, 1)\n\n self.partition_menu_layout.setGeometry(QRect(0,0, self.dimensions.width(), self.square_size * 2))\n\n\n################################################################################################################################################################################################################\n #LAYOUT DE TITRE#\n################################################################################################################################################################################################################\n\n self.title_layout = QHBoxLayout()\n\n\n self.titre = QLabel(self)\n self.titre.setText(\"Aucune partition\")\n self.titre.setAlignment(QtCore.Qt.AlignCenter)\n\n self.titre_text_size = int(self.square_size * .6)\n print(\"TITLE SIZE : \" + str(self.titre_text_size))\n self.titre.setStyleSheet(\"QLabel { color : rgba(230, 230, 230, 255) ; background-color : rgba(45, 45, 45, 255) ; font-family : Lato ; font-style : italic ; font-size : \"+str(self.titre_text_size)+\"px }\")\n\n self.title_layout.addWidget(self.titre,1)\n self.title_layout.setSpacing(0)\n self.title_layout.setGeometry(QRect(0,0, self.dimensions.width(), self.square_size))\n\n################################################################################################################################################################################################################\n #LAYOUT DE FICHIERS#\n################################################################################################################################################################################################################\n \n self.button_layout = QHBoxLayout()\n\n #new_icon = QIcon(\"assets/new_mieux.png\")\n #self.new_button = IconButton(new_icon, self, self.square_size, self.square_size, self.square_size, self.square_size, \"New File\")\n\n open_icon = QIcon(\"assets/open_mieux.png\")\n self.open_button = IconButton(open_icon, self, self.square_size, self.square_size, self.square_size, self.square_size, \"Ouvrir un fichier\")\n self.open_button.button.setCheckable(True)\n self.open_button.button.clicked.connect(self.open_file)\n self.open_button.button.setShortcut\n\n save_icon = QIcon(\"assets/save_mieux.png\")\n self.save_button = IconButton(save_icon, self, self.square_size, self.square_size, self.square_size, self.square_size, \"Sauvegarder un fichier\")\n self.save_button.button.setCheckable(True)\n self.save_button.button.clicked.connect(self.save_file)\n\n report_icon = QIcon(\"assets/error_report_mieux.png\")\n self.report_button = IconButton(report_icon, self, self.square_size, self.square_size, self.square_size, self.square_size, \"Signaler la partition actuelle\")\n self.report_button.button.setCheckable(True)\n self.report_button.button.clicked.connect(self.send_partition_mail)\n\n\n #self.button_layout.addWidget(self.new_button.button,0)\n self.button_layout.addWidget(self.open_button.button,0)\n self.button_layout.addWidget(self.save_button.button,0)\n self.button_layout.addWidget(self.report_button.button,0)\n self.button_layout.addStretch(0)\n\n self.button_layout.setSpacing(0)\n self.button_layout.setGeometry(QRect(0,0, self.dimensions.width(), self.square_size))\n\n################################################################################################################################################################################################################\n #LAYOUT DE PARTITIONS#\n################################################################################################################################################################################################################\n\n self.partition_text_layout = QHBoxLayout()\n\n self.partition_originale = QScrollArea(self)\n self.partition_originale.setViewportMargins(QMargins(int(self.square_size / 6), int(self.square_size / 6), int(self.square_size / 6), int(self.square_size / 6)))\n self.partition_originale.setStyleSheet(\"QScrollArea {background-color: rgba(230,230,230,255);}\")\n\n self.partition_modifiee = QScrollArea(self)\n self.partition_modifiee.setViewportMargins(QMargins(int(self.square_size / 6), int(self.square_size / 6), int(self.square_size / 6), int(self.square_size / 6)))\n self.partition_modifiee.setStyleSheet(\"QScrollArea {background-color: rgba(230,230,230,255);}\")\n\n\n self.text_size = 14\n\n self.partition_text_layout.addWidget(self.partition_originale, 0)\n self.partition_text_layout.addWidget(self.partition_modifiee, 0)\n self.partition_text_layout.setSpacing(self.square_size)\n self.partition_text_layout.setGeometry(QRect(int(self.dimensions.width() * .175), int(self.dimensions.height() * .166667), int(self.dimensions.width() * .65), int(self.dimensions.height() * .75)))\n\n self.showMaximized()\n\n\n def open_file(self, pressed):\n\n try:\n #label_b = QLabel(\"\")\n #self.partition_modifiee.setWidget(label_b)\n\n name = QFileDialog.getOpenFileName(self, 'Open File', 'C\\\\', 'Text files (*.txt)')\n path = name[0]\n self.partition = class_set.TxtPartition(path)\n \n label_a = QLabel()\n label_b = QLabel()\n\n self.partition_originale.setWidget(label_a)\n self.partition_modifiee.setWidget(label_b)\n\n with open(path, \"r\", encoding=\"utf-8\") as f:\n\n\n text = \"\"\n for t in self.partition.all_text:\n text += t\n\n partition_originale_text = QLabel()\n partition_originale_text.setText(text)\n partition_originale_text.setStyleSheet(\"QLabel { color : rgba(75, 75, 75, 255) ; background-color : rgba(0, 0, 0, 0) ; font-family : Lato ; font-size : \"+str(self.text_size)+\"px }\")\n\n partition_modifiee_text = QLabel()\n partition_modifiee_text.setText(text)\n partition_modifiee_text.setStyleSheet(\"QLabel { color : rgba(75, 75, 75, 255) ; background-color : rgba(0, 0, 0, 0) ; font-family : Lato ; font-size : \"+str(self.text_size)+\"px }\")\n\n\n\n self.partition_originale.setWidget(partition_originale_text)\n self.partition_modifiee.setWidget(partition_modifiee_text)\n\n #self.unfade(self.partition_originale.findChild(QLabel))\n self.dual_unfade(self.partition_originale.findChild(QLabel), self.partition_modifiee.findChild(QLabel))\n\n self.set_titre(self.partition.titre)\n\n print(self.partition.notes[0])\n\n except FileNotFoundError:\n pass\n\n def save_file(self, pressed):\n if(not self.partition == None):\n try:\n name = QFileDialog.getSaveFileName(self, 'Save File', 'C\\\\', 'Text files (*.txt)')\n path = name[0]\n file = open(path,'w+')\n self.partition.add_surplus()\n for i, txt in enumerate(self.partition.all_text):\n file.write(txt)\n #new_partition.write(\"\\n\")\n\n #file.write(self.partition.all_text)\n file.close()\n self.partition.remove_surplus()\n\n except FileNotFoundError:\n pass\n\n\n def switch_type(self):\n try:\n if self.partition:\n source = self.sender()\n \"\"\"if(self.diese):\n source.setIcon(self.bemol_icon)\n else:\n source.setIcon(self.diese_icon)\"\"\"\n\n self.partition.switch_type()\n partition_new = QLabel()\n text = \"\"\n for t in self.partition.all_text:\n text += t\n partition_new.setText(text)\n partition_new.setStyleSheet(\"QLabel { color : rgba(75, 75, 75, 255) ; background-color : rgba(0, 0, 0, 0) ; font-family : Lato ; font-size : \"+str(self.text_size)+\"px }\")\n \n self.partition_modifiee.setWidget(partition_new)\n self.unfade(self.partition_modifiee.findChild(QLabel))\n\n self.diese = not self.diese\n\n except AttributeError:\n pass\n\n\n def up_switch_note(self, pressed):\n try:\n if self.partition:\n if not self.diese:\n self.switch_type()\n\n self.partition.switch_notes(1)\n partition_new = QLabel()\n text = \"\"\n for t in self.partition.all_text:\n text += t\n partition_new.setText(text)\n partition_new.setStyleSheet(\"QLabel { color : rgba(75, 75, 75, 255) ; background-color : rgba(0, 0, 0, 0) ; font-family : Lato ; font-size : \"+str(self.text_size)+\"px }\")\n \n self.partition_modifiee.setWidget(partition_new)\n\n self.unfade(self.partition_modifiee.findChild(QLabel))\n except AttributeError:\n pass\n\n def down_switch_note(self, pressed):\n try:\n if self.partition:\n if self.diese:\n self.switch_type()\n\n self.partition.switch_notes(-1)\n partition_new = QLabel()\n text = \"\"\n for t in self.partition.all_text:\n text += t\n print(\"TEXT IN CODE 2 : \" + text)\n partition_new.setText(text)\n partition_new.setStyleSheet(\"QLabel { color : rgba(75, 75, 75, 255) ; background-color : rgba(0, 0, 0, 0) ; font-family : Lato ; font-size : \"+str(self.text_size)+\"px }\")\n \n self.partition_modifiee.setWidget(partition_new)\n\n self.unfade(self.partition_modifiee.findChild(QLabel))\n\n except AttributeError:\n pass\n\n\n def set_titre(self, titre):\n cpt = 0\n new_titre = \"\"\n\n for i in titre:\n cpt += 1\n new_titre = new_titre + i\n if cpt >= 75:\n new_titre = new_titre + \"...\"\n break\n\n self.titre.setText(new_titre)\n \n def fade(self, widget):\n self.effect = QGraphicsOpacityEffect()\n widget.setGraphicsEffect(self.effect)\n\n self.animation = QtCore.QPropertyAnimation(self.effect, b\"opacity\")\n self.animation.setDuration(500)\n self.animation.setStartValue(1)\n self.animation.setEndValue(0)\n self.animation.start()\n\n def unfade(self, widget):\n self.effect = QGraphicsOpacityEffect()\n widget.setGraphicsEffect(self.effect)\n\n self.animation = QtCore.QPropertyAnimation(self.effect, b\"opacity\")\n self.animation.setDuration(500)\n self.animation.setStartValue(0)\n self.animation.setEndValue(1)\n self.animation.start()\n\n def dual_fade(self, widget_a, widget_b):\n self.effect = QGraphicsOpacityEffect()\n widget_a.setGraphicsEffect(self.effect)\n widget_b.setGraphicsEffect(self.effect)\n\n self.animation = QtCore.QPropertyAnimation(self.effect, b\"opacity\")\n self.animation.setDuration(500)\n self.animation.setStartValue(1)\n self.animation.setEndValue(0)\n self.animation.start()\n\n def dual_unfade(self, widget_a, widget_b):\n self.effect = QGraphicsOpacityEffect()\n widget_a.setGraphicsEffect(self.effect)\n widget_b.setGraphicsEffect(self.effect)\n\n self.animation = QtCore.QPropertyAnimation(self.effect, b\"opacity\")\n self.animation.setDuration(500)\n self.animation.setStartValue(0)\n self.animation.setEndValue(1)\n self.animation.start()\n\n def send_partition_mail(self):\n server = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n\n from_address = \"tarpipion.assistobot@gmail.com\"\n from_address_pwd = \"bZJvJcuRR3NiHYv\"\n to_address = \"louis.euvrardarnaud@gmail.com\"\n\n server.login(from_address, from_address_pwd)\n server.sendmail(from_address, to_address, \"T'as du taf'\")\n server.quit()\n\n\n\n\n \"\"\"msg = MIMEMultipart('alternative')\n s = smtplib.SMTP('smtp.sendgrid.net', 587)\n s.login(USERNAME, PASSWORD)\n\n toEmail, fromEmail = \"to@email.com\", \"from@gmail.com\"\n msg['Subject'] = 'subject'\n msg['From'] = fromEmail\n body = 'This is the message'\n\n content = MIMEText(body, 'plain')\n msg.attach(content)\n\n\n filename = \"wrong_partition.txt\"\n f = file(filename)\n attachment = MIMEText(f.read())\n attachment.add_header('Content-Disposition', 'attachment', filename=filename) \n msg.attach(attachment)\n\n s.sendmail(fromEmail, toEmail, msg.as_string())\"\"\"\n\n\n# create pyqt5 app \nApp = QApplication(sys.argv) \n\n# create the instance of our Window \nwindow = MainWindow() \n \n# start the app \nsys.exit(App.exec_()) ","sub_path":"main/_main_.py","file_name":"_main_.py","file_ext":"py","file_size_in_byte":20888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"350043657","text":"import urllib.request\nimport json\nimport dml\nimport prov.model\nimport datetime\nimport uuid\n\n\nclass transformTweets(dml.Algorithm):\n contributor = 'gaotian_xli33'\n reads = ['emmaliu_gaotian_xli33_yuyangl.tweets']\n writes = ['emmaliu_gaotian_xli33_yuyangl.userLocation']\n\n @staticmethod\n def execute(trial=False):\n '''Retrieve some data sets (not using the API here for the sake of simplicity).'''\n startTime = datetime.datetime.now()\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('emmaliu_gaotian_xli33_yuyangl', 'emmaliu_gaotian_xli33_yuyangl')\n\n # Get Tweets data\n tweetsData = repo.emmaliu_gaotian_xli33_yuyangl.tweets_translated.find()\n locations = {}\n dataStored = []\n # Filter for user's location, project key value pairs.\n for item in tweetsData:\n if item['user']['location'] == '' or \".\" in item['user']['location']:\n continue\n\n location = item['user']['location']\n followers = item['user']['followers_count']\n friends = item['user']['friends_count']\n if location not in locations: # Write to dictionary\n locations[location] = {'followers_count': followers, 'friends_count': friends, 'COUNT': 1}\n else:\n locations[location]['followers_count'] += followers\n locations[location]['friends_count'] += friends\n locations[location]['COUNT'] += 1\n # Calculating averages here\n for key, value in locations.items():\n dataStored.append({'location': key, 'count': value['COUNT'],\n 'avg_followers_count': value['followers_count'] / value['COUNT'],\n 'avg_friends_count': value['friends_count'] / value['COUNT']})\n\n # sort by location's count with decreasing order\n dataStored.sort(key=lambda x: x['count'], reverse=True)\n\n with open(\"userLocation .json\", 'w') as outfile:\n json.dump(dataStored, outfile, indent=4)\n\n # store results into database\n repo.dropCollection(\"userLocation\")\n repo.createCollection(\"userLocation\")\n\n for i in dataStored:\n # print(str(i['location']) + ': ' + str(i['count']))\n repo['emmaliu_gaotian_xli33_yuyangl.userLocation'].insert(i)\n repo['emmaliu_gaotian_xli33_yuyangl.userLocation'].metadata({'complete': True})\n print(repo['emmaliu_gaotian_xli33_yuyangl.userLocation'].metadata())\n\n repo.logout()\n\n endTime = datetime.datetime.now()\n\n return {\"start\": startTime, \"end\": endTime}\n\n @staticmethod\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):\n '''\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n '''\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('emmaliu_gaotian_xli33_yuyangl', 'emmaliu_gaotian_xli33_yuyangl')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/emmaliu_gaotian_xli33_yuyangl') # The scripts are in # format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/emmaliu_gaotian_xli33_yuyangl') # The data sets are in # format.\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\n doc.add_namespace('bdp', '')\n this_script = doc.agent('alg:emmaliu_gaotian_xli33_yuyangl#transformTweets',\n {prov.model.PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'})\n resource = doc.entity('dat:emmaliu_gaotian_xli33_yuyangl#tweets',\n {'prov:label': '311, Service Requests', prov.model.PROV_TYPE: 'ont:DataResource',\n 'ont:Extension': 'json'})\n transform_tweets = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime)\n doc.wasAssociatedWith(transform_tweets, this_script)\n doc.usage(transform_tweets, resource, startTime, None,\n {prov.model.PROV_TYPE: 'ont:calculation',\n 'ont:Query': ''\n }\n )\n userLocation = doc.entity('dat:emmaliu_gaotian_xli33_yuyangl#get_tweets',\n {prov.model.PROV_LABEL: 'tweets from Amman', prov.model.PROV_TYPE: 'ont:DataSet'})\n doc.wasAttributedTo(userLocation, this_script)\n doc.wasGeneratedBy(userLocation, transform_tweets, endTime)\n doc.wasDerivedFrom(userLocation, resource, transform_tweets, transform_tweets, transform_tweets)\n\n repo.logout()\n\n return doc\n\n# transformTweets.execute()\n# doc = getTweets.provenance()\n# print(doc.get_provn())\n# print(json.dumps(json.loads(doc.serialize()), indent=4))\n\n## eof","sub_path":"emmaliu_gaotian_xli33_yuyangl/transformTweets.py","file_name":"transformTweets.py","file_ext":"py","file_size_in_byte":5230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"146526662","text":"\nimport os\nimport time\nfrom hippy.phpcompiler import compile_php\nfrom rpython.rlib.rpath import abspath\n\nTIMEOUT = 1.0\n\nclass BytecodeCache(object):\n def __init__(self, timeout=TIMEOUT):\n self.cached_files = {}\n self.timeout = timeout\n\n def compile_file(self, fname, space):\n absname = abspath(fname)\n now = time.time()\n try:\n bc, tstamp = self.cached_files[absname]\n if now - tstamp >= self.timeout:\n mtime = os.stat(absname).st_mtime\n if mtime > tstamp:\n raise KeyError\n except KeyError:\n f = open(absname)\n data = f.read(-1)\n f.close()\n tstamp = os.stat(absname).st_mtime\n bc = compile_php(absname, data, space)\n self.cached_files[absname] = (bc, tstamp)\n return bc\n","sub_path":"hippy/bytecode_cache.py","file_name":"bytecode_cache.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"508580673","text":"import random\nfrom math import pow, floor, log\n\nclass Wezel:\n\n def __init__(self, wartosc):\n self.wartosc = wartosc\n self.prawy = None\n self.lewy = None\n\n def insert(self, wartosc):\n if self.wartosc == wartosc:\n return\n elif self.wartosc < wartosc:\n if self.prawy is None:\n self.prawy = Wezel(wartosc)\n else:\n self.prawy.insert(wartosc)\n else:\n if self.lewy is None:\n self.lewy = Wezel(wartosc)\n else:\n self.lewy.insert(wartosc)\n\n def display(self):\n lines, _, _, _ = self._display_aux()\n for line in lines:\n print(line)\n\n def _display_aux(self):\n # No dziecko.\n if self.prawy is None and self.lewy is None:\n line = '%s' % self.wartosc\n width = len(line)\n height = 1\n middle = width // 2\n return [line], width, height, middle\n\n # Only lewy dziecko.\n if self.prawy is None:\n lines, n, p, x = self.lewy._display_aux()\n s = '%s' % self.wartosc\n u = len(s)\n first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s\n second_line = x * ' ' + '/' + (n - x - 1 + u) * ' '\n shifted_lines = [line + u * ' ' for line in lines]\n return [first_line, second_line] + shifted_lines, n + u, p + 2, n + u // 2\n\n # Only prawy dziecko.\n if self.lewy is None:\n lines, n, p, x = self.prawy._display_aux()\n s = '%s' % self.wartosc\n u = len(s)\n first_line = s + x * '_' + (n - x) * ' '\n second_line = (u + x) * ' ' + '\\\\' + (n - x - 1) * ' '\n shifted_lines = [u * ' ' + line for line in lines]\n return [first_line, second_line] + shifted_lines, n + u, p + 2, u // 2\n\n # Two dzieckoren.\n lewy, n, p, x = self.lewy._display_aux()\n prawy, m, q, y = self.prawy._display_aux()\n s = '%s' % self.wartosc\n u = len(s)\n first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s + y * '_' + (m - y) * ' '\n second_line = x * ' ' + '/' + (n - x - 1 + u + y) * ' ' + '\\\\' + (m - y - 1) * ' '\n if p < q:\n lewy += [n * ' '] * (q - p)\n elif q < p:\n prawy += [m * ' '] * (p - q)\n zipped_lines = zip(lewy, prawy)\n lines = [first_line, second_line] + [a + u * ' ' + b for a, b in zipped_lines]\n return lines, n + m + u, max(p, q) + 2, n + u // 2\n\ndef kregoslup(root, top):\n dziadek = None\n parent = top\n left_child = None\n print(\"\\n\\n\")\n \n while parent:\n left_child = parent.lewy\n \n if left_child:\n #print (left_child.wartosc)\n dziadek = rotujPrawo(dziadek, parent, left_child)\n parent = left_child\n \n else:\n dziadek = parent\n parent = parent.prawy\n \n return root\n\ndef rotujPrawo(dziadek, parent, left_child):\n left_child = parent.lewy\n if None != dziadek:\n print(\"a\")\n dziadek.prawy = left_child\n else:\n root = left_child\n #print(root.wartosc)\n \n parent.lewy = left_child.prawy\n left_child.prawy = parent\n\n return dziadek\n\ndef rotujLewo(dziadek, parent, right_child):\n if None != dziadek:\n dziadek.prawy = right_child\n else:\n root = right_child\n \n parent.prawy = right_child.lewy\n right_child.lewy = parent\n\ndef doskonale(root, n):\n dziadek = None\n parent = root\n root = kregoslup(root, root)\n m = int(pow(2, floor(log(n+1, 2))) -1)\n root = rotacje(root, n-m)\n\n while m > 1:\n m = m\n root = rotacje(root, m)\n \n return root\n\ndef rotacje(root, x):\n dziadek = None\n parent = root\n child = root.prawy\n\n for i in range(x):\n if p:\n try:\n if None != child:\n rotujLewo(dziadek, parent, child)\n dziadek = child\n parent = dziadek.prawy\n child = parent.prawy\n else:\n break\n except:\n break\n\ndef in_order(root):\n if not root:\n return\n \n in_order(root.lewy)\n print(root.wartosc)\n in_order(root.prawy)\n\nb = Wezel(random.randint(0, 100))\nx = int(input('Podaj liczbę elementów: '))\nprint(\"\\n\\n\\n\")\n\nfor a in range(x-1):\n b.insert(random.randint(0, 100))\nb.display()\n\n\n#kregoslup(b.wartosc, b)\n\ndef kk(root, top):\n tmp = top\n left_child = None\n\n while tmp:\n left_child = tmp.lewy\n if left_child:\n root, _ = rotate(root, tmp)\n tmp = left_child\n \n else:\n tmp = tmp.prawy\n \n return root\n\ndef rotate(root, tmp):\n if tmp.prawy is None:\n return root, tmp\n \n node = tmp.lewy\n tmp.lewy = node.prawy\n if node.prawy:\n node.prawy.wartosc = tmp\n if tmp.wartosc is None:\n root = node\n \n elif tmp == tmp.prawy.wartosc:\n tmp.prawy.wartosc = node\n \n else:\n tmp.lewy.wartosc = node\n \n node.prawy = tmp\n tmp.wartosc = node\n return root, node\n\n\nkk(b.wartosc, b)\nprint(\"\\n\\n\\n\")\nb.display()","sub_path":"Algorytmy/Algorytmy_Projekt_1.py","file_name":"Algorytmy_Projekt_1.py","file_ext":"py","file_size_in_byte":5285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"604641287","text":"import acm, string, ael, FLogger, at_time\nimport xlrd, csv\nimport pyodbc as odbc\nfrom shutil import copyfile\n\nglobal date\ndate = ael.date_today()\nglobal datetime\ndatetime = date.to_string() + ' 00:00:00'\nglobal midasDealDate\nmidasDealDate = date.to_string('%Y-%m-%d')\nglobal midasData\nmidasData = []\nglobal logger\nlogger = None\nglobal SQLConnection\nSQLConnection = None\n\nmidasFileReconChoiseList = ['CLIENT', 'SHADOW', 'BOTH']\n\ndef establishSQLConnection():\n global SQLConnection\n if SQLConnection == None:\n logger.info('Connecting to Midas DB for 4Front trade reconciliation...')\n dataSource='JHBPCM05015V05A\\FXB_MAIN1_LIVE'\n #dataSource='JHBPSM05017\\FXB_MAIN1_UAT'\n initialCatalog='MMG_FXF'\n connectionString = 'DRIVER={SQL Server};SERVER=%s;DATABASE=%s' % (dataSource, initialCatalog) \n sqlConnection = odbc.connect(connectionString, autocommit=True) \n SQLConnection = sqlConnection.cursor() \n\n return SQLConnection\n\ndef closeSQLConnection():\n global SQLConnection\n SQLConnection.close()\n\ndef executeSQLQuery(query):\n global SQLConnection\n sql = query\n \n result = SQLConnection.execute(sql).fetchall() \n return result\n\ndef copyAFile(source, desctination):\n copyfile(source, desctination)\n\ndef setFileName(index, fieldValues):\n global date, datetime, midasDealDate\n date = ael.date(fieldValues[0])\n datetime = date.to_string() + ' 00:00:00'\n midasDealDate = date.to_string('%Y-%m-%d')\n \n fieldValues[4] = ael_variables[4][4] + 'Trueup ' + date.to_string('%Y%m%d') + '.tab'\n fieldValues[5] = ael_variables[5][4] + 'Trueup ' + date.to_string('%Y%m%d') + '.tab'\n fieldValues[6] = ael_variables[6][4] + 'Trueup sh ' + date.to_string('%Y%m%d') + '.tab'\n fieldValues[7] = ael_variables[7][4] + 'Trueup sh' + date.to_string('%Y%m%d') + '.tab'\n return fieldValues\n\ndef loadMidasData(locationAndFile):\n global midasData\n file = open(locationAndFile, 'r')\n\n line = file.readline()\n line = file.readline()\n \n while line:\n line = string.split(line, \"\\t\")\n midasData.append(line)\n \n line = file.readline()\n \n del midasData[-1]\n del midasData[-1]\n del midasData[-1]\n \n file.close()\n\ndef getTrades(portfolio):\n global date, logger\n \n tradeQuery = acm.CreateFASQLQuery(acm.FTrade, 'AND')\n tradeQuery.AddAttrNode('Portfolio.Oid', 'EQUAL', portfolio.Oid())\n tradeQuery.AddAttrNode('ValueDay', 'GREATER_EQUAL', date.to_string('%Y-%m-%d'))\n\n trades = tradeQuery.Select()\n \n logger.info('Total Number of Front Arena Trades in portfolio %s: %i\\n' %(portfolio.Name(), len(trades)))\n \n return trades\n\ndef buildFrontArenaTradeDictionary(trades):\n tradeDictionary = dict()\n for trade in trades:\n if trade.OptionalKey().__contains__('VOID'):\n tradeDictionary[trade.OptionalKey()[5:]] = trade\n else:\n tradeDictionary[trade.OptionalKey()] = trade\n return tradeDictionary\n\ndef buildMidasTradeDictionary(midas_portfolio):\n global midasData\n \n midasTradeDictionary = {}\n \n for midasTrade in midasData:\n dealDate = midasTrade[9]\n midasPortfolio = midasTrade[23]\n midasBrokerCode = midasTrade[0]\n \n if midasPortfolio == midas_portfolio:\n dealNo = str(int(float(midasTrade[1])))\n shadowDealNo = str(int(float(midasTrade[22])))\n midasKey = ael.date_from_string(dealDate, '%Y-%m-%d').to_string('%Y%m%d') + '_' + dealNo + '_' + shadowDealNo\n midasTradeDictionary[midasKey] = midasTrade[24]\n return midasTradeDictionary\n\ndef reconcileMidasToFrontArena(frontArenaTradeDictionary, midasTradeDictionary):\n global logger\n \n frontArenaCopy = dict(frontArenaTradeDictionary)\n midasCopy = dict(midasTradeDictionary)\n \n logger.info('Number of outstanding Front Arena Trades: %i' %len(frontArenaCopy.keys()))\n logger.info('Number of outstanding Midas Trades: %i' %len(midasCopy.keys()))\n \n for frontTrade in frontArenaTradeDictionary.keys():\n for midasTrade in midasTradeDictionary.keys():\n if frontTrade == midasTrade:\n if (midasCopy[midasTrade] == 'REV' and frontArenaCopy[frontTrade].Status() != 'Void') or (midasCopy[midasTrade] != 'REV' and frontArenaCopy[frontTrade].Status() == 'Void'):\n logger.info('Midas trade %s has Period %s but its corresponding trade in Front Arena, %i, has status %s.' %(midasTrade, midasCopy[midasTrade], frontArenaCopy[frontTrade].Oid(), frontArenaCopy[frontTrade].Status()))\n continue\n\n del frontArenaCopy[frontTrade]\n del midasCopy[midasTrade]\n \n logger.info('Number of outstanding Front Arena Trades: %i' %len(frontArenaCopy.keys()))\n logger.info('Number of outstanding Midas Trades: %i' %len(midasCopy.keys()))\n \n logger.info('\\n')\n return frontArenaCopy, midasCopy\n\ndef reconcileMidasToFrontArenaForeFrontStreetFacing(frontArenaTradeDictionary, midasTradeDictionary, foreFrontTrades):\n global logger\n \n frontArenaCopy = dict(frontArenaTradeDictionary)\n midasCopy = dict(midasTradeDictionary)\n \n logger.info('Number of outstanding Front Arena Trades: %i' %len(frontArenaCopy.keys()))\n logger.info('Number of outstanding Midas Trades: %i' %len(midasCopy.keys()))\n \n for tradeLine in foreFrontTrades:\n midasDealNo = tradeLine[1]\n dealDate = ael.date_from_string(tradeLine[5][:10], '%Y-%m-%d').to_string('%Y%m%d')\n frontTradeNumber = tradeLine[3]\n \n uniqueKey = '%s_%i_0' %(dealDate, midasDealNo)\n \n if uniqueKey in midasTradeDictionary.keys() and uniqueKey in frontArenaTradeDictionary.keys():\n if (midasCopy[uniqueKey] == 'REV' and frontArenaCopy[uniqueKey].Status() != 'Void') or (midasCopy[uniqueKey] != 'REV' and frontArenaCopy[uniqueKey].Status() == 'Void'):\n logger.info('Midas trade %s has Period %s but its corresponding trade in Front Arena, %i, has status %s.' %(uniqueKey, midasCopy[uniqueKey], frontArenaCopy[uniqueKey].Oid(), frontArenaCopy[uniqueKey].Status()))\n continue\n\n del frontArenaCopy[uniqueKey]\n del midasCopy[uniqueKey]\n\n logger.info('Number of outstanding Front Arena Trades: %i' %len(frontArenaCopy.keys()))\n logger.info('Number of outstanding Midas Trades: %i' %len(midasCopy.keys()))\n \n logger.info('\\n')\n return frontArenaCopy, midasCopy\n\ndef reconcileMidasToFrontArenaForeFrontShadow(frontArenaTradeDictionary, midasTradeDictionary, foreFrontTrades):\n global logger\n \n frontArenaCopy = dict(frontArenaTradeDictionary)\n midasCopy = dict(midasTradeDictionary)\n \n logger.info('Number of outstanding Front Arena Trades: %i' %len(frontArenaCopy.keys()))\n logger.info('Number of outstanding Midas Trades: %i' %len(midasCopy.keys()))\n \n for tradeLine in foreFrontTrades:\n midasDealNo = tradeLine[0]\n midasShadowDealNo = tradeLine[1]\n dealDate = ael.date_from_string(tradeLine[3][:10], '%Y-%m-%d').to_string('%Y%m%d')\n frontTradeNumber = tradeLine[2]\n \n uniqueKey = '%s_%i_%i' %(dealDate, midasDealNo, midasShadowDealNo)\n \n if uniqueKey in midasTradeDictionary.keys() and uniqueKey in frontArenaTradeDictionary.keys():\n if (midasCopy[uniqueKey] == 'REV' and frontArenaCopy[uniqueKey].Status() != 'Void') or (midasCopy[uniqueKey] != 'REV' and frontArenaCopy[uniqueKey].Status() == 'Void'):\n logger.info('Midas trade %s has Period %s but its corresponding trade in Front Arena, %i, has status %s.' %(uniqueKey, midasCopy[uniqueKey], frontArenaCopy[uniqueKey].Oid(), frontArenaCopy[uniqueKey].Status()))\n continue\n\n del frontArenaCopy[uniqueKey]\n del midasCopy[uniqueKey]\n\n logger.info('Number of outstanding Front Arena Trades: %i' %len(frontArenaCopy.keys()))\n logger.info('Number of outstanding Midas Trades: %i' %len(midasCopy.keys()))\n \n logger.info('\\n')\n return frontArenaCopy, midasCopy\n\ndef getFrontArenaTradeNumbers(frontArenaTradeList):\n frontArenaTradeNumberTuple = ()\n for trade in frontArenaTradeList:\n frontArenaTradeNumberTuple = frontArenaTradeNumberTuple + (trade.Oid(),)\n return frontArenaTradeNumberTuple\n\ndef getFrontArenaTrades(front_portfolio, midas_portfolio):\n logger.info('Retreiving CFR Trades from Front Arena...')\n frontArenaCFRTrades = getTrades(front_portfolio)\n \n logger.info('Retrieving 4Front trades from Front Arena...')\n foreFrontPortfolio = acm.FPhysicalPortfolio[midas_portfolio]\n frontArena4FrontTrades = []\n if foreFrontPortfolio:\n frontArena4FrontTrades = getTrades(acm.FPhysicalPortfolio[midas_portfolio])\n \n logger.info('Total number of Front Arena Trades: %i' %(len(frontArenaCFRTrades) + len(frontArena4FrontTrades)))\n \n return frontArenaCFRTrades, frontArena4FrontTrades\n\ndef matchingFrontArenaTradesToMidasTrades(frontArena4FrontTrades, foreFrontTradesFromMidas, foreFrontTradesShadowFromMidas):\n global logger\n frontTrades = []\n for tradeLine in foreFrontTradesFromMidas:\n frontTrades.append(tradeLine[3])\n for tradeLine in foreFrontTradesShadowFromMidas:\n frontTrades.append(tradeLine[2])\n \n for trade in frontArena4FrontTrades:\n if trade.Oid() not in frontTrades:\n logger.info('The following Front Arena trade can not be found in Midas: %i with status %s' %(trade.Oid(), trade.Status()))\n\ndef removeVoidedAndReversedTrades(frontArenaTradeDictionary, midasReversedTrades):\n voidedMidasTrades = []\n for midasLine in midasReversedTrades:\n #print str(midasLine[5].replace('-','')), str(midasLine[2]), str(midasLine[3])\n #if '%s_%s_%s' %(str(midasLine[5].replace('-','')), str(midasLine[2]), str(midasLine[3])) == '20160810_134542_0':\n # print '@@' * 200\n voidedMidasTrades.append('%s_%s_%s' %(str(midasLine[4].replace('-', '')), str(midasLine[2]), str(midasLine[3])))\n\n #print frontArenaTradeDictionary.keys()\n #print voidedMidasTrades\n for trade in voidedMidasTrades:\n if trade in frontArenaTradeDictionary.keys():\n del frontArenaTradeDictionary[trade]\n \n return frontArenaTradeDictionary\n\ndef reportFrontArenaSummary(frontArenaTradeDictionary):\n global logger, date\n logger.info('The following Front Arena trades could not be found in Midas:\\n')\n for trade in frontArenaTradeDictionary:\n if ael.date(str(at_time.to_datetime(frontArenaTradeDictionary[trade].CreateTime()).date())) < date:\n logger.info('Trade Number: %i with Trade Status %s and creat time %s' %(frontArenaTradeDictionary[trade].Oid(), frontArenaTradeDictionary[trade].Status(), str(at_time.to_datetime(frontArenaTradeDictionary[trade].CreateTime()))))\n logger.info('\\n')\n\ndef reportMidasSummary(midasTradeDictionary):\n global logger\n logger.info('The following Midas trades could not be found in Front Arena:\\n')\n for trade in midasTradeDictionary:\n logger.info('Trade Number: %s with Trade Status %s' %(trade, midasTradeDictionary[trade]))\n logger.info('\\n')\n \nael_variables = [\n ['date', 'Report Date_General Information', 'date', None, date, 1, 0, 'The report date for which the recon should run.', setFileName, 1],\n ['portfolio', 'Portfolio(s)_General Information', acm.FPhysicalPortfolio, None, '', 1, 1, 'Portoflio(s) that will be reconciled.', None, 1],\n ['midasFileReconOption', 'Midas Recon Selection_General Information', 'string', midasFileReconChoiseList, 'BOTH', 1, 0, 'Which Midas recon should be run against Front Arena.', None, 1],\n ['skipFileTransfer', 'Skip File Transfer_General Information', 'int', [0, 1], 0, 0, 0, 'Files should not be copied. Use this if files were already copied.', None, 1],\n ['sourceMidasExcelFile', 'Source_Midas Client File Locations', 'string', None, 'Y:/Jhb/Internal Audit/Public/HeinrichC/', 1, 0, 'Source file location and file name of the Midas street facing trades in .xlsx format', None, 1],\n ['destinationMidasCSVFile', 'Destination_Midas Client File Locations', 'string', None, 'F:/', 1, 0, 'Destination file location and name of the Midas street facing trades in CSF format.', None, 1],\n ['sourceMidasShadowExcelFile', 'Source_Midas Shadow File Locations', 'string', None, 'Y:/Jhb/Internal Audit/Public/HeinrichC/', 1, 0, 'Source file location and file name of the Midas shadow trades in .xlsx format', None, 1],\n ['destinationMidasShadowCSVFile', 'Destination_Midas Shadow File Locations', 'string', None, 'F:/', 1, 0, 'Destination file location and name of the Midas shadow trades in CSF format.', None, 1]\n ]\n\ndef ael_main(dict):\n global date, midasData, midasDealDate, logger\n \n logger = FLogger.FLogger(logToConsole = False, logToFileAtSpecifiedPath = 'C:/temp/CFR_Recon_%s.txt' %date.to_string('%Y%m%d'))\n \n logger.info('Log File is available on: C:/temp/CFR_Recon_%s.txt' %date.to_string('%Y%m%d'))\n logger.info('Running Midas vs. Front Arena Reconcilliation...\\n')\n logger.info('*' * 100)\n logger.info('Parameters...')\n logger.info(' Report Date: %s' %date)\n logger.info(' Portfolio(s): %s' %dict['portfolio'])\n logger.info(' Midas Recon Type: %s' %dict['midasFileReconOption'])\n logger.info(' Source Midas Client File: %s' %dict['sourceMidasExcelFile'])\n logger.info(' Source Midas Shadow File: %s' %dict['sourceMidasShadowExcelFile'])\n logger.info(' Destination Midas Client File: %s' %dict['destinationMidasCSVFile'])\n logger.info(' Destination Midas Client File: %s' %dict['destinationMidasShadowCSVFile'])\n logger.info('*' * 100 + '\\n')\n \n \n if dict['midasFileReconOption'] in ('CLIENT', 'BOTH'):\n if not dict['skipFileTransfer']:\n logger.info('Copying file %s...' %dict['sourceMidasExcelFile'])\n copyAFile(dict['sourceMidasExcelFile'], dict['destinationMidasCSVFile'])\n logger.info('Loading Midas Data: %s...' %dict['destinationMidasCSVFile'])\n loadMidasData(dict['destinationMidasCSVFile'])\n \n if dict['midasFileReconOption'] in ('SHADOW', 'BOTH'):\n if not dict['skipFileTransfer']:\n logger.info('Copying file %s...' %dict['sourceMidasShadowExcelFile'])\n copyAFile(dict['sourceMidasShadowExcelFile'], dict['destinationMidasShadowCSVFile'])\n logger.info('Loading Midas Shadow Data: %s...' %dict['destinationMidasShadowCSVFile'] + '\\n')\n loadMidasData(dict['destinationMidasShadowCSVFile'])\n \n logger.info('Total Number of Midas Data: %i\\n' %len(midasData))\n \n portfolioCounter = 0\n numberOfPortfolios = len(dict['portfolio'])\n \n establishSQLConnection()\n\n logger.info('Retrieving all Reversed Midas Trades...\\n')\n midasReversedTrades = executeSQLQuery(\"SELECT * FROM OPENQUERY (MIDAS, 'select * from DEALSALLVW where RECI = ''R''')\")\n\n for front_portfolio in dict['portfolio']:\n portfolioCounter = portfolioCounter + 1\n logger.info('*' * 20 + ' Portfolio %i of %i: %s '%(portfolioCounter, numberOfPortfolios, front_portfolio.Name()) + '*' * 20)\n \n midas_portfolio = front_portfolio.Name()[-3:]\n\n logger.info('Building Midas trade dictionary...\\n')\n midasTradeDictionary = buildMidasTradeDictionary(midas_portfolio)\n\n frontArenaCFRTrades, frontArena4FrontTrades = getFrontArenaTrades(front_portfolio, midas_portfolio)\n \n logger.info('Building Front Arena trade dictionary...\\n')\n frontArenaTradeDictionary = buildFrontArenaTradeDictionary(frontArenaCFRTrades)\n \n logger.info('Total number of Front Arena Trades after CFR selection: %i' %len(frontArenaTradeDictionary))\n \n logger.info('Formatting Front Arena 4Front Trade Numbers for Midas Selection...\\n')\n frontArenaTradeNumberTuple = getFrontArenaTradeNumbers(frontArena4FrontTrades)\n \n logger.info('Retrieving 4Front street facing trades from Midas...\\n')\n foreFrontTradesFromMidas = []\n foreFrontTradesShadowFromMidas = []\n if frontArena4FrontTrades:\n for i in range(0, len(frontArenaTradeNumberTuple), 100):\n chunk = frontArenaTradeNumberTuple[i:i+100]\n resultSet = executeSQLQuery(\"SELECT * FROM OPENQUERY (MIDAS, 'SELECT * FROM FORTRESSPF WHERE FRONTDEALNO IN %s')\" %chunk.__str__())\n for result in resultSet:\n foreFrontTradesFromMidas.append(result)\n \n for trade in foreFrontTradesFromMidas:\n frontArenaTradeDictionary['%s_%i_0' %(ael.date_from_string(trade[5][:10], '%Y-%m-%d').to_string('%Y%m%d'), trade[1])] = acm.FTrade[trade[3]]\n\n logger.info('Total number of Front Arena Trades after 4Front Street Facing trade selection in Midas : %i' %len(frontArenaTradeDictionary))\n\n logger.info('Retrieving 4Front shadow trades from Midas...\\n')\n for i in range(0, len(frontArenaTradeNumberTuple), 100):\n chunk = frontArenaTradeNumberTuple[i:i+100]\n resultSet = executeSQLQuery(\"SELECT * FROM OPENQUERY (MIDAS, 'SELECT sh.MIDASDEALNO, sh.SHADOWDEALNO, sh.FRONTINTERNALNO, MAX(p.DATETIMEADDED) AS DEALDATETIME FROM PFSHADOW4F sh LEFT JOIN FORTRESSPF p ON sh.MIDASDEALNO = p.MIDASDEALNO WHERE sh.FRONTINTERNALNO IN %s GROUP BY sh.MIDASDEALNO, sh.SHADOWDEALNO, sh.FRONTINTERNALNO')\" %chunk.__str__())\n for result in resultSet:\n foreFrontTradesShadowFromMidas.append(result)\n\n for trade in foreFrontTradesShadowFromMidas:\n frontArenaTradeDictionary['%s_%i_%s' %(ael.date_from_string(trade[3][:10], '%Y-%m-%d').to_string('%Y%m%d'), trade[0], int(trade[1]))] = acm.FTrade[int(trade[2])]\n\n logger.info('Total number of Front Arena Trades after 4Front Shadow trade selection in Midas: %i' %len(frontArenaTradeDictionary))\n\n logger.info('Number of trades in Front Arena that is missing in Midas based on integration key identification: %i' %(len(frontArenaCFRTrades) + len(frontArena4FrontTrades) - len(frontArenaTradeDictionary.keys())))\n logger.info('Identifying missing trades in Midas...\\n')\n matchingFrontArenaTradesToMidasTrades(frontArena4FrontTrades, foreFrontTradesFromMidas, foreFrontTradesShadowFromMidas)\n\n logger.info('\\n')\n logger.info('Reconciling Midas trades to Front Arena Trades...')\n frontArenaTradeDictionary, midasTradeDictionary = reconcileMidasToFrontArena(frontArenaTradeDictionary, midasTradeDictionary)\n \n logger.info('\\n')\n logger.info('Reconciling Midas trades to Front Arena Trades 4Front Street facing trades...')\n frontArenaTradeDictionary, midasTradeDictionary = reconcileMidasToFrontArenaForeFrontStreetFacing(frontArenaTradeDictionary, midasTradeDictionary, foreFrontTradesFromMidas)\n \n logger.info('\\n')\n logger.info('Reconciling Midas trades to Front Arena Trades 4Front Shadow trades...')\n frontArenaTradeDictionary, midasTradeDictionary = reconcileMidasToFrontArenaForeFrontShadow(frontArenaTradeDictionary, midasTradeDictionary, foreFrontTradesShadowFromMidas)\n\n logger.info('\\n')\n logger.info('Removing trades that are Voided and Reversed in Front Arena and Midas respectively...')\n frontArenaTradeDictionary = removeVoidedAndReversedTrades(frontArenaTradeDictionary, midasReversedTrades)\n\n logger.info('-' * 20 + ' Summary of Front Arena breaks ' + '-' * 20)\n reportFrontArenaSummary(frontArenaTradeDictionary)\n \n logger.info('-' * 20 + ' Summary of Midas breaks ' + '-' * 20)\n reportMidasSummary(midasTradeDictionary)\n closeSQLConnection()\n","sub_path":"Python modules/CFR_Recon.py","file_name":"CFR_Recon.py","file_ext":"py","file_size_in_byte":20035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"65972832","text":"import PIL\nimport random\nimport numpy as np\n\nfrom .KandinskyTruth import KandinskyTruthInterfce\nfrom .KandinskyUniverse import kandinskyShape, overlaps\nfrom .KandinskyUniverse import SimpleUniverse\nfrom .RandomKandinskyFigure import Random\n\n\nclass TwoSquaresOneRandom(KandinskyTruthInterfce):\n def isfuzzy(self):\n return false\n\n def humanDescription(self):\n return \"contain two squares plus one random shape(square, triangle or circle)\"\n\n def true_kf(self, n=1):\n kfs = []\n i = 0\n randomKFgenerator = Random(self.u, 3, 3)\n while i < n:\n kf = randomKFgenerator.true_kf(1)[0]\n numberSquares = 0\n for s in kf:\n if s.shape == \"square\":\n numberSquares = numberSquares + 1\n if numberSquares > 1:\n kfs.append(kf)\n i = i + 1\n return kfs\n\n def false_kf(self, n=1):\n kfs = []\n i = 0\n randomKFgenerator = Random(self.u, 3, 3)\n while i < n:\n kf = randomKFgenerator.true_kf(1)[0]\n numberSquares = 0\n for s in kf:\n if s.shape == \"square\":\n numberSquares = numberSquares + 1\n if numberSquares < 2:\n kfs.append(kf)\n i = i + 1\n return kfs\n\n\n\nclass MyBase(KandinskyTruthInterfce):\n def _randomobject (self, colors, shapes, minsize = 0.1, maxsize = 0.5):\n o = kandinskyShape()\n o.color = random.choice (colors)\n o.shape = random.choice (shapes)\n o.size = minsize + (maxsize-minsize) * random.random ()\n o.x = o.size/2 + random.random () * (1-o.size )\n o.y = o.size/2 + random.random () * (1-o.size )\n return o\n\n # returns a array of shapes\n def _randomkf(self, min, max, colors, shapes):\n kf = []\n kftemp = []\n n = random.randint (min,max)\n\n minsize = 0.1\n if n == 3: minsize = 0.2\n if n == 2: minsize = 0.3\n if n == 1: minsize = 0.4\n \n maxsize = 0.6\n if n == 5: maxsize = 0.5\n if n == 6: maxsize = 0.4\n if n == 7: maxsize = 0.3\n if n > 7: \n m = n-7\n maxsize = 0.2 - m * (0.2)/70.0 \n\n if maxsize < 0.001: maxsize = 0.001\n if minsize > maxsize: minsize = maxsize\n\n # print (n, minsize, maxsize)\n i = 0\n maxtry= 20\n while i\n \n \n \n \n \n %s\n \n \n \"\"\"\n\n EMPTY_REDIRECT = REDIRECT % (0, \"\")\n\n INVALID_PATTERN_REDIRECT = REDIRECT % (5000, \"\"\"\n

Invalid pattern functions:


\n Red = %s
\n Green = %s
\n Blue = %s
\n You will be redirected in 5 seconds.\n \"\"\")\n\n INVALID_NAME_REDIRECT = REDIRECT % (5000, \"\"\"\n

Invalid pattern name: %s


\n This pattern name is already in use.\n You will be redirected in 5 seconds.\n \"\"\")\n\n INVALID_REQUEST_REDIRECT = REDIRECT % (5000, \"\"\"\n

Invalid request


\n You will be redirected in 5 seconds.\n \"\"\")\n\n def __init__(self, pixelUpdater, writerFactory, patternManager):\n self.updater = pixelUpdater\n self.writerFactory = writerFactory\n self.patterns = patternManager\n self.urlParser = UrlParser()\n self.homePageCreator = HomePageHtmlCreator()\n\n def createResponse(self, request):\n path, parameters = self.urlParser.parseURL(request)\n if path.startswith(\"/setPattern\"):\n name = parameters.get(\"name\", None)\n self._setPattern(name)\n return self.EMPTY_REDIRECT\n\n elif path.startswith(\"/addPattern\"):\n name = parameters.get(\"name\", None)\n if self.patterns.isUniqueName(name):\n red = parameters.get(\"red\", None)\n green = parameters.get(\"green\", None)\n blue = parameters.get(\"blue\", None)\n if self.patterns.addPattern(name, red, green, blue):\n return self.EMPTY_REDIRECT\n else:\n return self.INVALID_PATTERN_REDIRECT %(red, green, blue)\n else:\n return self.INVALID_NAME_REDIRECT % name\n\n elif path.startswith(\"/removePattern\"):\n name = parameters.get(\"name\", None)\n self.patterns.removePattern(name)\n return self.EMPTY_REDIRECT\n\n elif path.startswith(\"/setBrightness\"):\n val = int(parameters.get(\"brightness\", 255))\n self.updater.setBrightness(val)\n return self.EMPTY_REDIRECT\n\n elif path.startswith(\"/configure\"):\n return self._configurePattern(parameters)\n\n elif path == \"/home\" or path == \"/\":\n return self.homePageCreator.buildHomePage(self.patterns)\n\n print(\"PYTHON - Couldn't parse query: \", path)\n return self.INVALID_REQUEST_REDIRECT\n\n def _setPattern(self, name):\n self.patterns.setPattern(name)\n writer = self.patterns.getCurrentWriter()\n self.updater.setPixelWriter(writer)\n\n def _configurePattern(self, parameters):\n name = parameters.get(\"name\", None)\n config = self.patterns.getWriter(name).getConfigurer()\n return config.configure(parameters)\n","sub_path":"src/table/web/flask/FlaskHtmlResponseCreator.py","file_name":"FlaskHtmlResponseCreator.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"50785681","text":"import json\nimport sys\nimport hashlib\nimport glob\nfrom tqdm import tqdm\nfrom collections import defaultdict\nimport os\nimport magic\nimport networkx as nx\nimport argparse\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--hashes_storage\", type = str, default = \"data/hashes.json\", help = \"hashes file\")\n parser.add_argument(\"--dict_hashes\", type = str, default = \"data/hashes_magic_dict.json\", help = \"Hashes conversion dict. \")\n parser.add_argument(\"--nodes_180k\", type = str, default = \"data/nodes_180k.json\", help = \"Initial nodes\")\n parser.add_argument(\"--edges_180k\", type = str, default = \"data/edges_180k.json\", help = \"Initial edges. \")\n parser.add_argument(\"--marking_dict\", type = str, default = \"data/marking_dict.json\", help = \"Marking dict. \")\n parser.add_argument(\"--nodes_file\", type = str, default = \"data/nodes.json\", help = \"Output nodes file. \")\n parser.add_argument(\"--edges_file\", type = str, default = \"data/tuples.json\", help = \"Output edges/tuples file. \")\n args = parser.parse_args()\n\n with open(args.hashes_storage, \"r\") as f:\n hashes = json.loads(f.read())\n\n with open(args.dict_hashes, \"r\") as f:\n magic_dict = json.loads(f.read())\n\n with open(args.nodes_180k, \"r\") as f:\n nodes_180k = json.loads(f.read())\n\n with open(args.edges_180k, \"r\") as f:\n all_edges_180k = json.loads(f.read())\n\n with open(args.marking_dict, \"r\") as f:\n marking_dict = json.loads(f.read())\n\n counts = {}\n for key in tqdm(nodes_180k.keys(), mininterval=10):\n if key in magic_dict.keys():\n imgs = set(magic_dict[key])\n counts[key] = len(imgs.intersection(good_imgs))\n else:\n counts[key] = 0\n edggs = {}\n to_use = set([key for key, value in counts.items() if value >= 4])\n for key, value in all_edges_180k.items():\n if key in to_use:\n l = []\n for entry in value:\n if entry[\"s\"] in to_use:\n l.append(entry)\n edggs[key] = l\n\n\n with open(args.nodes_file, \"w\") as f:\n json.dump(new_nodes, f)\n\n with open(args.edges_file, \"w\") as f:\n json.dump(to_use_edg, f)\n","sub_path":"dataset_creation/filter_images.py","file_name":"filter_images.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"324620507","text":"#importing libraries and reading data\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\n# import seaborn as sns\n# from sklearn.preprocessing import StandardScaler\n# from sklearn.neighbors import KNeighborsClassifier\n# from sklearn.metrics import confusion_matrix\n# from sklearn.metrics import f1_score\n# from sklearn.metrics import accuracy_score\n# %matplotlib inline\ndf=pd.read_csv('data_1.csv')\n\n#shows column name that contains zero values\ncolumns=[]\nfor col in df.columns: \n columns.append(col) \na=[]\nf = (df != 0).all(axis=0)\nfor i in range(len(f)):\n if f[i]==False:\n a.append(i) \n\n\n#for i in range(len(a)):\n# print(columns[a[i]])\n\nfor i in range(len(a)):\n df.loc[df[columns[a[i]]] == 0,columns[a[i]]] = np.NaN\n df[columns[a[i]]].fillna((df[columns[a[i]]].mean()),inplace=True)\n df_2 = df.copy() \n\n#for column radius_mean\n#outliers check\ndata=df['radius_mean']\n# sns.boxplot(data)\n#checking skewness of radius_mean\n# df['radius_mean'].skew()\n\n# sns.distplot(df['radius_mean'])\n#removing skewness\ndf['radius_mean_log']=np.sqrt(df['radius_mean'])\n# sns.distplot(df['radius_mean_log'])\n# df['radius_mean_log'].skew()\n\n#calculating outliers\n#for outliers for fractal_dimension_se\nq1, q3= np.percentile(df['radius_mean_log'],[25,75])\niqr = q3 - q1\nlower_bound = q1 -(1.5 * iqr) \nupper_bound = q3 +(1.5 * iqr) \nmedian=np.median(df['radius_mean_log'])\ncount=0\nfor i in range (len(df['radius_mean_log'])):\n if (df.iloc[i]['radius_mean_log']>upper_bound) or (df.iloc[i]['radius_mean_log']upper_bound) or (df.iloc[i]['concavity_se_log']upper_bound) or (df.iloc[i]['concave_points_se_log']upper_bound) or (df.iloc[i]['symmetry_se_log']upper_bound) or (df.iloc[i]['fractal_dimension_se_log']upper_bound) or (df.iloc[i]['radius_worst_log']upper_bound) or (df.iloc[i]['texture_worst_log']upper_bound) or (df.iloc[i]['perimeter_worst_log']upper_bound) or (df.iloc[i]['area_worst_log']upper_bound) or (df.iloc[i]['radius_mean_log']upper_bound) or (df.iloc[i]['texture_mean_log']upper_bound) or (df.iloc[i]['perimeter_mean_log']upper_bound) or (df.iloc[i]['area_mean_log']upper_bound) or (df.iloc[i]['smoothness_mean_log']upper_bound) or (df.iloc[i]['compactness_mean_log']upper_bound) or (df.iloc[i]['concavity_mean_log']upper_bound) or (df.iloc[i]['concave_points_mean_log']upper_bound) or (df.iloc[i]['symmetry_mean_log']upper_bound) or (df.iloc[i]['fractal_dimension_mean_log']upper_bound) or (df.iloc[i]['radius_se_log']upper_bound) or (df.iloc[i]['texture_se_log']upper_bound) or (df.iloc[i]['perimeter_se_log']upper_bound) or (df.iloc[i]['area_se_log']upper_bound) or (df.iloc[i]['smoothness_se_log']upper_bound) or (df.iloc[i]['compactness_se_log']upper_bound) or (df.iloc[i]['smoothness_worst_log']upper_bound) or (df.iloc[i]['compactness_worst_log']upper_bound) or (df.iloc[i]['concavity_worst_log']upper_bound) or (df.iloc[i]['concave_points_worst_log']upper_bound) or (df.iloc[i]['symmetry_worst_log']upper_bound) or (df.iloc[i]['fractal_dimension_worst_log']to match majority class,random_state->reproductible results,\n #replace->sample with replacements\n#display new class\n#combine majority class with upsampled minority class\ndf_upsampled=pd.concat([df_majority,df_minority_upsampled])\ndf_upsampled.diagnosis_1.value_counts()\n\ndf.drop(['fractal_dimension_se_log','symmetry_se_log','fractal_dimension_mean_log','texture_se_log','smoothness_se_log','symmetry_mean_log','id','fractal_dimension_worst_log'],axis=1,inplace=True)\n\n# 'fractal_dimension_se_log','symmetry_se_log',\n#Train data\n\nfrom sklearn.model_selection import train_test_split\nX=df.drop('diagnosis_1',axis=1)\nY=df['diagnosis_1']\n\n# X_train,X_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=5)\n\n#decision tree\n\n\n\n#splitting into train and test\n# from sklearn.model_selection import train_test_split\nX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.3,random_state=5)\n\n\n#performing training using entropy\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier_entropy=DecisionTreeClassifier(criterion='entropy',random_state=42,max_depth=3)\n#creating model\nclassifier_entropy.fit(X_train,Y_train)\n\n#make predictions\n# y_pred=classifier_entropy.predict(X_test)\n\n\n\n#k nearest neighbour\n# from sklearn.neighbors import NearestNeighbors\n# classifier=KNeighborsClassifier(n_neighbors=11,p=2,metric='euclidean')\n# classifier.fit(X_train,Y_train)\n#\nfrom sklearn.ensemble import RandomForestClassifier\n\nrf = RandomForestClassifier(n_estimators=10)\nrf.fit(X_train,Y_train)\n# d=pd.DataFrame(dict(radius_mean_log=[],concavity_se_log=[],concave_points_se_log=[],radius_worst_log=[],texture_worst_log=[],perimeter_worst_log=[],area_worst_log=[],texture_mean_log=[],perimeter_mean_log=[],area_mean_log=[],smoothness_mean_log=[],compactness_mean_log=[],concavity_mean_log=[],concave_points_mean_log=[],radius_se_log=[],perimeter_se_log=[],area_se_log=[],compactness_se_log=[],smoothness_worst_log=[],compactness_worst_log=[],concavity_worst_log=[],concave_points_worst_log=[],symmetry_worst_log=[]))\n\n\n# new={'radius_mean_log':2.482545,'concavity_se_log':0.329457,'concave_points_se_log':0.104067,'radius_worst_log':3.009142,'texture_worst_log':3.323493,'perimeter_worst_log':5.305015,'area_worst_log':10.826478,'texture_mean_log':2.934507,'perimeter_mean_log':4.678428,'area_mean_log':9.01397,'smoothness_mean_log':0.476514,'compactness_mean_log':0.55364,'concavity_mean_log':0.552113,'concave_points_mean_log':0.443969,'radius_se_log':-0.823256,'perimeter_se_log':1.252191,'area_se_log':3.772761,'compactness_se_log':0.312679,'smoothness_worst_log':0.547482,'compactness_worst_log':0.848556,'concavity_worst_log':0.795927,'concave_points_worst_log':0.449889,'symmetry_worst_log':0.73846}\n\n# d=d.append(new,ignore_index=True)\n# rf.predict_proba(d)\n# z=x_test.head(3)\n# rf.predict_proba(z)\n#k nearest neighbour\n# classifier_entropy.predict_proba(z)\n\nimport pickle\nfilename='a.sav'\npickle.dump(rf,open(filename,'wb'))","sub_path":"Breast_cancer_detection/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":29588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"410762582","text":"from __future__ import print_function\nfrom dl_util import *\nfrom ml_util import *\nimport pickle\nimport keras\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D, MaxPooling2D, Input, GlobalMaxPooling2D\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\nimport json\nimport time\n\ndef Inception0(input):\n tower_1 = Conv2D(16, (1, 1), padding='same', activation='relu')(input)\n tower_1 = Conv2D(16, (3, 3), padding='same', activation='relu')(tower_1)\n\n tower_2 = Conv2D(16, (1, 1), padding='same', activation='relu')(input)\n tower_2 = Conv2D(16, (5, 5), padding='same', activation='relu')(tower_2)\n\n tower_3 = Conv2D(16, (1, 1), padding='same', activation='relu')(input)\n\n output = keras.layers.concatenate([tower_1, tower_2, tower_3], axis=-1)\n return output\n\n\ndef Inception(input):\n tower_1 = Conv2D(16, (1, 1), padding='same', activation='relu')(input)\n tower_1 = Conv2D(16, (3, 3), padding='same', activation='relu')(tower_1)\n\n tower_2 = Conv2D(16, (1, 1), padding='same', activation='relu')(input)\n tower_2 = Conv2D(16, (5, 5), padding='same', activation='relu')(tower_2)\n\n tower_3 = MaxPooling2D((3, 3), strides=(1, 1), padding='same')(input)\n tower_3 = Conv2D(16, (1, 1), padding='same', activation='relu')(tower_3)\n\n output = keras.layers.concatenate([tower_1, tower_2, tower_3], axis=-1)\n return output\n\n\ngenerator = ImageDataGenerator(rotation_range=180,\n width_shift_range=0.1,height_shift_range=0.1,\n fill_mode=\"constant\",cval = 0,\n horizontal_flip=True, vertical_flip=True,data_format='channels_last',)\n\n\nif __name__ == \"__main__\":\n\n print(\"Code Version 3.9 - fixed classification \")\n print()\n import argparse\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-d\", \"--dataset\", help= \"dataset to use\", required=True)\n parser.add_argument(\"-p\", \"--processor\", help= \"which processor to run- required in server\", required=False)\n parser.add_argument(\"-e\", \"--epochs\", help= \"epochs(default 30)\", required=False)\n parser.add_argument(\"-b\", \"--batch_size\", help= \"batch_size(default 128)\", required=False)\n parser.add_argument(\"-l\", \"--learning_rate\", help= \"initial learning_rate\", required=False)\n parser.add_argument(\"-c\", \"--concatenation_factor\", help= \"degree of concatenation\", required=False)\n #parser.add_argument(\"-t\", \"--task\", help= \"type of ML task (classification or regression)\", required=True)\n\n args = parser.parse_args()\n if platform.system() == 'Linux' and \"prismatic\" not in platform.node():\n if not args.processor:\n print(\"++++++++++++++++++++++++++\")\n print(\"No GPU mentioned on multi-GPU server\")\n print(\"++++++++++++++++++++++++++\")\n else:\n processor = args.processor\n print(\"++++++++++++++++++++++++++\")\n print(\"Setting GPU to \", processor)\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=processor\n print(\"++++++++++++++++++++++++++\")\n\n dataset = args.dataset\n if \"tox\" in dataset or \"hiv\" in dataset:\n task = \"classification\"\n else:\n task = \"regression\"\n # task = args.task\n print(\"++++++++++++++++++++++++++\")\n print(\"Dataset loaded is\", dataset)\n print('Task is', task)\n print(\"++++++++++++++++++++++++++\")\n\n if args.concatenation_factor:\n concat = int(args.concatenation_factor)\n else:\n concat = 50\n\n if args.epochs:\n epochs = int(args.epochs)\n else:\n epochs = 30\n\n if args.batch_size:\n batch_size = int(args.batch_size)\n else:\n batch_size = 128\n\n if args.learning_rate:\n learning_rate = float(args.learning_rate)\n else:\n learning_rate = 0.001\n print(\"============================\")\n print(\"Number of epochs is\", epochs)\n print(\"Batch size is\", batch_size)\n print(\"Learning rate is\", learning_rate)\n print(\"============================\")\n\n X = loadNumpy(dataset+'_x')\n y = loadData(dataset+'_y')\n\n X_train_val, X_test, y_train_val, y_test = train_test_split(X, y, test_size=0.2, random_state=1024)\n X_train, X_val, y_train, y_val = train_test_split(X_train_val, y_train_val, test_size=0.2, random_state=1024)\n\n from sklearn.preprocessing import RobustScaler\n rbs = RobustScaler(with_centering=True, with_scaling=True, quantile_range=(5.0, 95.0), copy=True)\n if task == \"regression\":\n y_train_s = rbs.fit_transform(y_train.reshape(-1,1))\n y_val_s = rbs.transform(y_val.reshape(-1,1))\n y_test_s = rbs.transform(y_test.reshape(-1,1))\n else:\n\n y_train_s, y_val_s, y_test_s = y_train, y_val, y_test\n\n input_shape = X_train.shape[1:]\n input_img = Input(shape=input_shape)\n\n x = Inception0(input_img)\n x = Inception(x)\n x = Inception(x)\n od=int(x.shape[1])\n x = MaxPooling2D(pool_size=(od,od), strides=(1,1))(x)\n x = Flatten()(x)\n x = Dense(100, activation='relu')(x)\n if task == \"regression\":\n output = Dense(1, activation='linear')(x)\n else:\n output = Dense(1, activation='sigmoid')(x)\n\n model = Model(inputs=input_img, outputs=output)\n #Concatenate for longer epochs\n Xt = np.concatenate([X_train]*concat, axis=0)\n yt = np.concatenate([y_train_s]*concat, axis=0)\n\n g = generator.flow(Xt, yt, batch_size=batch_size, shuffle=True)\n steps_per_epoch = 10000/batch_size\n\n optimizer = Adam(lr=learning_rate)\n model.summary()\n if task == \"regression\":\n model.compile(loss=\"mse\", optimizer=optimizer)\n else:\n model.compile(loss='binary_crossentropy',optimizer=optimizer)\n\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5,patience=10, min_lr=1e-6, verbose=1)\n\n start = time.time()\n history = model.fit_generator(g,\n steps_per_epoch=len(Xt)//batch_size,\n epochs=epochs,\n validation_data=(X_val,y_val_s),\n callbacks=[reduce_lr])\n stop = time.time()\n time_elapsed = stop - start\n\n name = \"chemception_\"+dataset+\"_epochs_\"+str(epochs)+\"_batch_\"+str(batch_size)+\"_learning_rate_\"+str(learning_rate)\n model.save(\"%s.h5\"%name)\n hist = history.history\n pickle.dump(hist, file(\"%s_history.pickle\"%name,\"w\"))\n print(\"########################\")\n print(\"model and history saved\",name)\n print(\"########################\")\n y_predict = model.predict(X_test)\n if task == \"regression\":\n r2 = r2_score(y_test_s,y_predict)\n mean_squared_err = mse(y_test_s,y_predict)\n mean_absolute_err = mae(y_test_s, y_predict)\n mean_absolute_percent_err = Mape(y_test_s, y_predict)\n stats = {\"mape\":mean_absolute_percent_err, \"mae\":mean_absolute_err, \"mse\":mean_squared_err, \"r2\":r2, \"time\":time_elapsed}\n print(\"Test MAPE:\", mean_absolute_percent_err)\n else:#classification\n accuracy = accuracy_score(y_test_s,y_predict)\n f1 = f1_score(y_test_s,y_predict)\n precision = precision_score(y_test_s,y_predict)\n recall = recall_score(y_test_s,y_predict)\n roc_auc = roc_auc_score(y_test_s,y_predict)\n stats = { \"accuracy\":accuracy, \"precision\":precision, \"recall\":recall, \"f1\":f1, \"auc\":roc_auc, \"time\":time_elapsed}\n print(\"Test AUC:\", auc)\n print(stats)\n saveData(stats,\"stats_\"+ name, \"model\")\n print('stats saved',\"model/\"+name)\n\n subject=name\n message=json.dumps(stats)\n send_email(subject, message)\n","sub_path":"run_chemception.py","file_name":"run_chemception.py","file_ext":"py","file_size_in_byte":7769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"267377962","text":"# -*- coding: utf-8 -*-\n\nimport datetime\nimport random\nimport time\nimport os\nimport abc\nimport csv\nimport codecs\nfrom glob import glob\n\nfrom GoogleScraper.proxies import Proxy\nfrom GoogleScraper.database import db_Proxy\nfrom GoogleScraper.parsing import get_parser_by_search_engine, parse_serp\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0\nfrom selenium.webdriver.support import expected_conditions as EC # available since 2.26.0\nfrom selenium.webdriver.common.keys import Keys\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nSEARCH_MODES = ('http', 'selenium', 'http-async')\n\n\nclass GoogleSearchError(Exception):\n pass\n\n\nclass InvalidNumberResultsException(GoogleSearchError):\n pass\n\n\nclass MaliciousRequestDetected(GoogleSearchError):\n pass\n\n\nclass SeleniumMisconfigurationError(Exception):\n pass\n\n\nclass SeleniumSearchError(Exception):\n pass\n\n\nclass StopScrapingException(Exception):\n pass\n\n\n\"\"\"\nGoogleScraper should be as robust as possible.\n\nThere are several conditions that may stop the scraping process. In such a case,\na StopScrapingException is raised with the reason.\n\nImportant events:\n\n- All proxies are detected and we cannot request further keywords => Stop.\n- No internet connection => Stop.\n\n- If the proxy is detected by the search engine we try to get another proxy from the pool and we\n call switch_proxy() => continue.\n\n- If the proxy is detected by the search engine and there is no other proxy in the pool, we wait\n {search_engine}_proxy_detected_timeout seconds => continue.\n + If the proxy is detected again after the waiting time, we discard the proxy for the whole scrape.\n\"\"\"\n\n\ndef get_base_search_url_by_search_engine(config, search_engine_name, search_mode):\n \"\"\"Retrieves the search engine base url for a specific search_engine.\n\n This function cascades. So base urls will\n be overwritten by search_engine urls in the specific mode sections.\n On the other side, if a search engine has no special url in it' corresponding\n mode, the default one from the SCRAPING config section will be loaded.\n\n Args:\n search_engine_name The name of the search engine\n search_mode: The search mode that is used. selenium or http or http-async\n\n Returns:\n The base search url.\n \"\"\"\n assert search_mode in SEARCH_MODES, 'search mode \"{}\" is not available'.format(search_mode)\n\n specific_base_url = config.get('{}_{}_search_url'.format(search_mode, search_engine_name), None)\n\n if not specific_base_url:\n specific_base_url = config.get('{}_search_url'.format(search_engine_name), None)\n\n ipfile = config.get('{}_ip_file'.format(search_engine_name), '')\n\n if os.path.exists(ipfile):\n with open(ipfile, 'rt') as file:\n ips = file.read().split('\\n')\n random_ip = random.choice(ips)\n return random_ip\n\n return specific_base_url\n\n\nclass SearchEngineScrape(metaclass=abc.ABCMeta):\n \"\"\"Abstract base class that represents a search engine scrape.\n \n Each subclass that derives from SearchEngineScrape needs to \n implement some common functionality like setting a proxy, \n returning the found results, caching results and pushing scraped\n data to a storage like a database or an output file.\n \n The derivation is divided in two hierarchies: First we divide child\n classes in different Transport mechanisms. Scraping can happen over \n different communication channels like Raw HTTP, scraping with the\n selenium framework or using the an asynchronous HTTP client.\n \n The next layer is the concrete implementation of the search functionality\n of the specific search engines. This is not done in a extra derivation\n hierarchy (otherwise there would be a lot of base classes for each\n search engine and thus quite some boilerplate overhead), \n instead we determine our search engine over the internal state\n (An attribute name self.search_engine) and handle the different search\n engines in the search function.\n \n Each mode must behave similarly: It can only scrape one search engine at the same time,\n but it may search for multiple search keywords. The initial start number may be\n set by the configuration. The number of pages that should be scraped for each\n keyword is also configurable.\n \n It may be possible to apply all the above rules dynamically for each\n search query. This means that the search page offset, the number of\n consecutive search pages may be provided for all keywords uniquely instead\n that they are the same for all keywords. But this requires also a\n sophisticated input format and more tricky engineering.\n \"\"\"\n\n malicious_request_needles = {\n 'google': {\n 'inurl': '/sorry/',\n 'inhtml': 'detected unusual traffic'\n },\n 'bing': {},\n 'yahoo': {},\n 'baidu': {},\n 'yandex': {},\n 'ask': {},\n 'blekko': {},\n 'duckduckgo': {},\n 'qwant': {}\n }\n\n def __init__(self, config, cache_manager=None, jobs=None, scraper_search=None, session=None, db_lock=None, cache_lock=None,\n start_page_pos=1, search_engine=None, search_type=None, proxy=None, proxies=None, proxy_quarantine=None,\n progress_queue=None):\n \"\"\"Instantiate an SearchEngineScrape object.\n\n Args:\n TODO\n \"\"\"\n # Set the config dictionary\n self.config = config\n\n # Set the cache manager\n self.cache_manager = cache_manager\n\n jobs = jobs or {}\n self.search_engine_name = search_engine\n assert self.search_engine_name, 'You need to specify an search_engine'\n\n self.search_engine_name = self.search_engine_name.lower()\n\n if not search_type:\n self.search_type = self.config.get('search_type', 'normal')\n else:\n self.search_type = search_type\n\n self.jobs = jobs\n\n # the keywords that couldn't be scraped by this worker\n self.missed_keywords = set()\n\n # the number of keywords\n self.num_keywords = len(self.jobs)\n\n # The actual keyword that is to be scraped next\n self.query = ''\n\n # The default pages per keywords\n self.pages_per_keyword = [1, ]\n\n # The number that shows how many searches have been done by the worker\n self.search_number = 1\n\n # The parser that should be used to parse the search engine results\n self.parser = get_parser_by_search_engine(self.search_engine_name)(config=self.config)\n\n # The number of results per page\n self.num_results_per_page = int(self.config.get('num_results_per_page', 10))\n\n # The page where to start scraping. By default the starting page is 1.\n if start_page_pos:\n self.start_page_pos = 1 if start_page_pos < 1 else start_page_pos\n else:\n self.start_page_pos = int(self.config.get('search_offset', 1))\n\n # The page where we are right now\n self.page_number = self.start_page_pos\n\n # Install the proxy if one was provided\n self.proxy = proxy\n if isinstance(proxy, Proxy):\n self.set_proxy()\n self.requested_by = self.proxy.host + ':' + self.proxy.port\n else:\n self.requested_by = 'localhost'\n\n self.proxies = proxies\n self.proxy_quarantine = proxy_quarantine\n\n # the scraper_search object\n self.scraper_search = scraper_search\n\n # the scrape mode\n # to be set by subclasses\n self.scrape_method = ''\n\n # Whether the instance is ready to run\n self.startable = True\n\n # set the database lock\n self.db_lock = db_lock\n\n # init the cache lock\n self.cache_lock = cache_lock\n\n # a queue to put an element in whenever a new keyword is scraped.\n # to visualize the progress\n self.progress_queue = progress_queue\n\n # set the session\n self.session = session\n\n # the current request time\n self.requested_at = None\n\n # The name of the scraper\n self.name = '[{}]'.format(self.search_engine_name) + self.__class__.__name__\n\n # How long to sleep (in seconds) after every n-th request\n self.sleeping_ranges = dict()\n self.sleeping_ranges = self.config.get(\n '{search_engine}_sleeping_ranges'.format(search_engine=self.search_engine_name),\n self.config.get('sleeping_ranges'))\n\n # the default timeout\n self.timeout = 5\n\n # the status of the thread after finishing or failing\n self.status = 'successful'\n\n self.html = ''\n\n self.keyword_planner = self.config.get('keyword_planner')\n\n @abc.abstractmethod\n def search(self, *args, **kwargs):\n \"\"\"Send the search request(s) over the transport.\"\"\"\n\n @abc.abstractmethod\n def set_proxy(self):\n \"\"\"Install a proxy on the communication channel.\"\"\"\n\n @abc.abstractmethod\n def switch_proxy(self, proxy):\n \"\"\"Switch the proxy on the communication channel.\"\"\"\n\n @abc.abstractmethod\n def proxy_check(self, proxy):\n \"\"\"Check whether the assigned proxy works correctly and react\"\"\"\n\n @abc.abstractmethod\n def handle_request_denied(self, status_code):\n \"\"\"Generic behaviour when search engines detect our scraping.\n\n Args:\n status_code: The status code of the http response.\n \"\"\"\n self.status = 'Malicious request detected: {}'.format(status_code)\n\n def store(self):\n \"\"\"Store the parsed data in the sqlalchemy scoped session.\"\"\"\n assert self.session, 'No database session.'\n\n if self.html:\n self.parser.parse(self.html)\n else:\n self.parser = None\n\n with self.db_lock:\n\n serp = parse_serp(self.config, parser=self.parser, scraper=self, query=self.query)\n\n self.scraper_search.serps.append(serp)\n self.session.add(serp)\n self.session.commit()\n\n # store_serp_result(serp, self.config)\n\n if serp.num_results:\n return True\n else:\n return False\n\n def next_page(self):\n \"\"\"Increment the page. The next search request will request the next page.\"\"\"\n self.start_page_pos += 1\n\n def keyword_info(self):\n \"\"\"Print a short summary where we are in the scrape and what's the next keyword.\"\"\"\n logger.info(\n '[{thread_name}][{ip}]]Keyword: \"{keyword}\" with {num_pages} pages, slept {delay} seconds before '\n 'scraping. {done}/{all} already scraped.'.format(\n thread_name=self.name,\n ip=self.requested_by,\n keyword=self.query,\n num_pages=self.pages_per_keyword,\n delay=self.current_delay,\n done=self.search_number,\n all=self.num_keywords\n ))\n\n def instance_creation_info(self, scraper_name):\n \"\"\"Debug message whenever a scraping worker is created\"\"\"\n logger.info('[+] {}[{}][search-type:{}][{}] using search engine \"{}\". Num keywords={}, num pages for keyword={}'.format(\n scraper_name, self.requested_by, self.search_type, self.base_search_url, self.search_engine_name,\n len(self.jobs),\n self.pages_per_keyword))\n\n def cache_results(self):\n \"\"\"Caches the html for the current request.\"\"\"\n self.cache_manager.cache_results(self.parser, self.query, self.search_engine_name, self.scrape_method, self.page_number,\n db_lock=self.db_lock)\n\n def _largest_sleep_range(self, search_number):\n \"\"\"Sleep a given amount of time dependent on the number of searches done.\n\n Args:\n search_number: How many searches the worker has done yet.\n\n Returns:\n A range tuple which defines in which range the worker should sleep.\n \"\"\"\n\n assert search_number >= 0\n if search_number != 0:\n s = sorted(self.sleeping_ranges.keys(), reverse=True)\n for n in s:\n if search_number % n == 0:\n return self.sleeping_ranges[n]\n # sleep one second\n return 1, 2\n\n def detection_prevention_sleep(self):\n # match the largest sleep range\n self.current_delay = random.randrange(*self._largest_sleep_range(self.search_number))\n time.sleep(self.current_delay)\n\n def after_search(self):\n \"\"\"Store the results and parse em.\n\n Notify the progress queue if necessary.\n \"\"\"\n self.search_number += 1\n\n if not self.store():\n logger.debug('No results to store for keyword: \"{}\" in search engine: {}'.format(self.query,\n self.search_engine_name))\n\n if self.progress_queue:\n self.progress_queue.put(1)\n self.cache_results()\n\n def before_search(self):\n \"\"\"Things that need to happen before entering the search loop.\"\"\"\n # check proxies first before anything\n if self.config.get('check_proxies', True) and self.proxy:\n if not self.proxy_check(self.proxy):\n self.startable = False\n\n def update_proxy_status(self, status, ipinfo=None, online=True):\n \"\"\"Sets the proxy status with the results of ipinfo.io\n\n Args:\n status: A string the describes the status of the proxy.\n ipinfo: The json results from ipinfo.io\n online: Whether the proxy is usable or not.\n \"\"\"\n ipinfo = ipinfo or {}\n\n with self.db_lock:\n\n proxy = self.session.query(db_Proxy).filter(self.proxy.host == db_Proxy.ip).first()\n if proxy:\n for key in ipinfo.keys():\n setattr(proxy, key, ipinfo[key])\n\n proxy.checked_at = datetime.datetime.utcnow()\n proxy.status = status\n proxy.online = online\n\n self.session.add(proxy)\n self.session.commit()\n\n\nfrom GoogleScraper.http_mode import HttpScrape\nfrom GoogleScraper.selenium_mode import get_selenium_scraper_by_search_engine_name\n\n\nclass ScrapeWorkerFactory():\n def __init__(self, config, cache_manager=None, mode=None, proxy=None, proxies=None, proxy_quarantine=None,\n search_engine=None, session=None, db_lock=None, cache_lock=None, scraper_search=None,\n captcha_lock=None, progress_queue=None, browser_num=1):\n\n self.config = config\n self.cache_manager = cache_manager\n self.mode = mode\n self.proxy = proxy\n self.proxies = proxies\n self.proxy_quarantine = proxy_quarantine\n self.search_engine = search_engine\n self.session = session\n self.db_lock = db_lock\n self.cache_lock = cache_lock\n self.scraper_search = scraper_search\n self.captcha_lock = captcha_lock\n self.progress_queue = progress_queue\n self.browser_num = browser_num\n\n self.jobs = dict()\n\n def is_suitabe(self, job):\n\n return job['scrape_method'] == self.mode and job['search_engine'] == self.search_engine\n\n def add_job(self, job):\n\n query = job['query']\n page_number = job['page_number']\n\n if query not in self.jobs:\n self.jobs[query] = []\n\n self.jobs[query].append(page_number)\n\n def get_worker(self):\n\n if self.jobs:\n\n if self.mode == 'selenium':\n\n return get_selenium_scraper_by_search_engine_name(\n self.config,\n self.search_engine,\n cache_manager=self.cache_manager,\n search_engine=self.search_engine,\n jobs=self.jobs,\n session=self.session,\n scraper_search=self.scraper_search,\n cache_lock=self.cache_lock,\n db_lock=self.db_lock,\n proxy=self.proxy,\n proxies=self.proxies,\n proxy_quarantine=self.proxy_quarantine,\n progress_queue=self.progress_queue,\n captcha_lock=self.captcha_lock,\n browser_num=self.browser_num,\n )\n\n elif self.mode == 'http':\n\n return HttpScrape(\n self.config,\n cache_manager=self.cache_manager,\n search_engine=self.search_engine,\n jobs=self.jobs,\n session=self.session,\n scraper_search=self.scraper_search,\n cache_lock=self.cache_lock,\n db_lock=self.db_lock,\n proxy=self.proxy,\n progress_queue=self.progress_queue,\n )\n\n return None\n\nclass KeywordPlannerScraper():\n\n \"\"\"Scrape keywords volume search and average bids on Keyword Planner.\n\n Args:\n Keywords input into Keyword planner. Same keywords as the scrapejob.\n\n \"\"\"\n def __init__(self):\n self.selector = {\n 'signin_link': '//*[@id=\"header-links\"]/a[1]',\n 'email': 'Email',\n 'next_button': 'next',\n 'pw': 'Passwd',\n 'signin_button': 'signIn',\n 'search_volume': 'spkc-d',\n 'textarea': 'gwt-debug-upload-text-box',\n 'get_search_volume': 'gwt-debug-upload-ideas-button-content',\n 'get_search_volume_failed': 'spcf-b',\n 'download': 'gwt-debug-search-download-button',\n 'download_link': 'gwt-debug-download-button-content',\n 'downloadfailed': 'spee-b',\n 'savefile': 'gwt-debug-retrieve-download-content',\n }\n\n def keyword_planner_scraper(self, keywords, browser):\n # do the actual work\n driver = self.login_keyword_planner(browser)\n\n if isinstance(keywords, list):\n results = {}\n while len(keywords) > 0:\n self.drive_into_keyword_planner(driver, keywords)\n results.update(self.parse_results_keyword_planner())\n keywords.pop(0)\n if len(keywords) > 0:\n driver.get('https://adwords.google.com/KeywordPlanner')\n else:\n self.drive_into_keyword_planner(driver, keywords)\n results = self.parse_results_keyword_planner()\n\n\n driver.quit()\n return results\n\n def login_keyword_planner(self, browser):\n\n \"\"\"log into Google's Keyword Planner tool. Your username (typically a gmail account)\n and password needs to be stored into environment variables. Respectively under MAIL_USERNAME and\n MAIL_PASSWORD.\n \"\"\"\n\n # creates the webdriver instance with a profile to prevent the Save Dialog from appearing\n if browser == 'chrome':\n try:\n\n chromeOptions = webdriver.ChromeOptions()\n prefs = {\"download.default_directory\" : os.getcwd()}\n chromeOptions.add_experimental_option('prefs',prefs)\n\n driver = webdriver.Chrome(chrome_options=chromeOptions)\n\n except WebDriverException as e:\n # we don't have a chrome executable or a chrome webdriver installed\n raise\n\n elif browser == 'phantomjs':\n try:\n\n dcap = dict(DesiredCapabilities.PHANTOMJS)\n dcap[\"phantomjs.page.settings.userAgent\"] = random_user_agent(only_desktop=True)\n\n driver = webdriver.PhantomJS(desired_capabilities=dcap)\n\n except WebDriverException as e:\n logger.error(e)\n\n elif browser == 'firefox':\n try:\n\n profile = webdriver.FirefoxProfile()\n profile.set_preference(\"browser.download.folderList\",2)\n profile.set_preference(\"browser.download.manager.showWhenStarting\", False)\n profile.set_preference(\"browser.download.dir\", os.getcwd())\n profile.set_preference(\"browser.helperApps.neverAsk.saveToDisk\",'text/csv')\n\n driver = webdriver.Firefox(firefox_profile=profile)\n\n except WebDriverException as e:\n logger.error(e)\n\n driver.get('https://adwords.google.com/KeywordPlanner')\n\n # click on the 'Sign In' link on top right of the page\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, self.selector['signin_link'])))\n signin_link = driver.find_element_by_xpath(self.selector['signin_link'])\n signin_link.click()\n\n # fill in the Email form\n WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, self.selector['email'])))\n email = driver.find_element_by_id(self.selector['email'])\n email.send_keys(os.environ.get('MAIL_USERNAME') + Keys.ENTER)\n\n # # click on the Next button\n # WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.ID, self.selector['next_button'])))\n # next_button = driver.find_element_by_id(self.selector['next_button'])\n # next_button.click()\n\n # fill in the Password form\n WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID, self.selector['pw'])))\n pw = driver.find_element_by_id(self.selector['pw'])\n pw.send_keys(os.environ.get('MAIL_PASSWORD') + Keys.ENTER)\n\n # # click on the 'Sign In' button\n # WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.ID, self.selector['signin_button'])))\n # signin = driver.find_element_by_id(self.selector['signin_button'])\n # signin.click()\n\n return driver\n\n def drive_into_keyword_planner(self, driver, keywords):\n # click on the tool 'Get search volume data and trends'\n WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CLASS_NAME, self.selector['search_volume'])))\n search_volume = driver.find_elements_by_class_name(self.selector['search_volume'])\n search_volume[1].click()\n\n # fill in the Keywords form\n WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID, self.selector['textarea'])))\n textarea = driver.find_element_by_id(self.selector['textarea'])\n textarea.send_keys(keywords)\n\n # click on 'Get search volume'\n WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.ID, self.selector['get_search_volume'])))\n get_search_volume = driver.find_element_by_id(self.selector['get_search_volume'])\n get_search_volume.click()\n\n # this loop makes sure Keyword Planner does get the volume search for the keywords.\n # Sometimes it fails so it will loop until we get the results\n try:\n while True:\n time.sleep(5)\n # WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CLASS_NAME, self.selector['get_search_volume_failed'])))\n get_search_volume_failed = driver.find_elements_by_class_name(self.selector['get_search_volume_failed'])\n if get_search_volume_failed[0].text == 'There was a problem retrieving ideas, please try again.':\n time.sleep(5)\n get_search_volume = driver.find_element_by_id(self.selector['get_search_volume'])\n get_search_volume.click()\n else:\n break\n except NoSuchElementException:\n pass\n\n # click on the Download button\n WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, self.selector['download'])))\n download = driver.find_element_by_id(self.selector['download'])\n download.click()\n\n # a popup should appear about our download, this clicks on the new Download button\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, self.selector['download_link'])))\n download_link = driver.find_element_by_id(self.selector['download_link'])\n download_link.click()\n\n # this loop makes sure Keyword Planner does prepare our output file.\n # Sometimes it fails so it will loop until it works\n try:\n while True:\n time.sleep(5)\n # WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CLASS_NAME, self.selector['downloadfailed'])))\n downloadfailed = driver.find_elements_by_class_name(self.selector['downloadfailed'])\n if downloadfailed[0].text == 'Your download operation failed. Please try again.':\n time.sleep(5)\n download_link = driver.find_element_by_id(self.selector['download_link'])\n download_link.click()\n else:\n break\n except NoSuchElementException:\n pass\n\n # click on the final 'Save file' button\n WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.ID, self.selector['savefile'])))\n savefile = driver.find_element_by_id(self.selector['savefile'])\n savefile.click()\n\n def parse_results_keyword_planner(self):\n\n \"\"\"parse the newly Keyword Planner output file into a dict\"\"\"\n\n # these 2 lines help to find the file we just downloaded,\n # since it is not possible to change the filename at save\n time.sleep(5)\n d = datetime.datetime.now()\n dday = '0' + str(d.day) if len(str(d.day)) == 1 else str(d.day)\n dmonth = '0' + str(d.month) if len(str(d.month)) == 1 else str(d.month)\n filenames = glob('Keyword Planner ' + str(d.year) + '-' + str(dmonth) + '-' + str(dday) + ' at ' + '*.csv')\n keyword_planner_results_as_a_dict = {}\n\n for filename in filenames:\n with codecs.open(filename, 'r', encoding='utf-16') as f:\n results=csv.DictReader(f, dialect='excel-tab')\n for r in results:\n keyword_planner_results_as_a_dict['Keyword'] = r['Keyword']\n keyword_planner_results_as_a_dict[r['Keyword']] = {\n 'avg_monthly_search': r['Avg. Monthly Searches (exact match only)'],\n 'competition': r['Competition'],\n 'suggested_bid': r['Suggested bid']\n }\n os.remove(filename)\n\n return keyword_planner_results_as_a_dict","sub_path":"GoogleScraper/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":26611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"580855749","text":"\"\"\"\n SoftLayer.tests.CLI.modules.dns_tests\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n :license: MIT, see LICENSE for more details.\n\"\"\"\nimport os.path\n\nimport mock\n\nfrom SoftLayer.CLI import exceptions\nfrom SoftLayer.CLI import formatting\nfrom SoftLayer.CLI.modules import dns\nfrom SoftLayer import testing\nfrom SoftLayer.testing import fixtures\n\n\nclass DnsTests(testing.TestCase):\n def set_up(self):\n self.client = testing.FixtureClient()\n self.env = mock.MagicMock()\n\n def test_dump_zone(self):\n command = dns.DumpZone(client=self.client)\n\n output = command.execute({'': '1234'})\n self.assertEqual('lots of text', output)\n\n def test_create_zone(self):\n command = dns.CreateZone(client=self.client)\n\n output = command.execute({'': 'example.com'})\n self.assertEqual(None, output)\n\n @mock.patch('SoftLayer.CLI.formatting.no_going_back')\n def test_delete_zone(self, no_going_back_mock):\n no_going_back_mock.return_value = True\n command = dns.DeleteZone(client=self.client)\n\n output = command.execute({'': 'example.com', '--really': False})\n self.assertEqual(None, output)\n\n no_going_back_mock.return_value = False\n command = dns.DeleteZone(client=self.client)\n\n self.assertRaises(exceptions.CLIAbort,\n command.execute, {'': 'example.com',\n '--really': False})\n\n def test_list_zones(self):\n command = dns.ListZones(client=self.client)\n\n output = command.execute({'': None})\n self.assertEqual([{'serial': 2014030728,\n 'updated': '2014-03-07T13:52:31-06:00',\n 'id': 12345, 'zone': 'example.com'}],\n formatting.format_output(output, 'python'))\n\n def test_list_all_zones(self):\n command = dns.ListZones(client=self.client)\n\n output = command.execute({'': 'example.com'})\n self.assertEqual({'record': 'a',\n 'type': 'CNAME',\n 'id': 1,\n 'value': 'd',\n 'ttl': 100},\n formatting.format_output(output, 'python')[0])\n\n def test_add_record(self):\n command = dns.AddRecord(client=self.client)\n\n output = command.execute({'': 'example.com',\n '': 'hostname',\n '': 'A',\n '': 'd',\n '--ttl': 100})\n self.assertEqual(None, output)\n\n def test_edit_record(self):\n command = dns.EditRecord(client=self.client)\n\n output = command.execute({'': 'example.com',\n '': 'hostname',\n '': 'A',\n '--data': 'd',\n '--id': 1,\n '--ttl': 100})\n self.assertEqual(None, output)\n\n output = command.execute({'': 'example.com',\n '': 'hostname',\n '': 'A',\n '--data': 'd',\n '--id': None,\n '--ttl': 100})\n self.assertEqual(None, output)\n\n @mock.patch('SoftLayer.CLI.formatting.no_going_back')\n def test_delete_record(self, no_going_back_mock):\n no_going_back_mock.return_value = True\n self.client['Dns_Domain'].getResourceRecords.return_value = [\n fixtures.Dns_Domain.getResourceRecords[0]]\n command = dns.RecordRemove(client=self.client)\n output = command.execute({'': 'example.com',\n '': 'hostname',\n '--id': '1',\n '--really': False})\n self.assertEqual([{'record': '1'}],\n formatting.format_output(output, 'python'))\n\n output = command.execute({'': 'example.com',\n '': 'hostname',\n '--id': None,\n '--really': False})\n self.assertEqual([{'record': 1}],\n formatting.format_output(output, 'python'))\n\n no_going_back_mock.return_value = False\n self.assertRaises(exceptions.CLIAbort,\n command.execute, {'': 'example.com',\n '': 'hostname',\n '--id': 1,\n '--really': False})\n\n def test_parse_zone_file(self):\n zone_file = \"\"\"$ORIGIN realtest.com.\n$TTL 86400\n@ IN SOA ns1.softlayer.com. support.softlayer.com. (\n 2014052300 ; Serial\n 7200 ; Refresh\n 600 ; Retry\n 1728000 ; Expire\n 43200) ; Minimum\n\n@ 86400 IN NS ns1.softlayer.com.\n@ 86400 IN NS ns2.softlayer.com.\n\n IN MX 10 test.realtest.com.\ntesting 86400 IN A 127.0.0.1\ntesting1 86400 IN A 12.12.0.1\nserver2 IN A 1.0.3.4\nftp IN CNAME server2\ndev.realtest.com IN TXT \"This is just a test of the txt record\"\n IN AAAA 2001:db8:10::1\nspf IN TXT \"v=spf1 ip4:192.0.2.0/24 ip4:198.51.100.123 a\"\n\n\"\"\"\n expected = [{'data': 'ns1.softlayer.com.',\n 'record': '@',\n 'record_type': 'NS',\n 'ttl': '86400'},\n {'data': 'ns2.softlayer.com.',\n 'record': '@',\n 'record_type': 'NS',\n 'ttl': '86400'},\n {'data': '127.0.0.1',\n 'record': 'testing',\n 'record_type': 'A',\n 'ttl': '86400'},\n {'data': '12.12.0.1',\n 'record': 'testing1',\n 'record_type': 'A',\n 'ttl': '86400'},\n {'data': '1.0.3.4',\n 'record': 'server2',\n 'record_type': 'A',\n 'ttl': None},\n {'data': 'server2',\n 'record': 'ftp',\n 'record_type': 'CNAME',\n 'ttl': None},\n {'data': '\"This is just a test of the txt record\"',\n 'record': 'dev.realtest.com',\n 'record_type': 'TXT',\n 'ttl': None},\n {'data': '\"v=spf1 ip4:192.0.2.0/24 ip4:198.51.100.123 a\"',\n 'record': 'spf',\n 'record_type': 'TXT',\n 'ttl': None}]\n zone, records, bad_lines = dns.parse_zone_details(zone_file)\n self.assertEqual(zone, 'realtest.com')\n self.assertEqual(records, expected)\n self.assertEqual(len(bad_lines), 13)\n\n def test_import_zone_dry_run(self):\n command = dns.ImportZone(client=self.client, env=self.env)\n path = os.path.join(testing.FIXTURE_PATH, 'realtest.com')\n output = command.execute({\n '': path,\n '--dry-run': True,\n })\n\n # Dry run should not result in create calls\n self.assertFalse(self.client['Dns_Domain'].createObject.called)\n record_service = self.client['Dns_Domain_ResourceRecord']\n self.assertFalse(record_service.createObject.called)\n\n self.assertEqual(None, output)\n\n def test_import_zone(self):\n command = dns.ImportZone(client=self.client, env=self.env)\n path = os.path.join(testing.FIXTURE_PATH, 'realtest.com')\n output = command.execute({\n '': path,\n '--dry-run': False,\n })\n\n self.assertFalse(self.client['Dns_Domain'].createObject.called)\n record_service = self.client['Dns_Domain_ResourceRecord']\n self.assertEqual(record_service.createObject.call_args_list,\n [mock.call({'data': 'ns1.softlayer.com.',\n 'host': '@',\n 'domainId': 12345,\n 'type': 'NS',\n 'ttl': '86400'}),\n mock.call({'data': 'ns2.softlayer.com.',\n 'host': '@',\n 'domainId': 12345,\n 'type': 'NS',\n 'ttl': '86400'}),\n mock.call({'data': '127.0.0.1',\n 'host': 'testing',\n 'domainId': 12345,\n 'type': 'A',\n 'ttl': '86400'}),\n mock.call({'data': '12.12.0.1',\n 'host': 'testing1',\n 'domainId': 12345,\n 'type': 'A',\n 'ttl': '86400'}),\n mock.call({'data': '1.0.3.4',\n 'host': 'server2',\n 'domainId': 12345,\n 'type': 'A',\n 'ttl': None}),\n mock.call({'data': 'server2',\n 'host': 'ftp',\n 'domainId': 12345,\n 'type': 'CNAME',\n 'ttl': None}),\n mock.call({'data':\n '\"This is just a test of the txt record\"',\n 'host': 'dev.realtest.com',\n 'domainId': 12345,\n 'type': 'TXT',\n 'ttl': None}),\n mock.call({'data': '\"v=spf1 ip4:192.0.2.0/24 '\n 'ip4:198.51.100.123 a -all\"',\n 'host': 'spf',\n 'domainId': 12345,\n 'type': 'TXT',\n 'ttl': None})])\n\n self.assertEqual(\"Finished\", output)\n","sub_path":"SoftLayer/tests/CLI/modules/dns_tests.py","file_name":"dns_tests.py","file_ext":"py","file_size_in_byte":10759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"642722368","text":"#!/usr/bin/env python\n# -*- coding=utf-8 -*-\n\ndef search_2d_mat(mat, target):\n return binary_search_2d_mat(mat, target)\n\ndef binary_search_2d_mat(mat, target):\n ret = -1\n for m in range(len(mat)):\n ret = binary_search_r(mat[m], target, 0, len(mat[m]) - 1)\n if ret != -1:\n return True\n return False\n\ndef binary_search_r(data, target, left, right):\n if left > right:\n return -1\n mid = (left + right) // 2\n if data[mid] == target:\n return mid\n elif data[mid] > target:\n return binary_search_r(data, target, left, mid - 1)\n else:\n return binary_search_r(data, target, mid + 1, right)\n\ndef binary_search(data, target):\n \"\"\"binary search\n\n Args:\n data (list): input list (binary search works only on a sorted list)\n target (int): target value\n \n Returns:\n int: the index of the target value in the list\n \"\"\"\n\n return _binary_search(data, target, 0, len(data) - 1)\n\n\ndef _binary_search(data, target, left, right):\n \"\"\"binary search algorithm\n\n First, compare the target value with the element located at middle of the left and right bounds.\n If the target value is greater than the value at middle, increase the left bound, else decrease\n the right bound.\n Repeat this process recursively until left bound is greater than right bound.\n If the target value equal the value at middle, we return the index of middle.\n If the target value is not present in the list, we return -1.\n \n Args:\n data (list): input list\n target (int): target value\n left (int): left bound of the input list\n right (int): right bound of the input list\n \n Returns:\n int: the index of the target value in the list\n \"\"\"\n\n if left > right:\n return -1\n\n mid = (left + right) // 2\n if data[mid] == target:\n return mid\n elif data[mid] > target:\n return _binary_search(data, target, left, mid - 1)\n else:\n return _binary_search(data, target, mid + 1, right)\n\ndef binary_search_iter(data, target):\n left, right = 0, len(data) - 1\n while left <= right:\n mid = (left + right) // 2\n if data[mid] == target:\n return mid\n elif target < data[mid]:\n right = mid - 1\n else:\n left = mid + 1\n return -1\n\ndef binary_search_sparse(strs, s, left, right):\n if left > right:\n return -1\n\n mid = (left + right) // 2\n if strs[mid] == '':\n near_left = mid - 1\n near_right = mid + 1\n while True:\n if near_left < left and right < near_right:\n return -1\n elif left <= near_left and strs[near_left] != '':\n mid = near_left\n elif near_right <= right and strs[near_right] != '':\n mid = near_right\n near_left -= 1\n near_right += 1\n\n if strs[mid] == s:\n return mid\n elif s < strs[mid]:\n return binary_search_sparse(strs, s, left, mid - 1)\n else:\n return binary_search_sparse(strs, s, mid + 1, right)\n\nif __name__ == \"__main__\":\n data = [1, 3, 4, 13, 40, 193]\n target = 40\n print('org:', data)\n result = binary_search(data, target)\n if result != -1:\n print('target {} is present at index {}'.format(target, result)) \n else:\n print('target {} is not present in the list'.format(target))","sub_path":"python/binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"331851827","text":"\"\"\" BLOB API\n\"\"\"\nfrom core_main_app.access_control.api import (\n can_change_owner,\n can_write,\n)\nfrom core_main_app.access_control.api import (\n has_perm_administration,\n can_read_or_write_in_workspace,\n can_read_id,\n)\nfrom core_main_app.access_control.decorators import access_control\nfrom core_main_app.commons import exceptions\nfrom core_main_app.components.blob.access_control import (\n can_write_blob_workspace,\n can_write_blob,\n can_write_metadata,\n can_write_metadata_list,\n)\nfrom core_main_app.components.blob.models import Blob\n\n\n@access_control(can_write_blob)\ndef insert(blob, user):\n \"\"\"Insert the blob in the blob repository.\n\n Args:\n blob:\n user:\n\n Returns:\n\n \"\"\"\n # if blob is already created\n if blob.id:\n raise exceptions.ApiError(\n \"Unable to save the blob: change is not allowed. Insert method only for blob creation.\"\n )\n # if blob is not set\n if blob.blob is None:\n raise exceptions.ApiError(\n \"Unable to save the blob: blob field is not set.\"\n )\n # save blob in database\n blob.save_object()\n return blob\n\n\n@access_control(can_write_blob_workspace)\ndef assign(blob, workspace, user):\n \"\"\"Assign blob to a workspace.\n\n Args:\n blob:\n workspace:\n user:\n\n Returns:\n\n \"\"\"\n blob.workspace = workspace\n return blob.save()\n\n\n@access_control(can_write)\ndef delete(blob, user):\n \"\"\"Delete the blob.\n\n Args:\n blob:\n user:\n\n Returns:\n\n \"\"\"\n # delete blob in database\n return blob.delete()\n\n\n@access_control(can_read_id)\ndef get_by_id(blob_id, user):\n \"\"\"Return blob by its id.\n\n Args:\n blob_id:\n user:\n\n Returns:\n\n \"\"\"\n return Blob.get_by_id(blob_id)\n\n\n@access_control(has_perm_administration)\ndef get_all(user):\n \"\"\"Return all blobs.\n\n Args:\n\n Returns:\n List of Blob instances.\n\n \"\"\"\n return Blob.get_all()\n\n\ndef get_all_by_user(user):\n \"\"\"Return all blobs by user.\n\n Args:\n user: User\n\n Returns:\n List of Blob instances for the given user id.\n\n \"\"\"\n return Blob.get_all_by_user_id(str(user.id))\n\n\n@access_control(can_read_or_write_in_workspace)\ndef get_all_by_workspace(workspace, user):\n \"\"\"Get all data that belong to the workspace.\n\n Args:\n workspace:\n user:\n\n Returns:\n\n \"\"\"\n return Blob.get_all_by_workspace(workspace)\n\n\n@access_control(can_change_owner)\ndef change_owner(blob, new_user, user):\n \"\"\"Change blob's owner.\n\n Args:\n blob:\n user:\n new_user:\n\n Returns:\n \"\"\"\n # FIXME: user can transfer data to anybody, too permissive\n blob.user_id = str(new_user.id)\n blob.save()\n\n\ndef get_none():\n \"\"\"Returns None object, used by blobs\n\n Returns:\n\n \"\"\"\n return Blob.get_none()\n\n\n@access_control(can_write_metadata)\ndef add_metadata(blob, metadata, user):\n \"\"\"Add metadata to blob\n\n Args:\n blob:\n metadata:\n user:\n\n Returns:\n\n \"\"\"\n blob._metadata.add(metadata)\n blob.save()\n\n\n@access_control(can_write_metadata_list)\ndef add_metadata_list(blob, metadata_list, user):\n \"\"\"Add list of metadata to blob\n\n Args:\n blob:\n metadata_list:\n user:\n\n Returns:\n\n \"\"\"\n for metadata in metadata_list:\n blob._metadata.add(metadata)\n blob.save()\n\n\n@access_control(can_write_metadata)\ndef remove_metadata(blob, metadata, user):\n \"\"\"Remove metadata from blob\n\n Args:\n blob:\n metadata:\n user:\n\n Returns:\n\n \"\"\"\n blob._metadata.remove(metadata)\n blob.save()\n metadata._blob = None\n metadata.save()\n","sub_path":"core_main_app/components/blob/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"486631701","text":"from typing import List\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n adj = [[] for _ in range(numCourses)]\n for sublist in prerequisites:\n adj[sublist[0]].append(sublist[1])\n status = [0]*numCourses # 0 for unvisited, 1 for visited, -1 for visiting\n for i in range(numCourses):\n if self.hascycle(adj,i,status):\n return False\n return True\n \n def hascycle(self,adj,node,status):\n if status[node] == 1:\n return False\n if status[node] == -1:\n return True\n status[node] = -1\n for i in adj[node]:\n if self.hascycle(adj,i,status):\n return True\n status[node] = 1\n return False\n\nx = Solution()\n#a = [[1,0],[2,6],[1,7],[6,4],[7,0],[6,5]]\na = [[0,1],[1,0]]\nres = x.canFinish(2,a)\nprint(res)","sub_path":"leetcode207.py","file_name":"leetcode207.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"567223161","text":"# coding=utf-8\n\n# 试剂浓度\nCONCENTRATION = {\n 'mv_conc': 50.0, # Monovalent cation concentration (mM)\n 'dv_conc': 0.0, # Divalent cation concentration (mM)\n 'dntp_conc': 0.8, # dNTP concentration (mM)\n 'dna_conc': 50.0, # DNA concentration (nM)\n}\n\n# For homodimer/heterodimer/end stability calculation\nSECONDARY_STRUCTURE = {\n 'temp_c': 37, # Simulation temperature for dG calcs (C)\n 'max_loop': 30, # Maximum size of loops in the structure\n}\nSECONDARY_STRUCTURE.update(CONCENTRATION)\n\n# For Tm calculations\nTM_PARAMETER = {\n 'max_nn_length': 60, # Maximum length for nearest-neighbor calcs\n 'tm_method': 'santalucia', # Tm calculation method (breslauer or santalucia)\n # Salt correction method (schildkraut, owczarzy, santalucia)\n 'salt_corrections_method': 'santalucia',\n}\nTM_PARAMETER.update(CONCENTRATION)\n\nMIN_PRIMER_LEN, OPT_PRIMER_LEN, MAX_PRIMER_LEN = 16, 22, 30\nMIN_TM, OPT_TM, MAX_TM = 50., 60., 70.\nMIN_GC, OPT_GC, MAX_GC = 30., 50., 70\nMAX_DELTA_TM = 5. # delta Tm between primer pair\nMAX_SECONDARY_STRUCTURE_DELTA_TM = 10. # delta Tm between OPT_TM and secondary structure Tm\nWEIGHTS = {\n 'Tm': 0.9,\n 'length': 0.2,\n 'GC': 0.8,\n 'secondary_structure': 0.5,\n 'delta_Tm': 0.8,\n}\n","sub_path":"genoprime/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"326624926","text":"from flask import Flask, render_template, request, jsonify\r\nimport db\r\nimport psycopg2\r\n\r\nconn = psycopg2.connect(\r\n host=\"localhost\",\r\n database=\"postgres\",\r\n user=\"postgres\",\r\n password=\"Vsr@18267\",\r\n port=\"5432\"\r\n)\r\nprint(conn)\r\ntable_customer_query = '''\r\n CREATE TABLE Todo(\r\n ID INT PRIMARY KEY NOT NULL,\r\n NAME Varchar NOT NULL,\r\n COMPANY varchar\r\n )\r\n'''\r\ncur = conn.cursor()\r\n\r\ncur.execute(table_customer_query)\r\nconn.commit()\r\nprint(\"Table created\")","sub_path":"table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"62111411","text":"from flask import Flask, render_template, request, redirect, url_for, session, jsonify\nimport pymysql, hashlib, math\nimport ssl\nimport json\nfrom urllib.request import *\nfrom bs4 import BeautifulSoup\nimport re\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport xlwt\nimport sys\nimport requests\nssl._create_default_https_context=ssl._create_unverified_context()\n#创建数据库\ndb = pymysql.connect(host=\"localhost\", user=\"root\", password=\"\", db=\"green\", port=3307) # port=3307 因为数据库3306被占用\n# 创建游标 (相当于指针���\ncur = db.cursor()\n# 实例化应用\napp = Flask(__name__)\napp.secret_key = '123456'\n# 路由\n\n# 前台逻辑\n\n@app.route(\"/\") # / 默认为首页\ndef index():\n cur = db.cursor()\n sql = \"select * from rendering \"\n cur.execute(sql)\n res = cur.fetchall()\n sql1 = \"select * from cases\"\n cur.execute(sql1)\n res1 = cur.fetchall()\n return render_template(\"/green-master/index.html\", data=res, case=res1)\n@app.route(\"/lore\")\ndef lore():\n return render_template(\"/green-master/lore.html\")\n@app.route(\"/effect_item1\")\ndef effect_item1():\n return render_template(\"/green-master/effect_item1.html\")\n@app.route(\"/effect_item\")\ndef effect_item():\n return render_template(\"/green-master/effect_item.html\")\n@app.route(\"/effect\")\ndef effect():\n\n return render_template(\"/green-master/effect.html\")\n@app.route(\"/case_item\")\ndef case_item():\n return render_template(\"/green-master/case_item.html\")\n@app.route(\"/case\")\ndef case():\n return render_template(\"/green-master/case.html\")\n@app.route(\"/about\")\ndef about():\n return render_template(\"/green-master/about.html\")\n\n\n# 获取表单数据\n@app.route(\"/obtain\", methods=['post'])\ndef obtain():\n\n # sql = \"insert into obtain(area, room, hall, floor) values ('%s',%s, '%s',%s)\" % (area, room, hall, floor)\n # cur.execute(sql)\n # db.commit()\n\n# 首页预测房价\n# 爬取太原市小店区房价\n# info = []\n# for i in range(33, 40):\n# URL = \"http://taiyuan.esf.fang.com/house-a0459/i${i}/\"\n# headers = {\n# 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'\n# }\n#\n# res = requests.get(URL)\n# soup = BeautifulSoup(res.text, 'html.parser', exclude_encodings='utf-8')\n# house_Infos = soup.select('.shop_list .clearfix')\n# # print(house_Infos)\n# for item in house_Infos:\n# if len(item.select('h4 a span')) == 0:\n# continue\n# con = item.select('.tel_shop')[0].text\n# # print(con)\n# house = re.sub('[\\n, \\r\\n, \" \"]', '', con).split(\"|\") # 房子信息\n# # house[1] = re.sub('\\D', '', house[1])\n# house[1] = ''.join(re.findall(\"[\\d,.]\", house[1])) # 匹配非数字\n# price = (item.select('.price_right .red')[0].text)\n# house.append(price)\n# info.append(house)\n#\n# columns = ['roomnum', 'AREA', 'floor', 'dire', 'C_year', 'who\\'s', 'price']\n# save_file = pd.DataFrame(info, columns=columns)\n# save_file.to_csv('house.csv', index=False, encoding=\"utf_8_sig\")\n # df['AREA'] = df['AREA'].astype(float)\n df = pd.read_csv('house.csv', engine='python', encoding='utf_8_sig')\n df[['室', '厅']] = df['roomnum'].str.extract('(\\d+)室(\\d+)厅') # 截取\n # del df['roomnum']\n df['floor'] = df['floor'].str.extract('([\\u4e00-\\u9fa5]层)')\n df['C_year'] = df['C_year'].str.extract('(\\d+)')\n df['price'] = df['price'].str.extract('(\\d+)')\n df = df.dropna(axis=0)\n pd.set_option('display.max_column', None)\n # print(df['dire'].value_counts())\n # print(df['floor'])\n del df['dire']\n df1 = pd.get_dummies(df[['floor']])\n # print(df1.head(10))\n X = pd.concat([df[['AREA', '室', '厅']], df1], axis=1)\n y = df['price']\n\n from sklearn import datasets\n from sklearn import metrics\n from sklearn import linear_model\n from sklearn.model_selection import train_test_split\n\n ###这个模块中含有评分函数,性能度量,距离计算等\n from sklearn import metrics\n # X_train, X_test, y_train, y_test = train_test_split(X, y,random_state=1)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=17)\n # print(X_train.shape)\n # print(y_train.shape)\n # print(X_test.shape)\n # print(y_test.shape)\n ##加载线性回归模型\n reg = LinearRegression()\n ##将训练数据传入开始\n m = reg.fit(X, y)\n # print(reg.coef_) #系数,有些模型没有系数(如k近邻)\n # print(reg.intercept_) #与y轴交点,即截距\n n = reg.score(X, y)\n # print(n)\n model_ridge = linear_model.Ridge(alpha=5)\n model_ridge.fit(X_train, y_train)\n # print(model_ridge.coef_)\n # print(model_ridge.intercept_)\n\n y_pred = reg.predict(X_test)\n y_ridge_pred = model_ridge.predict(X_test)\n # print(\"使用LinearRegression模型的均方误差为:\", metrics.mean_squared_error(y_test, y_pred))\n # print(\"使用LinearRegression模型的均方根误差为:\", np.sqrt(metrics.mean_squared_error(y_test, y_pred)))\n # print(\"使用Ridge Regression模型的均方误差为:\", metrics.mean_squared_error(y_test, y_ridge_pred))\n # print(\"使用Ridge Regression模型的均方根误差为:\", np.sqrt(metrics.mean_squared_error(y_test, y_ridge_pred)))\n\n from sklearn.model_selection import cross_val_predict\n predicted = cross_val_predict(reg, X, y, cv=10)\n # print(\"使用交叉验证的均方误差为:\", metrics.mean_squared_error(y, predicted))\n\n plt.figure('reg')\n plt.plot(y, predicted, '.')\n # plt.plot([y.min(), y.max()], [y.min(), y.max()], 'ro', lw=0.5)\n plt.plot(X, y, 'k--',lw=0.5)\n plt.scatter(y, predicted)\n # plt.show()\n\n\n\n\n area = request.form['area']\n room = request.form['room']\n hall = request.form['hall']\n floor = request.form['floor']\n if floor == '0':\n ceng = [0, 1, 0]\n elif floor == '1':\n ceng = [0, 0, 1]\n else:\n ceng = [1, 0, 0]\n floor = [int(area), int(room), int(hall)] + ceng\n\n # print(X.head(10))\n price = np.round(reg.predict([floor])[0], 2)\n # print(price)\n # plt.plot(floor, [floor for x in floor], 'ro')\n # plt.show()\n\n if ceng == [0, 1, 0]:\n gaodu = \"高层\"\n elif ceng == [0, 0, 1]:\n gaodu = \"中层\"\n else:\n gaodu = \"底层\"\n print(area, room, hall, gaodu,price)\n sql = \"insert into price (area, room, hall, gao,price) values ('%s','%s','%s','%s',%s)\" % (area, room, hall, gaodu,price)\n cur.execute(sql)\n db.commit()\n return json.dumps(price)\n\n\n\n#装修效果图\n@app.route(\"/openeffect\")\ndef openeffect():\n sql = \"select * from rendering \"\n cur.execute(sql)\n res = cur.fetchall()\n return render_template(\"/green-master/effect.html\", data=res)\n\n#装修案例\n@app.route(\"/opencase\")\ndef opencase():\n sql = \"select * from cases\"\n cur.execute(sql)\n res = cur.fetchall()\n return render_template(\"/green-master/case.html\", data=res)\n\n#装修案例(轮播,200平米详情)\n@app.route(\"/openeffect_item\")\ndef openeffect_item():\n return render_template(\"/green-master/effect_item.html\")\n\n#装修案例(轮播,橱柜详情)\n@app.route(\"/openeffect_item_1\")\ndef openeffect_item_1():\n return render_template(\"/green-master/effect_item1.html\")\n\n#装修知识\n@app.route(\"/openlore\")\ndef openlore():\n\n return render_template(\"/green-master/case_item.html\")\n\n#关于我们(查看更多)\n@app.route(\"/openabout\")\ndef openabout():\n return render_template(\"/green-master/case.html\")\n\n# 联系我们\n@app.route(\"/contact\")\ndef contact():\n return render_template(\"/green-master/contact.html\")\n\n# 装修团队\n@app.route(\"/team\")\ndef team():\n return render_template(\"/green-master/team.html\")\n\n# 装修现场\n@app.route(\"/openlive\")\ndef openlive():\n sql = \"select * from live\"\n cur.execute(sql)\n res = list(cur.fetchall())\n for item in res:\n res[res.index(item)] = list(item)\n print(res)\n return render_template(\"/green-master/live.html\", data=res, n_id=id)\n\n\n\n\n\n\n\n\n\n\n\n\n# 后台逻辑\n@app.route(\"/admin\") # 后台界面\ndef admin():\n if 'username' in session:\n return render_template(\"/blue-master/index.html\", level=session['level'])\n else:\n return redirect(url_for(\"login\"))\n@app.route(\"/login\")\ndef login():\n return render_template(\"/blue-master/login.html\")\n\n@app.route(\"/loginout\")\ndef loginout():\n del session['username']\n del session['level']\n return redirect(url_for(\"login\"))\n\n@app.route(\"/checklogin\", methods=['post'])\ndef checklogin():\n username = request.form['username']\n password = request.form['password']\n s = hashlib.md5()\n s.update(password.encode())\n password = s.hexdigest()\n #组织sql语句\n sql = \"select password,level from users where username='%s'\" % username\n #执行sql 语句\n cur.execute(sql)\n #获取查询结果\n password0 = \"\"\n res = cur.fetchone() # 输出结果\n if res != None:\n password0 = res[0]\n if password0 == password: # 对比密码\n # return \"登陆成功\"\n session['username'] = username\n session['level'] = res[1]\n return redirect(url_for(\"admin\"))\n else:\n # return \"登陆失败\"\n return redirect(url_for(\"tips\", state=\"no\", href=\"login\", time=3))\n\n\n@app.route(\"/tips///